Question:
I'm trying to use MySQL to create a view with the "WITH" clause

WITH authorRating(aname, rating) AS
   SELECT aname, AVG(quantity)
   FROM book
   GROUP BY aname

But it doesn't seem like MySQL supports this.

I thought this was pretty standard and I'm sure Oracle supports this. Is there anyway to force MySQL to use the "WITH" clause?  I've tried it with the MyISAM and innoDB engine.  Both of these don't work.

Answer:
Oracle does support WITH.
It would look like this.
```
```
WITH emps as (SELECT * FROM Employees)
SELECT * FROM emps WHERE ID < 20
UNION ALL
SELECT * FROM emps where Sex = 'F'
```
```
@ysth WITH is hard to google because it's a common word typically excluded from searches.
You'd want to look at the
SELECT docs
to see how subquery factoring works.
I know this doesn't answer the OP but I'm cleaning up any confusion ysth may have started.


Question: I'm working on a social networking system that will have comments coming from several different locations.  One could be friends, one could be events, one could be groups--much like Facebook.  What I'm wondering is, from a practical standpoint, what would be the simplest way to write a comments table?  Should I do it all in one table and allow foreign keys to all sorts of different tables, or should each distinct table have its own comment table?  Thanks for the help!

Answer:
This is an equivalent question to
this one
.
EDIT: Based on a comment, it isn't clear that this is an equivalent question, so I spell it out below.
Both questions ask about projects (both happen to be Social Networks, but that's just coincidence) where there is a question about the performance of the database. Both have a diverse set of objects that share a common collection of attributes (in one it is Events, that occur on each object, in the other it is Comments that occur on each object).
Both questions effectively ask whether it is more efficient to create a UNION query that combines the disparate common features, or to factor them out into a common table, with appropriate foreign keys.
I see them as equivalent; the best answer to one will apply equally to the other.
(If you disagree, I am happy to hear why; please leave a comment.)


Question:
I am looking for a regex pattern that would match several different combinations of
zeros such as 00-00-0000 or 0 or 0.0 or 00000

Please help

Thanks!

EDIT:

Well, I have web service that returns me a result set, based on what it returns me I can decide if the result is worth displaying on the page. So if I get either 00-00-0000 or 0 or 00000 I would assume that data was not found, however if it brings back 001 or 000123 or 0356.00 - 1000 or 0.6700, this would be valid.

Hope this clarifies my question

Thanks

Answer:
You need to better define what is valid to appear between the zeros.  Going from your question, I'll assume you're looking for any number of zeros with any number and grouping of "-" and "." between them....
```
0([-.]?0+)*
```
Hope you don't mind, SoapBox:
Based on the question edit, what you are looking for is any string that has non-zero digits in it, so:
```
[1-9]
```
or, if the regex engine automatically anchors start and end of string:
```
.*[1-9].*
```
may be the better solution.
This is the reverse of the test you asked for but that's a simple matter to change (reverse the sense of the if-statement).


Question:
I'm researching Open Source GIS resources - and wonder out of all the Open Source tools that are out there - what people are actually using / finding useful.

http://en.wikipedia.org/wiki/GIS_software

Answer:
Here's a few I use regularly
postgis
gdal
mapserver
uDig
grass
geos
geoserver
gmt
openlayers
tilecache
qgis
Big list here
http://opensourcegis.org/


Question: i have a winforms application.  i have a user control with a lot of icons.  the user can load this control on a form many times (in a tabbed layout).  right now i am loading the icons each time the control is created (could be up to 50 times in teh app).  is there any way to cache these icons in the application.  if i did this, would that decrease the number of gdi handles that i am using as this is becoming an issue.

Answer:
You can make a singleton class for each icon. The first reference it creates the handle. Subsequent calls uses the existing handle.
Without knowing more about your user control my next suggestion can be only be very general. But you could have a single bitmap layer on which you draw all your icons. The remaining elements of your user control would exists above and around this bitmap.
Unfortunately this idea may be problematic performance wise. Require you to refactor the code you all ready use for arranging icons. Finally it is non-institutive from how frameworks with a control-form structure ideally works.
We ran into a resource problem with entry forms for the parameteric shape we ship with our CAM software. Too many text entries caused various forms of strangeness and leaks. So we instead created labels with borders that looked like text entries and had ONE text entry (and a combo box entry too). When the user tabs, enters, or clicked the single text entry moved to the new entry and the label was setup for the previous entry.
This is totally a non-intuitive setup than how you would normally code this but it was the only way to deal with our resource problem.
In my experience it seems that GUI Frameworks have issues when you have to deal with dozens or hundreds of entries and that you have to approach the problem using a different design.


Question:
I have an onclick handler for an <a> element (actually, it's a jQuery-created handler, but that's not important).  It looks like this:

function handleOnClick() {
    if(confirm("Are you sure?")) {
        return handleOnClickConfirmed();
    }
    return false;
}

From this function, the this object is accessable as the <a> element clicked.  However, handleOnClickConfirmed's this is a Window element!  I want handleOnClickConfirmed to have the same this as handleOnClick does.  How would I do this?

(I know I can pass this as an argument to handleOnClickConfirmed, but some of my code already uses handleOnClickConfirmed and I don't want to have to rewrite those calls.  Besides, I think using this looks cleaner.)

Answer:
The following ought to do it:
```
```
function handleOnClick() {
    if( confirm( "Sure?" ) ) {
        return handleOnClickConfirmed.call( this );
    }
    return false;
}
```
```
The
```
call()
```
function attached to
```
Function
```
objects is designed to allow this; calling a function with a desired context. It's an extremely useful trick when setting up event handlers that call back into functions within other objects.


Question:
can anyone show me how to get the users within a certain group using sharepoint?

so i have a list that contains users and or groups. i want to retrieve all users in that list. is there a way to differentiate between whether the list item is a group or user. if its a group, i need to get all the users within that group.

im using c#, and im trying to do thins by making it a console application.

im new to sharepoint and im really jumping into the deep end of the pool here, any help would be highly appreciated.

cheers..

Answer:
The first thing you need to know is that when you have a list with a User / Group field you must be aware of its type. When you have one user or group within the item value, the field type is SPFieldUserValue. However, if the field has multiple user / group selection the field type is SPFieldUserValueCollection.
I'll assume that your field allows a single user / group selection and you already has the following objects:
```
```
SPSite site;
SPWeb web;
SPListItem item;
```
```
Now, we'll check the field value for a user / group and retrieve a list of users, independant of which kind it is (the field's name is
"Users"
).
```
```
SPFieldUserValue usersField = new SPFieldUserValue(mainWeb, item["Users"].ToString());
bool isUser = SPUtility.IsLoginValid(site, usersField.User.LoginName);
List<SPUser> users = new List<SPUser>();

if (isUser)
{
    // add a single user to the list
    users.Add(usersField.User);
}
else
{
    SPGroup group = web.Groups.GetByID(usersField.LookupId);

    foreach (SPUser user in group.Users)
    {
        // add all the group users to the list
        users.Add(user.User);
    }
}
```
```
I hope it helps you.
Tks,
Pedro José Batista


Question:
I'm trying to display the contents of an ordered array in something like a JTextField.

for (int i=0; i<array.length; i++) {
    this.textField.setText(array[i]);
}

This won't work for two reasons. The first minor reason: if the array length is 4 then jtextfield is getting it's value reset 4 times rather than appending each element onto the last.
Second reason: The JTextField only takes strings. I can't find anything I can use in Swing that will let me display integers to the user. Any help?

Answer:
You can concatenate all those integers into a string the then present that value in the textfield.
```
```
StringBuilder sb = new StringBuilder();
for( int i : array ) {  // <-- alternative way to iterate the array
     sb.append( i );
     sb.append( ", " );
}

sb.delete(sb.length()-2, sb.length()-1); // trim the extra ","
textField.setText( sb.toString() );
```
```
You can use a JTextArea instead of the textfield too.


Question: I am using a RichTextBox in WPF, and am trying to set the default paragraph spacing to 0 (so that there is no paragraph spacing).  While I could do this in XAML, I would like to achieve it programmatically if possible.  Any ideas?

Answer:
Using Line Height
```
```
RichTextBox rtb = new RichTextBox();
Paragraph p = rtb.Document.Blocks.FirstBlock as Paragraph;
p.LineHeight = 10;
```
```


Question: How do I create an ASP.NET web service that returns JSON formatted data?

Answer:
The most important thing to understand is to know how to represent data in JSON format.
Please refer
http://www.json.org/
to know more about it.
Once you understand this, then the rest part is pretty straight forward.
Please check the following URL for an example of the same.
http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=264
http://code.msdn.microsoft.com/JSONSampleDotNet
http://www.phdcc.com/xml2json.htm
I recommend Jquery library for this.  It's a lightweight rich library which supports calling web services, handle json data format output etc.
Refer www.jquery.com for more info.


Question:
Given a jQuery result set, how do you convert that back into plain HTML?

<div class="abc">
    foo <strong>FOO</strong>
</div>
<div class="def">
    bar
</div>

--

var $mySet = $('div');

Given $mySet, how would you go about returning to the plain HTML above?

Answer:
```
```
var $mySet = $('div');
var html = $mySet.html();
```
```
If you want the element's HTML as well (untested):
```
```
var $mySet = $('div');
var html = $mySet.clone().wrap('

').html();
```
```
By the way, here $ is part of the variable name.  Javascript doesn't require a $ like in PHP for variable names, but it doesn't hurt to have it.


Question: I'd like to use visitor IP addresses into a company name. This will be used for displaying something like "Hello visitor from Apple Inc." . Note I am looking for the company name, not the domain name. Extra points for determining the originating country. The app is written in Ruby on Rails, but examples in other languages will do. Thanks!

Answer:
There are databases for this kind of thing, but they are hardly 100% accurate, so I'd think long and hard before using them to make assumptions regarding content you present to your visitors. If you still want to do it, here are two companies that offer databases that include organization level detail:
http://www.maxmind.com/app/ip-location
http://www.ip2location.com/
Edit to clarify based on additional answers:
The organization level detail in the databases from these vendors is different than ISP information, which is what the others are referring to. The databases from the vendors above are actually assigned organizational information based on research, not reverse lookup on IP ownership.


Question:
Here I am faced with an issue that I believe(or at least hope) was solved 1 million times already.
What I got as the input is a string that represents a length of an object in imperial units. It can go like this:

$length = "3' 2 1/2\"";

or like this:

$length = "1/2\"";

or in fact in any other way we normally would write it.

In effort to reduce global wheel invention, I wonder if there is some function, class, or regexp-ish thing that will allow me to convert Imperial length into Metric length?

Answer:
The regexp would look something like this:
```
```
"([0-9]+)'\s*([0-9]+)\""
```
```
(where \s represents whitespace - I'm not sure how it works in php). Then you extract the first + second group and do
```
```
(int(grp1)*12+int(grp2))*2.54
```
```
to convert to centimeters.


Question:
Like this: const void * test = sqlite3_column_blob(stat, 1);
Can I delete or delete[] test?

Answer:
Look at its API Manual. If it is a C API, you probably have to
```
free
```
it. If it doesn't provide its own function like sqlite3_free (pcre does this for example), you have to use that function.
What you can't do is delete it using C++'s delete operator, since you have got a void pointer. You cannot delete a void pointer, since the compiler has to know about its type. (and void is an incomplete type. you can't delete incomplete types either).


Question:
I have a project built and packaged with a specific version of jsp-apiand servlet-api jar files. Now I want these jars to be loaded when deploying the web project on any application server for example tomcat, WAS, Weblogic etc.

The behaviour I have seen on tomcat is that it gives messages that the packaged version of these apis are not loaded along with an offending class.

Is there any way I could override these server settings or behaviour?

My concern is that letting the default behaviour of a server may allow different behaviour on different servers or even on different versions of same app server.

Answer:
If you have control over the server where you want to install this webapp you can replace the core jars with yours.
Additionally you can prepend the jars in the startup of the app server.
Update:
As for the second part, you'll need to modify the startup file of the application server it self.
I don't have an installation at hand but lets suppose in the dir $YOUR_APPSERV/bin there are a bunch of scripts ( either .cmd or .sh files )
Some of them start the app server , some other help to configure it.
You need to modify one of those in such a way the command line look like this:
(assume a windows installation)
```
```
java -Xbootclasspath/p:c:\cutomjars\myJar.jar;customjars\myOtherJar.jar ..................... // the rest of the normal command line.
```
```
-bootclasspath/p prepends the jars to the app classpath
-bootclasspath/a appends the jars to the app claspath
This option let you override any class in the JVM with those specified in the jars, so you can even substitute java.lang.String if you want to.
That's one approach. Unfortunately -Xbootclasspath is an option for Sun JVM ( that is JRockit does not have it, nor the IBM's VM what ever his name is )
There was another option where you declare a folder where all the extensions are. Plus, there is an ext directory in the jre.
Take a deep dive into your application server bin directory and find out what each script is used for, I'm pretty sure you'll make it through.
Here's a more formal explanation of this topic:
http://java.sun.com/j2se/1.5.0/docs/tooldocs/findingclasses.html
I hope it helps.
BTW, I use to do this years ago, to substitue the CORBA package with a veeeery old version.  So this works for sure.


Question: While looking at the syntax-case section in R6RS, I saw the keyword make-variable-transformer, described as an identifier macro. The example given is very minimal, and I am not groking why it is necessary, or what use-cases require it. Finding additional examples of its use is also proving difficult. Presumably it makes some form of syntax transformation possible, or more elegant?

Answer:
After reading
http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-13.html#node_sec_12.3
my take is as follows:
If
```
mac
```
is a syntax transformer
```
(mac foo (bar baz))
```
would replace the entire s-expr with the result of the transformation this could result in anything say
```
(SOMETHING)
```
, while
```
(foo mac bar)
```
would replace only
```
mac
```
resulting in
```
(foo SOMETHING bar)
```
.
Normally
```
(set! mac 'foo)
```
would signal an error it seems that the transformer can not appear on the left of a set expression, but if
```
mac
```
is a variable transformer
```
(set! mac 'foo)
```
would instead call
```
mac
```
with the whole s-expr.
My intuition tells me this would be useful if you start implementing datatypes with macros.


Question:
Maybe this cannot be done, but please help or suggest how this can be achieved without writing something to disk.

Lets suppose there are two string values that I want to share between two independent applications.

You are welcome to provide code sample in any programming language.

Answer:
What you probably want to do is create a memory-mapped file. You can create a memory-mapped file that doesn't have any backing store on disk, but is instead backed by the system page file. Have a look at the documentation for
```
CreateFileMapping
```
, in particular when the first parameter is
```
INVALID_HANDLE_VALUE
```
.
You can give such a file mapping a unique system-wide name, and then other applications can open it using
```
OpenFileMapping
```
and providing the same name.
Once you have such a block of shared memory, you can put any information you like into it. Note that since the memory is shared across processes, you don't want to store any pointers into the block of memory (which precludes doing things like storing a
```
std::string
```
there).


Question:
I have a Jar file, which contains other nested Jars. When I invoke the new JarFile() constructor on this file, I get an exception which says:

java.util.zip.ZipException: error in opening zip file

When I manually unzip the contents of this Jar file and zip it up again, it works fine.

I only see this exception on WebSphere 6.1.0.7 and higher versions. The same thing works fine on tomcat and WebLogic.

When I use JarInputStream instead of JarFile, I am able to read the contents of the Jar file without any exceptions.

Answer:
It could be related to log4j.
Do you have log4j.jar file in the websphere java classpath (as defined in the startup file) as well as the application classpath ?
If you do make sure that the log4j.jar file is in the java classpath and that it is NOT in the web-inf/lib directory of your webapp.
It can also be related with the
ant version
(may be not your case, but I do put it here for reference):
You have a .class file in your class path (i.e. not a directory or a .jar file). Starting with ant 1.6, ant will open the files in the classpath checking for manifest entries. This attempted opening will fail with the error "java.util.zip.ZipException"
The problem does not exist with ant 1.5 as it does not try to open the files. - so make sure that your classpath's do not contain .class files.
On a side note, did you consider having
separate jars
?
You could in the manifest of your main jar, refer to the other jars with this attribute:
```
```
Class-Path: one.jar two.jar three.jar
```
```
Then, place all of your jars in the same folder.
Again, may be not valid for your case, but still there for reference.


Question:
I have a question about using new[].

Imagine this:

Object.SomeProperty = new[] {"string1", "string2"};

Where SomeProperty expects an array of strings.

I know this code snippet will work. But i want to know what it does under the hood. Does new[] makes an instance of the class object and in SomeProperty it converts it automatically to a string object?

Thanks

Answer:
This is just syntactical sugar. The compiler will infer the type actually necessary here and create code that is equivalent to the explicit construct:
```
```
Object.SomeProperty = new string[] {"string1", "string2"};
```
```
There's no such thing as
```
new[]
```
that gets executed at runtime.


Question:
For this WCF service I have developed, I have to set MaxReceivedMessageSize to 5MB. My current problem is figuring out whether it is better to have a larger MaxBufferPoolSize value, like 5MB, or retain the original 512KB value.

Does anyone knows what is the recommended setting for this scenario?

In short, should I set MaxBufferPoolSize = 5242880 (5MB), or MaxBufferPoolSize = 524288 (512KB)?

UPDATE: For clarification, the service is meant to insert a new customer record along with some scanned documents. As a result, the message size may reached up to 5MB.

We could try and separate the upload of the scanned document using alternate technologies, but the requirement was both customer record and scanned documents must be in the same transaction, so we decided to go with this approach, until we figure out how to use WCF's transaction capability.

Answer:
5 Mb seems like a lot of data to transfer over a Web Service.
The first thing you should look for is to send less data.
Secondly you need to set the size to your needs.


Question:
What would be the best way to display & program simple game board (say chess, checkers and such) in C#? In terms of controls and underlying game logic.

An idea that came to my mind was to use Picture Box (or class inheriting from it) with Board & Field classes.

Is that a decent solution after all?

How would I separate graphics from game logic using this solution (I believe Board & Field classes may not be enough)?

Is PictureBox efficient enough for such purpose?

Googling some also brought me to solutions using button/label for each game field. But back to Board, Field and PictureBox.

Extendability - designing it properly would easily allow to implement any other board game (or even card game) as it's all about board with modifiable fields after all.

Answer:
In an object-oriented approach, think about the objects involved in your game (e.g. the board, the pieces) … let them each provide a drawing method that takes a
```
Graphics
```
object and draws itself on it.
The drawing itself could be done on a
```
PictureBox
```
– this is the ideal control for such purpose – but this isn't really all that important because once your drawing logic is in place, it won't depend on the kind of control.
In general,
don't
use workarounds with different controls. These might be nice for a conventional GUI. Not so much for games (or any kind of graphics-heavy application).


Question:
I'm using Java 1.5 and I'd like to launch the associated application to open the file. I know that Java 1.6 introduced the Desktop API, but I need a solution for Java 1.5.

So far I found a way to do it in Windows:

Runtime.getRuntime().exec(new String[]{ "rundll32",
                          "url.dll,FileProtocolHandler", fileName });

Is there a cross-platform way to do it? Or at least a similar solution for Linux?

Answer:
SWT
gives you the possibility to lokk for the standard program to open a file via:
```
```
final Program p = Program.findProgram(fileExtension);
p.execute(file.getAbsolutePath());
```
```
Strictly this isn't Cross-Platform since SWT is platform dependent, but for every platform you can use a diffenrent SWT jar.


Question:
You are given a heap of code in your favorite language which combines to form a rather complicated application. It runs rather slowly, and your boss has asked you to optimize it. What are the steps you follow to most efficiently optimize the code?

What strategies have you found to be unsuccessful when optimizing code?

Re-writes: At what point do you decide to stop optimizing and say "This is as fast as it'll get without a complete re-write." In what cases would you advocate a simple complete re-write anyway? How would you go about designing it?

Answer:
Profile before attempting any optimisation.
9 times out of 10, the time won't be consumed where you might guess it is.
The usual unsuccessful strategy is micro-optimisation, when what is actually required is the appropriate algorithm.
Obligatory Donald Knuth quote:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"


Question:
I just set up SSHd through Cygwin on a Windows XP Pro box overseas using a RAT and discluded the openssh package from the install.
I ran the cywin shell (from c:\cywin) and ran
Now, It's under a port I know is safe and fowarded properly, but I won't share it's number. It's not a common port, but it's under 40000.
Firewalls are off etc etc.
I'm on the first Admin account made on the box. (It's full admin)
I've run the following commands

chmod +r  /etc/passwd

chmod +r  /etc/group

hmod  777  /var

/*Created New Admin User Account To Be Used via SSH*/

mkpasswd -cl > /etc/passwd

mkgroup --local > /etc/group

I can connect locally, but not externally.
I know my ports etc are fine.

Any possible problems, as i really need this tunnel up :P

Answer:
Profile before attempting any optimisation.
9 times out of 10, the time won't be consumed where you might guess it is.
The usual unsuccessful strategy is micro-optimisation, when what is actually required is the appropriate algorithm.
Obligatory Donald Knuth quote:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"


Question:
Do you know any documentation about the rules of using update sites? I have managed the last 2 and a half years the update site of our company, and these are the problems I have to address:

Not all projects use the same eclipse version. We had projects that used eclipse 2.1 (WSAD), eclipse 3.0 (RAD 6), eclipse 3.2 (RAD 7), eclipse 3.3 and eclipse 3.4.

The update site of our company mostly packages things together. So I have written litte plugins (sometimes fragements) to package e.g. the configuration of Checkstyle for our company together with the current version of Checkstyle.

We release two times a year new versions of what has changed. So if I have 1 update site or 4, this will change dramatically the load I have to take.

So the question is: How many update sites should we use, and if the number is more than 1, how can I minimize the work to do to maintain the update sites?

Answer:
I suggest to put everything on one web server and deploy the packages for each version of Eclipse to a different URL:
http://your.server/eclipse-3.3/site.xml
http://your.server/eclipse-3.4/site.xml
etc.
This will make it easy to deploy, to keep things apart and it will make it simple for users to see "ah, this is the one for me".


Question:
I need to validate a certain property to one of my classes. When I set the property, the class should validate the input and if incorrect, set the object to an invalid state.

Question : The property value must be in a certain mask/format eg. &&&&-&&&&-&&&&. I cannot use regular expressions. Is it possible to validate text against a mask value?

Answer:
Is it possible to validate text
  against a mask value ?
Of course it's possible, in that you could write a function to take a string and a mask and check one against another.
So I'm unclear on what you're asking - are you asking if there are functions in the standard .Net libraries to do this? Or asking for an implementation of a mask-validation function? Or something else?
If you're looking for something in the library to help,
MaskedTextProvider
would probably do it, although it's overkill.


Question:
I am getting a runtime error 13 at the end of the following code:

Sub plausibilitaet_check()

Dim rs As DAO.Recordset
Dim rs2 As ADODB.Recordset
Dim db As database
Dim strsql As String
Dim strsql2 As String
Dim tdf As TableDef

Set db = opendatabase("C:\Codebook.mdb")
Set rs = db.OpenRecordset("plausen1")

Set rs2 = CreateObject("ADODB.Recordset")
rs2.ActiveConnection = CurrentProject.Connection

For Each tdf In CurrentDb.TableDefs

   If Left(tdf.Name, 4) <> "MSys" Then
        rs.MoveFirst
        strsql = "SELECT * From [" & tdf.Name & "] WHERE "

        Do While Not rs.EOF
            On Error Resume Next

            strsql2 = "select * from table where GHds <> 0"
            Set rs2 = CurrentDb.OpenRecordset(strsql2)

The error occurs at  Set rs2 = CurrentDb.OpenRecordset(strsql2)

Can someone see where I am going wrong?

Answer:
CurrentDB.OpenRecordset returns an instance of DAO.Recordset. You are trying to assign the result to ADODB.Recordset
Change the rs2 definition to
```
dim rs2 as DAO.Recordset
```


Question:
I am using oracle wallet to store the oracle database passwords,
the batch file to create the wallet asks for password when you run it.
is there any way to modify the batch file , and provide the password before hand

so that i can avoid inputtting the password every time i run that.

so to generalize the problem, is there any way i can write to input stream of another program.

so that i can avoid prompts from my automation scripts.

Answer:
You can use the pipe operator "|" to redirect the standard output stream of one program into the input stream of another.  I works both on unix and windows platforms.
In your example you would have a script doing just
```
```
echo mypassword
```
```
and you would run this from the command line:
```
```
myscript | wallet
```
```
I assume that your script would be called myscript.bat, and the wallet program wallet.exe, change these accordingly.


Question:
To follow on from my question yesterday....

MySQL Table Design for a Questionnaire

I sat down with my boss yesterday afternoon to run through how I was proposing to design the database.  However, now I am more confused than ever.

He has been using Access for many years, and has questioned whether I will be able to produce reports from only using one column for the answer (ENUM).  He feels from his experience with Access that each possible response (i.e. Very Satisfied, Fairly Satified, Fairly Unsatisfied, Very Unsatisfied), should have it's own column and numerical value(i.e. 100, 66.6, 33.3, 0).

This is so that the database can produce reports that show the average satisfaction nationally and for each retailer individually.

I would really appreciate some guidence, as I really don't want to get this wrong?

Thank you

Answer:
In this case I wouldn't go for an enum, I'd go for a "score" column. So the columns might be:
```
```
userid, questionid, score
1,1,4
1,2,4
1,3,3
2,1,1
2,2,4
...
```
```
1 being very unsatisfied and 4 being very satisfied.
Then a query like:
```
```
select 25*avg(score) from Blah
```
```
will give you your overall percentage.
```
```
select 25*avg(score), questionid from Blah group by questionid
```
```
will give you a % per question.
Access isn't really a database, so don't listen to your boss ;)


