q:
I would like to draw lines (of arbitrary position and length) onto a surface in pygame, which itself is an image loaded from a file on disk.

Can anyone point me to some example code that does this?

[A]
Help on module pygame.draw in pygame:
NAME
    pygame.draw - pygame module for drawing shapes
FILE
    d:\program files\python25\lib\site-packages\pygame\draw.pyd
FUNCTIONS
    aaline(...)
        pygame.draw.aaline(Surface, color, startpos, endpos, blend=1): return Rect
        draw fine antialiased lines
```
```
aalines(...)
    pygame.draw.aalines(Surface, color, closed, pointlist, blend=1): return Rect

arc(...)
    pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1): return Rect
    draw a partial section of an ellipse

circle(...)
    pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect
    draw a circle around a point

ellipse(...)
    pygame.draw.ellipse(Surface, color, Rect, width=0): return Rect
    draw a round shape inside a rectangle

line(...)
    pygame.draw.line(Surface, color, start_pos, end_pos, width=1): return Rect
    draw a straight line segment

lines(...)
    pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect
    draw multiple contiguous line segments

polygon(...)
    pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect
    draw a shape with any number of sides

rect(...)
    pygame.draw.rect(Surface, color, Rect, width=0): return Rect
    draw a rectangle shape
```
```


q:
Ok, i have simple scenario:

have two pages:
login and welcome pages.
im using FormsAuthentication with my own table that has four columns: ID, UserName, Password, FullName

When pressed login im setting my username like:

FormsAuthentication.SetAuthCookie(userName, rememberMe ?? false);

on the welcome page i cant use:

Page.User.Identity.Name

to provide to user which user currently logged, BUT i dont user username like at all examples in http://asp.net web site i want to user FullName field

i think that always go to db and request fullname when page loads its crazy and dont like to user Sessions or Simple Cookie mayby FormsAuth provider has custom fields for this

[A]
Forms authentication works using cookies.  You could construct your own auth cookie and put the full name in it, but I think I would go with putting it into the session.  If you use a cookie of any sort, you'll need to extract the name from it each time.   Tying it to the session seems more natural and makes it easy for you to access.  I agree that it seems a waste to go back to the DB every time and I would certainly cache the value somewhere.
Info on constructing your own forms authentication cookie can be found
here
.

s: huggingface

c: devops

d: intermediate


q: Every PHP programmer likely uses at least some form of a template engine and a database abstraction layer, but apart from those what extras do you consider essential or would  recommend your fellow programmers try out?

[A]
A good framework.
PHP has many to choose from:
Zend's
,
Solar
,
CakePHP
,
Symfony
,
Kohana
. A good framework will take of most of the tedious parts of application development, allowing you to spend more time on implementing project-specific domain logic. A framework will also help enforce a consistent coding style, usually has plenty of documentation and most are very well tested and stable overall.
A good IDE.
For any serious developer a good IDE is a must. Project organization, directory navigation, code-completion and various useful extensions (for example, for file versioning systems) are all big productivity boosters. PHP has several good IDE's including
Zend Studio
and
PDT for Eclipse
.
Build system.
Build scripts are useful for automatic repetitive tasks such as setting directory/file permissions, SVN updates, running tests and so forth before moving a project between phases (dev / staging / production). I use mainly
Phing
(an
Ant
clone) for building and deploying projects.
Profiling and debugging tools.
Those two needs are solved by same tool -
xdebug
, which offers improved debugging capabilities and can also generate
kcachegrind
reports for profiling your application. I then use
webgrind
to access those reports.
Op-code cache.
PHP incurs a major performance hit from its run-time complilation scheme.
Op-code caches
do wonders to improve on this by caching scripts in their compiled state, avoiding the overhead of compilation on cache hit. I use
APC
as my op-code cache when I have the opportunity.
Various open-source packages.
PHP being open-source as a language, has a long tradition of open-source development. There are many high-quality / useful packages for most common (and some uncommon) needs, which can save major development time. I've used
wordpress
and
joomla
as blogging platforms,
HTML Purifier
for sanitizing and validating HTML,
minify
for minifying and concatenating CSS and Javascript among others.
Source file versioning.
A must regardless of programming language. I use
SVN
with a
tortoise
client (for windows).


q: Is it possible to write connect and open a SQL Compact 3.5 database from within MS Access 2003?  I want to be able to use MS Access 2003 to manipulate data in a SQL Compact 3.5 database.  If it is possible, then what statements would be used to open the database?

[A]
Though I did not try it specifically with SQL Compact, connecting to the server should be standard:
Check that the ADODB file (msado21.tlb) is correctly refernced in your available tools
Write down your connection string somewhere like this one:
MyConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=YourDatabaseName;Data Source=YourSQLServerInstanceName"
This string is written for an 'integrated security' context. In cas you want to change it for an SQL security context, please check
here
to update the string. Ideally, this string should be declared as a public variable in your code.
Once this is done, you can open an ADODB recordset and begin to manipulate it:
```
```
public sub connectionTest
Dim activeConnection as ADODB.connection, _
    activeRecordset as ADODB.recordset

Set activeConnection = New ADODB.connection
activeConnection.connectionString = myCOnnectionString
activeConnection.open

set activeRecordset = New ADODB.recordset
'this will open a read-only recordset'
activeRecordset.open _
    "SELECT * FROM myTableName", _
    activeConnection, _
    adOpenStatic, _
    adLockReadOnly

if activeRecordset.EOF and activeRecordset.BOF then
    debug.print "No records in this table"
else
    activeRecordset.moveFirst
    do while not activeRecordset.EOF
        debug.print activerecordset.fields("myFieldName").value
        activeRecordset.moveNext
    loop
endif

activeRecordset.close
set activeRecordset = nothing
activeConnection.close
set activeConnection = nothing

end sub
```
```


q:
Say I have an interface like this:

public interface ISomeInterface
{
...
}

I also have a couple of classes implementing this interface;

public class SomeClass : ISomeInterface
{
...
}

Now I have a WPF ListBox listing items of ISomeInterface, using a custom DataTemplate.

The databinding engine will apparently not (that I have been able to figure out) allow me to bind to interface properties - it sees that the object is a SomeClass object, and data only shows up if SomeClass should happen to have the bound property available as a non-interface property.

How can I tell the DataTemplate to act as if every object is an ISomeInterface, and not a SomeClass etc.?

Thanks!

[A]
The short answer is DataTemplate's do not support interfaces (think about multiple inheritance, explicit v. implicit, etc). The way we tend to get around this is to have a base class things extend to allow the DataTemplate specialization/generalization. This means a decent, but not necessarily optimal, solution would be:
```
```
public abstract class SomeClassBase
{

}

public class SomeClass : SomeClassBase
{

}

<DataTemplate DataType="{x:Type local:SomeClassBase}">
    <!-- ... -->
</DataTemplate>
```
```


q:
If you have a C# function with Sqlaccess, is it mandatory to close all objects/handles, or is everything cleaned up automatically once you exit the function

For example:

void DoSqlStuff()
{
    SqlConnection sqlConn = new SqlConnection(...);
    SqlCommand cmd = new SqlCommand(...);
    SqlDataReader sqlData= null;

    sqlConn,Open();
    sqlData = cmd.ExecutReader();

    while(sqlData.Read())
    {
         ...
    }
}

Is it optional, recommended or mandatory to close SqlConn and SqlData?

Thanks.

[A]
You should close the SqlConnection object as soon as you're done with it.  If you don't then the connection will remain open, and will not be available to handle other requests.
The using statement is useful for this.  It will call Dispose() on the object for you:
```
```
using (SqlConnection cn = new SqlConnection(connectionString))
{
    SqlCommand cm = new SqlCommand(commandString, cn)
    cn.Open();
    cm.ExecuteNonQuery();
}
```
```


q: I am trying to input data from a .txt file into a scheme structure.  Each element is separated by a tab in the data file and each structure set is on a new line.  I want to be able to read in the data from one line into a structure and make a list of each structure set in the file.  Any suggestions?

[A]
Sounds like a CSV file with tabs instead of commas. If you're using PLT Scheme (DrScheme/mzscheme)
neil's csv library is probably what you want.
Here is the documentation
.
Here is how to load it remotely:
```
```
(require (planet neil/csv:1:2/csv))
```
```
At least, that's what the instructions say. On my slightly oodate DrScheme, this is what worked:
```
```
(require (planet "csv.ss" ("neil" "csv.plt" 1 (= 1))))
```
```