Question:
I am a newbie for Visual Basic 6 project.  I downloaded some tutorials for testing; however, I am not able to drag, move, or edit the UI form designer objects in those projects.

Does anybody know there is an object lock function in VB6?

If there is, how can I unlock it?

Answer:
In this case I wouldn't go for an enum, I'd go for a "score" column. So the columns might be:
```
```
userid, questionid, score
1,1,4
1,2,4
1,3,3
2,1,1
2,2,4
...
```
```
1 being very unsatisfied and 4 being very satisfied.
Then a query like:
```
```
select 25*avg(score) from Blah
```
```
will give you your overall percentage.
```
```
select 25*avg(score), questionid from Blah group by questionid
```
```
will give you a % per question.
Access isn't really a database, so don't listen to your boss ;)


Question: I'm using reflection to loop through a Type's properties and set certain types to their default.  Now, I could do a switch on the type and set the default(Type) explicitly, but I'd rather do it in one line.  Is there a programmatic equivalent of default?

Answer:
I do the same task like this.
```
```
//in MessageHeader
   private void SetValuesDefault()
   {
        MessageHeader header = this;
        Framework.ObjectPropertyHelper.SetPropertiesToDefault<MessageHeader>(this);
   }

//in ObjectPropertyHelper
   public static void SetPropertiesToDefault<T>(T obj)
   {
            Type objectType = typeof(T);

            System.Reflection.PropertyInfo [] props = objectType.GetProperties();

            foreach (System.Reflection.PropertyInfo property in props)
            {
                if (property.CanWrite)
                {
                    string propertyName = property.Name;
                    Type propertyType = property.PropertyType;

                    object value = TypeHelper.DefaultForType(propertyType);
                    property.SetValue(obj, value, null);
                }
            }
    }

//in TypeHelper
    public static object DefaultForType(Type targetType)
    {
        return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
    }
```
```


Question: In my application I need to hash a string before I save it to a text file. Does anyone know how to do that?

Answer:
You can try with CriptoASP. Don't mind about the 'ASP' in the name, it's an ActiveX DLL you can instantiate from VB6. It provides methods for generate random numbers, hashes with MD2, MD4, MD5 and SHA and some kind of encryption/decryption.
You can download it from
CriptoASP
I'm sorry, web's language is in spanish, but I think you can undertand the very easy use of the COM with the examples at bottom of
Doc. for CriptoASP
, just change
Server.CreateObject
with the new object sentence in VB6.
Tell me if you want a translate of the examples or documentation.
To save it to a text file you can use FSO (File System Object).


Question:
I have strange problem with sharepoint and ajax functionality. We have an UpdatePanel placed inside webpart. When partial postback occurs, page title gets missing.

We have found that temporary partial solution is to write title element into one line and not use any spaces or controls inside it..not even a literal control.

But we need some way to provide sommon title for all pages, so title would look like this:
My default title - Current page title

Any ideas how to solve this?

Answer:
this looks like pure sharepoint's problem..also it looks like just sites based on publishing page layout are affected.
I debugged response in firebug and for some reason it returns setting for page title, so response from server contains not just update panel information, but also empty page title.
I debugged our webparts and none of them plays with page title. I would suggest not to use publishing or just not use any controls inside title.
We are currently working on this issue in company i work for, so i'll upload uour findings when we figure out something.


Question:
I've a python script that has to launch a shell command for every file in a dir:

import os

files = os.listdir(".")
for f in files:
    os.execlp("myscript", "myscript", f)

This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.

How can I do? Do I have to fork() before calling os.execlp()?

Answer:
The
```
os.exec*()
```
functions
replace
the current programm with the new one. When this programm ends so does your process. You probably want
```
os.system()
```
.


Question: I want a way to list files in a directory and putting a check box beside each one of them so I can select some of them and perform operations with each selected file, what's the best way to do this?

Answer:
You can use checked list box control which is built-in winforms control (see links below):
http://www.functionx.com/vcsharp/controls/checkedlistbox1.htm
http://msdn.microsoft.com/en-us/library/3ss05xx6.aspx


Question:
What is the masked text provider used for? Why is it different from regex?

Is it possible to translate the regex format to mask or vise versa ?

Thanks

Answer:
A masked edit area forces the user to fill the field in a certain way: e.g. a mask that looks like ### will only allow a maximum of 3 numbers to be entered.
A regular expression, on the other hand, is normally only checked for after the user has entered all the text. The validation happens too late to provide feedback on a character by character basis.


Question:
I am trying to comment an API (.Net) that I am exposing to a customer.
I am doing this by using XML comments, and extracting via SandCastle.

This is all fine and dandy, however I have unittesting for the API, and thought the code from these would be good to place in the example tags.

So does anyone know of a good way to extract unit test code and place in the example tags?
Or does anyone have better ideas?

Of course I redistribute the unit tests with the API, but it would be good to have them in the documentation.

Answer:
I see that Jon Skeet har an answer, that requires some work:
Automatically Unit Test Example Code
Has anyone gone and implemented this?
Is there an easier way?
This question is about getting a metod body from a cs file:
Get a method's contents from a cs file
I have made a project to do this:
http://code.google.com/p/addsourcetodocumentation/


Question:
Basically I have a small template that looks like:

<xsl:template name="templt">
    <xsl:param name="filter" />
    <xsl:variable name="numOrders" select="count(ORDERS/ORDER[$filter])" />
</xsl:template>

And I'm trying to call it using