q: I've noticed on bank websites, etc, my user IDs aren't saved (they don't appear in a dropdown like other commonly entered stuff does) and there's no prompt for it to remember your password. How is this done? How do the sites notify the browser that they are in 'special' or else exceptions? Just curious.

[A]
Usually you just need to put the autocomplete="off" into the form or field you want to block.
Keep in mind that users can get around this with a scriptlet, plugin, or grease-monkey script.
https://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion#Exceptions_and_Recommended_Workarounds
http://msdn.microsoft.com/en-us/library/ms533032(VS.85).aspx


q:
I have an enum

public enum FileExtentions {
    mp3,
    mpeg
}

And I have a FileInfo of which I want to check if the extension is in the previous enum.
I was hoping I could do a

FileExtensions.Any(e=>e.ToString().Equals(file.Extension));

But that would have been too awesome.
Any ideas?

[A]
While pressing submit I thought of the answer myself:
```
```
Enum.GetNames(typeof(FileExtensions)).Any(f=>f.Equals("."+file.Extension))
```
```


q: Can someone give me some example code that creates a surface with a transparent background in pygame?

[A]
This should do it:
```
```
image = pygame.Surface([640,480], pygame.SRCALPHA, 32)
image = image.convert_alpha()
```
```
Make sure that the color depth (32) stays explicitly set else this will not work.


q:
Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.

How can you determine if another point c is on the line segment defined by a and b?

I use python most, but examples in any language would be helpful.

[A]
Check if the cross product of
```
b-a
```
and
```
c-a
```
is
```
0
```
: that means all the points are collinear. If they are, check if
```
c
```
's coordinates are between
```
a
```
's and
```
b
```
's. Use either the x or the y coordinates, as long as
```
a
```
and
```
b
```
are separate on that axis (or they're the same on both).
```
```
def is_on(a, b, c):
    "Return true iff point c intersects the line segment from a to b."
    # (or the degenerate case that all 3 points are coincident)
    return (collinear(a, b, c)
            and (within(a.x, c.x, b.x) if a.x != b.x else
                 within(a.y, c.y, b.y)))

def collinear(a, b, c):
    "Return true iff a, b, and c all lie on the same line."
    return (b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y)

def within(p, q, r):
    "Return true iff q is between p and r (inclusive)."
    return p <= q <= r or r <= q <= p
```
```
This answer used to be a mess of three updates. The worthwhile info from them: Brian Hayes's
chapter
in
Beautiful Code
covers the design space for a collinearity-test function -- useful background.
Vincent's answer
helped to improve this one. And it was Hayes who suggested testing only one of the x or the y coordinates; originally the code had
```
and
```
in place of
```
if a.x != b.x else
```
.
(This is coded for exact arithmetic with integers or rationals; if you pass in floating-point numbers instead, there will be problems with round-off errors. I'm not even sure what's a good way to define betweenness of 2-d points in float coordinates.)


q:
I have one table that saves comments for a varied set of content types. These are saved in other tables (news, articles, users).
I wonder what's the best way to connect these tables?
In previous projects I used a second table for each kind of content. They held the id of the certain content mapped to ids of the comments table. So for each comment I had the comment entry itself and a 'connector' entry.
An alternative would be to use a separate comments table for any kind of content.
At the end both ways contain some redundancy flaw.

So which one should I use or is there the ONE solution?

[A]
I would probably have a separate comments table for each content table so that I could take advantage of the foreign key relationships to automatically manage updates/deletes when the original content is changed/deleted.  So if I had news and articles tables, then I would have news_comments and article_comments tables.  Each of these would have a content_id field and a user_id field.  The content_id field would refer back to the content table and user_id field would refer back to the users table.  I'd set up foreign key relationships between the appropriate content and comment table and the users and each comment table and have the changes propagate on update/delete.  You might also want to set up indices on the id fields so that you are doing index joins between them.
If you have a single comments table, you would have to manage the relationships manually in code rather than having the DB handle it for you -- since you can only have the FK relate to  one other table.


q:
I'm in a hypothetical situation in which I need to list students in a school. I have one table view controller that has several sections, representing a school. Each school has subsequent students. Now, I have the requirement to give the user the capability to view all students for a particular school by clicking on the school name in a top level view of my navigation controller.

The question here is, do I branch out my current "StudentsViewController" and add complex logic in order to allow it to display an individual School's students, or would you experts recommend a new class to handle that table?

The tradeoffs are rather straight forward in that I can indeed probably put everything in one view controller at the cost of some confusing/complex logic. On the other hand, there will be a great deal of repeated code if I write another controller that handles an individual school's students.

What do the experts recommend on this one?

[A]
I think it would depend on the model you are using to hold your data.
Lets say you have an array of arrays,
(array of schools, each school holds an array of students.)
In this case, I would stick with one tableController.
The logic doesn't have to be hairy if your model design is simple, and I think it would be cleaner and "more correct" than multiple subclasses in this case.
Don't forget anywhere the system passes you an
NSIndexPath
you have the section and row numbers. (
School
and
Student
)
indexPath.section
and
indexPath.row


q:
How do you concatenate characters in java? Concatenating strings would only require a + between the strings, but concatenating chars using + will change the value of the char into ascii and hence giving a numerical output. I want to do System.out.println(char1+char2+char3... and create a String word like this.

I could do

System.out.print(char1);
System.out.print(char2);
System.out.print(char3);

But, this will only get me the characters in 1 line. I need it as a string. Any help would be appreciated.

Thanks

[A]
Do you want to make a string out of them?
```
```
String s = new StringBuilder().append(char1).append(char2).append(char3).toString();
```
```
Note that
```
```
String b = "b";
String s = "a" + b + "c";
```
```
Actually compiles to
```
```
String s = new StringBuilder("a").append(b).append("c").toString();
```
```
Edit
: as litb pointed out, you can also do this:
```
```
"" + char1 + char2 + char3;
```
```
That compiles to the following:
```
```
new StringBuilder().append("").append(c).append(c1).append(c2).toString();
```
```
Edit (2)
: Corrected string append comparison since, as cletus points out, a series of strings is handled by the compiler.
The purpose of the above is to illustrate what the compiler does, not to tell you what you should do.


q:
When I supply the script with the argument: hi[123].txt it will do exactly what I want.
But if I specify the wildcard character ( hi*.txt ) it will be re-reading some files.

I was wondering how to modify this script to fix that silly problem:

#!/bin/sh

count="0"
total="0"
FILE="$1"  #FILE specification is now $1 Specification..

for FILE in $@
do
  #if the file is not readable then say so
     if [ ! -r $FILE ];
         then
         echo "File: $FILE not readable"
     exit 0
     fi

# Start processing readable files
  while read line
          do

             if [[ "$line" =~ ^Total ]];
                 then
                   tmp=$(echo $line | cut -d':' -f2)

                   total=$(expr $total + $tmp)

                   echo "$FILE (s) have a total of:$tmp "
                   count=$(expr $count + 1)

             fi

        done < $FILE
done
echo " Total is: $total"
echo " Number of files read is:$count"

[A]
I don't know what is wrong with it, but one little point i noticed:
Change
```
for FILE in $@
```
into
```
for FILE in "$@"
```
. Because if files have embedded spaces, you are now on the safe way. It will expand into
```
"$1" "$2" ...
```
then, instead of
```
$1 $2 ...
```
(and note everywhere you use $FILE too remember to
```
""
```
it).
And what others say, you don't need to initialize
```
FILE
```
before you enter the loop. It will be set to each of the filenames of the expanded positional parameters in the for loop automatically.
However, i would go with an awk script like this:
```
```
awk -F: '
/^Total/ {
    total += $2
    # count++ not needed. see below
    print FILENAME "(s) have a total of: " $2
}

END {
    print "Total is: " total
    print "Number of files read is: " (ARGC-1)
}' foo*.txt
```
```
Note that when a file contains multiple "^Count" lines, you would indeed say you read more files than you actually read if you rely on
```
count
```
to tell you the number of files read.


q:
I'm trying to use SharpZipLib to pull specified files from a zip archive. All of the examples I've seen always expect that you want to unzip the entire zip, and do something along the lines of:

       FileStream fileStreamIn = new FileStream (sourcePath, FileMode.Open, FileAccess.Read);

        ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
        ZipEntry entry;

        while (entry = zipInStream.GetNextEntry() != null)
        {
            // Unzip file
        }

What I want to do is something like:

ZipEntry entry = zipInStream.SeekToFile("FileName");

As my needs involve using a zip as a package and only grabbing files into memory as needed.

Is anyone familiar with SharpZipLib? Does anyone know if I can do this without running through the entire zip by hand?

[A]
ZipFile.GetEntry should do the trick:
```
```
using (var fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
using (var zf = new ZipFile(fs)) {
   var ze = zf.GetEntry(fileName);
   if (ze == null) {
      throw new ArgumentException(fileName, "not found in Zip");
   }

   using (var s = zf.GetInputStream(ze)) {
      // do something with ZipInputStream
   }
}
```
```


q: I'd like to add a logo to the left of my title on my navigation bar. The title property seems to only take an NSString.  What's the best way to add an image to the navigation bar?

[A]
Set
```
UINavigationItem.titleView
```
to a
custom view
(or just a straight UIImageView).


q:
I'm a php guy, but I have to do some small project in JSP.
I'm wondering if there's an equivalent to htmlentities function (of php) in JSP.

[A]
```
```
public static String stringToHTMLString(String string) {
    StringBuffer sb = new StringBuffer(string.length());
    // true if last char was blank
    boolean lastWasBlankChar = false;
    int len = string.length();
    char c;

    for (int i = 0; i < len; i++)
        {
        c = string.charAt(i);
        if (c == ' ') {
            // blank gets extra work,
            // this solves the problem you get if you replace all
            // blanks with  , if you do that you loss
            // word breaking
            if (lastWasBlankChar) {
                lastWasBlankChar = false;
                sb.append(" ");
                }
            else {
                lastWasBlankChar = true;
                sb.append(' ');
                }
            }
        else {
            lastWasBlankChar = false;
            //
            // HTML Special Chars
            if (c == '"')
                sb.append(""");
            else if (c == '&')
                sb.append("&");
            else if (c == '<')
                sb.append("<");
            else if (c == '>')
                sb.append(">");
            else if (c == '\n')
                // Handle Newline
                sb.append("<br/>");
            else {
                int ci = 0xffff & c;
                if (ci < 160 )
                    // nothing special only 7 Bit
                    sb.append(c);
                else {
                    // Not 7 Bit use the unicode system
                    sb.append("&#");
                    sb.append(new Integer(ci).toString());
                    sb.append(';');
                    }
                }
            }
        }
    return sb.toString();
}
```
```


q: What to do when after all probing, a reportedly valid object return 'undefined' for any attribute probed? I use jQuery, $('selector').mouseover(function() { }); Everything returns 'undefined' for $(this) inside the function scope. The selector is a 'area' for a map tag and I'm looking for its parent attributes.

[A]
Your question is a bit vague, so maybe you can provide more details?
As for finding out about an object and the values of its properties, there are many ways to do it, including using Firebug or some other debug tools, etc. Here is a quick and dirty function that might help get you started until you can provide more details:
```
```
function listProperties(obj) {
   var propList = "";
   for(var propName in obj) {
      if(typeof(obj[propName]) != "undefined") {
         propList += (propName + ", ");
      }
   }
   alert(propList);
}
```
```
That will display a list of the properties of the object that you pass it that are not
```
undefined
```
.
Hope that helps...


q:
I need help to replace all \n (new line) caracters for
 in a String, but not those \n inside [code][/code] tags.
My brain is burning, I can't solve this by my own :(

Example:

test test test
test test test
test
test

[code]some
test
code
[/code]

more text

Should be:

test test test<br />
test test test<br />
test<br />
test<br />
<br />
[code]some
test
code
[/code]<br />
<br />
more text<br />

Thanks for your time.
Best regards.

[A]
I would suggest a (simple) parser, and not a regular expression.  Something like this (bad pseudocode):
```
```
stack elementStack;

foreach(char in string) {
    if(string-from-char == "[code]") {
        elementStack.push("code");
        string-from-char = "";
    }

    if(string-from-char == "[/code]") {
        elementStack.popTo("code");
        string-from-char = "";
    }

    if(char == "\n" && !elementStack.contains("code")) {
        char = "<br/>\n";
    }
}
```
```


q:
I came across the Adobe Flex framework one day.  After watching http://www.adobe.com/products/flex/media/flexapp/'> the demo of Flex,  it looks to me it is a bundle of different Ajax controls.  I have no working knowledge of Flex at all and know very little about Flex.  Therefore, I would like to hear from the developers here with some Flex experience to explain a bit more pros and cons of this Framework.  In particular:

 How productive it is to program in Flex compared to the .Net + Silverlight?

 Any technical advantages over other frameworks?

 Any disadvantages ?

 Does it have any known scaling issues?

 What kind of web servers can it be hosted on?

 Any other things I should be aware of about Flex?

[A]
Well ~~ .. it's more that Silverlight is similar to Flex. It's not Ajax so much as a kind of 'walled-garden' inside of which you have a rich programming environment. Somewhat like Java apps say.
The usual criticism derives from just that. Flex/Flash applications tend to be ignorant of the browser (more or less) so that stuff like back-button usually gives unexpected results.
It'll run on all the current browsers on all platforms. You don't
need
to "host" flex as you build a SWF file that gets loaded into the browser and is executed by the Flash Player which your users are expected to have already downloaded/installed .. (95+%) penetration helps.
I've been using Flex for the last year or so and it's served my purposes well. It can be integrated nicely with javascript stuff on your web pages and provides a very rich set of capabilities for doing all sorta things like web-services and XML processing and of course all your video/audio/music rich media.


q:
So I'm about to start of a small project for my sporting club for member registrations and I'm trying to decide between WebForms or MVC.

Allit will be is a user login and data capture forms (or and data retrieval), so I was initally thinking WebForms with FBA but I've wanted to have a play with MVC for a while and I was thinking that it wouldn't be too bad a choice.

But not really having a lot of knowledge of MVC I don't know if it'd be a wrong fit.

So what's a good way to decide if WebForms or MVC is the right choice?

[A]
Is this a critical, production level application or a small one-off?  Can you deal with the extra time that the learning curve of MVC will take or do you need to have it done right-away?  Can you afford to scrap the whole thing and start over if MVC doesn't work out?  Are you willing to have the platform change (probably not much now that it's in beta) while you are developing?   Is there another project that is less critical that you could use MVC on to learn it.
Depending on how you answer these questions, learning MVC on this project might be worth it. Personally, I think it is a better architecture, but a less mature technology at this point.  It has certainly increased the testability of my web code.  I expect to move all of my development in this direction over the next year or so, though I doubt if I will change gears in any of the projects that I have had under development for awhile.  I've just started my first new project in MVC.  I wasn't willing to commit to it until it went into beta and I think that it will be in production before I'm finished with the project.


q: How can I send a monitor into/out-of a different power state (like sleep)?

[A]
The latest version is maintained on IDesign's site here:
http://idesign.net/Downloads/GetDownload/1887
Older version are available on the O'Reilly site.
Programming WCF Services 3rd Edition (PWSTE) Samples:
http://examples.oreilly.com/9780596805494/
Programming WCF Services 2nd Edition (PWSSE) Samples:
http://examples.oreilly.com/9780596521301/
I found this via:
http://oreilly.com/catalog/9780596521301/
and clicking on "Examples"
Download the zip file and it has all the code for ServiceModelEx. I hope this helps.


q: What are some common, real world examples of using the Builder Pattern?  What does it buy you?  Why not just use a Factory Pattern?

[A]
You use it when you have lots of options to deal with.  Think about things like jmock:
```
```
m.expects(once())
    .method("testMethod")
    .with(eq(1), eq(2))
    .returns("someResponse");
```
```
It feels a lot more natural and is...possible.
There's also xml building, string building and many other things.  Imagine if
```
java.util.Map
```
had put as a builder.  You could do stuff like this:
```
```
Map<String, Integer> m = new HashMap<String, Integer>()
    .put("a", 1)
    .put("b", 2)
    .put("c", 3);
```
```


q: what is the proper way to scale an SDL Surface? I found one explanation online but it required redrawing the Surface pixel by pixel. It seems like there should be some way of doing this natively through SDL rather than redrawing the image like that. I haven't been able to find anything in the SDL documentation that covers this. I am able to resize surfaces without any problem by modifying the surfaces width and height, but the resulting surface is clipped.

[A]
SDL doesn't support scaled blitting. According to the documentation of
SDL_BlitSurface
:
Note: the SDL blitter does not (yet)
  have the capability of scaling the
  blitted surfaces up or down like it is
  the case with other more sophisticated
  blitting mechanisms. You have to
  figure something out for yourself if
  you want to scale images (e.g. use
  SDL_gfx).
You could find SDL_gfx
here
. Writing your own blitting function isn't that bad, it might be a fun and useful learning experiment (though you'd be reinventing the wheel). Using OpenGL is also an option, as stuff like scaling and rotating could be done in a single function call.


q: The execvp() function executes the program that is given as an argument. It checks the $PATH variable to find the program. I'm writing something in which I would like to check to see if several programs exist before calling any exec() functions. What's the best way to do this?

[A]
You can use getenv to get the PATH environment variable and then search through it.
http://www.opengroup.org/onlinepubs/000095399/functions/getenv.html
You can then use fopen to check for the existence of the specific binary names.
You can also do something like system("which App"). which searches $PATH for you.
http://en.wikipedia.org/wiki/System_(C_standard_library)
http://en.wikipedia.org/wiki/Which_(Unix)


q:
I'm a long time C++/Java developer trying to get into Python and am looking for the stereotypical "Python for C++ Developers" article, but coming up blank.  I've seen these sort of things for C#, Java, etc, and they're incredibly useful for getting up to speed on language features and noteworthy differences.  Anyone have any references?

As a secondary bonus question, what open source Python program would you suggest looking at for clean design, commenting, and use of the language as a point of reference for study?

Thanks in advance.

[A]
I never really understood the "Language X for Language Y developers" approach.  When I go looking to learn Language X I want to learn how to program in it the way that Language X programmers do, not the way Language Y programmers do.  I want to learn the features, idioms, etc. that are unique to the language that I am learning.  I want to be able to take advantage of the things that make the language special and use that knowledge to expand my ways of thinking and solving problems.  I don't think I would get the same sort of insights from a tutorial that was framed in the context of another language.  If you can learn your first language without a tutorial geared towards something you already know you should be able to pick up a second language the same way (and in my experience, the more languages you know the easier it is to learn new ones).
With that said, I would recommend
The Python Tutorial
as a good, quick, and easy way to get going with Python and
Dive Into Python
as a more complete introduction, also available for free
here
.  I would also agree with what others have said regarding looking at the code for the standard libraries as a source of good examples and design practices, the standard python libraries are pretty clean and easy to read.


q:
I'm using LINQ to Entities (not LINQ to SQL) and I'm having trouble creating an 'IN' style query.  Here is my query at the moment:

var items = db.InventoryItem
                .Include("Kind")
                .Include("PropertyValues")
                .Include("PropertyValues.KindProperty")
                .Where(itm => valueIds.Contains(itm.ID)).ToList<InventoryItem>();

When I do this however, the following exception is thrown:

LINQ to Entities does not recognize the method 'Boolean Contains(Int64)' method, and this method cannot be translated into a store expression.

Does anyone have a workaround or another solution for this?

[A]
You need to either use this one:
```
```
.Where(string.Format("it.ID in {0}", string.Join(",", valueIds.ToArray())));
```
```
or construct the WHERE part dynamically, as in
this
post.
P.S. - Information has been updated and this answer updated as follows to maintain relevance:
The link referenced contains the following update:
...in EF4 we added support for the
Contains method and at least in this
specific case for collection-valued
parameters. Therefore this kind of
code now works right out of the box
and it is not necesary to use any
additinal expression building method:
```
```
var statusesToFind = new List<int> {1, 2, 3, 4};
var foos = from foo in myEntities.Foos
           where statusesToFind.Contains(foo.Status)
           select foo;
```
```


q:
Is there an elegant way in Perl to find the newest file in a directory (newest by modification date)?

What I have so far is searching for the files I need, and for each one get it's modification time, push into an array containing the filename, modification time, then sort it.

There must be a better way.

[A]
you could try using the shell's
```
ls
```
command:
```
```
@list = `ls -t`;
$newest = $list[0];
```
```


q:
I am using RRDtool for storing data for displaying graphs. I update the RRD by  RRDs::update and this fails when trying to rewrite the information, means update data for a time in the past (e.g. someone moved the system timer back). The error I get is:

ERROR: Cannot update /opt/dashboard/rrd/Disk/192.168.120.168_disk_1.rrd with
'1228032301:24:24' illegal attempt to update using time 1228032301 when last
update time is 1228050001 (minimum one second step)

I want to always allow the rewrite, how can I do this?

[A]
According to the RRD documentation, that timestamp number
must
increase with each update. Given your constraints, I'd modify your update routine so that if the update fails, you catch the exception and redo the update with the time field set to 'N'. That will make RRDtool use the current time as the update time.
Alternatively, if you don't want to deal with the catch-and-retry code, just modify your update code to always use 'N' as the time value -- then the update will always work.
It may be helpful to have a quick look at the documentation for the RRDtool
update command
.


q:
i'm wanting to generate a random salt value and put it into the Application state.

Now, i'm using a web farm, so the Application state will be different per machine. I don't want to purchase distributed state farm apps, either.

So .. what are some solutions for this? I thought i could hard-code it in the code OR the web.config file .. but that means the same salt for eva .. not very safe.

Anyone have any suggestions?

Remember - i'm after a unique key (eg a guid) that is the same across all machines. Maybe a config file is the only way?

[A]
If I understand correctly, you want the machines to share a value, and you don't want the value to be the same forever. Ideally you'd prefer not to store it.
So, have the "first" machine generate a random value at startup, (using whatever entropy it can such as /dev/random. If you don't need a secure value, and don't have enough entropy at startup to create one anyway, use the time or whatever), and communicate it to all the others. As new machines join the cluster, they need to be able to find the value from one machine already in the cluster. Machines dropping out make no difference.
Which machine is the "first"? Well, if you can always boot one machine before any others, and give it time to get to the point of generating a value, then you can use the trivial algorithm:
1) Look for other machines. If you find one, ask it the value.
2) If you don't find one, generate the value yourself.
If multiple machines are starting up at once then they need to decide amongst themselves which is the "leader". You could do this by choosing one yourself (e.g. a machine declares itself "leader" as soon as it receives a particular connection via the admin interface: on startup each machine waits until it either gets this connection, or hears from another machine that the other machine is the leader). It's trivial to do automatically on a token ring: the machine with the least MAC address or whatever is leader. But nobody uses token ring any more...
At the opposite extreme of an unreliable network I'm not sure it's even possible, unless all the machines know how many there will be in total (in which case it's just like the token ring, except that they all talk to each other until they've figured out who's the leader). With reliable broadcast, which is what you can assume within reasonable bounds on ethernet, I'm sure there's an optimal algorithm published somewhere, but I forget what it is (if I ever knew). I'd guess that everyone broadcasts who they think the leader is at regular intervals (including their own claim if they've not yet seen a better one). Once you've been listening to that for long enough (approx one interval), you'll know who the leader is, and you can start using the seed.
If the value is a secret, then obviously communication within the cluster must be secure. You might get that for free, depending on the network architecture.


q: The build instructions of V8 JavaScript Engine mention only Visual Studio 2005 and 2008. Has anybody been successful with MinGW on Windows XP/Vista?

[A]
I've tried, but seems it automatically detect the WIN32 platform and tries to invoke the vc++ compiler, I tried to adding to the PATH the mingw-gcc compiler (I've not vc++ installed) and the build script correctly sees it, but doesn't compile out of the box.
I suppose deleting the "WIN32 flag" will do the work, since for successfully compiling under mingw the compiler needs to thinks to be on unix enviroment, but then even if it compiles probably it will have some problems due to the different platform.


q:
When I am stuck with a problem:

I search Google for code snippets.

I look at isolating the problem, so that I can better explain it to others in order to get answers.

What search techniques do you use to find the solution to your problem?

I started asking questions in Stack Overflow.

What other techniques or methods do you follow, to fix the problem more quickly?

[A]
Well there's:
Google
Google
Google
Stack Overflow
Google
Google
Maybe a book if I have one.
Seriously, I started (hobby) programming in the 1980s and even into the mid 90s you had to know things and have a technical library.  Then Google came along and it's easier to Google something than it is to look up (bookmarked!) API documentation (Google "java stringbuilder" will get me there faster than navigating will) let alone an actual book (electronic or paper).
Most problems you're trying to solve have been solved before.  Many times.
The rest of debugging comes down to decomposition, possibly unit testing (which is related to decomposition) and verifying your assumptions.
By "decomposition", I mean that your solution is structured in such a way that small pieces can be individually tested and readily understood.  If you have a 7000 line method you're (probably) doing something wrong.
Understanding what assumptions you've made is key too so you can verify them.  For example, when I started with PHP I wrote a piece of code like this:
```
```
$fields = $_SESSION["fields"]; // $fields is an associative array
$fields["blah"] = "foo";
```
```
and I was scratching my head trying to figure out why it didn't work (the array wasn't being updated next time I queried $_SESSION).  I came from a Java background where you might do this:
```
```
Map fields = (Map)httpSession.get("fields");
fields.put("blah", "foo");
```
```
and that would most definitely work.  PHP however
copies
the array.  A working solution is to use references:
```
```
$fields =& $_SESSION["fields"]; // $fields is an associative array
$fields["blah"] = "foo";
```
```
or simply:
```
```
$_SESSION["fields"]["blah"] = "foo";
```
```
The last thing I'll say about debugging and writing robust code in general is to understand the boundaries of your solution.  By this I mean if you're implementing a linked list then the boundary conditions will revolve around when the list is empty.


q: I know this is a longshot but I was wondering if anyone knows if this is possible.

[A]
I know nothing about air.
But if AIR has JavaScript access, and you can access the container document (
How do I share a javascript object between different pages in Adobe AIR?
) then all you need to work out is how to obtain Document.location from it.


q:
I have a object of type ICollection<string>.  What is the best way to convert to string[].

How can this be done in .NET 2?

How can this be done cleaner in later version of C#, perhaps using LINQ in C# 3?

[A]
You could use the following snippet to convert it to an ordinary array:
```
```
string[] array = new string[collection.Count];
collection.CopyTo(array, 0);
```
```
That should do the job :)


q: After moving to .NET 2.0+ is there ever a reason to still use the systems.Collections namespace (besides maintaining legacy code)?  Should the generics namespace always be used instead?

[A] In some circumstances the generic containers perform better than the old ones. They should at least perform as well as the old ones in all circumstances. And they help to catch programming errors. It's a rare combination of a more helpful abstraction and better performance, so there isn't much of a reason to avoid them. Only if you are forced to by a crummy library you have to work with that was written before generics.


q:
I have a class that inherits a generic dictionary and an inteface

public class MyDictionary: Dictionary<string, IFoo>, IMyDictionary
{
}

the issue is that consumers of this class are looking for the '.Keys' and ".Values" properties of the interface so i added:

    /// <summary>
    ///
    /// </summary>
    ICollection<string> Keys { get; }

    /// <summary>
    ///
    /// </summary>
    IEnumerable<IFoo> Values { get; }

to the interface.

Now, the implementation needs to have this as well but when i implement these, i get this error:

"The keyword new is required because it hides property Keys . .. "

so what do i need to do.  Should i be adding a "new" in front of these get properties?

[A]
The reason is that your keys and values properties are hiding the implementation of the keys and values properties in the Dictionary class.
EDIT:  Yes all you have to do is add the new keyword into you property.  So you code will look somthing like this:
```
```
class IFoo
{ }

interface MyDictionary
{
    ICollection<string> Keys { get; }

    /// <summary>
    ///
    /// </summary>
    IEnumerable<IFoo> Values { get; }
}

class IStuff : Dictionary<string, IFoo>, MyDictionary
{
    #region MyDictionary Members

    //Note the new keyword.
    public new ICollection<string> Keys
    {
        get { throw new NotImplementedException(); }
    }

    public new IEnumerable<IFoo> Values
    {
        get { throw new NotImplementedException(); }
    }

    #endregion
}
```
```
I would still recommend implementing IDictionary though.


q:
I have a hosting account with servergrid.com. I want to backup my database, they say I have to use Sql Server Integration Service to backup the database and I would need a commercial version of Sql Server management studio.

I have Sql Server 2005 Developer Edition. I have no idea how to do SSIS backup. I tried playing around with the Sql Server Integration Services Project in VS2005 .. but I failed.

Google also seems to have no step-by-step guide for Non-DBA's like me.

Can anybody point me to/write me a Step-by-Step instructions on how to backup database using SSIS? and also if possible how to restore the database again to the host

[A]
SSIS is not really a database backup tool.
If you have a fixed number of tables, you can
export
the data from SQL Server to comma-separated or raw files - i.e. do the data export using SSIS. It is easy to create such package using SSIS project if you have small number of tables. But if you have a lot of tables it is all manual process. Also it could be hard to automate this - every time you add/remove/change a table or a column, you have to regenerate the SSIS package used to export your data.
SSIS does only data export, so you need a separate tool to do metadata backup (table and stored proc definitions). You can export the metadata using Management Studio (simply script database to text file).
One can call these two tools together a poor man backup tool, but if you metadata changes often you'll probably want to use the real SQL backup tool. Not sure why the hosting guys say you have to use SSIS - maybe they don't want to give you backup permissions to ensure DB safety, but SSIS is not the simplest way to do database backup.


q:
The curses.ascii module has some nice functions defined, that allow for example to recognize which characters are printable (curses.ascii.isprint(ch)).

But, diffrent character codes can be printable depending on which locale setting is being used. For example, there are certain polish characters:

>>> ord('a')
97
>>> ord('ą')
177
>>>

I'm wondering, is there a better way to tell if a number represents printable character then the one used in curses.ascii module:

def isprint(c): return _ctoi(c) >= 32 and _ctoi(c) <= 126

which is kind of locale-unfriendly.

[A]
If you convert the character to a unicode then you can use unicodedata:
```
```
>>> unicodedata.category(u'ą')[0] in 'LNPS'
True
```
```


q: If I've got a variable that contains the fully-qualified name of a file (for example, a project file), should it be called projectFile, projectFileName or projectPath? Or something else?

[A]
I usually go with these:
```
FileName
```
for the file name only (without path)
```
FilePath
```
for the parent path only (without the file name)
```
FileFullName
```
for the fully qualified name with path
I don't think there is such a thing as an accepted standard for this. I depends on your (team's) preferences and whether you need to differentiate between the three in a given situation.
EDIT: My thoughts on these particular naming conventions are these:
intuitively, a "Name" is a string, so is a "Path" (and a "FileName")
a "Name" is relative unless it is a "FullName"
related variable names should begin with the same prefix ("File" + ...), I think this improves readability
concretions/properties are right-branching: "File" -> "FileName"
specializations are left-branching: "FileName" -> "ProjectFileName" (or "ProjectFileFullName")
a "File" is an object/handle representing a physical object, so "ProjectFile" cannot be a string
I cannot always stick to these conventions, but I try to. If I decided to use a particular naming pattern I am consistent even if it means that I have to write more descriptive (= longer) variable names. Code is more often read than written, so the little extra typing doesn't bother me too much.


q: what is the value of using IDictionary here?

[A]
The value of using an interface is always the same: you don't have to change client code when switching to another backend implementation.
Consider that profiling your code later shows that a hash table implementation (used in the
```
Dictionary
```
class) isn't suited for your task and that a binary search tree would perform better. If you've coded to an interface then switching the implementation is straightforward. If, however, you've used a concrete class, you've got to change a lot more code in a lot more places. => This costs time and money.


q:
I've been facing this issue where, the hibernate objects on serialization produces unexpect xmls containing all the instrumented code from Hibernate.

We did some cleaning of the object before serializing the object.

But, is there a standard option available to serialize the object directly?

[A]
I've not used XStream before, but I have serialized Hibernate-managed entities. It isn't fun.
There are two big issues:
Lazy loading;
One-to-many relationships.
The former is obvious - you need the actual data to serialize. The latter is less so - any one-to-many relationships you declare against collection interfaces (eg:
```
Set<T>
```
) will get plugged by Hibernate's own (unserializable!) collection implementations. This may well be where Hibernate's classes are bleeding into your objects.
I ended up writing reflective code (actually introspective) that did this:
With the session open, touched the entire object graph to force-load any unloaded entities;
Closed the Hibernate session (including any transactions involving its connection);
Walked the object graph, replacing any lists, sets or maps with instances of ArrayList, HashSet or HashMap (known-serializable collections).
Note that step 2 is important - if you replace the collections prior to closing the session, Hibernate will just put its own collections right back upon close...
Edit:
@cliff.meyers spotted a detail of the implementation I forgot to mention: if you do this, you need to limit object graph walking only to your own entities, and watch for circular reference paths (eg: by caching references to objects you've already walked).


q: With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?

[A]
Same as almost all other OO languages, keep all instances of the class in a collection of some kind.
You can try this kind of thing.
```
```
class MyClassFactory( object ):
    theWholeList= []
    def __call__( self, *args, **kw ):
         x= MyClass( *args, **kw )
         self.theWholeList.append( x )
         return x
```
```
Now you can do this.
```
```
object= MyClassFactory( args, ... )
print MyClassFactory.theWholeList
```
```


q:
How to run NAnt scripts in command line and get the timings of each task on the log file?

using nant <record> task or
NAnt -buildfile:testscript.build testnanttarget

This produces console output but I can't see any timing information.

All I want each log message prefixed with datatime.

[A]
You can use the
tstamp task
to display the current date/time. Just include it everywhere where you want timing information. It will not prefix each line with a timestamp, but at least you can time some strategic points.
```
```
<tstamp />
```
```


q:
I'm looking for ideas on how to implement audit trails for my objects in C#, for the current project,basically I need to:

Store the old values and new values of a given object.

Record creation of new objects.

Deletion of old object.

Is there any generic way of doing this,like using C# Generics,so that I don't have to write code for events of the base object like on creation,on deletion etc.(ORM objects).The thing is that if there was a way to inject audit trail if one is using a .Anybody have any experiences or any methods they follow.Any way to do this in a Aspect-oriented (AOP) mannner.

Please share your ideas etc.

[A]
Question is pretty similar to
How do you implement audit trail for your objects (Programming)?
We've implemented a similar solution, using AOP (aspectJ implementation). Using this particular points can be captured and specific operations can be performed.
This can be plugged in and plugged off when we like.
However, our implementation was in J2EE..
If you really want to do it in the app layer, i would suggest this.
Hope it helps..


q:
How do i check in C++ if a file is a regular file (and is not a directory, a pipe, etc.)? I need a function isFile().

DIR *dp;
struct dirent *dirp;

while ((dirp = readdir(dp)) != NULL) {
if ( isFile(dirp)) {
     cout << "IS A FILE!" << endl;
i++;
}

I've tried comparing dirp->d_type with (unsigned char)0x8, but it seems not portable through differents systems.

[A]
You need to call stat(2) on the file, and then use the S_ISREG macro on st_mode.
Something like (adapted from
this answer
):
```
```
#include <sys/stat.h>

struct stat sb;

if (stat(pathname, &sb) == 0 && S_ISREG(sb.st_mode))
{
    // file exists and it's a regular file
}
```
```


q:
On researching another question I noted that the stat function in Perl can take a dirhandle as its argument (instead of a filehandle or filename).

However I can't find any examples of correct use of this - there are none in the Perl manual.

Can anyone show an example of how to use it?

[A]
You use it just like you would
```
stat
```
on a filehandle:
```
```
<~> $ mkdir -v foo ; perl -e 'opendir($dh , "./foo"); @s = stat $dh; print "@s"'
mkdir: created directory `foo'
2049 11681802 16877 2 1001 1001 0 4096 1228059876 1228059876 1228059876 4096 8
```
```
(Personally, I like using
```
File::stat
```
to get nice named accessors, so that I don't have to remember (or lookup) that the fifth element is the UID...)


q:
There's a lot of conflicting information about this topic. So let's try to agree on a definitive answer:

Which one of these random number generator in C create better randomness: rand, random or arc4random?

note: Just to make the question clear, this is not a question about true randomness, it's only a clash between those 3.

As pointed out, this question doesn't make much sense, as this is not about C, but about a specific implementation, in my case, cocoa (more specifically the iphone sdk, but my guess is they are the same as far as these functions go). Still, there's some useful information here. I concluded by implementing arc4random, mostly because of its ease of use (no seeding needed), which is an important factor that no one pointed out.

I'm closing the question, and adding the cocoa tag for cocoa developers looking for information on RNGs. Many thanks for those who contributed, and sorry for the confusion.

[A]
The implementation of rand() is not specified by the C standard, however most compilers use a linear congruential generator. random() and arc4random() aren't standard C either, but they are better than the usual implementation of rand()
I'd say: arc4random() is better than random() is better than rand()
rand() is really terrible. You could easily do better than all three however.
It also depends what you want the random numbers for. A good random number generator for encryption/security may not be a good random number generator for simulation and vice-versa.


q:
Thanks for a solution in C,
now I would like to achieve this in C++ using std::sort and vector:

typedef struct
{
  double x;
  double y;
  double alfa;
} pkt;

vector< pkt > wektor; filled up using push_back(); compare function:

int porownaj(const void *p_a, const void *p_b)
{
  pkt *pkt_a = (pkt *) p_a;
  pkt *pkt_b = (pkt *) p_b;

  if (pkt_a->alfa > pkt_b->alfa) return 1;
  if (pkt_a->alfa < pkt_b->alfa) return -1;

  if (pkt_a->x > pkt_b->x) return 1;
  if (pkt_a->x < pkt_b->x) return -1;

  return 0;
}

sort(wektor.begin(), wektor.end(), porownaj); // this makes loads of errors on compile time

What is to correct? How to use properly std::sort in that case?

[A]
```
std::sort
```
takes a different compare function from that used in
```
qsort
```
. Instead of returning –1, 0 or 1, this function is expected to return a
```
bool
```
value indicating whether the first element is less than the second.
You have two possibilites: implement
```
operator <
```
for your objects; in that case, the default
```
sort
```
invocation without a third argument will work; or you can rewrite your above function to accomplish the same thing.
Notice that you have to use strong typing in the arguments.
Additionally, it's good not to use a function here at all. Instead, use a function object. These benefit from inlining.
```
```
struct pkt_less {
    bool operator ()(pkt const& a, pkt const& b) const {
        if (a.alfa < b.alfa) return true;
        if (a.alfa > b.alfa) return false;

        if (a.x < b.x) return true;
        if (a.x > b.x) return false;

        return false;
    }
};

// Usage:

sort(wektor.begin(), wektor.end(), pkt_less());
```
```


q:
All,

I'd like to check Django out and maybe hack together some web pages to see how it feels - but after having a look at a few tutorials like this one I am starting to wonder if there is any way of getting it up and runinng without typying cmd line stuff for 1/2 hour.

Can people point out some good straightforward resources/tutorials to get the thing up and running?

I plan doing this on Windows environment.

[A] It doesn't take half an hour, nor should you think that development is mostly about writing code. There is always going to setup work and such involved. That being said, I understand your plight. You might have luck finding a project that interests you and already exists. Simply checking out their latest revision should let you run it, poke around locally, and if you make some actual progress with the code you can contribute it instead of going to waste in the name of just messing around.


q:
Is there any lib that convert very long numbers to string just copying the data?

These one-liners are too slow:

def xlong(s):
    return sum([ord(c) << e*8 for e,c in enumerate(s)])

def xstr(x):
    return chr(x&255) + xstr(x >> 8) if x else ''

print xlong('abcd'*1024) % 666
print xstr(13**666)

[A]
You want the struct module.
```
```
packed = struct.pack('l', 123456)
assert struct.unpack('l', packed)[0] == 123456
```
```


q: The title basically spells it out. What interfaces have you written that makes you proud and you use a lot. I guess the guys that wrote IEnumerable<T> and not least IQueryable<T> had a good feeling after creating those.

[A]
I guess the guys that wrote IEnumerable … had a good feeling after creating [it].
I'm not so sure.
```
IEnumerable
```
was quite a failure, as interfaces go. This is evident from the fact that
```
IEnumerable<T>
```
, its generic counterpart, actually offers a completely
different
interface. (Well, “different” isn't a good word; basically, it adds disposability and de-emphasizes the completely useless
```
Reset
```
method; however, this method is of course still present.)
Additionally, similar languages that have similar constructs (Java comes to mind) have a much better, more extensible construct to fulfill the same needs (and more). For example, Java's iterators can be extended to be bidirectional or to allow modifying access (whereas
```
IEnumerable
```
is always read-only).
EDIT:
Since there's so much controversy in the comments, let me clarify. I'm not saying that
```
IEnumerable
```
(or
```
IEnumerator
```
) are
bad
interfaces. They're adequate. However, they could have been made better. If nothing else, then at least the
```
Reset
```
method seems like clutter.
Terjet said that he “use[s] it all the time” – which is precisely my point!
```
IEnumerable
```
is a pivotal interface of the whole .NET framework. It's ubiquitous. There'd be no .NET without it. Is it therefore too much to ask for a
perfect
interface?
“Adequate” is just another word for failure.


q:
When trying to serialize a type (a generic List<T> which T is a class marked with XmlRootAttribute) into XML using XmlSerializer, a FileNotFoundException is thrown (sometimes) and serialization fails.

It seems that XmlSerializer tries to create a temporary file with a random file name in the Temp folder of user under which the application is running, but the file gets deleted somehow.

Anyone seen this? Any workarounds?

[A]
XmlSerializer works by generating
code
to do the serialization/deserialization, and storing this in a temporary assembly.  (This approach gives good performance for repeated serialization/deserialization but (traditionally) shockingly awful performance for the first run)
To help mitigate the shocking performance, from VS2005 onwards (and earlier using less well known techniques), you can explicitly create the serialization assembly at build time and ship it with your main assembly.
If you
don't
create/ship the serialization assembly, then the framework tends to throw an exception when it's looking for it, though normally it catches the exception, builds the assembly on the fly, and gets on with things.  If you're running under a debugger, with 'break-on-throw' set though, it can be a bit alarming to have the FileNotFound exception being thrown deep in the bowels of the framework.
Are you
sure
that the FileNotFound exception is directly associated with the serialization failure you're seeing?  Have you tried including the serialization assembly explicitly?


q:
In .NET there is the CultureInfo class in the System.Globalization namespace. It has two similar properties both returning values of the CultureInfo type: CurrentCulture and CurrentUICulture.

What is the difference between them?

Which one should I use when and why?

[A]
```
CurrentCulture
```
is the .NET representation of the default user locale of the system. This controls default number and date formatting and the like.
```
CurrentUICulture
```
refers to the default user interface language, a setting introduced in Windows 2000. This is primarily regarding the UI localization/translation part of your app.
Whatever regional options the system is configured to have will be the "Current" values in your .NET app.
Often times they are both the same. But on my system they would be different: I prefer my numbers and dates in the German format, so the
```
CurrentCulture
```
would be German, but I also prefer all my applications in English, so the
```
CurrentUICulture
```
would be English.
There is a nice article on the topic:
Sorting it all Out: Why we have both CurrentCulture and CurrentUICulture


q:
What are the best ways of developing a subscription type website that provides lesson content (like Lynda.com)?

How do you protect the content from download (audio and video)?

What's the best way to handle passwords?
Can the user have a login name and password, and then also have an additional password that changes on a regular basis and is distributed by the site to reduce people using other people's passwords?

How do you minimize people sharing their passwords with other people?

[A]
Protecting content is pretty easy: simply write a page which has access to the user's session / security details and check to see if they are authorized to download the file that was requested.  You could do this easily with a Java Servlet or any other web platform like ASP.NET, PHP, etc.
I would recommend against this technique of multiple passwords.  It's going to be a hassle for your customers.  It also creates the perception that you assume your customers are trying to cheat the system.  What I would do instead is log all users logins as well as user accesses for a particular file and also log the IP addresses.  You can write some code to analyze this data and look for concurrent logins from different IPs.  You could also write code to prevent multiple logins as well.


q: I need a conditional compilation switch that knows if I am compiling for the mono or MS .NET runtime. How can I do this?

[A]
The Mono compiler defines
```
__MonoCS__
```
BUT, BUT, BUT
, the whole point of Mono is that you can take an assembly that you built with VS and run it on Mono, or vice versa.
It seems to me that if you need to have Mono vs MS.NET differences, then you need to be making those decisions at run-time.
The standard way to detect Mono at Runtime is:
```
```
bool runningOnMono = Type.GetType ("Mono.Runtime") != null;
```
```


q:
I'm using the following as a way of seeing listing the various methods in my developement

print basename(__FILE__) . "::serve_table()"

is there any function that's able to return the name of a class method so I don't have to trpe it each time?


q: What are the tensions between multithreading and exception-safety in C++? Are there good guidelines to follow? Does a thread terminate because of an uncaught exception?

[A]
I believe the C++ standard does not make any mention of multithreading - multithreading is a platform-specific feature.
I'm not exactly sure what the C++ standard says about uncaught exceptions in general, but according to
this page
, what happens is platform-defined, and you should find out in your compiler's documentation.
In a quick-and-dirty test I did with g++ 4.0.1 (i686-apple-darwin8-g++-4.0.1 to be specific), the result is that
```
terminate()
```
is called, which kills the entire program.  The code I used follows:
```
```
#include <stdio.h>
#include <pthread.h>

void *threadproc(void *x)
{
  throw 0;

  return NULL;
}

int main(int argc, char **argv)
{
  pthread_t t;
  pthread_create(&t, NULL, threadproc, NULL);

  void *ret;
  pthread_join(t, &ret);

  printf("ret = 0x%08x\n", ret);

  return 0;
}
```
```
Compiled with
```
g++ threadtest.cc -lpthread -o threadtest
```
.  Output was:
```
```
terminate called after throwing an instance of 'int'
```
```


q:
For example so that it works like this
toString (Var x)= "x"

[A]
Use the
```
show
```
function:
```
```
putStrLn (show x)
```
```
will print out the "x" variable. (Naturally, you don't need to use it with
```
putStrLn
```
, either --
```
show
```
returns a string that can be used anywhere like a string.)


q:
Am looking for checkpointing library for C#. Any ideas ?

see  http://en.wikipedia.org/wiki/Application_checkpointing

[A]
If I understand you correctly (and the question is pretty vague so I'm not sure of this at all) then Windows Workflow Foundation certainly has this capability.  However, it's almost certainly overkill for what you're asking.
Okay, you added a link that better explains what you mean by checkpointing.
With that in mind, .Net doesn't have anything built in to support this directly.  However, anything that uses a state machine where the state machine can be persisted, can be  inspected/validated, and is transactional has this sort of thing naturally built-in.  WWF is one example of that.


q:
I defined a Controller to force authentication by using the [Authorize] attribute. When a session times out, the request is still passed down and executed instead of forcing a redirect.

I do use FormsAuthentication to login and logoff users.

Any ideas on how to control that?

Example:

[Authorize]
public class ProjectsController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

[A]
To track user sessions ASP.NET uses the
ASP.NET_SessionId
cookie. To track authenticated users ASP.NET uses the
ASPXAUTH
cookie (by default).
When a session times out the
ASP.NET_SessionId
cookie might no longer be sent by the client but the
ASPXAUTH
cookie is still sent which might explain why your action is rendered.
To override default forms authentication values you might take a look
here
. I also suggest you to use the
firebug
extension to see exactly which cookies are sent by the client.


q:
Sup bros,

Is there anything out there for C++ which displays the class hierarchies as a tree on the left panel?  I've been using VisualWorks Smalltalk for a while, and the way that classes are displayed, and methods broken out, makes it very easy to build a mental picture of what the class does.  Sadly, I can't find anything similar for C++.  Does Eclipse perhaps have such a mode?

Thanks,
frapple_hok

[A]
Caveat emptor:
I've never used this tool myself.  (Though perhaps I'll start...)
From long experience I've learned that I can put
"emacs"
+
anything
into
google
and find it.  (Literally anything!  Some people have waayyy too much free time on their hands...)
In this case,
"emacs class browser"
turns up
EBROWSE,
which might be what you are looking for.
In terms of a "left panel", emacs supports splitting a single window up vertically (split-window-vertically) or horizontally (split-window-horizontally) however you like.  Or using multiple windows if you prefer (make-frame-command).
In terms of more typical IDE features, emacs supports font-locking (colorizing), make integration (jump to error), gdb integration (debugging), language-based auto-indent, TAGS [etags] (jump to tag definition), diff'ing two files (or file against revision), checkin/checkout to/from source code revision systems, spell-checking, etc.  (I'm sure other stackoverflow entries have highlighted emacs's many features.  Or try
slashdot.
Definitely check out the
"complete"
function!
(require 'completion)
And perhaps
"align-regexp"
too!)


q: how do you handle them?

[A]
In domain names, you can do use IDN domains, if they are supported by the registrars you want to register them with.
Elsewhere in the URL, they are generally sent by the browser as utf8 urlencoded. Only recently I was looking at:
http://en.wikipedia.org/wiki/Pfeffern%C3%BCsse
And found it curious that there was a ü in the URL. Firefox shows it as a proper character though.


q:
Every time I start Visual Studio 2008, the first time I try to run the project I get the error CS0006 The metadata file ... could not be found. If I do a rebuild of the complete solution it works.

Some information about the solution:

I'm building in debug mode and Visual Studio complains about not finding dll:s in the release folder.

The projects Visual Studio complains about are used by many other projects in the solution.

I have changed the default output path of all projects to a ......\build\debug\ProjectName and ......\build\release\ProjectName respectively. (Just to get all build files in one directory)

I have the same problem with a another solution.

The solution was created from scratch.

There are 9 projects in the solution. One WPF and 8 class libraries using dotnet 3.5.

Any ideas on what is causing this problem?

[A]
I had this issue, not sure if it will help but mine was caused by having two different versions of the same project referenced by two different solutions.  When I built the solution with the reference to the correct project first the second solution would build fine, however, if I cleaned the first solution and tried to build the second solution it would fail with these dll reference error messages.
The solution for me was figuring out I had two projects with the same name which had been accidentally duplicated and removing the reference to the old incorrect project and adding a reference to the new one.
In any case it seems that these messages are a bit of a red herring, I would check your build output and find the first project that fails to build and very carefully check the references on that project.


q:
This is a question brought up in a local user group mailing list at dot.net.nz ...

I when I create an XHTML page
  old-fashioned way, I used to use the
  following syntax for my CSS
  declarations:

<link rel=”stylesheet” type=”text/css” media=”screen” href=”css/screen.css” />

<link rel=”stylesheet” type=”text/css” media=”print” href=”css/printer.css” />

Now, since I code using ASP.NET 2.0
  and beyond; I fell in love with the
  Themes. However, I don’t know how to
  do the same thing using Themes.

[A]
You can declare the media type inside the stylesheets. For example, printer.css:
```
```
@media print
{
    /* Print CSS rules here */
}
```
```


q:
Assuming the following directory structure,

htdocs/
  images/
  css/
  .htaccess
system/
  index.php
  ...

I would like to route all incoming requests through that php script. I have been trying some rewrite rules within the htaccess, but I can't seem to be able to route to files that are outside the document root. I couldn't find a reason for this in the apache manuals, so eventually resorted to "Include" an apache config file, where the rules are different.

Is there a way of rewriting outside of the docroot?

[A]
No, you cannot route outside the docroot without potentially enormous risk.
You should place the
```
index.php
```
within the
```
htdocs
```
folder and rewrite it there, not outside.  If you were to rewrite to handle the index, accessing outside the docroot, and you made one little mistake it's potentially exploited by any hacker rewriting the request string.  Not pretty!


q:
In SQL Server, I can do something like this:

UPDATE tbl1
   SET col2 = tbl2.col2
  FROM table1 tbl1
 INNER JOIN table2 tbl2
    ON tbl1.col1 = tbl2.col1

I haven't bothered to look whether this is part of any SQL standard or not, and I'm sure there are other ways to do it, but it is astoundingly useful.

Here's my problem. I need to do something similar in SQL (i.e, not a host language) with SQLITE3. Can it be done?

[A]
I've discovered this can be done with
```
INSERT OR REPLACE INTO
```
. A little more verbose than T-SQL's equivalent, but just as handy.


q:
A good friend of mine works for a large asp.net shop, with a web farm with many web servers (dozens).  The application logs exceptions and messages to the event log on each box (not to a centralized location).

Does anyone know of a convenient way to perform unified reporting on event logs on a number of different boxes?

Or, which is better:
- write tools that connect to each event log on each box?
- change architecture to log events to the database?
- some other mechanism I haven't considered?

[A]
I would use
Log4Net
(or something similar) for the logging, saving the files to disk, and rotating log file periodically. (I'm not a big fan of the Windows event log, personally.) Then have a background service on each box which uploads the log file into a database table - keeping track of which log entry came from which box.
This gives simple searching over the whole web farm while maintaining the information about which log entry came from where.
Similar questions:
"Is writing server log files to a database a good idea?"
"Logging for web application"


q:
Is there a medium-sized Clojure sample application that could be used as a "best-practices" example, and a good way to see what such an application would look like in terms of code and code organization? A web application would be particularly interesting to me, but most important is that the program do something commonly useful (blog, bug-tracking, CMS, for example), and not something mathematical that I've never ever had to implement in the real world (solving the N-queens problem, simulating Life, generate Fibonacci sequences, and such usual fare of function programming languages).

Thanks!

[A]
If you browse the
clojure-contrib
source code you can see how libraries are implemented in clojure.
You can also checkout "
ClojureScript
" under the same source tree.
Allows code written in a very small
      subset of Clojure to be automatically translated to JavaScript.
The ClojureScript translator is a full Clojure app.
I'd also recomend checking out the Stewart Halloway's
Port of Practical Common Lisp samples to Clojure
if you haven't already.


q: What's the best way to consume REST web services from .NET?

[A]
Probably WCF; check out
http://hyperthink.net/blog/announcing-the-wcf-rest-starter-kit/


q: I'd like to automatically login to VSS when I open it, and skip the login prompt altogether.  Is this possible?

[A]
Answering my own question:
1 - Right-click My Computer, click Properties
2 - Click "Advanced" -> "Environment Variables"
3 - Under User variables for , click "New".
4 - Variable name = "SSUSER", Variable Value = < your VSS username >
5 - Repeat steps 3 & 4 for "SSPWD" and < your VSS password >


q: Has anybody seen such a thing? Small self-sufficient modules are preferred.

[A]
SymPy
is a symbolic maths library written entirely in Python and has full support for rational numbers.  From the
tutorial
:
```
```
>>> from sympy import *
>>> a = Rational(1,2)

>>> a
1/2

>>> a*2
1

>>> Rational(2)**50/Rational(10)**50
1/88817841970012523233890533447265625
```
```
There is also GMP for Python (
GMPY
) which, while not pure Python, is probably more efficient.


q:
In C++, on the stack, a simple variable is assigned a memory address so that we can use a pointer to contain this memory to point to it; then is a pointer also assigned a memory address?

If yes, can we have a pointer of pointers?

[A]
Yes, you are right. We can have pointers to pointers:
```
```
int a;
int b;
int * pa = &a;
int ** ppa = &pa;

// set a to 10
**ppa = 10;

// set pa so it points to b. and then set b to 11.
*ppa = &b;
**ppa = 11;
```
```
Read it from right to left:
ppa is a pointer to a pointer to an int
. It's not limited to
```
**
```
. You can have as many levels as you want.
```
int ***
```
would be a
pointer to pointer to pointer to int
.
I answered a similar question regarding whether primitive variables have addresses here:
Is primitive assigned a memory address?
, the same applies to pointers too. In short, if you never take the address of an object, the compiler doesn't have to assign it an address: It can keep its value in a register.


q:
I understand how Map is easily parallelizable - each computer/CPU can just operate on a small portion of the array.

Is Reduce/foldl parallelizable? It seems like each computation depends on the previous one. Is it just parallelizable for certain types of functions?

[A]
Not sure what platform/language you're thinking of, but you can parallelize reduce operators like this:
```
```
// Original
result = null;
foreach(item in map) {
    result += item;
}

// Parallel
resultArray = array();
mapParts = map.split(numThreads);
foreach(thread) {
    result = null;
    foreach(item in mapParts[thread]) {
        result += item;
    }
    resultArray += result;    // Lock this!
}
waitForThreads();
reduce(resultArray);
```
```
As you can see, a parallel implementation is easily recursive.  You split the map up, operate on each part in its own thread, then perform another reduce once those threads are done to bring the pieces together.
(This is the programmatic reasoning behind
Piotr Lesnick's answer
.)


q:
I've got an ASP.NET application running and on the production box it's using about 450MB RAM, however, it shouldn't be using quite so much, and it seems to increase over time, so it seems there might be a leak or atleast something not being released properly.

I took a look with PerfMon and there was 416MB in GC Gen2.

Anyone have any idea for finding out what it's keeping in memory? Could I just grab dotTrace/ANTS and somehow attach it to my IIS (6 - on windows server 2003) - or is there a better way? :-)

Thanks.

[A]
Although this is a specific blog about a technology you're probably not using it does cover how to diagnose memory issues -
http://blogs.msdn.com/tess/archive/2008/09/12/asp-net-memory-issues-high-memory-usage-with-ajaxpro.aspx
Dig through Tess's work, she's got a lot of debugging/ diagnosis posts and I'm sure  you can find more which are of use to you.


q:
in Microsoft Access, is there a way which I can programatically set the Confirm Action Queries flag on the options screen to False? Ideally when the database is started up I would like to check if it's true, and if so, mark it as false for the currently logged in user.

The application is locked down reasonably tightly, so ideally, we don't want to have to give users acces to the action menu.

Thanks in advance.

PG

[A]
Place the following in a method when the database starts:
```
```
If Application.GetOption("Confirm Action Queries") Then
    Application.SetOption "Confirm Action Queries", False
End If
```
```


q:
i have code like, sorry i dont have the exact code now. but its valid.

<iframe src="..." borderframe="0" scrolling="no" width=728px" height="90px"></iframe>

the target is a html file that contains code for a banner.
everything displays well. but when i resize browser or go to maximize. the content is shiftet to the left by 1 pixel. so the banner is displayed missing the first vertical 1px line. and only 727px is visible.

anyone has an idea?

thank you.

[A]
I have an idea, but you haven't given us the whole picture, so I might be way off.
I would guess that the iframe is positioned with a percentage or some sort of division calculation like 40% left of parent.  Then at certain browser widths this number doesn divide evenly and gets truncated.  Say it is at 100px in from the left side, and you shrink the parent by 2/3rds so that its positioning would become 66.66 pixels, and the browser cuts this off to 66, giving an apparent error of one pixel left.


q:
I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch.

What's included, and where can I get other good quality libraries from?

[A]
The Python Global Module Index (
http://docs.python.org/modindex.html
) lists out every module included in Python 2.6.
Sourceforge has all sorts of good Python modules - one that came in handy for me recently was PyExcelerator, a module for writing straight to MS Excel workbooks.  The Python Package Index, (
http://pypi.python.org/
) is also a good source of Python modules.


q:
I would like to use [Authorize] for every action in my admin controller except the Login action.

[Authorize (Roles = "Administrator")]
public class AdminController : Controller
{
    // what can I place here to disable authorize?
    public ActionResult Login()
    {
        return View();
    }
}

[A]
I don't think you can do this with the standard Authorize attribute, but you could derive your own attribute from AuthorizeAttribute that takes a list of actions to allow and allows access to just those actions.  You can look at the source for the AuthorizeAttribute at
www.codeplex.com
for ideas on how to do this.  If you did, it might look like:
```
```
[AdminAuthorize (Roles = "Administrator", Exempt = "Login, Logout") ]
public class AdminController : Controller
{
    public ActionResult Login()
    {
        return View();
    }

    public ActionResult Login()
    {
        return View();
    }

    ... other, restricted actions ...
}
```
```
EDIT
:  FYI, I eventually ran across a need to do something similar on my own and I went a different direction.  I created a default authorization filter provider and apply a global authorize filter.  The authorization filter provider uses reflection to check if an action or controller has a specific authorize attribute applied and, if so, defers to it.  Otherwise, it applies a default authorization filter.  This is coupled with a PublicAttribute derived from AuthorizeAttribute that allows public access.  Now, I get default secured access, but can grant public access via
```
[Public]
```
applied to an action or controller.  More specific authorization can also be applied as necessary.  See my blog at
http://farm-fresh-code.blogspot.com/2011/04/default-authorization-filter-provider.html


q:
I'm using the following code to have a non-JS navigation:

<ol id="navigation">
    <li id="home"><a href="#"><img src="./images/nav/home-hover.png" alt="Home" /></li>
    ...
</ol>

And the CSS:

#navigation a {
    display: block;
    height: 25px;
}

#navigation a img {
    display: none;
}

#navigation a:hover img {
    display: block;
}

#home a {
    background: url('./images/nav/home-normal.png') no-repeat;
    width: 100px;
}

My problem is they won't change images on hover in IE6. I'm using the :hover on an anchor so that should be fine and am using display rather than visibility which is another thing that doesn't work in IE6.

I'd really like not having to add a load of javascript for image replacing/preloading (embedding something like jQuery isn't an option) - can anyone help me here?

Thanks,

[A]
IE doesn't repaint anchors unless any rule on
```
<a>
```
itself changes. Add anything for
```
a:hover
```
, e.g.:
```
```
#navigation a:hover {border:0} /* no-op */
```
```
BTW: unfortunately popular screen readers don't read things with
```
display:none
```
, so your menu ends up being inaccessible.
I suggest having
```
<img>
```
visible by default, and hiding it on hover.


q:
There is a simple C++ method to use pattern matching on strings? The code should sound like this:

if (regexpcmp("l?nole*[0-9]", "linoleum1")) {
  //we have a match!
} else {
   //no match
}

[A]
Did you already look at
Boost.Regex
?
```
```
const boost::regex e("l?nole*[0-9]");
if (regex_match("linoleum1", e)) {
  //we have a match!
} else {
  //no match
}
```
```


q: How do I embed a WMV file in an ASP.NET Web page? I want it visible as a player, not just a link. Is there an ASP.NET control for this? I don't see one on the VS 2008 toolbar, and can't find one in the help. And I'm not yet ready to move this site to Silverlight, where media is really easy.

[A]
WMV is primarily a Microsoft file format.  There is no inherent browser support for this format, so you're going to need a browser plugin to play it.
I'm pretty sure you can embed Windows Media Player on a page to play it, but that'll limit you to clients running Windows and who happen to have Media Player installed.
If you need to support a wide audience, I'd seriously consider re-encoding your video to something like FLV and using a Flash based video player.  I haven't got statistics to hand that back this up - but Flash Video is the most widely supported video format in the browser.


q: What's the best way to get a list of users that are assigned to a SharePoint portal?

[A]
It depends on exactly what list of users you want.
All users that exist in a SharePoint web (but don't necessarily have permission):
SPWeb.AllUsers
Users that exist in a SharePoint web but have been granted some permission:
SPWeb.Users
Users that exist in a SharePoint site collection (but don't necessarily have permission):
SPWeb.SiteUsers
Note: I am assuming you are using WSS 3.0 / MOSS 2007 but this should work for WSS 2.0.
Also look at:
SPWeb.AllUsers vs. SPWeb.Users
SPWeb.AllUsers vs. SPWeb.Users vs. SPWeb.Groups


q:
I have DataTemplate containing a TextBox. I'm setting this template to a listbox item on a selection.

I'm unable to set focus to textbox in the template. I tried to call MyTemplate.FindName, but it ends up with an Invalid Operation Exception: This operation is valid only on elements that have this template applied.

How can I access it?

[A]
Since you know the name of the
```
TextBox
```
you want to focus, this becomes relatively easy. The idea is to get hold of the template as it's applied to the
```
ListBoxItem
```
itself.
First thing you want to do is get the selected item:
```
```
var item = listBox1.ItemContainerGenerator.ContainerFromItem(listBox1.SelectedItem) as ListBoxItem;
```
```
Then you can pass that into this little helper function which focuses a control based on its name:
```
```
public void FocusItem(ListBoxItem item, string name)
{
    if (!item.IsLoaded)
    {
        // wait for the item to load so we can find the control to focus
        RoutedEventHandler onload = null;
        onload = delegate
        {
            item.Loaded -= onload;
            FocusItem(item, name);
        };
        item.Loaded += onload;
        return;
    }

    try
    {
        var myTemplate = FindResource("MyTemplateKey") as FrameworkTemplate; // or however you get your template right now

        var ctl = myTemplate.FindName(name, item) as FrameworkElement;
        ctl.Focus();
    }
    catch
    {
        // focus something else if the template/item wasn't found?
    }
}
```
```
I guess the tricky bit is making sure you wait for the item to load. I had to add that code because I was calling this from the
```
ItemContainerGenerator.StatusChanged
```
event and sometimes the
```
ListBoxItem
```
hadn't been fully initialized by the time we entered the method.


q:
Is it possble to have something like this in ASP.NET MVC...

[Authorize]
[AcceptVerbs(HttpVerbs.Get)]
public string AddData(string Issues, string LabelGUID)
{
    return "Authorized";
}

[AcceptVerbs(HttpVerbs.Get)]
public string AddData()
{
    return "Not Authorized";
}

So if the user is not logged in, it defaults to the un-Authorized action.

[A]
I don't believe so. The controller action with the best parameter match will get selected and then the attributes will be applied.
You could use
```
```
if (Request.IsAuthenticated)
{
    return "Authorized";
}
else
{
    return "Not Authorized";
}
```
```
Under the hood [Authorize] is essentially doing the same thing
```
```
protected virtual bool AuthorizeCore(IPrincipal user)
{
    if (user == null)
    {
        throw new ArgumentNullException("user");
    }

    if (!user.Identity.IsAuthenticated)
    {
        return false;
    }

    ...snip...
}
```
```


q:
Well basically I have this script that takes a long time to execute and occasionally times out and leaves semi-complete data floating around my database. (Yes I know in a perfect world I would fix THAT instead of implementing commits and rollbacks but I am forced to not do that)

Here is my basic code (dumbed down for simplicity):

$database = new PDO("mysql:host=host;dbname=mysql_db","username","password");

while (notDone())
{
    $add_row = $database->prepare("INSERT INTO table (columns) VALUES (?)");
    $add_row->execute(array('values'));

    //PROCESSING STUFF THAT TAKES A LONG TIME GOES HERE
}

$database = null;

So my problem is that if that if the entire process within that while loop isn't complete then I don't want the row inserted to remain there.  I think that somehow I could use commits/rollbacks at the beginning and end of the while loop to do this but don't know how.

[A]
Take a look at
this tutorial
on transactions with PDO.
Basically wrap the long running code in:
```
```
$dbh->beginTransaction();
...
$dbh->commit();
```
```
And
according to this PDO document page
:
"When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back.  "
So you will lose the transaction that was pending when the script timed out.
But really, you ought to redesign this so that it doesn't depend on the scriipt staying alive.


q: One thing I really like about AS3 over AS2 is how much more compile-time type-checking it adds. However, it seems to be somewhat lacking in that there is no type-checked enumeration structure available. What's a good (best / accepted) way to do custom enumerated types in AS3?

[A]
your answer after the jump :-)
Enumerations with classes


q: How do I achieve authorization with MVC asp.net?

[A] There is an Authorization feature with MVC, using ASP.NET MVC beta and creating the MVC project from Visual Studio, automatically adds a controller that used authorization. One thing that will help with your google search, is that it is a "filter". So try searching on "Authorization Filter MVC" and anything preview 4 or greater will help.


q:
How can I use Connection pool in Java+MySQL+Tomcat 6?

I've read this article http://dev.mysql.com/tech-resources/articles/connection_pooling_with_connectorj.html but it is still not quite clear for me.

Where do I use the Connector/J? Do I put it in a static variable? Do I use a SessionListener? Does it need any configuration?

Thank you in advance!

[A]
You should read the
Tomcat 6 JNDI document
. Look for the "JDBC Data Sources" section and it will tell you everything you need to know about pooling connections with Tomcat.


q:
In a WPF UserControl, I have to make to call to a WebService. I am making this call on a separate thread but I want to inform the user that the call may take some time.

The WebMethod returns me a collection of objects and I bind it to a ListBox in my UC. So far, so good... This part works really well. However, I want to display a progress bar (or an animation of any kind...) during the call. This animation would be on top and centered in the ListBox control.

I tried Adorner and it partially works. However, I have to draw all controls in protected override void OnRender(DrawingContext drawingContext)... I simply want to add a control for a couple of seconds...

Anybody has an idea of how I could achieve this?

Thanks!

[A]
Don't go with the adorner - what I do is have two separate container controls (usually grids) that occupy the same area of the screen. One is my "progress" control, and the other is my "content" control. I set the visibility of the progress control to Collapsed and the visibility of the content control to Visible by default.
If you have it set up that way, when you start the asynchronous call to the webservice you can make the progress control visible and the content control collapsed. When the webservice finishes, have it use Dispatcher.BeginInvoke to update the UI, and at that point, switch the progress control back to collapsed and the content control back to visible.
I generally make the progress control indeterminate. Here is an example; in this, I have a separate UserControl called ProgressGrid that has my progress bar.
```
```
<Grid x:Name="layoutRoot">
        <Grid x:Name="contentGrid" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="Visible">
             <!-- snip -->
        </Grid>

        <controls:ProgressGrid x:Name="progressGrid" Text="Signing in, please wait..." Visibility="Collapsed"/>
    </Grid>
```
```
And in the code behind, just something simple like this:
```
```
private void SignInCommand_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        contentGrid.Visibility = Visibility.Collapsed;
        progressGrid.Visibility = Visibility.Visible;
    }
```
```


q:
In jQuery, if I assign class=auto_submit_form to a form, it will be submitted whenever any element is changed, with the following code:

/* automatically submit if any element in the form changes */
$(function() {
  $(".auto_submit_form").change(function() {
    this.submit();
  });
});

However, if I want to the form to submit only when specified elements are changed:

/* submit if elements of class=auto_submit_item in the form changes */
$(function() {
  $(".auto_submit_item").change(function() {
    $(this).parents().filter("form").submit();
  });
});

I'm just learning jQuery. Is there a better way to do this?

[A]
```
```
/* submit if elements of class=auto_submit_item in the form changes */
$(function() {
   $(".auto_submit_item").change(function() {
     $("form").submit();
   });
 });
```
```
Assumes you only have one form on the page.  If not, you'll need to do select the form that is an ancestor of the current element using
```
$(this).parents("form").submit()
```


q:
I need to create simple reusable javascript object publishing several methods and parameterized constructor. After reading through several "OOP in JavaScript" guides I'm sitting here with an empty head. How on the Earth can I do this?

Here my last non-working code:

SomeClass = function(id) {
    this._id = id;
}
(function() {
    function intFun() {
        return this._id;
    }
    SomeClass.prototype.extFun = function() {
        return incFun();
    }
})();

[A]
This is my usual approach:
```
```
MyClass = function(x, y, z) {
   // This is the constructor. When you use it with "new MyClass(),"
   // then "this" refers to the new object being constructed. So you can
   // assign member variables to it.
   this.x = x;
   ...
};
MyClass.prototype = {
    doSomething: function() {
        // Here we can use the member variable that
        // we created in the constructor.
        return this.x;
    },
    somethingElse: function(a) {
    }
};

var myObj = new MyClass(1,2,3);
alert(myObj.doSomething()); // this will return the object's "x" member
alert(myObj.x); // this will do the same, by accessing the member directly
```
```
Normally the "this" keyword, when used in one of the object's methods, will refer to the object itself. When you use it in the constructor, it will refer to the new object that's being created. So in the above example, both alert statements will display "1".
An exception to this rule is when you pass one of your member functions somewhere else, and then call it. For example,
```
```
myDiv.onclick = myObj.doSomething;
```
```
In this case, JavaScript ignores the fact that "doSomething" belongs to "myObj". As a result, the "this" inside doSomething will point to another object, so the method won't work as expected. To get around this, you need to specify the object to which "this" should refer. You can do so with JavaScript's "call" function:
```
```
myDiv.onclick = function() {
    myObj.doSomething.call(myObj);
}
```
```
It's weird, but you'll get used to it eventually. The bottom line is that, when passing around methods, you also need to pass around the object that they should be called on.


q:
i have a few classes that i am trying to move to using generics

Class1: Curve

this class has the following code:

public class Curve : IEnumerable

  IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator(); // Calls non-interface method
    }

  public RTRatePointEnumerator GetEnumerator()
    {
        return new RTRatePointEnumerator(_hash);
    }

Class 2:

  public class CurvePointEnumerator : IEnumerator

what is the recommended conversion of these two classes to using generics

[A]
```
IEnumerable<T> and IEnumerator<T>
```
gah, it swallowed my code


q:
Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following Haskell code:

[(i,j) | i <- [1,2], j <- [1..4]]

which yields

[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)]

Can I obtain a similar behavior in Python in a concise way?

[A]
Are you asking about this?
```
```
[ (i,j) for i in range(1,3) for j in range(1,5) ]
```
```