<xsl:call-template name="templt">
    <xsl:with-param name="filter" select="PRICE &lt; 15" />
</xsl:call-template>

Unfortunately it seems to evaluate it before the template is called (So effectively "false" is being passed in) Enclosing it in quotes only makes it a string literal so that doesn't work either. Does anybody know if what I'm trying to achive is possible? If so could you shed some light on it? Cheers

Answer:
how about the following:
```
```
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template name="templt">
    <xsl:param name="filterNodeName" />
    <xsl:param name="filterValue" />
    <xsl:variable name="orders" select="ORDERS/ORDER/child::*[name() = $filterNodeName and number(text()) < $filterValue]" />
    <xsl:for-each select="$orders">
      <xsl:value-of select="."/>
    </xsl:for-each>
  </xsl:template>

  <xsl:template match="/">
    <xsl:call-template name="templt">
      <xsl:with-param name="filterNodeName" select="'PRICE'" />
      <xsl:with-param name="filterValue" select="15" />
    </xsl:call-template>
  </xsl:template>
</xsl:stylesheet>
```
```
If you still want to use a single parameter only, you could tokenize in template 'templt' first.


Question:
Is it possible to provide Unicode input to a console app, and read the Unicode char/string via Console.ReadKey()?

I know Unicode works when reading the input via other methods, but unfortunately I need to use the 'interception' feature provided by ReadKey.

Update:

When pasting a Unicode character such as U+03BB (λ) into the console, 3 keys are read.

Alt + NumPad1

Alt + NumPad1

Alt + NumPad8

I have tried to see if this is some kind of encoding, but can not see anything.

Answer:
The ConsoleKeyInfo object returned by Console.ReadKey() has a property called KeyChar containing the Unicode char of the pressed key or key combination (if the key or key combination has a Unicode equivalent). So...
```
```
char c = Console.ReadKey().KeyChar;
```
```
You'll get a '\0' char if the key doesn't have a Unicode equivalent (for example, a function key).
You can use a StringBuilder to concatenate these chars together into a Unicode string if necessary.


Question:
Here is a little test program:

#include <iostream>

class Test
{
public:
    static void DoCrash(){ std::cout<< "TEST IT!"<< std::endl; }
};

int main()
{
    Test k;
    k.DoCrash(); // calling a static method like a member method...

    std::system("pause");

    return 0;
}

On VS2008 + SP1 (vc9) it compiles fine: the console just display "TEST IT!".

As far as I know, static member methods shouldn't be called on instanced object.

Am I wrong? Is this code correct from the standard point of view?

If it's correct, why is that? I can't find why it would be allowed, or maybe it's to help using "static or not" method in templates?

Answer:
static methods can be called also using an object of the class, just like it can be done in Java. Nevertheless, you shouldn't do this. Use the scope operator like
```
Test::DoCrash();
```
Maybe you think of namespaces:
```
```
namespace Test {
    void DoCrash() {
        std::cout << "Crashed!!" << std::endl;
    }
};
```
```
which can only be called by
```
Test::DoCrash();
```
from outside that namespace if the function is not imported explicitly using a
```
using directive/declaration
```
into the scope of the caller.


Question:
I write a Text Editor with Java , and  I want to  add Undo function to it

but without UndoManager Class , I need to use a Data Structure like Stack or LinkedList but the Stack class in Java use Object parameters e.g : push(Object o) , Not Push(String s)
I need some hints or links .
Thanks

Answer:
Assuming you are using Java 5, Stack is a generic class. You can instantiate it according to the objects it should hold.
You can then use:
```
```
Stack<String> stack = new Stack<String>();
String string = "someString";
stack.push(string);
```
```
Also note that in the case you are using Java 1.4 or below, you can still push String objects into the stack. Only that you will need to explicitly downcast them when you pop() them out, like so:
```
```
Stack stack = new Stack();
String string = "someString";
stack.push(string);

String popString = (String) stack.pop(); // pop() returns an Object which needs to be downcasted
```
```


Question:
I need a byte buffer class in Java for single-threaded use. I should be able to insert data at the back of the buffer and read data at the front, with an amortized cost of O(1). The buffer should resize when it's full, rather than throw an exception or something.

I could write one myself, but I'd be very surprised if this didn't exist yet in a standard Java package, and if it doesn't, I'd expect it to exist in some well-tested public library.

What would you recommend?

Answer:
Not sure if it is "the best", but you have a nice example of
Circular Byte buffer here
.
Those
Java Utilities - OstermillerUtils
classes are under
GPL license
.
This Circular Byte Buffer implements the circular buffer producer/consumer model for bytes. Filling and emptying the buffer is done with standard Java InputStreams and OutputStreams.
Using this class is a simpler alternative to using a PipedInputStream and a PipedOutputStream.
PipedInputStreams and PipedOutputStreams don't support the mark operation, don't allow you to control buffer sizes that they use, and have a more complicated API that requires a instantiating two classes and connecting them.


Question: What is the difference between the value and itemValue attribute of the radiobutton in Jsf?

Answer:
From this IBM article
Adding row selection to a JSF datatable using radio buttons
:
The
attribute id
is for the component value of the Radio Button Group. It will be bound to the Value field
The attribute selectedRowId is for the
item value
of the radio button, and will be bound to the item value field


Question:
By definition algorithms are independent from the medium they run on. E.g. I use Excel tables to play with data structures and to do some move/shuffling/marking experiments before implementing an algorithm in a programming language.

What tools and techniques do you use to design and simulate the function of an algorithm? How do you use drawing programs? A special specification language?

Answer:
I guess it depends on the complexity of the algorithm.
Quite often I'll actually draw a quick sketch of a flowchart on some paper.  There are some excellent diagramming tools available, but I still haven't found one that is as quick as a good old fashioned sketch on a piece of paper.
Other than that, I often end up throwing together a really 'quick and dirty' mock up of the algorithm in a VB.NET windows forms or console application.  With some of the more recent features like LINQ-to-SQL, you can even put together prototypes that rely on database access in a very short space of time.


Question:
I want to build a secure web-service betweeen a Java producer and a Java consumer. I want to authenticate using Active Directory using the domain accounts that the producer and consumer are running under.

Could you give me an example of this?

(ie: AD trusted automated alternative to manual keystores.)

Answer:
Look at
Spring WS
and the and
security certificate authentication
,
7.2.2.1.3 JaasPlainTextPasswordValidationCallbackHandler
, and
7.2.2.3.3 JaasCertificateValidationCallbackHandler
.
There are some examples that tie this together through additional research.


Question: I want to change background color of Datagrid header in Silverlight.

Answer:
Although the DataGrid does not expose a Header Background property, it does have a property for the ColumnHeaderStyle. Using the technique that DaniCE has previously suggested for a single column we can replace the header template for all header columns including the empty space on the right hand side. The down side with replacing the entire template for a header is that we lose the sorting arrows and separators which are present in the default header template. Fortunately we can use a
template browser
to extract the default template being used and then modify a copy of it.
Here I've thrown together a quick example that will change the background of the column headers to LightBlue while keeping the separators and sorting. Take a look at the default DataGridColumnHeader template in a
template browser
to see how to deal with modifying the Background when the mouse hovers over the ColumnHeader.
```
```
<data:DataGrid x:Name="grid">
    <data:DataGrid.ColumnHeaderStyle>
        <Style
            xmlns:primitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"
            xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
            TargetType="primitives:DataGridColumnHeader" >
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="primitives:DataGridColumnHeader">
                        <Grid Name="Root">
                            <vsm:VisualStateManager.VisualStateGroups>
                                <vsm:VisualStateGroup x:Name="SortStates" >
                                    <vsm:VisualStateGroup.Transitions>
                                        <vsm:VisualTransition GeneratedDuration="00:00:0.1" />
                                    </vsm:VisualStateGroup.Transitions>
                                    <vsm:VisualState x:Name="Unsorted" />
                                    <vsm:VisualState x:Name="SortAscending">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="SortIcon" Storyboard.TargetProperty="Opacity" Duration="0" To="1.0" />
                                        </Storyboard>
                                    </vsm:VisualState>
                                    <vsm:VisualState x:Name="SortDescending">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="SortIcon" Storyboard.TargetProperty="Opacity" Duration="0" To="1.0" />
                                            <DoubleAnimation Storyboard.TargetName="SortIconTransform" Storyboard.TargetProperty="ScaleY" Duration="0" To="-.9" />
                                        </Storyboard>
                                    </vsm:VisualState>
                                </vsm:VisualStateGroup>
                            </vsm:VisualStateManager.VisualStateGroups>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="*" />
                                <RowDefinition Height="*" />
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto" />
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <Rectangle x:Name="BackgroundRectangle" Stretch="Fill" Fill="LightBlue" Grid.ColumnSpan="2" Grid.RowSpan="2"  />
                            <ContentPresenter Grid.RowSpan="2" Content="{TemplateBinding Content}" Cursor="{TemplateBinding Cursor}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="{TemplateBinding Padding}" />
                            <Rectangle Name="VerticalSeparator" Grid.RowSpan="2" Grid.Column="2" Width="1" VerticalAlignment="Stretch" Fill="{TemplateBinding SeparatorBrush}" Visibility="{TemplateBinding SeparatorVisibility}" />
                            <Path Grid.RowSpan="2" Name="SortIcon" RenderTransformOrigin=".5,.5" HorizontalAlignment="Left" VerticalAlignment="Center" Opacity="0" Grid.Column="1" Stretch="Uniform" Width="8" Data="F1 M -5.215,6.099L 5.215,6.099L 0,0L -5.215,6.099 Z ">
                                <Path.Fill>
                                    <SolidColorBrush Color="#FF444444" />
                                </Path.Fill>
                                <Path.RenderTransform>
                                    <TransformGroup>
                                        <ScaleTransform x:Name="SortIconTransform" ScaleX=".9" ScaleY=".9"  />
                                    </TransformGroup>
                                </Path.RenderTransform>
                            </Path>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </data:DataGrid.ColumnHeaderStyle>
</data:DataGrid>
```
```
Hope this helps!


Question: Does anyone of you know, if and if so, how can I check, with my application code, if a server has ssl enabled or not?

Answer:
not sure on your language of preference but here it is in c#
```
```
public bool IsSecureConnection()
{
    return HttpContext.Current.Request.IsSecureConnection ||
           HttpContext.Current.Request.Headers["HTTP_X_SSL_REQUEST"].Equals("1");
}
```
```
Please note this header is custom, but I think you get the idea.  I've seen folk simply query request for "https" and besides looking dirty it's probably reasonably acceptable, depends on your security model.
Or are you asking whether it's simply available at all?
I


Question:
I need a RegExp which matches a word or multiple words in quotes.

[\w]* matches a word

"[\w\W&&[^"]]*" matches multiple words in quotes.

(btw, not sure why \w\W works, but not a simple . (which should match all characters)

So how do i combine these two regexp?

Answer:
Does
```
"[^"]+"
```
do what you want? (Match a double-quote, match one or more chars that are not double quotes, then match a second double-quote.)


Question: how can access the binary data file(.DAT). i am using geonames API. can anyone help me?

Answer:
Assuming you are using C# (from the tag), you can use
```
BinaryReader
```
class
to read binary data. See
How to read and write to a binary file
:
```
```
FileStream fs = File.Open(Environment.CurrentDirectory + @"\settings.bin", FileMode.Open);
BinaryReader reader = new BinaryReader(fs);

long number = reader.ReadInt64();
byte[] bytes = reader.ReadBytes(3);
string s = reader.ReadString();

reader.Close();
fs.Close();

Console.WriteLine(number);
foreach (byte b in bytes)
{
    Console.Write("[{0}]", b);
}
Console.WriteLine();
Console.WriteLine(s);
```
```


Question: Can breakpoints be used in interrupt service routines (ISRs)?

Answer:
Yes -
in an emulator
.
Otherwise, no. It's difficult to pull off, and a bad idea in any case. ISRs are (usually) supposed to work with the hardware, and hardware can easily behave very differently when you leave a gap of half a second between each instruction.
Set up some sort of logging system instead.
ISRs also ungracefully "steal" the CPU from other processes, so many operating systems recommend keeping your ISRs extremely short and doing only what is
strictly
necessary (such as dealing with any
urgent
hardware stuff, and scheduling a task that will deal with the event properly). So in theory, ISRs should be so simple that they don't need to be debugged.
If it's hardware behaviour that's the problem, use some sort of logging instead, as I've suggested. If the hardware doesn't really mind long gaps of time between instructions, then you could just write most of the driver in user space - and you
can
use a debugger on that!


Question:
Starting with the following LINQ query:

from a in things
where a.Id == b.Id &&
a.Name == b.Name &&
a.Value1 == b.Value1 &&
a.Value2 == b.Value2 &&
a.Value3 == b.Value3
select a;

How can I remove (at runtime) one or more of the conditions in the where clause in order to obtain queries similar to the following ones:

from a in things
where a.Id == b.Id &&
a.Name == b.Name &&
a.Value2 == b.Value2 &&
a.Value3 == b.Value3
select a;

Or

from a in things
where
a.Name == b.Name &&
a.Value3 == b.Value3
select a;

Answer:
Rather than try to change existing where clauses, I'd refactor it to this:
```
```
from a in things
where a.Id == b.Id
where a.Name == b.Name
where a.Value1 == b.Value1
where a.Value2 == b.Value2
where a.Value3 == b.Value3
select a;
```
```
That then becomes:
```
```
things.Where(a => a.Id == b.Id)
      .Where(a => a.Name == b.Name)
      .Where(a => a.Value1 == b.Value1)
      .Where(a => a.Value2 == b.Value2)
      .Where(a => a.Value1 == b.Value3);
```
```
Now it should be reasonably clear how to proceed - conditionalise the calls to Where:
```
```
IQueryable<Whatever> query = things;
if (useId) {
    query = query.Where(a => a.Id == b.Id);
}
query = query.Where(a => a.Name == b.Name);
if (checkValue1) {
    query = query.Where(a => a.Value1 == b.Value1);
}
// etc
```
```


Question: Can jQuery ajax made browser request a new location in redirect header send by server?

Answer:
Haven't tried jQuery, and a quick peek at the doc doesn't really tell me what a redirect response is handled as. But in Prototype JS any response code other than 2xx "Success" is a onFailure event, thus a redirect is a failure. You could probably parse the response (somehow) in the error block to see what code it is and get the address, wich you can set the document.location to... But it doesn't sound very safe, or practical.
It's more common to print an error of some kind.  Or, if the request requires a logged in user, to assume the session has timed out and redirect to the login page.


Question:
I'm trying to change assembly binding (from one version to another) dynamically.

I've tried this code but it doesn't work:

      Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
      ConfigurationSection assemblyBindingSection = config.Sections["assemblyBinding"];

      assemblyBindingSection.SectionInformation.ConfigSource = "bindingConf.xml";
      config.Save(ConfigurationSaveMode.Modified);

      ConfigurationManager.RefreshSection("assemblyBinding");

with bindingConf.xml containing the assemblyBinding section configuration.

So can a change this section at runtime? how to do it? What alternatives do I have?

Answer:
The best way I've found to dynamically bind to a different version of an assembly is to hook the
```
AppDomain.AssemblyResolve
```
event. This event is fired whenever the runtime is unable to locate the exact assembly that the application was linked against, and it allows you to provide another assembly, that you load yourself, in its place (as long as it is compatible).
For example, you can put in a static constructor on your application's main class that hooks the event like this:
```
```
using System.Reflection;

static Program()
{
    AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)
    {
        AssemblyName requestedName = new AssemblyName(e.Name);

        if (requestedName.Name == "AssemblyNameToRedirect")
        {
            // Put code here to load whatever version of the assembly you actually have

            return Assembly.LoadFrom("RedirectedAssembly.DLL");
        }
        else
        {
            return null;
        }
    };
}
```
```
This method avoids the need to deal with the assembly bindings in configuration files and is a bit more flexible in terms of what you can do with it.


Question: Is it better to use a stored procedure or doing it the old way with a connection string and all that good stuff? Our system has been running slow lately and our manager wants us to try to see if we can speed things up a little and we were thinking about changing some of the old database calls over to stored procedures. Is it worth it?

Answer:
The first thing to do is check the database has all the necessary indexes set up. Analyse where your code is slow, and examine the relevant SQL statements and indexes relating to them. See if you can rewrite the SQL statement to be more efficient. Check that you aren't recompiling an SQL (prepared) statement for every iteration in a loop instead of outside it once.
Moving an SQL statement into a stored procedure isn't going to help if it is grossly inefficient in implementation. However the database will know how to best optimise the SQL and it won't need to do it repeatedly. It can also make the client side code cleaner by turning a complex SQL statement into a simple procedure call.


Question:
I'm trying to update a variable in APC, and will be many processes trying to do that.

APC doesn't provide locking functionality, so I'm considering using other mechanisms... what I've found so far is mysql's GET_LOCK(), and php's flock(). Anything else worth considering?

Update: I've found sem_acquire, but it seems to be a blocking lock.

Answer:
If you don't mind basing your lock on the filesystem, then you could use fopen() with mode 'x'. Here is an example:
```
```
$f = fopen("lockFile.txt", 'x');
if($f) {
    $me = getmypid();
    $now = date('Y-m-d H:i:s');
    fwrite($f, "Locked by $me at $now\n");
    fclose($f);
    doStuffInLock();
    unlink("lockFile.txt"); // unlock
}
else {
    echo "File is locked: " . file_get_contents("lockFile.txt");
    exit;
}
```
```
See www.php.net/fopen


Question:
I have to analyse some existing Erlang code.

Does anybody knows about a tool able to visually / graphically trace the modules calls ?

The behaviour should be : give a directory containing the source code, and get a gui / picture / file of the calls (module1->module2->module3....).

Something like an UML reverse-engineering, but ala Erlang ?

Thanks.

Answer:
```
xref
```
in OTP works like this. It gives you data about which dependencies exist between applications and modules and produces call graphs.
Here's an overview of
```
xref
```
.


Question:
I need to generate a CTL for use with IIS7.

I generated a CTL file using MakeCTL (on Win2k3 SDK) and put only my own RootCA certificate in the CTL.

However, when I then use adsutil.vbs to set my website to use this CTL, I get:

ErrNumber: -2147023584 (0x80070520)
Error Trying To SET the Property: SslCtlIdentifier

I'm using adsutil.vbs like this:

cscript adsutil.vbs set w3svc/2/SslCtlIdentifier
    where  is the friendly name of the CTL

The problem is, I am not able to set a friendly name. At the end of the wizard it says "Friendly Name: ".

In IIS6 I can create a CTL with a friendly name (showing in Certificates MMC) but if I export it from there, when I import it, it no longer has a friendly name.

Can anyone show me how to do it please?

Answer:
I'm experiencing exactly the same problem and am having the same trouble finding an answer.
There appears to be no documented way to create a friendly name for Certificate Trust Lists using MakeCTL. And the only documented way to add a CTL to IIS7 uses the adsutil script Neil references above, yet it requires a friendly name. I assume we could dig into a programatic way to do this but I'm not looking to get that deep.
The core of this problem is that IIS7 seems to have lost favor for CTL's, else it would have some UI support for them. Are people using some alternative to CTL's in combination with Client Side Certificates?
I find it odd this isn't a bigger problem for IIS7.
Update:
I finally came back to this and have figured out the Friendly Name issue. To get a friendly name assigned you must store the CTL in the Certificate Store rather than to a file (I had always used the file approach previously). So, using MakeCTL in the wizard mode (no arguments) and choosing to 'Certificate Store' on the 'Certificate Trust List Storage' page results in a new page that let's you specify a Friendly Name.
So I now have a CTL in the 'Intermediate Certification Authorities' certificate store of LocalMachine. Now I am trying to use 'netsh http add sslcert' to assign the CTL to my site.
Before I could use this command I had to remove the existing SSL cert that was assigned to my site for server authentication. Then in my netsh command I specify the thumbprint of that very same SSL cert I removed, plus a made up appid, plus 'sslctlidentifier=MyCTL sslctlstorename=CA'. The resulting command is:
netsh http add sslcert ipport=10.10.10.10:443 certhash=adfdffa988bb50736b8e58a54c1eac26ed005050 appid={ffc3e181-e14b-4a21-b022-59fc669b09ff} sslctlidentifier=MyCTL sslctlstorename=CA
(the IP addr is munged), but I am getting this error:
SSL Certificate add failed, Error: 1312 A specified logon session does not exist. It may already have been terminated.
I am sure the error is related to the CTL options because if I remove them it works (though no CTL is assigned of course).
Can anyone help me take this last step and make this work?
UPDATE 01-07-2010:
I never resolved this with IIS 7.0 and have since migrated our app to IIS 7.5 and am giving this another try. I installed IIS6 Compatibility on my test server and tried the steps documented
here
using adsutil.vbs. I immediately ran into this same error that Niel did above:
ErrNumber: -2147023584 Error trying to SET the Property: SslCtlIdentifier
when running this command:
adsutil.vbs set w3svc/1/SslCtlIdentifier MyFriendlyName
I then went on to try the next adsutil.vbs command documented and it failed with the same error.
I have verified that the CTL I created has a Friendly Name of MyFriendlyName and that it exists in the 'Intermediate Certification Authorities\Certificate Trust List' store of LocalComputer.
So once again I am at a dead standstill. I don't know what else to try. Has anyone ever gotten CTL's to work with IIS7 or 7.5? Ever? Am I beating a DEAD horse. Google turns up nothing but my own posts and other similar stories.
Update 6/08/10
- I can now confirm that KB981506 resolves this issue. There is a patch associated with this KB that must be applied to Server 2008 R2 machines to enable this functionality. Once that is installed all works flawlessly for me.


Question:
I am about to make some changes to an existing Apache C module to fix some possible security flaws and general bad practices. However the functionality of the code must remain unchanged (except in cases where its fixing a bug). Standard regression testing stuff seems to be in order. I would like to know if anyone knows of a good way to run some regression unit tests againt the code. I'm thinking something along the lines of using C-Unit but with all the tie ins to the Apache APR and status structures I was wondering if there is a good way to test this. Are there any pre-built frameworks that can be used with C-unit for example?

Thanks

Peter

Answer:
I've been thinking of answering this for a while, but figured someone else might come up with a better answer, because mine is rather unsatisfactory: no, I'm not aware of any such unit testing framework.
I think your best bet is to try and refactor your C module such that it's dependencies on the httpd code base are contained in a very thin glue layer. I wouldn't worry too much about dependencies on APR, that can easily be linked into your unit test code. It's things like using the request record that you should try to abstract out a little bit.
I'll go as far and suggest that such a refactoring is a good idea if the code is suspected to contain security flaws and bad practices. It's just usually a pretty big job.
What you might also consider is running integration tests rather than unit tests (ideally both), i.e. come up with a set of requests and expected responses from the server, and run a program to compare the actual to expected responses.
So, not the response you've been looking for, and you probably thought of something along this line yourself. But at least I can tell you from experience that if the module can't be replaced with something new for business reasons, then refactoring it for testability will likely pay off in the longer term.


Question:
I've got an executable file, and I would like to know which version(s) of the Microsoft .NET Framework this file needs to be started.

Is there an easy way to find this information somewhere?

(So far I tried ILDASM and DUMPBIN without any luck.)

Answer:
I think the closest you can reliably get is to determine what version of the
CLR
is required. You can do this by using ILDASM and looking at the "MANIFEST" node or Reflector and looking at the dissasembly view of the "Application.exe" node as IL. In both cases there is a comment that indicates the CLR version. In ILDASM, the comment is "// Metadata version" and in Reflector the comment is "Target Runtime Version".
Here are examples for a .NET WinForms application named WindowsFormsApplication1.exe:
ILDASM:
```
```
// Metadata version: v2.0.50727
.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 2:0:0:0
}
.assembly extern System
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 2:0:0:0
}
```
```
Reflector:
```
```
.module WindowsFormsApplication1.exe
.subsystem 0x0002
// MVID: {CA3D2090-16C5-4899-953E-4736D6BC0FA8}
// Target Runtime Version: v2.0.50727
```
```
You can also look at the list of referenced assemblies and look for the reference with the highest version number.
Again, using ILDASM looking at the "MANIFEST" node data:
```
```
.assembly extern System.Drawing
{
  .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A )                         // .?_....:
  .ver 2:0:0:0
}
.assembly extern System.Core
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 3:5:0:0
}
```
```
And using Reflector, looking at the dissambly (still as IL) for each reference listed:
```
```
.assembly extern System.Core
{
    .ver 3:5:0:0
    .publickeytoken = (B7 7A 5C 56 19 34 E0 89)
}
```
```
By finding the reference with the highest version metadata you can determine what version of the Framework that reference came from, which would indicate that you need the same version of the Framework installed for the application to run. That being said, I wouldn't treat this as 100% reliable, but I don't think it will change any time soon.


Question:
Given two date ranges, what is the simplest or most efficient way to determine whether the two date ranges overlap?

As an example, suppose we have ranges denoted by DateTime variables StartDate1 to EndDate1 and StartDate2 to EndDate2.

Answer:
I believe that it is sufficient to say that the two ranges overlap if:
```
```
(StartDate1 <= EndDate2) and (StartDate2 <= EndDate1)
```
```


Question:
I need to loop through all the matches in say the following string:

<a href='/Product/Show/{ProductRowID}'>{ProductName}</a>

I am looking to capture the values in the {} including them, so I want {ProductRowID} and {ProductName}

Here is my code so far:

Dim r As Regex = New Regex("{\w*}", RegexOptions.IgnoreCase)
Dim m As Match = r.Match("<a href='/Product/Show/{ProductRowID}'>{ProductName}</a>")

Is my RegEx pattern correct?  How do I loop through the matched values? I feel like this should be super easy but I have been stumped on this this morning!

Answer:
Change your RegEx pattern to
```
\{\w*\}
```
then it will match as you expect.
You can test it with an
online .net RegEx tester
.


Question:
Given test.txt containing:

test
message

I want to end up with:

testing
a message

I think the following should work, but it doesn't:

Get-Content test.txt |% {$_-replace "t`r`n", "ting`r`na "}

How can I do a find and replace where what I'm finding contains CRLF?

Answer:
A CRLF is two characters, of course, the CR and the LF. However,
```
`n
```
consists of both. For example:
```
```
PS C:\> $x = "Hello
>> World"

PS C:\> $x
Hello
World
PS C:\> $x.contains("`n")
True
PS C:\> $x.contains("`r")
False
PS C:\> $x.replace("o`nW","o There`nThe W")
Hello There
The World
PS C:\>
```
```
I think you're running into problems with the
```
`r
```
. I was able to remove the
```
`r
```
from your example, use only
```
`n
```
, and it worked. Of course, I don't know exactly how you generated the original string so I don't know what's in there.


Question:
I create new project in Netbeans, but when I look the library it still using JDK 1.6 (default) I want to change into JDK 6 Update 10 but how? I already instal JDK 6 Update 10 but when I import org.hibernate the neatbeans didn't know which library that org.hibernate.

someone can help me? THX

Answer:
JDK 1.6 is the current released version.
I really hope you aren't talking about Java 10 there.
And even worse would be if you wanted to use Java 1.1! Which was out over 10 years ago.


Question:
Am new to Lucene.Net
Which is the best Analyzer to use in Lucene.Net?
Also,I want to know how to use Stop words and word stemming features ?

Answer:
I'm also new to Lucene.Net, but I do know that the Simple Analyzer omits any stop words, and indexes all tokens/works.
Here's a link to some Lucene info, by the way, the .NET version is an almost perfect, byte-for-byte rewrite of the Java version, so the Java documentation should work fine in most cases:
http://darksleep.com/lucene/
. There's a section in there about the three analyzers, Simple, Stop, and Standard.
I'm not sure how Lucene.Net handles word stemming, but this link,
http://www.onjava.com/pub/a/onjava/2003/01/15/lucene.html?page=2
, demonstrates how to create your own Analyzer in Java, and uses a PorterStemFilter to do word-stemming.
...[T]he Porter stemming algorithm (or "Porter stemmer") is a process for removing the more common morphological and inflexional endings from words in English
I hope that is helpful.


Question:
Is there a way to get a list ordered by two fields, say last and first names?

I know .listOrderByLastAndFirst and .list(sort:'last, first') won't work.

Answer:
If you were sorting lists on the contents of their items, you would need to implement a comparator which would have some smarts to enable to you decide the sort order based on multiple properties.
Some examples of Groovy-style comparators are shown
here
However if the list you are sorting is being returned from a database query, you would be better off sorting it using a CrteriaQuery and sorts on that


Question:
I really don't know how to describe it, but if you understood it and had experience on that field, may be you can help me with something 'Open Source' and 'Ready-made'.

I want to create something like a box 'or widget', where you can change its content by hitting some buttons on the top of the box. (Hey the box is on a web page and this should use Ajax and Javascript).

I have tried some ready scritps, but I found them limited and they drive me crazy, JS frameworks also don't seems to offer such solution.
Any body have any idea on that field?

Answer:
Have you tried Jquery?
Visit www.jquery.com
Some example can be found at
http://www.openjs.com/scripts/events/keyboard_shortcuts/
Also please check the In-place editing example at
http://www.appelsiini.net/projects/jeditable
http://docs.jquery.com/Tutorials:Edit_in_Place_with_Ajax


Question: I am writing an iframe based facebook app. Now I want to use the same html page to render the normal website as well as the canvas page within facebook. I want to know if I can determine whether the page has been loaded inside the iframe or directly in the browser?

Answer:
Browsers can block access to
```
window.top
```
due to
same origin policy
. IE bugs also take place. Here's the working code:
```
```
function inIframe () {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}
```
```
```
top
```
and
```
self
```
are both
```
window
```
objects (along with
```
parent
```
), so you're seeing if your window is the top window.


Question:
I have an XML document with several <person> elements, each of which contains the <name> of the person, and several <preferred-number> elements inside a grouping <preferred-numbers> element.

I already found that to obtain the greatest <preferred-number> I have to do an <xsl:apply-template> with a <xsl:sort> inside it and then take the first element, as XSLT v1.0 doesn't have fn:max().

But I guess that this would give me the greatest value from all. So, how could I arrange a stylesheet to extract each person's <name> with their greatest <preferred-number>?

Answer:
When it comes to sorting stuff in XSLT 1.0 you have to use a slightly roundabout approach as I recall. If you haven't already you'll want to look into
Muenchian grouping
to give you some ideas to start with.
I've found
this site
to be a very useful resource.


Question:
This is my code:

internal enum WindowsMessagesFlags {
    WM_EXITSIZEMOVE      = 0x00000232,
    WM_DISPLAYCHANGE     = 0x0000007e,
    WM_MOVING            = 0x00000216,
}

protected override void WndProc(ref Message m) {
    switch(m.Msg) {
        case (int)WindowsMessagesFlags.WM_DISPLAYCHANGE:
            FixWindowSnapping();
            break;
        case (int)WindowsMessagesFlags.WM_EXITSIZEMOVE:
            SaveWindowProperties();
            break;
        case (int)WindowsMessagesFlags.WM_MOVING:
            KeepProperLocation(ref m);
            break;
    }
}

Is there anyway to prevent the casting?

Answer:
Sort of - cast m.Msg instead:
```
```
protected override void WndProc(ref Message m) {
    switch((WindowsMessagesFlags) m.Msg) {
        case WindowsMessagesFlags.WM_DISPLAYCHANGE:
                FixWindowSnapping();
                break;
        case WindowsMessagesFlags.WM_EXITSIZEMOVE:
                SaveWindowProperties();
                break;
        case WindowsMessagesFlags.WM_MOVING:
                KeepProperLocation(ref m);
                break;
    }
}
```
```
The reason you need the cast at all is because in C# enums aren't just numbers - they're numbers associated with the type. This prevents you from doing (without casting):
```
```
HttpStatusCode status = someWindowsMessageFlag;
```
```
This is clearly a good thing :) When you need to, however, you can always go "via" the underlying type (int in this case).


Question:
I am using Eclipse 3.3.2 with the Flex Builder Plugin (3.0.194161) and the Flex SDK 3.2. Recently the intellisense has started forgetting about everything in the flash.* package EXCEPT flash.errors.*

The code still compiles, but attempting to automatically resolve something (CTRL+SPACE) removes any of the flash.* import statements and thus causes a compile error. As it stands I have to either not use CTRL+SPACE, or re-add my flash.* before compiling.

I have tried recreating the workspace/project and have re-installed the Flex SDK, but I still get the same problem.

Any thoughts?

Answer:
I was able to work around the problem by adding the following SWC to my library path: FLEX_SDK\libs\player\10\playerglobal.swc
It looks like the problem is caused by {targetPlayerMajorVersion} no longer resolving, though I have no idea how that happened.
Edit:
Known bug, as described in
FB-16703
and
"Targeting Flash Player 10"


Question: I have an ActiveX plugin that we need (if possible) to run in Firefox. Is there a plugin (or other way) for Firefox that will allow this?

Answer:
You used to be able to in Firefox 1.5 but not any longer I believe, the
plugin
doesnt seem to be supported anymore.
More info
here


Question:
Imagine I have a document (word document).

I have an enumeration which will indicate how to extract data from the document. So if I want just text, the images, or both (3 members of the enumeration).

I have a case statement based on this enumeration, but without falling into a code smell, how can I write code which isn't too repetitive? For every condition in the switch, should I have a seperate method (the easiest way), or a method accepting a paremeter (like the value of the enumeration), and then use if statements to say if(xyz) do abc, and so on.

Or is there a quicker, more efficient way?

Answer:
I would use a Strategy pattern coupled with a factory to create the appropriate strategy based on the value of the enumeration.
EDIT
As others have pointed out you could also determine the correct strategy via a Map as well.  Factory is my choice because it only encapsulates the logic and doesn't require any data storage.
```
```
public interface IExtractionStrategy
{
    object Extract( Document doc );  // or what ever result is best
}

public class TextExtractionStrategy : IExtractionStrategy
{
    public object Extract( Document doc )
    {
     .... algorithm for extracting text...
    }
}

public class ImageExtractionStrategy : IExtractionStrategy
{
    public object Extract( Document doc )
    {
     .... algorithm for extracting images...
    }
}

public static class StrategyFactory
{
     IExtractionStrategy GetStrategy( ExtractionEnum strategyType )
     {
         switch (strategyType)
         {
             case ExtractionEnum.Text:
                 return new TextExtractionStrategy();
                 break;
             case ExtractionEnum.Image:
                 return new ImageExtractionStrategy();
                 break;

             ...
         }
     }
}
```
```


Question:
For months now I've been trying to find a code syntax formatting extension that works for BlogEngine.Net.  I'm not fond of the behavior of the default formatting extension, and have tried a couple of others (manoli is among them), but they always seem to interact badly with the TinyMCE editor.  Does anyone know of an extension that works, or a different approach that will allow me to make code samples pretty on my blog without hacking the crap out of the HTML myself?

Thanks.

Answer:
I would try using Windows Live Writer along w/ the Paste From Visual Studio plugin. One you go WLW, you'll never go back to that damn TinyMCE interface.
WLW here:
http://get.live.com/writer/overview
Plugin here:
http://gallery.live.com/liveItemDetail.aspx?li=d8835a5e-28da-4242-82eb-e1a006b083b9&l=8


Question:
For the better part of 10 years + we have relied on various network mapped drives to allow file sharing.  One drive letter for sharing files between teams, a seperate file share for the entire organization, a third for personal use etc.  I would like to move away from this and am trying to decide if an ECM/Sharepoint type solution, or home grown app, is worth the cost and the way to go?  Or if we should simply remain relying on login scripts/mapped drives for file sharing due to its relative simplicity?  Does anyone have any exeperience within their own organization or thoughts on this?

Thanks.

Answer:
SharePoint is very good at document sharing.
Documents generally follow a process for approval, have permissions, live in clusters... and these things lend themselves well to SharePoints document libraries.
However there are somethings that don't lend themselves well to living inside SharePoint... do you have a virtual hard drive (.vhd) file that you want to share with a workmate? Not such a good idea to try and put a 20GB file into SharePoint.
SharePoint can handle large files, and so can SQL Server behind it... but do you want your SQL Server bandwidth being saturated by such large files? Do you want your backup of SQL Server to hold copies of such large files multiple times?
I believe that there are a few Microsoft partners who offer the ability to disassociate file blobs from the SharePoint database, so that SharePoint can hold the metadata and a file system holds the actual files, and SharePoint simply becomes the gateway to manage access, permissions, and offer a centralised interface to files throughout an organisation. This would offer you the best of both worlds.
Right now though, I consider SharePoint ideal for documents, and I keep large files (that are not document centric) on Windows file shares.


Question:
Lets say I need to write several functions processing some data. These functions are performing a single task - some mathematical calculations. I suppose there is no need to combine them with some data members.

Shall I use:

a class without data members and declare these functions as static methods so I can use them without creating class object,

or an anonymous namespace,

or maybe I need something more complicated in terms of architecture and design?

Actually, the language I am writing in is C++, but I think this question doesn't depend on what the language of development is.

Answer:
SharePoint is very good at document sharing.
Documents generally follow a process for approval, have permissions, live in clusters... and these things lend themselves well to SharePoints document libraries.
However there are somethings that don't lend themselves well to living inside SharePoint... do you have a virtual hard drive (.vhd) file that you want to share with a workmate? Not such a good idea to try and put a 20GB file into SharePoint.
SharePoint can handle large files, and so can SQL Server behind it... but do you want your SQL Server bandwidth being saturated by such large files? Do you want your backup of SQL Server to hold copies of such large files multiple times?
I believe that there are a few Microsoft partners who offer the ability to disassociate file blobs from the SharePoint database, so that SharePoint can hold the metadata and a file system holds the actual files, and SharePoint simply becomes the gateway to manage access, permissions, and offer a centralised interface to files throughout an organisation. This would offer you the best of both worlds.
Right now though, I consider SharePoint ideal for documents, and I keep large files (that are not document centric) on Windows file shares.


Question:
Is there a way to query or just access newly added object (using ObjectContext.AddObject method) in Entity Framework? I mean situation when it is not yet saved to data store using SaveChanges

I understand that queries are translated to underlying SQL and executed against data store, and it don't have this new object yet. But anyway, I'm curious - if it is not oficially supported, maybe it is possible in theory. If it's not, how developer can deal with it? Manually track new objects and query them using Linq to objects?

The same question also applies to LinqToSql.

Answer:
In EF, if you use this code, you have all the entities that are already loaded in the context (including newly added ones) :
```
```
context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Unchanged).Select(o => o.Entity).OfType<YourObjectType>()
```
```


Question:
I know there is a similar problem on this forum, but the solutions did not really work for me.  I am populating form controls with fields from a few different data sources, and the data shows up great.

I have an ImageButton control, which has an OnClick Event set to grab all of the data from the form.  Unfortunately, when I click the button, it seems as though the page is reloading first, and THEN is executes the OnClick call.  The data that was hand-entered, or hard-coded seems to be pulled fine from the controls it was entered in, but anything that was pulled from a datasource is not able to be read.  Any ideas.  this is the last hurdle in a project that I have been working on for 6 months.

Answer:
In EF, if you use this code, you have all the entities that are already loaded in the context (including newly added ones) :
```
```
context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified | EntityState.Unchanged).Select(o => o.Entity).OfType<YourObjectType>()
```
```


Question: I'm stuck on what appears to be a CSS/z-index conflict with the YouTube player. In Firefox 3 under Windows XP, Take a look at this page: http://spokenword.org/program/21396 Click on the Collect button and note that the pop-up <div> appears under the YouTube player. On other browsers the <div> appears on top. It has a z-index value of 999999. I've tried setting the z-index of the <object> element containing the player to a lower value, but that didn't work. Any idea how to get the pop-up to appear over the player?

Answer:
Try to add the
```
wmode
```
parameter to be
```
opaque
```
like this:
(Note that it's included in
both
a
```
<param>
```
tag
and
a
```
wmode
```
attribute on the
```
<embed>
```
tag.)
```
```
<object width='425' height='344'>
    <param name='movie' value='http://www.youtube.com/v/Wj_JNwNbETA&hl=en&fs=1'>
    <param name='type' value='application/x-shockwave-flash'>
    <param name='allowfullscreen' value='true'>
    <param name='allowscriptaccess' value='always'>
    <param name="wmode" value="opaque" />
    <embed width='425' height='344'
            src='http://www.youtube.com/v/Wj_JNwNbETA&hl=en&fs=1'
            type='application/x-shockwave-flash'
            allowfullscreen='true'
            allowscriptaccess='always'
            wmode="opaque"
    ></embed>
    </object>
```
```


Question:
What is a generic list manipulation function in C?
(I saw this when I was going through some materials.)

What  is the difference between this function and a function which can accept elements of any kind?

Are they same...? How can we implement them individually if they are not same?

Answer:
A generic list is likely to be singly-linked, and probably assumes that the items in the list have a structure like this:
```
```
typedef struct list_item list_item;

struct list_item
{
    list_item *next;
    ...data for node...
};
```
```
Using this layout, you can write functions to manipulate lists using just the next pointers.
Sometimes, the '
```
...data for node...
```
' will be a simple '
```
void *
```
'; that is, the list items will contain pointers to the next node in the list (or NULL if there is no next node) and pointers to the data.
```
```
typedef struct list list;

struct list
{
    list *next;
    void *data;
};
```
```
Since you can cast any pointer to '
```
void *
```
', you can have any mix of data types in the list - but your code must know how to handle them.
You ask about 'a' generic list function, but there probably isn't a single one-function-does-all design, and certainly not a simple one.  There are a number of possible sets of functions that could make generic list functions.  One set, inspired by Lisp, would consist of:
```
```
void *car(list *lp);    // Return the data for the first item on the list
list *cdr(list *lp);    // Return the tail of the list
list *cons(list *lp1, list *lp2);   // Construct a list from lists lp1 and lp2

list *cond(list *lp, void *data);  // Append data item to list
```
```
You probably want to provide the ability to test whether the list is empty, and a few other items.
One good exposition, admittedly in C++, is found in Koenig's "
Ruminations on C++
".  The ideas can be adapted into C quite easily - it isn't dreadfully hard (though the storage management in C is harder than in C++).


Question:
What is forward reference in C with respect to pointers?

Can I get an example?

Answer:
See this page on
forward references
.  I don't see how forward referencing would be different with pointers and with other PoD types.
Note that you can forward declare types, and declare variables which are pointers to that type:
```
```
struct MyStruct;
struct MyStruct *ptr;
struct MyStruct var;  // ILLEGAL
ptr->member;  // ILLEGAL

struct MyStruct {
    // ...
};

// Or:

typedef struct MyStruct MyStruct;
MyStruct *ptr;
MyStruct var;  // ILLEGAL
ptr->member;  // ILLEGAL

struct MyStruct {
    // ...
};
```
```
I think this is what you're asking for when dealing with pointers and forward declaration.


Question:
I need to create an application that when a user copies a file into an specific folder, my application will be activated and the file will be changed, also, when the user reads back any file in the folder, changes will also be made to the file.

Is it possible?

I'll use .net for this.

I think the folder C:\WINDOWS\assembly is somehow like this?

Any help will be appreciated!
Thanks!

Answer:
Well, I'm sure you could write an explorer extension that would do that, but the more typical method that I know of is to write a windows service that monitors the directory in question using the FileSystemWatcher class to monitor events.
The service can then perform the requested actions (or spawn an executable to do it).
One caveat I have noticed is that sometimes the file watcher can miss events if a lot of activity occurs at once (as of .net 2.0 - haven't checked 3.5).
If you use that method, make sure you check the directory contents yourself when you receive a change notification rather than relying on what the filewatcher tells you. I ended up combining the filewatcher event handling with an infrequent poll just to make sure I didn't miss anything.


Question:
I'm trying to verify that a parameter is an instance of a specific class in Rails:

def schedule(action, *args)
  if arg.is_a? Aircraft
    ...
  end
end

I'm doing this in a library class (the file is in lib/) and I get an uninitialized constant Aircraft error. Aircraft is a model class, with a corresponding aircraft.rb file in app/models.

Can I use model classes and instances in a library? How?

Error context:

The error happens in RSpec tests; the code works in the browser. I tried requiring the model in the _spec.rb file, no success at the moment.

Answer:
This will give you access to the Aircraft model:
```
```
require File.dirname(__FILE__) + "/../app/models/aircraft"
```
```
[edit]
Daniel brings up a good point about the context. If you're using a rake task make sure you load the environment:
```
```
task :my_task => :environment do
  # something happens...
end
```
```


Question:
I am trying to create an expression tree that represents the following:

myObject.childObjectCollection.Any(i => i.Name == "name");

Shortened for clarity, I have the following:

//'myObject.childObjectCollection' is represented here by 'propertyExp'
//'i => i.Name == "name"' is represented here by 'predicateExp'
//but I am struggling with the Any() method reference - if I make the parent method
//non-generic Expression.Call() fails but, as per below, if i use <T> the
//MethodInfo object is always null - I can't get a reference to it

private static MethodCallExpression GetAnyExpression<T>(MemberExpression propertyExp, Expression predicateExp)
{
    MethodInfo method = typeof(Enumerable).GetMethod("Any", new[]{ typeof(Func<IEnumerable<T>, Boolean>)});
    return Expression.Call(propertyExp, method, predicateExp);
}

What am I doing wrong? Anyone have any suggestions?

Answer:
There are several things wrong with how you're going about it.
You're mixing abstraction levels. The T parameter to
```
GetAnyExpression<T>
```
could be different to the type parameter used to instantiate
```
propertyExp.Type
```
. The T type parameter is one step closer in the abstraction stack to compile time - unless you're calling
```
GetAnyExpression<T>
```
via reflection, it will be determined at compile time - but the type embedded in the expression passed as
```
propertyExp
```
is determined at runtime. Your passing of the predicate as an
```
Expression
```
is also an abstraction mixup - which is the next point.
The predicate you are passing to
```
GetAnyExpression
```
should be a delegate value, not an
```
Expression
```
of any kind, since you're trying to call
```
Enumerable.Any<T>
```
. If you were trying to call an expression-tree version of
```
Any
```
, then you ought to pass a
```
LambdaExpression
```
instead, which you would be quoting, and is one of the rare cases where you might be justified in passing a more specific type than Expression, which leads me to my next point.
In general, you should pass around
```
Expression
```
values. When working with expression trees in general - and this applies across all kinds of compilers, not just LINQ and its friends - you should do so in a way that's agnostic as to the immediate composition of the node tree you're working with. You are
presuming
that you're calling
```
Any
```
on a
```
MemberExpression
```
, but you don't actually
need to know
that you're dealing with a
```
MemberExpression
```
, just an
```
Expression
```
of type some instantiation of
```
IEnumerable<>
```
. This is a common mistake for people not familiar with the basics of compiler ASTs.
Frans Bouma
repeatedly made the same mistake when he first started working with expression trees - thinking in special cases. Think generally. You'll save yourself a lot of hassle in the medium and longer term.
And here comes the meat of your problem (though the second and probably first issues would have bit you if you had gotten past it) - you need to find the appropriate generic overload of the Any method, and then instantiate it with the correct type. Reflection doesn't provide you with an easy out here; you need to iterate through and find an appropriate version.
So, breaking it down: you need to find a generic method (
```
Any
```
). Here's a utility function that does that:
```
```
static MethodBase GetGenericMethod(Type type, string name, Type[] typeArgs,
    Type[] argTypes, BindingFlags flags)
{
    int typeArity = typeArgs.Length;
    var methods = type.GetMethods()
        .Where(m => m.Name == name)
        .Where(m => m.GetGenericArguments().Length == typeArity)
        .Select(m => m.MakeGenericMethod(typeArgs));

    return Type.DefaultBinder.SelectMethod(flags, methods.ToArray(), argTypes, null);
}
```
```
However, it requires the type arguments and the correct argument types. Getting that from your
```
propertyExp
```
```
Expression
```
isn't entirely trivial, because the
```
Expression
```
may be of a
```
List<T>
```
type, or some other type, but we need to find the
```
IEnumerable<T>
```
instantiation and get its type argument. I've encapsulated that into a couple of functions:
```
```
static bool IsIEnumerable(Type type)
{
    return type.IsGenericType
        && type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}

static Type GetIEnumerableImpl(Type type)
{
    // Get IEnumerable implementation. Either type is IEnumerable<T> for some T,
    // or it implements IEnumerable<T> for some T. We need to find the interface.
    if (IsIEnumerable(type))
        return type;
    Type[] t = type.FindInterfaces((m, o) => IsIEnumerable(m), null);
    Debug.Assert(t.Length == 1);
    return t[0];
}
```
```
So, given any
```
Type
```
, we can now pull the
```
IEnumerable<T>
```
instantiation out of it - and assert if there isn't (exactly) one.
With that work out of the way, solving the real problem isn't too difficult. I've renamed your method to CallAny, and changed the parameter types as suggested:
```
```
static Expression CallAny(Expression collection, Delegate predicate)
{
    Type cType = GetIEnumerableImpl(collection.Type);
    collection = Expression.Convert(collection, cType);

    Type elemType = cType.GetGenericArguments()[0];
    Type predType = typeof(Func<,>).MakeGenericType(elemType, typeof(bool));

    // Enumerable.Any<T>(IEnumerable<T>, Func<T,bool>)
    MethodInfo anyMethod = (MethodInfo)
        GetGenericMethod(typeof(Enumerable), "Any", new[] { elemType },
            new[] { cType, predType }, BindingFlags.Static);

    return Expression.Call(
        anyMethod,
            collection,
            Expression.Constant(predicate));
}
```
```
Here's a
```
Main()
```
routine which uses all the above code and verifies that it works for a trivial case:
```
```
static void Main()
{
    // sample
    List<string> strings = new List<string> { "foo", "bar", "baz" };

    // Trivial predicate: x => x.StartsWith("b")
    ParameterExpression p = Expression.Parameter(typeof(string), "item");
    Delegate predicate = Expression.Lambda(
        Expression.Call(
            p,
            typeof(string).GetMethod("StartsWith", new[] { typeof(string) }),
            Expression.Constant("b")),
        p).Compile();

    Expression anyCall = CallAny(
        Expression.Constant(strings),
        predicate);

    // now test it.
    Func<bool> a = (Func<bool>) Expression.Lambda(anyCall).Compile();
    Console.WriteLine("Found? {0}", a());
    Console.ReadLine();
}
```
```


Question:
I have 5 HP Compaq t5530 Thin Clients with Windows CE 6.0 installed in 'em. I have a Windows 2003 server. Those 6 PCs should be used for browsing. And a user can browse for an hour and be able to extend time. I need to develop a simple client-server program to control the internet usability.

What would be a suggested route to solve this?

Answer:
So you are after a time-controlled browser application, and nothing else?  First question: do you have the BSP (board support package) for this device?
Yes
: Modify the IESAMPLE source code, which is the browser that ships with CE, to have the display you want and remove things like the close button, and maybe even the caption bar.  I'd probably even have it
implement all of the required shell functions
so it could run as the device shell completely. The
IEShell sample
would be a very good start.  Then modify HKLM\Init in your project to have the reworked IESAMPLE launch at device boot and you're done.
No
: It not going to be as easy, but it's still doable.  Create an app using the
IWebBrowser2 COM control
that has the UI elements you want (like the above suggestions).  Modify HKLM\Init to launch your app after explorer.exe (you probably will have to let explorer run to be a shell app) or if you do this in C++, implement the required shell functions.  If you let Explorer run, then you need your app to find, disable and hide the Start bar when it initializes.  How you get your app to persist will be hardware dependent - I know nothing about these devices.