Question:
I would want to do something like:

>>> lst = [1, 2, 3, 4, 5]
>>> lst.find(lambda x: x % 2 == 0)
2
>>> lst.findall(lambda x: x % 2 == 0)
[2, 4]

Is there anything nearing such behavior in Python's standard libraries?

I know it's very easy to roll-your-own here, but I'm looking for a more standard way.

Answer:
You can use the filter method:
```
```
>>> lst = [1, 2, 3, 4, 5]
>>> filter(lambda x: x % 2 == 0, lst)
[2, 4]
```
```
or a list comprehension:
```
```
>>> lst = [1, 2, 3, 4, 5]
>>> [x for x in lst if x %2 == 0]
[2, 4]
```
```
to find a single element, you could try:
```
```
>>> next(x for x in lst if x % 2 == 0)
2
```
```
Though that would throw an exception if nothing matches, so you'd probably want to wrap it in a try/catch.  The () brackets make this a generator expression rather than a list comprehension.
Personally though I'd just use the regular filter/comprehension and take the first element (if there is one).
These raise an exception if nothing is found
```
```
filter(lambda x: x % 2 == 0, lst)[0]
[x for x in lst if x %2 == 0][0]
```
```
These return empty lists
```
```
filter(lambda x: x % 2 == 0, lst)[:1]
[x for x in lst if x %2 == 0][:1]
```
```


Question:
Presently I have a some legacy code, which generates the op code. If the code has more number of macros then the code generation takes so much of time (In terms of hours!!).
I have gone through the logic, they are handling the macro by searching for it and doing a replace of each variable in it some thing like inlining.

Is there a way that I can optimize it without manipulating the string?

Answer:
I have an application which has its own grammer. It supports all types of datatypes that a typical compiler supports (Even macros). More precisely it is a type of compiler which generates the opcodes by taking a program (which is written using that grammer) as input.
For handling the macros, it uses the text replacement logic
For Example:
Macro Add (a:int, b:int)
```
```
int c = a + b
```
```
End Macro
// Program Sum
..
int x = 10, y = 10;
Add(x, y);
..
// End of the program
After replacement it will be
// Program Sum
..
int x = 10, y = 10;
int c = x + y
..
// End of program
This text replacement is taking so much of time i.e., replacing the macro call with macro logic.
Is there a optimal way to do it?


Question:
Hello I was writing a Regular Expression (first time in my life I might add) but I just can't figure out how to do what I want. So far, so good since I already allow only Letters and spaces (as long as it's not the first character) now what I'm missing is that I don't want to allow any numbers in between the characters...could anybody help me please?

/^[^\s][\sa-zA-Z]+[^\d\W]/

Answer:
If you only want to allow letters and spaces, then what you have is almost correct:
```
```
/^[a-zA-Z][\sa-zA-Z]*$/
```
```
The
```
$
```
at the end signifies the end of the string.
Edited to correct answer, thanks to @Alnitak


Question:
I am new to RESTful stuff.  But, I want to use it in my rails app.  When I add this to my routes.rb map.resources :notes I get routes to these methods created:

index

create

new

edit

show

update

destroy

What I am wondering is what is the difference between edit/update and create/new?  Is there any standard definitions of how these method pairs vary and what each one does?

Answer:
When you use the scaffold generator in Rails 2
```
create
```
is the action called when the form from the
```
new
```
action is submitted.  Likewise,
```
update
```
is the action called when the form from the
```
edit
```
action is submitted.
As far as I know, you can blow that away and define them to do whatever you want depending on what
```
create/new/edit/update
```
means to your application.


Question:
Does anyone know of a way to paste over a visually selected area without having the selection placed in the default register?

I know I can solve the problem by always pasting from an explicit register. But it's a pain in the neck to type "xp instead of just p

Answer:
try -
```
```
:set guioptions-=a
:set guioptions-=A
```
```


Question:
We have a major VB6 trading application which uses MS Access (Don't ask!) It is always blasting trades into an MS Access database.

The rest of the infrastructure here has moved on considerably and I want to read this Access database periodically and copy any new trades into a SQL server database.

The SQL and C# needed to do this is trivially easy.

BUT I want to make sure I do it in such a way that does not lock the Access database or cause problems for the VB6 app. In other words when populating my DataTable from Access I do NOT want to lock the database and prevent the VB6 app writing to it. I seem to remember from old ADO there were share modes you could use for this purpose.

What sort of connection string should I use from .NET to accomplish this?

Answer:
Just an idea ... but have you thought about upgrading the database so that the tables themselves are actually stored in SQL Server and Access just become the front end?  It's been a little while, but if I remember correctly, Access should have a wizard (yuck!) to help you do this.
With old ADO you could set the cursor or lock type mechanism to one of the following:
Cursor Type
adOpenForwardOnly
This type of cursor can only be used to move forward through the recordset. This option is used when a list box or combo box is to be  populated.
adOpenKeyset
This is the best type of cursor to use when we expect a large recordset because we are not informed when changes are made to data that can affect our recordset.
adOpenDynamic
This cursor allows us to see all the changes made by other users that affect our recordset. It is the most powerful type of cursor but the slowest one.
adOpenStatic
The static cursor is useful when we have a small recordset.
Lock Type
adLockReadonly
This lock mode is used when no additions, updates or deletions are allowed from recordset
adLockPesimistic
In pessimistic locking, the record is locked as soon as editing begins and remains  locked until editing is completed.
adLockOptimistic
This occurs when the update method is called on the record. the record is unlocked even while edit but is temporarily locked when the changes are saved to the database
adLockBatchOptimistic
This option allows us to perform optimistic locking when we are updating a batch of records
Not sure how that exactly translates into the .NET world ... but maybe this can get you pointed in the right direction.


Question:
I have a PHP script that processes file uploads. The script tries to organise the files that are uploaded and may create new folders to move the files into if needed. These files will be below the www root directory (ie, a web browser will be able to access them).

My question is, what permissions should I set for the folders that get created and for the files that are moved into them (using mkdir() and move_uploaded_file())?

Answer:
Your webserver needs read and write permission in those folders, execute permission should be revoked (assuming UNIX-like systems). If not, a user could upload a script and have it executed by sending a HTTP request for it.
But IMO the whole concept is a potential security hole. Better store the files in a folder
outside
the webserver root, so that no direct acceess is possible. In your web application, you can have a PHP download page that scans the upload directory and displays a list of download links. These download links lead to another script, that reads the fiels from you storage dir und sends them to the user.
Yes, this is more work. But the scenario is very common, so you should be able to find some source code with example implementations easily. And it it much less work that having your server hacked...


Question:
Let's say you got a file containing texts (from 1 to N) separated by a $
How can a slit the file so the end result is N files?

text1 with newlines $

  text2 $etc... $

  textN

I'm thinking something with awk or sed but is there any available unix app that already perform that kind of task?

Answer:
Maybe
```
split -p
```
pattern
?
Hmm.  That may not be exactly what you want. It doesn't split a line, it only starts a new file when it sees the pattern.  And it seems to be supported only on BSD-related systems.
You could use something like:
```
```
awk 'BEGIN {RS = "$"} { ... }'
```
```
edit:
You might find some inspiration for the
```
{ ... }
```
part here:
http://www.gnu.org/manual/gawk/html_node/Split-Program.html
edit:
Thanks to comment from dmckee, but
```
csplit
```
also seems to copy the whole line on which the pattern occurs.


Question:
I need an regular expression pattern to only accept positive whole numbers.  It can also accept a single zero.

I do not want to accept decimals, negative number and numbers with leading zeros.

Any suggestions?

Answer:
```
```
/([1-9][0-9]*)|0/
```
```


Question:
It's a tricky question I was asked the other day... We're working on a pretty complex telephony (SIP) application with mixed C++ and PHP code with MySQL databases and several open source components.

A telecom engineer asked us to estimate the performance of the application (which is not ready yet). He went like 'well, you know how many packets can pass through the Linux kernel per second, plus you might know how quick your app is, so tell me how many calls will pass through your stuff per second'.

Seems nonsense to me, as there are a million scenarios that might happen (well, literally...)

However... is there a way to estimate application performance (knowing the hardware it will run on, being able to run standard benchmarks on it, etc) before actual testing?

Answer:
You certainly can bound the problem with upper (max throughput) limits.  There is nothing nonsense about that.  In fact, not knowing that stuff indicates a pretty haphazard approach to a problem - especially in the telephony world.
You can work through the problem yourself - what is the minimum "work" you have to accomplish for a transaction or whatever unit of task you have in your app?
Some messages to and from, some processing and a database hit for example? Getting information on the individual pieces will give you an idea of the fastest possible throughput. If you load up the system and see significantly lower performance then you can take time to figure out where you are possibly losing throughput with inefficient algorithms, etc.
EDIT
To do this exercise you need to know all the steps your app does for each use case. Then you can identify the max throughput for each use case. You should definitely know this stuff prior to release and going live.
I'm ignoring the worst case analysis as that - as you point out - is quite a bit harder.


Question: What im wondering how to do is when someone edits a list item and it goes through my event code that is fired when a change is made and save is hit, i dont want anyone to be able to edit that list item itself while its still processnig that request. So i was wondering if while in that event i can disable the individual item from being edited by someone else untill it is done doing what it is doing.

Answer:
Not sure if I understand exactly what you are want.
Try adding a field, hidden if you like, to the list or content type to use as a flag. When you enter your event code, make sure you check the flag first and if not set, set it and do your stuff. After you have done your stuff, unset the flag.
Here is some code to illustrate. Note that I have used a column named "updating". You can use the properties of the SPListItem as well if you do not care to add a column.
Oh, and don't forget to call DisableEventFiring before you to SPListItem.Update and then EnableEventFiring() afterwards. For get this and you will have a very nasty infinite loop on your hands.
.b
```
```
public override void ItemAdding(SPItemEventProperties properties)
    {
        if (properties.ListItem["updating"].ToString() == "updating")
        {
            properties.Cancel = true;
            properties.ErrorMessage = "Item is currently updating, please try again later";
        }
        else
        {
            properties.ListItem["updating"] = "updating";
            this.DisableEventFiring();
            properties.ListItem.Update();
            this.EnableEventFiring();

            // do your stuff

            properties.ListItem["updating"] = "";
            this.DisableEventFiring();
            properties.ListItem.Update();
            this.EnableEventFiring();
        }
    }
```
```


Question:
Similar to this question, but for VB.NET since I learned this is a language thing.

For instance, would the compiler know to translate

Dim s As String = "test " + "this " +
  "function"

to

Dim s As String = "test this function"

and thus avoid the performance hit with the string concatenation?

Answer:
While I'm looking it up,
here's the download page for the spec
.
Section 11.2 looks like it
would
be the right bit - it's basically the equivalent of 7.18 in the C# 3.0 spec - but it doesn't contain the same guarantee. I suspect the compiler still does it, but I can't see any guarantee. I'll have another look though.
Section 11.2 does state that "A constant expression is an expression
whose value can be fully evaluated at compile time
" (my emphasis) but I can't see that it actually guarantees that it
will
fully evaluate it at compile time. Frankly it would be odd to make a category of expression based on this condition but not actually use it.
A quick test shows that the current VB compiler does indeed do the concatenation at compile time, but there really
should
be a guarantee in the spec if that's the intention.
Section 7.3 get a bit closer:
When the operands of an expression are
  all primitive type constants, it is
  possible for the compiler to evaluate
  the expression at compile time. Such
  an expression is known as a constant
  expression.
Now String isn't a primitive type in terms of the CLR (
Type.IsPrimitive
would return false) but it
is
in terms of the VB spec.
It's still not saying that it
will
evaluate it though...


Question: How can I validate a username and password against Active Directory? I simply want to check if a username and password are correct.

Answer:
Probably easiest way is to PInvoke LogonUser Win32 API.e.g.
http://www.pinvoke.net/default.aspx/advapi32/LogonUser.html
MSDN Reference here...
http://msdn.microsoft.com/en-us/library/aa378184.aspx
Definitely want to use logon type
```
```
LOGON32_LOGON_NETWORK (3)
```
```
This creates a lightweight token only - perfect for AuthN checks.  (other types can be used to build interactive sessions etc.)


Question:
I want to write a script that will stop a scheduled task on a remote computer, do some stuff, and then start the schedule task back up.

How can I do it?

Answer:
Note:
"schtasks"
(see the other, accepted response) has replaced
"at"
.  However, "at" may be of use if the situation calls for compatibility with older versions of Windows that don't have schtasks.
Command-line help for "at":
```
C:\>at /?
The AT command schedules commands and programs to run on a computer at
a specified time and date. The Schedule service must be running to use
the AT command.

AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
AT [\\computername] time [/INTERACTIVE]
    [ /EVERY:date[,...] | /NEXT:date[,...]] "command"

\\computername     Specifies a remote computer. Commands are scheduled on the
                   local computer if this parameter is omitted.
id                 Is an identification number assigned to a scheduled
                   command.
/delete            Cancels a scheduled command. If id is omitted, all the
                   scheduled commands on the computer are canceled.
/yes               Used with cancel all jobs command when no further
                   confirmation is desired.
time               Specifies the time when command is to run.
/interactive       Allows the job to interact with the desktop of the user
                   who is logged on at the time the job runs.
/every:date[,...]  Runs the command on each specified day(s) of the week or
                   month. If date is omitted, the current day of the month
                   is assumed.
/next:date[,...]   Runs the specified command on the next occurrence of the
                   day (for example, next Thursday).  If date is omitted, the
                   current day of the month is assumed.
"command"          Is the Windows NT command, or batch program to be run.
```


Question:
I'm thinking of forming a Hackers Club at work.  My idea is that we would meet monthly and at each meeting one member would present an interesting hack he had created.  (The hacks presented wouldn't necessarily have to be software hacks; they could also be the sort of things you read about in MAKE magazine.)

There would also be ANSI standard pizza, veggie pizza, and beer and pop available for socializing afterward.  I'm even thinking of calling the club "TMRC" even though it will have nothing to do with model railroads.

Has anyone ever tried doing something like this or have any advice?

Answer:
We do this at the office. I call it 'Developer Fight Club'
Usually do challenges of varying difficulty and compete against one another.
At the end of it, we go over our solutions, do code-reviews and discussions, and then use either benchmark results or other people as the deciding factor for who wins.
Typically, the loser has to buy lunch for the winner :)
For ideas of things to do, try stuff from
Top Coder
, programming questions on Stack Overflow, or even simple "
crackme
" applications available on different programming sites.
The main rules you'll need to adhere to are:
Make It Fun
Make It Educational Make
Make It Fair
Try to rotate the challenges, so either everyone is really good at the subject, equally bad, or at least mix it up often enough that it doesn't favor one person's skillset too much.


Question:
I would like to begin developing for the Blackberry platform and, specifically, the Bold and also the Storm device which is coming out soon.  Do I need to get into Java and J2ME or can I develop sites in ASP.NET and just keep utilizing the skills I already have?

I am completely new to mobile platform development and have no idea what it will take to target these Blackberry devices.  I am hoping to continue to use my ASP skills.

Answer:
Are you talking about websites (because you say "develop sites in ASP.NET") or native Blackberry applications (because you say "developing for the Blackberry platform")?
Applications which run on the Blackberry use J2ME. If your application is accessed from a browser on the Blackberry, then it's the server the web app runs on that determines the language, not that it's being accessed from the Blackberry browser.
Then there's Blackberry MDS for integration with enterprise apps. I don't know much about this (never used it or seen an application that uses it) but it's described here:
http://na.blackberry.com/eng/services/mobile.jsp
Paul


Question:
For both .NET Winforms and Windows Presentation Foundation, if I have a text box that the user has just entered text into, and a button, if the user clicks the button the "LostFocus" event fires before the button click event fires.  However if the user uses a keyboard shortcut for the button (e.g. Button's text is "&Button" or "_Button" and user performs Alt+B), then the "LostFocus" event fires after the button click event, which is less useful.

Do you know of reasonable workarounds?  We have various things that we want to occur in LostFocus before ButtonClick.

Answer:
What would happen if you did this first of all in the button handler? (or perhaps subclass the button and override OnClick to apply this logic "worldwide").
```
```
Button b = (Button) sender;
b.Focus();
```
```
Would that get round the issue?


Question:
I have a table which has a field sort_id. In this field there are numbers from 1 to n, that define the order of the data sets.
Now I want to delete some elements and afterwards I want to reorder the table. Therefore I need a query that "finds" the gaps and changes the sort_id field according to the modifications.

Sure, I could do something like this:

SELECT sort_id FROM table WHERE id = 5

Then save the sort_id and afterwards:

DELETE FROM table WHERE id = 5
UPDATE table SET sort_id = sort_id - 1 WHERE sort_id > {id from above}

But I'd like to do the reordering process in one step.

Answer:
for sql server 2005:
this is how you get the new sequence:
```
```
SELECT row_number() over(order by sort_id) as RN
FROM table
```
```
updating the table means you should join that select to your update:
```
```
update t1
set sort_id = t2.RN
FROM table t1
     join (SELECT row_number() over(order by sort_id) as RN FROM table) t2
        on t1.UniqueId = t2.UniqueId
```
```


Question:
I feel like I'm re-inventing the wheel here, but I need to find a way of taking a URL from a catchall,and redirecting that to another route.

The reason for this is because I need to do some things like adding session cookies for certain urls, and then pass them on to their relevant action.

What's the best way of implementing this?

Thanks in advance for any help!

Answer:
If I understand question...
Looking at your previous question (
redirect-to-controller-but-with-a-different-master-using-a-catchall-wildcard
) you want to take the wildcard from:
```
```
routes.MapRoute(
    "Partner",
    "partners/{partner}/{*wildcard}",
    new { controller = "Partners", action = "PartnerRedirect" }
);
```
```
And in the Partners/PartnerRedirect action, send it to the right controller/action specified in the wildcard?
I have no idea the best way to do this, but looking at ways to unit test url routing brought up this:
http://weblogs.asp.net/stephenwalther/archive/2008/07/02/asp-net-mvc-tip-13-unit-test-your-custom-routes.aspx
I'm not sure if it is an exact fit (ie. might not have to mock stuff), but it looks like all the data is returned from GetRouteData to pass to RedirectToAction method.


Question:
We're looking to encrypt a field using DB-side encryption via NHibernate (most examples we've come across are app-side, which is not what we would like). The issue has been raised a couple of times, but no answers yet it seems.

On SQL Server 2005, for instance, and forgetting key-related issues for now, this means INSERTing EncryptByKey(Key_GUID(MyKey), MyValueToEncrypt) and SELECTing DecryptByKey(MyEncryptedField). The property might be a string, whereas the field has to be a varbinary.

We've vaguely got somewhere - using upper() and lower() instead of encryption functions - by combining paired properties, one mapped with a custom user type and the other with a formula attribute.

However if anyone has any ideas on how to do this in a nicer way, we'd be most grateful for a few pointers :o)

Answer:
There is a project on SourceForge, MindLib, that has useful NHibernate utility functions and libraries.  One of those is an EncryptedString library which allows you to store an encrypted string.  Unfortunately, this is not doing it on the server side, as you originally requested.
I've been looking for something similar.  The only thing I could come up with is to create a User Function in SQL Server to encrypt the string.  Something like
this
.
MindLib EncryptedString


Question:
I have a list of n GUIDs and I need to hash them into a single value.  This value could be the size of a Guid object or the size of an Int32, it doesn't really matter, but it does need to be statistically unique (say with a probably similar to MD5).

So one approach could be to sort them, concatenate the bytes and take an MD5 hash of all the bytes... but this isn't very quick.

Another idea: I notice that it is fairly standard practice in .NET to implement the GetHashCode method of a composing object as the XOR of the hash codes of the composed objects.  Therefore could it be mathematically sensible to XOR my list of GUIDs?

Any ideas welcome!

Answer:
If you want the hash to be valid for the
set
(i.e. order doesn't matter) then XORing the hashcode of each GUID is a good choice.
If you've actually got a
sequence
of GUIDs and the order matters then I'd suggest using the same approach I wrote about
in another answer
- repeatedly add/multiply.
(Note that XORing the hashcodes probably won't get you the same answer as XORing the GUIDs themselves and then hashing the result. It may be, but that depends on the implementation of GUID.GetHashCode(). I'd hash each value and XOR the results together - aside from anything else, that's trivial to implement.)


Question:
My stored procedure has an output parameter:

@ID INT OUT

How can I retrieve this using ado.net?

using (SqlConnection conn = new SqlConnection(...))
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add parameters

    conn.Open();

    // *** read output parameter here, how?
    conn.Close();
}

Answer:
Not my code, but a good example i think
source:
http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624
```
```
using System;
using System.Data;
using System.Data.SqlClient;

class OutputParams
{
    [STAThread]
    static void Main(string[] args)
    {

    using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;"))
    {
        SqlCommand cmd = new SqlCommand("CustOrderOne", cn);
        cmd.CommandType=CommandType.StoredProcedure ;

        SqlParameter parm= new SqlParameter("@CustomerID",SqlDbType.NChar) ;
        parm.Value="ALFKI";
        parm.Direction =ParameterDirection.Input ;
        cmd.Parameters.Add(parm);

        SqlParameter parm2= new SqlParameter("@ProductName",SqlDbType.VarChar);
        parm2.Size=50;
        parm2.Direction=ParameterDirection.Output;
        cmd.Parameters.Add(parm2);

        SqlParameter parm3=new SqlParameter("@Quantity",SqlDbType.Int);
        parm3.Direction=ParameterDirection.Output;
        cmd.Parameters.Add(parm3);

        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();

        Console.WriteLine(cmd.Parameters["@ProductName"].Value);
        Console.WriteLine(cmd.Parameters["@Quantity"].Value.ToString());
        Console.ReadLine();
    }
}
```
```


Question:
Where can I setup custom errors for directories in my application such as App_Code, App_Browsers, etc.?  I already have customErrors configured in the web.config and that works as expected.  For example,

http://www.mysite.com/bla.aspx > redirects to 404 page

but

http://www.mysite.com/App_Code/ > displays "The system cannot find the file specified."

There's no physical App_Code directory for my site.  Is this something that I can change in IIS?

Answer:
One way is to provide a redirect in the global.asax file:
```
```
void Application_Error(object sender, EventArgs e)
{
    //uncomment this to narrow down 'helpful' microsoft messages
    //HttpRequest request = ((HttpApplication)sender).Context.Request;

    Exception ex = Server.GetLastError();
    //ErrorManager is a custom error handling module
    ErrorManager.ProcessError(ex);
    Response.Redirect("~/error.aspx?error=" + HttpUtility.UrlEncode(ex.Message), true);
}
```
```
{ On a side note, I was getting an exception that I just couldn't track down - it just said 'file not found' but didn't say which file was missing. It turned out to be a broken image reference in a css file - breaking on line two of the code above helped identify the missing file }


Question: It seems like v2 of Log4j has been in development for literally years.  The Apache Log4J site no longer lists a roadmap, the dev mailing list seems almost entirely about 1.2 (which is appreciated!), use of v1.3 is discouraged, and the 2.0 branch is listed as "experimental".  What's a believer to believe?

Answer:
Well then I guess you already answered your own question, the devs have obviously stopped focusing on 2.0 builds a long time ago and have instead decided to continue the 1.x codebase.
And if you are on their mailing list, then ask them, the source of the issue.


Question:
how do i insert items into an html listbox from a database?
im using asp c#. i cant make the listbox run at server because the application wont work if i do that. so i have to insert values from a database into an html listbox. I just need to display 1 column of data. cheers..

Answer:
There are two ways of doing this I can think of:
First, you can place an
```
<asp:Placeholder />
```
tag on the page and generate the listbox in code:
```
```
var select = new HtmlSelect() { Size = 5 };

//assuming the data has been placed in an IEnumarble
foreach (var item in items)
{
    select.Items.Add(new ListItem() { Value = item });
}
selectPlaceholder.Controls.Add(select);
```
```
Second, you could create a WebService or ashx handler to provide the data and populate the list from javascript.


Question:
I need to have a set of overloaded functions in my code but I get convertion wanrings.
Here is a test code:

#include windows.h

void f(DWORD arg){...}

//void f(SIZE_T arg){}

void main(void)
{
DWORD dword=0;
SIZE_T size_t=dword;
f(size_t);

}

The compiler gives warning:

test.cpp(11) : warning C4244: 'argument' : conversion from 'SIZE_T' to 'DWORD', possible loss of data

If I uncomment void f(SIZE_T arg) I get

test.cpp(5) : error C2084: function 'void f(DWORD)' already has a body

How can I avoid having this warning or error?

Answer:
```
size_t
```
is guaranteed to be an unsigned integral type, but the number of bits it has isn't specified.  It could be equal to a
```
DWORD
```
(32 bits), or it could be 64 bits on a 64-bit platform.  For maximal portability, you shouldn't assume it has a certain number of bits, which is what the compiler is warning you about.  If you know your value will never exceed 2^32 (which is a reasonable assumption in 99.99% of cases), then you can just cast to a
```
DWORD
```
to get rid of the warning:
```
```
SIZE_T sz = dword;
f((DWORD)sz);  // no warning here
```
```
The error you're getting is because in your case,
```
size_t
```
is actually 32 bits, and so the function signatures of your two
```
f
```
functions are identical - they both take a single unsigned 32-bit parameter.  You'll have to use separate names for them in order to guarantee that your program is portable between 32- and 64-bit platforms:
```
```
void f_DWORD(DWORD arg) { ... }
void f_size_t(size_t arg) { ... }
```
```
One final note:
```
size_t
```
is a built-in type.
```
SIZE_T
```
is non-standard and is almost definitely a typedef or a #define for
```
size_t
```
.  You should use
```
size_t
```
instead of
```
SIZE_T
```
, and you should also avoid naming your variables
```
size_t
```
, since that introduces confusion by shadowing a type name with a variable name.


Question:
I have a repository which contains some unversioned directories and files. The server running svn was recently changed and since the checkout was done using the url svn://OLD-IP, I relocated my svn working copy, this time to the url svn://NEW-DOMAIN-NAME.

Now since there are some unversioned resources, the switch did not happen properly and the working copy got locked. A cleanup operation did not work either because of these unversioned resources.

I looked up in the net and found about svn ignore and tried that but to no use. I am unable to release all locks. Any ideas on solving the problem? Once I release the locks, I believe I can use svn ignore and carry on the relocate operation.

Answer:
Check your
```
svn status
```
output and the legend for the letters at
```
svn help status
```
.
Quite often, the problem is that there is a file where svn expects a directory, or other kinds of similar confusion (the letters should tell you which it is). If there are any conflicts (
```
C
```
), solve them first. You can recover lost directories with
```
svn update
```
, and
```
svn revert
```
can often help too (if there is anything important on your working copy which is not in the repository, make a backup of the working copy first!).
After most of the confusion has been cleared,
```
svn cleanup
```
and
```
svn update
```
/
```
svn switch
```
(
```
update
```
is nothing more than a special case of
```
switch
```
) should start working again.
In the worst case, you can do another checkout and manually copy over any locally modified files.


Question:
I have a form that sits behind ASP.NET forms authentication.  So far, the implementation follows a typical "out of the box" type configuration.

One page allows users to post messages.  If the user sits on that page for a long time to compose the message, it may run past the auth session expiration.  In that case, the post does not get recorded... they are just redirected to the login page.

What approach should I take to prevent the frustrating event of a long message being lost?

Obviously I could just make the auth session really long, but there are other factors in the system which discourage that approach.  Is there a way I could make an exception for this particular page so that it will never redirect to the Login so long as its a postback?

Answer:
My coworker came up with a general solution to this kind of problem using an HttpModule.
Keep in mind he decided to to handle his own authentication in this particular application.
Here goes:
He created an HttpModule that detected when a user was no longer logged in. If the user was no longer logged in he took the ViewState of that page along with all the form variables and stored it into a collection. After that the user gets redirected to the login page with the form variables of the previous page and the ViewState information encoded in a hidden field.
After the user successfully reauthenticates, there is a check for the hidden field. If that hidden field is available, a HTML form is populated with the old post's form variables and viewstate. Javascript was then used auto submit this form to the server.


Question: I am invoking a C library via JNI that prints to stdout.  How can I redirect this output to System.out?

Answer:
```
System.out
```
is
```
stdout
```
.  Is there some more fundamental problem you're having (mixed up output, perhaps?).
Since another member has also mentioned that last point - I should explain further:
```
System.out
```
and
```
stdout
```
both correspond to file descriptor #1.
However both Java's
```
OutputStream
```
(and derived classes) and C's
```
stdio
```
library have their own (independent) buffering mechanisms so as to reduce the number of calls to the underlying
```
write
```
system call.  Just because you've called
```
printf
```
or similar, it's not guaranteed that your output will appear straightaway.
Because these buffering methods are independent, output from within Java code could (in theory) get mixed up or otherwise appear out-of-order relative to output from the C code.
If that's a concern, you should arrange to call
```
System.out.flush()
```
before calling your JNI function, and in your C function (if it's using
```
stdio
```
rather than the low-level
```
write
```
call) you should call
```
fflush(stdout)
```
before returning.


Question:
I can't seem to find a true restful Blog API - are there any?
I'm writing some blog software and wondered if there was a standard restful API, if not I'll go buy the RESTful Web Services book and design my own.

Answer:
How about
AtomPub
?
Atom is the name of an XML-based Web
  content and metadata syndication
  format, and an application-level
  protocol for publishing and editing
  Web resources.
It isn't limited to blogs, but blogs certainly fall under the realm of applications are used for "publishing and editing Web resources".


Question:
I'm having a problem with a administrative app I'm working on.  I'm build an interface for stopping, starting and querying various services across 40 or so servers.

I'm looking at service.controller and have been successful in stopping and starting various services with button events but now I'm trying to figure out a way to return the service status to a text box and query for service status every 10 seconds or so and I feel like I'm hitting a brick wall.

Does anyone have any tips or insight?

Thanks!!

Answer:
You can trigger the periodic service check by using a Timer object. You can run your service queries on the Elapsed event.
```
```
private void t_Elapsed(object sender, ElapsedEventArgs e)
    {
        // Check service statuses
    }
```
```
As for displaying statuses in a text box, you should be able to use the ToString() method on the service status and display that in a regular text box. Remember that you may or may not be on the GUI thread when reacting to the timer events, so you'll need to invoke yourself on to the main thread.
```
```
private delegate void TextUpdateHandler(string updatedText);

    private void UpdateServerStatuses(string statuses)
    {
        if (this.InvokeRequired)
        {
            TextUpdateHandler update = new TextUpdateHandler(this.UpdateServerStatuses);
            this.BeginInvoke(update, statuses);
        }
        else
        {
            // load textbox here
        }
    }
```
```


Question:
Do you know what's the format of the DepartureWindow parameter for sabre web-services' OTA_AirLowFareSearch call? Whatever I pass, it shows me an error.

This is the entire documentation for those parameters (I kid you not):

<!--"DepartureDateTime" represents the date and time of departure.-->
<DepartureDateTime>2004-11-22T15:00:00</DepartureDateTime>
<!--"DepartureWindow" represents a window of time to search prior and post departure.-->
<!--Example: JR.DFW/S-OYLAS22NOV1500‡ZRD09001700-->
<DepartureWindow>09001700</DepartureWindow>

I've already tryied passing the number of seconds since DepartureDateTime and a unix timestamp without success. The error message it's:

Error response received. The error was: INVALID TIME WINDOW IN  Z FIELDS

Thanks

Answer:
You must specify time within window in DepartureDateTime
```
```
<ns1:DepartureDateTime>2009-01-03T15:00:00</ns1:DepartureDateTime>
 <ns1:DepartureWindow>11001559</ns1:DepartureWindow>
```
```
works fine for me


Question:
I'm programming in FORTRAN and C on an SGI running Irix 6.5, but this should be applicable to all Unix-like systems.  How do I find which library I need to link to my program when I get an "unresolved text symbol" link error?  Here's an example of what I'm seeing from the linker:

ld32: ERROR  33 Unresolved text symbol "ortho2_" -- first referenced by ./libfoo.a

Do I just have to know which libraries are required, or is there some tool or command that can help me figure this out?

Answer:
You can use the
```
nm
```
command to list the dynamic symbols from a shared library:
```
```
nm -D /lib/libc.so.6
```
```
and then
```
grep
```
for the symbol you are looking for.  Omit the -D for static libraries.  You can use this in a loop or with xargs to scan multiple libraries.
I usually just use google (assuming the symbol is from a publicly available library).


Question: Are delegates the same thing as callbacks?  Or are they related somehow?

Answer:
generically, a delegate is an object used to access a method external to the object owning the method, while a callback is a variable that holds a delegate
in C#, the terms are used interchangeably


Question:
Let's say I have a table:

i j
---
a 1
a 2
a 3
a 4
b 5
b 6
b 7
b 8
b 9

Obvoiusly SELECT a, GROUP_CONCAT(b SEPARATOR ',') GROUP BY a would give me

a  1,2,3,4
b  5,6,7,8,9

But what if I want to get only a LIMITED number of results, like 2, for example:

a  1,2
b  5,6

Any ideas?

Answer:
One solution would be to limit the rows in the group to the top two, before computing the aggregate.
```
```
SELECT t.i, GROUP_CONCAT(t.j)
FROM
  (SELECT t1.i, t1.j
   FROM mytable AS t1
     LEFT JOIN mytable AS t2
       ON (t1.i = t2.i AND t1.j >= t2.j)
   GROUP BY t1.i, t1.j
   HAVING COUNT(*) <= 2) AS t
GROUP BY t.i;
```
```
Another solution, if you know the values in
```
j
```
are of a fixed length, is to simply use
```
SUBSTRING()
```
on the result:
```
```
SELECT i, SUBSTRING( GROUP_CONCAT(j), 1, 3 )
FROM mytable
GROUP BY i;
```
```


Question: The basics have already been answered here. But is there a pre-built PHP lib doing the same as Lingua::Identify from CPAN?

Answer:
There's a PEAR package
```
Text_LanguageDetect
```
that I've used before. Get's the job done well enough. I'm not sure of any other libs that are more mature.


Question:
The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message:

You can either make the non static method static or make an instance of that class to use its properties.

What the reason behind this? Am not concern with the solution, rather the reason.

private java.util.List<String> someMethod(){
    /* Some Code */
    return someList;
}

public static void main(String[] strArgs){
     // The following statement causes the error.
    java.util.List<String> someList = someMethod();
}

Answer:
The method you are trying to call is an instance-level method; you do not have an instance.
```
static
```
methods belong to the class, non-
```
static
```
methods belong to instances of the class.


Question:
Say I have this simple form:

class ContactForm(forms.Form):
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

And I have a default value for one field but not the other.  So I set it up like this:

default_data = {'first_name','greg'}
form1=ContactForm(default_data)

However now when I go to display it, Django shows a validation error saying last_name is required:

print form1.as_table()

What is the correct way to do this?  Since this isn't data the user has submitted, just data I want to prefill.

Note: required=False will not work because I do want it required when the user submits the data. Just when I'm first showing the form on the page, I won't have a default value.

Answer:
From the django docs is this:
```
```
from django import forms
class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)
```
```
The "required=False" should produce the effect you're after.


Question:
How exactly using VB6 can I can call any Windows shell command as you would from the command-line?

For example, something as trivial as:

echo foo

Answer:
Shell and ShellExecute?
http://msdn.microsoft.com/en-us/library/aa242087.aspx
```
```
Dim RetVal
RetVal = Shell("C:\WINDOWS\CALC.EXE", 1)   ' Run Calculator.
```
```


Question:
I have a file in cvs that has Sticky Options set to -kk.  This replaces all cvs keywords with just the keyword name to facilitate diffs.   For example, $Author: Alex B$ becomes $Author$.

How do I disable the -kk behavior and get back to "normal" cvs where keywords are substituted in?   I've tried rm'ing the file and updating, I've tried cvs update -A and neither changes the flag.

Answer:
```
```
cvs update -kkv <filename>
```
```
will reset the sticky options to
```
keyword
```
and
```
value
```
Edit:
Corrected
```
checkout
```
to
```
update
```
, thanks to
Alex B
for the correction.


Question:
Is it expensive?

I am developing an HtmlHelper that renders directly to Response.Output in order to save unnecesary string creation and I need to choose between:

<% Validator.RenderClient(Response.Output); %>

and

<% Validator.RenderClient(); %>

and get the textWriter from HttpContext.Current.Response

Answer:
from reflector
```
```
public static HttpContext get_Current()
{
    return (ContextBase.Current as HttpContext);
}
```
```
calls ContextBase
which calls
```
```
public static object HostContext
{
    get
    {
        object hostContext =
          Thread.CurrentThread.GetIllogicalCallContext().HostContext;
        if (hostContext == null)
        {
            hostContext = GetLogicalCallContext().HostContext;
        }
        return hostContext;
    }
```
```
...
so there is a bit of threading 'stuff' going on; the specific I don't really know.


Question:
Does anyone know if it's possible to determine, using JavaScript, whether the user's browser allows checkboxes and radio buttons to be focused? In other words, whether you can tab to select them.

I can't just use browser detection to do this, because in at least one case (Safari), the user can turn the ability on and off.

Also in Safari, the focus() function is defined even when this ability is turned off, and it doesn't throw an error. So checking that function won't work.

Answer:
JavaScript cannot read the browser's settings. Doing so would be a security violation.
That being said, there is no way to test for something
not
happening if it requires the user's interaction without giving them explicit directions so to perform the testable action. So there is no passive way to test for the user having disabled tabbing.
It's rather like changing screen resolution in Windows. The user changes resolution and because VGA is passive there's no way for the OS to tell whether that change was successful unless the user performs an action. You need to ask them, set a timeout and assume it doesn't work if you get a negative result. You can't tell the difference between a negative result an no user interaction.


Question:
Writing the code for the user authentication portion of a web site (including account registration, logins, and password resets) is pretty simple, but what do you need to make a really good user authentication setup?  For example, I'd consider not storing plaintext passwords to be a bare minimum requirement for a web site, but that piece of advice seems to be largely transmitted by word of mouth, and plenty of sites still fail to follow it.

What is some other good advice or good requirements for the user auth portion of a web site?  For example, should usernames be user-selected, or should they be email addresses?  Any pitfalls for the user registration portion?  (CAPTCHAs are probably worth a whole topic by themselves.)  Any pitfalls for the password reset portion?  Anything else?

Edit:

Somewhat duplicated here : best-practices-for-login-pages

Answer:
On the username topic, it depends on how the username will be used on the site (beyond logging in). If your site is based on user generated content and you display the username with the content, allow the user to pick their own and make sure it is not an email address. Also, if the username will be displayed, I generally provide a bit of a warning on the registration form to let the user know, so they don't use their full name only to be angry later when it is displayed on the site.
I would recommend checking the availability and validity of a username through some type of Ajax call while the user is on the form. Having the form re-load with the password and password confirmation gone, just to have to think of a new username and re-input the data is a pain.
Other things to consider would be to enforce min/max lengths and some rules around passwords... don't make it difficult to sign up though. Also, accept special characters in the password. I have a couple of very strong passwords that I like to use and a lot of sites don't let me use them, so my account ends up being less secure than I would have made it on my own.
CAPTCHA is a good idea, just make sure it isn't super-difficult to figure out, that can be frustrating too.
There are a lot of things to consider and several options for each, but hopefully this will get you started.


Question:
Suppose I have #define foo in various header files. It may expand to some different things. I would like to know (when compiling a .cc file) when a #define is encountered, to what it will expand, it which file it is and where it got included from.

Is it possible? If not, are there any partial solutions that may help?

Feel free to add comments with clarification requests.

Edit: current answers seem to concentrate on the case when there is one #define and I just want to jump to definition or know what the definition is. That's the simple case and yes, your solutions work. But when I have the same #define in different files, and want to know which one kicks in first, none of these techniques is useful. Okay, I actually used #warning carefully to find the right place. But this requires much work.

Answer:
Use #warning. It's described
here
.


Question:
Does anyone have any experience migrating from one DBMS to another?  If you have done this, why did you do it? Features? Cost? Corporate Directive?

At times, I've worked with DBAs who insisted that we not use features specific to a DBMS (for example, CLR Stored Procedures in SQL Server.)  The DBAs point is, if we use these features, it will make it more difficult to switch to another DBMS if we have to.  But so far, I've never been asked to switch.

Answer:
In my opinion its silly not to take advantage of all the features of the db your using.  Changing DBMS regardless of how many features you use is going to be difficult.  There are minute differences between the systems (like some record Date and some record date and time) that will cause a huge headache to change.  There is no such thing of just switching to a new dbms.
From a business perspective there is a lot of work to be done.  Analysis on the new dbs to change to.  Figuring out the impact of changing dbs on the new system.  Having development change the existing systems, testing the changes etc.  The list goes on and on.  Making a switch like that on an enterprise system takes months if not years.  The last place I worked had to change dbs, and it took us a solid 11 months to do it and about 2 million dollars for consultants, hardware, software, and employee salaries.  It's a big deal.  If someone is saying not to use features, because that "may" happen someday and it'll be easier to do,  Most likely, that person is off their rocker.  The extra amount of time and money it will take to convert those features is minuscule compared to everything else (most likely).  IMO if it will save time and money now buy using those features, then that is the best course of action.
We did it because the systems we had running on the old dbms were too big.  There was too much data, and we needed something a lot more powerful.  Plus, it wasn't supported anymore.


Question:
I'm working on an online tool for students in my faculty to calculate their final grade for their degrees, and for a while I've had little problems. Students seem to like using the new UI and I've suffered no criticism for a while. Now, I need to add some functionality to the program, meaning the UI will have to chance slightly, but in some very noticeable places.

After watching the whole New Facebook thing kick off, along with the slating of applications with bad UI here on SO and the Ribbon on MS Office receiving mixed reviews I've wondered to myself whether a UI should ever really be changed if users seem to like it. Should a UI be updated after a number of years to keep users interested/be more efficient? Should features be held back in sake of a clean UI?

Answer: Ideally when you first design your UI you create something flexible enough to add any feature you want in the future.  In the real world, this is seldom the case.  I would say UI updates should be slow and incremental if at all possible (that was the real problem with the facebook change, one big change all of a sudden), and if not then people should be given plenty of notice of the change, and while you're changing you should be sure to plan for future additions so as to not annoy your user base more often than absolutely necessary.


Question: How do I get the HTTP status code (eg 200 or 500) after calling curl_easy_perform?

Answer:
http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html
```
CURLINFO_RESPONSE_CODE

Pass a pointer to a long to receive the last received HTTP or FTP code. This
option was known as CURLINFO_HTTP_CODE in libcurl 7.10.7 and earlier. This
will be zero if no server response code has been received. Note that a
proxy's CONNECT response should be read with CURLINFO_HTTP_CONNECTCODE
and not this.
```
```
```
curl_code = curl_easy_perform (session);
long http_code = 0;
curl_easy_getinfo (session, CURLINFO_RESPONSE_CODE, &http_code);
if (http_code == 200 && curl_code != CURLE_ABORTED_BY_CALLBACK)
{
         //Succeeded
}
else
{
         //Failed
}
```
```


Question:
The JUnit framework contains 2 Assert classes (in different packages, obviously) and the methods on each appear to be very similar. Can anybody explain why this is?

The classes I'm referring to are: junit.framework.Assert and org.junit.Assert.

Answer:
I believe they are refactoring from
```
junit.framework
```
to
```
org.junit
```
and
```
junit.framework.Assert
```
is maintained for backwards compatibility.


Question:
I need to connect to Outlook through ASP.NET web application using user credentials. What are my options?

FYI: User logs into the web site by using Windows Authentication. I'm working with Outlook 2003.

Answer:
I'm going to do something similar, and I don't see a reason it wouldn't work: write an
Outlook Addin
that uses
object remoting
to communicate with whatever other services or tools you're working on.  Since it's an ASP.NET application, maybe you want to use a web service instead of object remoting.
Do you want the ASP.NET application to start Outlook if it's not already running?
Is one Outlook process going to be shared by many users, or do you want to connect to user-specific Outlook processes?  Do you want the ASP.NET application to act as a server that Outlook tries to connect to, or the other way around?
If the edge cases are complicated, you could try writing a Windows Service to act as an intermediary or gateway between the two e.g. a service that runs on each Outlook machine and starts Outlook on demand.


Question:
I am new to C#. I wanted to do a simple program with some type of loops.
I wanted my program to loop through the numbers that the user enters and if it is less than a number then write keep guessing,but once they enter the number 25 i wanted it to say Merry Christmas..  Please Help

int number;

do
{
    Console.WriteLine("Guess a number between 20 through 25");
    number = int.Parse(Console.ReadLine());
}  while (number < 25);

C# Beginner

Answer:
```
```
int number;

do
{
    Console.WriteLine("Guess a number between 20 through 25");
    number = int.Parse(Console.ReadLine());
} while (number < 25);

if (number == 25)
    Console.WriteLine("Merry Christmas");
```
```


Question: I'm creating an asp.net app with just some lite data access from xml files.  However, I need to be able to authenticate administrative users (via forms) to manage that data.  I don't want to stand up a sql db just for authentication purposes.  I'd like to use xml, but not sure about security with that.  Any suggestions?  Custom role provider?  MyOpenID?

Answer:
```
```
int number;

do
{
    Console.WriteLine("Guess a number between 20 through 25");
    number = int.Parse(Console.ReadLine());
} while (number < 25);

if (number == 25)
    Console.WriteLine("Merry Christmas");
```
```


Question: Are there any things to be careful about when defining the method_missing method in Ruby?  I'm wondering whether there are some not-so-obvious interactions from inheritance, exception throwing, performance, or anything else.

Answer:
A somewhat obvious one: always redefine
```
respond_to?
```
if you redefine
```
method_missing
```
.  If
```
method_missing(:sym)
```
works,
```
respond_to?(:sym)
```
should always return true.  There are many libraries that rely on this.
Later:
An example:
```
```
# Wrap a Foo; don't expose the internal guts.
# Pass any method that starts with 'a' on to the
# Foo.
class FooWrapper
  def initialize(foo)
    @foo = foo
  end
  def some_method_that_doesnt_start_with_a
    'bar'
  end
  def a_method_that_does_start_with_a
    'baz'
  end
  def respond_to?(sym, include_private = false)
    pass_sym_to_foo?(sym) || super(sym, include_private)
  end
  def method_missing(sym, *args, &block)
    return foo.call(sym, *args, &block) if pass_sym_to_foo?(sym)
    super(sym, *args, &block)
  end
  private
  def pass_sym_to_foo?(sym)
    sym.to_s =~ /^a/ && @foo.respond_to?(sym)
  end
end

class Foo
  def argh
    'argh'
  end
  def blech
    'blech'
  end
end

w = FooWrapper.new(Foo.new)

w.respond_to?(:some_method_that_doesnt_start_with_a)
# => true
w.some_method_that_doesnt_start_with_a
# => 'bar'

w.respond_to?(:a_method_that_does_start_with_a)
# => true
w.a_method_that_does_start_with_a
# => 'baz'

w.respond_to?(:argh)
# => true
w.argh
# => 'argh'

w.respond_to?(:blech)
# => false
w.blech
# NoMethodError

w.respond_to?(:glem!)
# => false
w.glem!
# NoMethodError

w.respond_to?(:apples?)
w.apples?
# NoMethodError
```
```


Question:
  ArrayList filters = new ArrayList();
  filters.Add(new string[] { "Name", "Equals", "John" });

  ObjectDataSource1.SelectParameters.Add("AppliedFilters",
           string.Join(",",(string[])filters.ToArray(typeof(string))));

Am trying to add a parameter to my object data source which is bound to my select method which should accept a string[]. But as the SelectParameters.Add takes in (string,string) or the other 3 overloads which do not seem to function for me correctly.

The select method accepts a string param though i prefer it accept a string[] or arraylist, but for now I can live with accepting a string which i should convert back to string[]

Resolution:
followed this article link text

Closed as duplicate of the question referenced above.

Answer:
A somewhat obvious one: always redefine
```
respond_to?
```
if you redefine
```
method_missing
```
.  If
```
method_missing(:sym)
```
works,
```
respond_to?(:sym)
```
should always return true.  There are many libraries that rely on this.
Later:
An example:
```
```
# Wrap a Foo; don't expose the internal guts.
# Pass any method that starts with 'a' on to the
# Foo.
class FooWrapper
  def initialize(foo)
    @foo = foo
  end
  def some_method_that_doesnt_start_with_a
    'bar'
  end
  def a_method_that_does_start_with_a
    'baz'
  end
  def respond_to?(sym, include_private = false)
    pass_sym_to_foo?(sym) || super(sym, include_private)
  end
  def method_missing(sym, *args, &block)
    return foo.call(sym, *args, &block) if pass_sym_to_foo?(sym)
    super(sym, *args, &block)
  end
  private
  def pass_sym_to_foo?(sym)
    sym.to_s =~ /^a/ && @foo.respond_to?(sym)
  end
end

class Foo
  def argh
    'argh'
  end
  def blech
    'blech'
  end
end

w = FooWrapper.new(Foo.new)

w.respond_to?(:some_method_that_doesnt_start_with_a)
# => true
w.some_method_that_doesnt_start_with_a
# => 'bar'

w.respond_to?(:a_method_that_does_start_with_a)
# => true
w.a_method_that_does_start_with_a
# => 'baz'

w.respond_to?(:argh)
# => true
w.argh
# => 'argh'

w.respond_to?(:blech)
# => false
w.blech
# NoMethodError

w.respond_to?(:glem!)
# => false
w.glem!
# NoMethodError

w.respond_to?(:apples?)
w.apples?
# NoMethodError
```
```


Question:
I have a form that contains a bunch of checkboxes.  Before submitting the form, I'd like to grab the values of the checkboxes and stick them into a text field, then submit that.

So I might have:
   Red
   Orange
X  Yellow
   Blue
X  Green

And I'd like my textfield to end up with the content "Yellow, Green" .

This doesn't seem too complicated, but I am totally out of my league.  I already use jQuery for a few other things so I have the framework ready, if that makes it easer.

Thanks for any advice --

Answer:
First hack at it (without testing):
```
```
var serializedCheckboxes = '';
$("input type='checkbox'").each(function() {
 if($(this).attr("checked")) {
  serializedCheckboxes += $(this).attr("value") + ',';
 }
});

$("input name='allchecks').attr("value", serializedCheckboxes);
```
```


Question: I am trying to use the Event Log to write some debug information and I can't make it works. It complains about not being able to find the Event Source. Do I have to install something on the OS?

Answer:
Here a code that I modified from one of our application. This might help you to start with the creation.
```
```
System.Diagnostics.EventLog eventLog1 = new System.Diagnostics.EventLog();
string eventLogName = "StackOverFlowEventName";
string eventLogSource = "StackOverFlowWebsite";

//This code HERE will create the Event for you
if (!System.Diagnostics.EventLog.SourceExists(eventLogSource))
{
    System.Diagnostics.EventLog.CreateEventSource(eventLogSource, eventLogName);
}

eventLog1.Source = eventLogSource;
eventLog1.Log = eventLogName;
eventLog1.WriteEntry("This is a test");
```
```


Question:
I'm trying to get the following SQL statement to work:

UPDATE myschema.tableA update_tableA
   SET field_id =
   ( SELECT src.field_id
         FROM myschema.srcTable src
         INNER JOIN myschema.tableB tableB ON
            update_tableA.id = tableB.id
            AND SDO_ANYINTERACT( tableB.shape, src.shape ) = 'TRUE' );

When I run this statement, I get the following error:

ORA-00904: "UPDATE_TABLEA"."ID": invalid identifier

Can I not use a variable scoped outside of the nested select within the nested select?  Any thoughts?

P.S. The identifier is indeed valid in the database table.  The problem appears to be scope, but I want to make sure that is indeed an issue.

Answer:
Looking at the SQL above, here is what I am thinking
1) myschema.tableA doesn't have ID column (it could be field_id)
2) The SELECT doesn't seem to provide a join condition
```
SELECT src.field_id
         FROM myschema.srcTable src
         INNER JOIN myschema.tableB tableB ON
```
Where is the condition to JOIN src with tableB?


Question:
It has to be simple, here's my CSS:

.progressImage
{
  position:relative;
  top:50%;
}

.progressPanel
{
height:100%;
width:100%;
text-align:center;
display:none;
}

<asp:Panel ID="pnlProgress" runat="server" CssClass="progressPanel">
<asp:Image ID="Image1" runat="server" CssClass="progressImage" ImageUrl="~/Images/Icons/loading.gif" />
</asp:Panel>

I toggle panel display depending on user action.

Works great in FireFox, but shows up at the top of the page in Safari.

p.s. "vertical-align:middle;" doesn't work either.

p.p.s. setting "position:relative;" on the panel doesn't work, setting "position:relative;" on the panel and "position:absolute;" on the image breaks it in FF and does nothing in Safari

THIS WORKED:

.progressPanel
{
  height:100%;
  width:100%;
  position:relative;
}

.progressImage
{
  position:absolute;
  top:50%;
  left:50%;
}

Answer:
Ensure the parents container is also set to position: relative and has a height specified, without it the position wont work correctly.
```
```
.progressPanel
{
    height:100%;
    width:100%;
    text-align:center;
    display:none;
    position: relative;
}
```
```
alternatively, why not set the background property of the panel to your gif?
```
```
background: url('path/to/image.gif') no-repeat center middle;
```
```
That will always be centered.


Question:
I need to store a tree data structure in my database, for which I plan on using django-treebeard or possibly django-mptt.  My source of confusion is that each node could be one of three different possible types: root nodes will always be a type A entity, leaf nodes a type C entity, and anything in between will be a type B entity.  I would like to know the best way to model this situation.

update:  I first tried model inheritance, and I think that this could be the best way to go. Unfortunately django-treebeard's public API isn't really designed to handle this.  I ended up getting it to work with GenericForeignKey.  Thank you very much for the answers.

Answer:
Your three types are probably easiest handled as FK associations with the fundamental tree.
The tree can be homogenous -- class
```
MyNode
```
is a direct subclass of
```
treebeard.Node
```
.  Your node can have a flag (Root, Middle, Leaf) and FK's for A or B or C.  This allows you some SQL-like flexibility in querying MyNode instance.
This allows your tree to grow.  A node can start as a type C (leaf) and then morph to a type B (intermediate).  You change the status, and change the FK's.
The alternative is a bit more complex.
```
```
class MyA( treebeard.Node ):
    pass

class MyB( treebeard.Node ):
    pass

class MyC( treebeard.Node ):
    pass
```
```
In this case, you can't "morph" a node.  When a node starts as a
```
MyC
```
, and gets children, you have to remove the original
```
MyC
```
instance, and replace it with a
```
MyB
```
version that has a new node as a child.  This isn't impossible, but it can be painful.


Question:
I have an HTML document that is using  to embed a control.  In some cases, IE fails to load the control in the  tag and loads my alternative text.

Only problem... I don't know why it is failing.  It doesn't show up as an error in the exclamation in the lower-left.  I overrode the window.onerror method, but that didn't get fired.  I see nothing in the event log.

How do I get any type of feedback to figure out what my problem is?  Can IE go into a "verbose mode"?  Is there some magic error log somewhere telling me why my object isn't loading into IE?

Thanks,
Brian

Answer:
Often a failure in the object tag won't show up as an IE error, since the object is running from its own plugin codebase, not the browser's interpreter.
Are you loading this file locally? Or is it a hosted page? IE has different permissions for execution of objects. What is the type of the object? A code snippet would also help.
You could also use something like Charles Web Debugging proxy to see if the browser is even attempting to connect to the filename. If it's not, you know it's a problem with the code, but if it is making the call, you might be able to see what's returned in the HTTP headers - a server error (404, 500?), blankness, etc.


Question:
I am using the Html.TextBox helper to create textboxes.  I want to set attributes on the textbox, which I understand is done using the following overload:

Html.TextBox (string name, object value, object htmlAttributes)

However, I want to maintain the functionality where the HTML helper automatically uses the value from either ViewData or ViewData.Model and I do not see a way to just specify the name and the htmlAttributes.  Is this possible?

Answer:
[EDIT]  After looking at the
source code
, it appears that all you need to do is specify the value as null in the signature that takes a name, value, and htmlAttributes.  If the value is null, it will attempt to use the value from the ViewData.
```
```
Html.TextBox( "name", null, new { @class = "css-class" } );
```
```


Question: What is the best way to get the TAPI version and additional TAPI information with C#?

Answer:
Interop.
Use the
lpdwAPIVersion
parameter of the lineInitializeEx function.
http://msdn.microsoft.com/en-us/library/ms735983(VS.85).aspx
"Upon successful completion of this request, this location is filled with the highest API version supported by TAPI, thereby allowing the application to detect and adapt to having been installed on a system with a different version of TAPI."
You're going to have to start plugging away with Interop calls sooner or later when you're programming TAPI.


Question:
I am about to start a web project and have been working almost exclusively with a LAMP stack for the past 5 years.  I would like to build something larger and more scalable and hence have been looking into Java EE.  The division of logic between JSP and EJB seems ideal for what I want to do.

Can anyone recommend resources for getting familiar with Java EE?  And perhaps if anyone knows of technologies that are more scalable than PHP that I should consider as well, I'm all ears.

Thanks a lot!

Answer:
I think given your background in Linux and MySQL, the best place to start would be Java's
Servlet API
.  Java Servlets are the basic unit in Java EE for handling HTTP requests and responses on the server side.  In most of the Java EE work that I have done, servlets cover about 50% of development.  The other 50% is database development, which you seem to have done in the past.
For your servlet container, I would recommend
Apache Tomcat
.  Tomcat has a robust development community contributing regularly, and is used at the heart of several enterprise application server solutions, such as JBoss.
Good luck in your project!


Question:
I have only recently started working with the MVC approach, so I suppose this is an easy one for you gurus here:

Where do I put access control?

In a view? I don't want to have any logic besides switches and flags in my templates, so that sounds like the least viable option

In the model? Should each business object decide what data it will reveal about itself based on who's asking?

In the controller? That's where I have it now but it makes it hard to keep business rules consistent

Or is there another option?

Answer:
This will depend on what framework you're using as that and the language will dictate a lot of the tools you have available to you.
From a high level, you should have access security configured at points-of-entry. And you should double-check access security at every level that could be considered autonomous or reused from multiple parts of your application (who knows if security was checked by your co-worker's portal that uses your logic layer? etc.). The other thing to worry about is data security, and that belongs as close to your data as possible (so, yes to your #2 above, but understand that it's separate).
This is akin to the difference between application logic and domain logic, which I'm fond of talking about. If there is any logic that is specific to one particular application (web app compared to a windows service, or whatever) then that logic should be defined in that application only. If some logic crosses the boundary between applications (is reusable between applications) then it qualifies as domain logic and should be defined in your model. Your applications can make use of domain logic, but they should not own it.


Question:
I'm having an issue with JQuery and Safari (Windows Version).  The code works on FF/IE7/Chrome but not Safari.

I have a simple <li> that has a <div> embedded in to - clicking the <li> should expose the hidden div, but not in Safari.

The HTML:

<ul>
<li>something</li>
<li>something2</li>
<li class="more">
        <a href="" class="moreFacetsLink">Click to see more options</a>
        <div class="moreFacets">bunch of text</div>
</li>
</ul>

Here is the JQuery code:

     $('.moreFacetsLink').click(function () {

        $(this).siblings('div').toggle();
     });

Any thoughts as to what may be going on here?  Again - this seems to work on all other browsers!

I'm a newbie when it comes to JQuery.

Thanks!

Answer:
How accurate is your HTML pasting?
You never closed your "moreFacetsLink" anchor tag, which probably makes Safari think that it was implicitly closed, and the "bunch of text" is surrounded by an additional, HREF-less Class-less Unclosed anchor tag... evidenced by the fact that this:
```
```
$(".moreFacetsLink").click(function () {
    $(this).siblings("a").children("div").toggle();
});
```
```
... does what you want with your submitted markup.
Close off your anchor tag properly (bonus points for including the href attribute) and you should be good to go.


Question:
I am trying to create a delegate protocol for a custom UIView. Here is my first attempt:

@protocol FunViewDelegate
@optional
- (void) funViewDidInitialize:(FunView *)funView;
@end

@interface FunView : UIView {
@private
}

@property(nonatomic, assign) id<FunViewDelegate> delegate;

@end

This doesn't work because the FunView interface has not been declared at the time of the FunViewDelegate declaration. I have tried adding a prototype ala C++ before the @protocol:

@interface FunView;

But this just drives the compiler nuts. How am I supposed to do this?

Answer:
It would seem that you can forward declare protocols:
```
```
@protocol FunViewDelegate;

@interface FunView : UIView {
@private
    id<FunViewDelegate> delegate;
}
@property(nonatomic, assign) id<FunViewDelegate> delegate;
@end

@protocol FunViewDelegate
@optional
- (void) funViewDidInitialize:(FunView *)funView;
@end
```
```


Question: I have a folder in NTFS that contains tens of thousands of files. I've deleted all files in that folder, save 1. I ran contig.exe to defragment that folder so now it's in 1 fragment only. However, the size of that folder is still 8MB in size. This implies that there's a lot of gap in the index. Why is that? If I delete that one file, the size of the index automatically goes to zero. My guess is because it gets collapsed into the MFT. Is there any way to get NTFS to truly defragment the index file by defragmenting it based on the content of the file? Any API that you're aware of? Contig.exe only defragment the physical file.

Answer:
I guess this is one way in which NTFS is just like almost every other FS - none of them seem to like shrinking directories.
So you should apply a high-tech method that involves using that advanced language, "BAT" :)
collapse.bat
```
```
REM Invoke as "collapse dirname"
ren dirname dirname.old
mkdir dirname
cd dirname.old
move * ../dirname/
cd ..
rmdir dirname.old
```
```


Question:
Is there a simple attribute or data contract that I can assign to a function parameter that prevents null from being passed in C#/.NET?  Ideally this would also check at compile time to make sure the literal null isn't being used anywhere for it and at run-time throw ArgumentNullException.

Currently I write something like ...

if (null == arg)
  throw new ArgumentNullException("arg");

... for every argument that I expect to not be null.

On the same note, is there an opposite to Nullable<> whereby the following would fail:

NonNullable<string> s = null; // throw some kind of exception

Answer:
There's nothing available at compile-time, unfortunately.
I have a bit of a
hacky solution
which I posted on my blog recently, which uses a new struct and conversions.
In .NET 4.0 with the
Code Contracts
stuff, life will be a lot nicer. It would still be quite nice to have actual language syntax and support around non-nullability, but the code contracts will help a lot.
I also have an extension method in
MiscUtil
called ThrowIfNull which makes it a bit simpler.
One final point - any reason for using "
```
if (null == arg)
```
" instead of "
```
if (arg == null)
```
"? I find the latter easier to read, and the problem the former solves in C doesn't apply to C#.


Question:
I am writing a Clone method using reflection. How do I detect that a property is an indexed property using reflection?  For example:

public string[] Items
{
   get;
   set;
}

My method so far:

public static T Clone<T>(T from, List<string> propertiesToIgnore) where T : new()
{
    T to = new T();

    Type myType = from.GetType();

    PropertyInfo[] myProperties = myType.GetProperties();

    for (int i = 0; i < myProperties.Length; i++)
    {
        if (myProperties[i].CanWrite && !propertiesToIgnore.Contains(myProperties[i].Name))
        {
            myProperties[i].SetValue(to,myProperties[i].GetValue(from,null),null);
        }
    }

    return to;
}

Answer:
```
```
if (propertyInfo.GetIndexParameters().Length > 0)
{
    // Property is an indexer
}
```
```


Question:
I am looking for the VB.NET equivalent of

var strings = new string[] {"abc", "def", "ghi"};

Answer:
```
```
Dim strings As String() = New String() {"abc", "def", "ghi"}
```
```


Question: In a Windows program, what is the canonical way to parse the command line obtained from GetCommandLine into multiple arguments, similar to the argv array in Unix?  It seems that CommandLineToArgvW does this for a Unicode command line, but I can't find a non-Unicode equivalent.  Should I be using Unicode or not?  If not, how do I parse the command line?

Answer:
```
CommandLineToArgvW()
```
is in shell32.dll.  I'd guessthat the Shell developers created the function for their own use, and it was made public either because someone decided that 3rd party devs would find it useful or because some court action made them do it.
Since the Shell developers only ever needed a Unicode version that's all they ever wrote.  It would be fairly simple to write an ANSI wrapper for the function that converts the ANSI to Unicode, calls the function and converts the Unicode results to ANSI (and if Shell32.dll ever provided an ANSI variant of this API, that's probably exactly what would do).


Question:
I have an XSD file that is encoded in UTF-8, and any text editor I run it through doesn't show any character at the beginning of the file, but when I pull it up in Visual Studio's debugger, I clearly see an empty box in front of the file.

I also get the error:

Data at the root level is invalid. Line 1, position 1.

Anyone know what this is?

Update: Edited post to qualify type of file. It's an XSD file created by Microsoft's XSD creator.

Answer:
It turns out, the answer is that what I'm seeing is a
Byte Order Mark
, which is a character that tells whatever is loading the document what it is encoded in.  In my case, it's encoded in utf-8, so the corresponding BOM was
```
EF BB BF
```
, as shown below.  To remove it, I opened it up in
Notepad++
and clicked on "Encode in UTF-8 without BOM", as shown below:
.
To actually see the BOM, I had to open it up in
TextPad
in Binary mode:, and conducted a
Google search for "
```
EF BB BF
```
"
.
It took me about 8 hours to find out this was what was causing it, so I thought I'd share this with everyone.
Update
: If I had read Joel Spolsky's blog post:
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
, then I might not have had this problem.


Question:
When implementing the ViewModel in a Model-View-ViewModel architecture WPF application there seem to be two major choices how to make it databindable. I have seen implementations that use DependencyProperty for properties the View is going to bind against and I have seen the ViewModel implementing INotifyPropertyChanged instead.

My question is when should I prefer one over the other? Are there any performance differences? Is it really a good idea to give the ViewModel dependencies to WPF? What else do I need to consider when make the design decision?

Answer:
The choice is totally based on your business logic and UI abstraction level. If you dont want a good separation then DP will work for you.
DependencyProperties will be applicable mainly at the VisualElements level so it won't be good idea if we create lot of DPs for each of our business requirements. Also there is a greater cost for DP than a INotifyPropertyChanged. When you design a WPF/Silverlight try to design UI and ViewModel totally separate so that at any point of time we can change the Layout and UI controls (Based on theme and Styles)
Refer this post also -
https://stackoverflow.com/questions/275098/what-applications-could-i-study-to-understand-datamodel-view-viewmodel
. The link has a lot of reference to Model-View-ViewModel pattern, which is very relevant to this discussion.


Question:
In the Windows registry, how does CurrentControlSet differ from
ControlSet001 and ControlSet002? Which should be set when installing for all
users?

We are trying to add an environment variable for all users. Is this correct?

HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Envinronment

Answer:
Yes, you only need to update the
```
CurrentControlSet
```
key...
```
ControlSet001
```
and
```
ControlSet002
```
are alternating backups of
```
CurrentControlSet
```
, you don't need to update them.
Edit: As K noted,
```
CurrentControlSet
```
is an alternating symbolic link to either
```
ControlSet001
```
or
```
ControlSet002
```
. The other key is kept as a backup for the
Load Last Known Good Configuration boot option.
Edit 2: See Microsoft KB Article 100010: What are Control Sets? What is CurrentControlSet?
Original page link broken
, see
archive.org backup page
instead.


Question:
I have a simple WPF application with a menu.  I need to add menu items dynamically at runtime.  When I simply create a new menu item, and add it onto its parent MenuItem, it does not display in the menu, regardless of if UpdateLayout is called.

What must happen to allow a menu to have additional items dynamically added at runtime?

Note: the following code doesn't work.

            MenuItem mi = new MenuItem();
            mi.Header = "Item to add";
            mi.Visibility = Visibility.Visible;
            //addTest is a menuitem that exists in the forms defined menu
            addTest.Items.Add(mi);
            addTest.UpdateLayout();

At the moment, the default menu items are defined in the xaml file.  I want to add additional menu items onto this menu and its existing menu items.  However, as stated, the above code does nothing.

Answer:
```
```
//Add to main menu
MenuItem newMenuItem1 = new MenuItem();
newMenuItem1.Header = "Test 123";
this.MainMenu.Items.Add(newMenuItem1);

//Add to a sub item
MenuItem newMenuItem2 = new MenuItem();
MenuItem newExistMenuItem = (MenuItem)this.MainMenu.Items[0];
newMenuItem2.Header = "Test 456";
newExistMenuItem.Items.Add(newMenuItem2);
```
```


Question: I moved a bunch of projects to Solution Folders to chop up our list of projects into manageable folders, now each of the folders projects are not in alphabetical order. This only occurs on machines other than my own. Any ideas how to alleviate this?

Answer:
See the following bug information on MS Connect:
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=312252&wa=wsignin1.0
To summarize:
"
The order they show up in solution explorer is the order in which they were written to the solution file.   However, if the folder is collapsed on startup it will be sorted when you expand it.
"
Therefore, the fast solution would be to hand edit the solution file and put the projects in the order you wish.


Question:
I am currently looking at the "unload" event of a window to try to determine how the "unload" event was triggered, but am having little success. Is there a way to determine how the javascript event was triggered?

Page Refresh

Back Button (or navigate away from the page)

Closing the Browser

Essentially I need to execute some code only when the browser window is being closed, not refreshed or navigated away from.

Purpose: When a customer does an update of our software, the update will redirect their first Internet request to an offer page. There is a button for a "Do Not Bother" option, but some users will simply close their browser. Upon closing the browser, I need to duplicate the "Do Not Bother" functionality so the user no longer gets redirected to the offer page. Simply attaching to the "unload" event will not work due to the different ways of leaving a page.

Answer:
No, and if there was it would be browser dependent.
What kind of code are you trying to run when the user closes the page?
Is it to logout the user?
Then the user would not be logged out if the browser crashes or the network connection breaks (and probably not if the computer goes to sleep/hibernation mode).
If it is for logout-purposes you should probably use a timestamp variable at the server that gets updated with every request (or use a ajax-ping), and logout the user if it hasn't been seen for a specified time.
Update: Found
this answer
here at stackoverflow.


Question:
I want a query that returns a list of all the (user) stored procedures in a database by name, with the number of lines of code for each one.

i.e.

sp_name     lines_of_code
--------    -------------
DoStuff1    120
DoStuff2    50
DoStuff3    30

Any ideas how to do this?

Answer:
```
```
select t.sp_name, sum(t.lines_of_code) - 1 as lines_ofcode, t.type_desc
from
(
    select o.name as sp_name,
    (len(c.text) - len(replace(c.text, char(10), ''))) as lines_of_code,
    case when o.xtype = 'P' then 'Stored Procedure'
    when o.xtype in ('FN', 'IF', 'TF') then 'Function'
    end as type_desc
    from sysobjects o
    inner join syscomments c
    on c.id = o.id
    where o.xtype in ('P', 'FN', 'IF', 'TF')
    and o.category = 0
    and o.name not in ('fn_diagramobjects', 'sp_alterdiagram', 'sp_creatediagram', 'sp_dropdiagram', 'sp_helpdiagramdefinition', 'sp_helpdiagrams', 'sp_renamediagram', 'sp_upgraddiagrams', 'sysdiagrams')
) t
group by t.sp_name, t.type_desc
order by 1
```
```
Edited so it should also now work in SQL Server 2000- 2008 and to exclude Database Diagram-related sprocs and funcs (which appear like user created objects).


Question:
I want to store a very large amount of vector data on a server and only poll the parts I need at a given point...

This shouldn't be a problem.

Is there any way to take a vector file like an svg file and import it into a database? I could always write an svg parser to import it into my database, but is there any standard way of doing this or storing vector data in a database ?

Answer:
I don't think you can call it a standard, but here is an interesting link to an academic paper:
A Design and Implementation of Spatial Database Based on XML-SVG
Abstract:
SVG, which stands for Scalable Vector Graphics, is an open standard in text that makes it possible to represent graphic information in compact, portable form and mostly faces on publishing the spatial vector graphics in network environment. In practice, it's impossible to avoid a great capacity of spatial data processing, which had made SVG document is too big to be implemented during publishing on the Internet.
It is slowed down the executing speed of the system on client side and is weaken its advantages and superiority. Such SVG database has been proposed as the solution for managing all the graphics and its attributes in a Web server. SVG document is mapped into SVG database that works as a buffer in the server. The issuance efficiency has been improved to a great extent.


Question: Using strictly SQL (no PHP or anything else), is it possible to create a table and insert default data into that table only if that table doesn't exist?

Answer:
Use the CREATE TABLE ... SELECT format:
```
create table if not exists tablename as
select * from defaultdata;
```


Question:
How can I tell the preprocessor not to replace a specific macro?

The specific problem is the following: Windows header files define the GetMessage macro.

My C++ header files with my API have a GetMessage method. I do not want to rename my method. But when using the API on Windows, including windows.h replaces my GetMessage method call with GetMessageA.

Answer:
have you tried just doing an
```
#undef GetMessage
```
or even
```
#ifdef GetMessage
#undef GetMessage
#endif
```
and then calling the windows GetMessageA or GetMessageW directly, whichever is appropriate.
you should know if you are using char* for wchar_t8..
(thanks don.neufeld)
Brian also says that
Jus some useful info, you can also use the #pragma push_macro/pop_macro to push and pop macro definitions. This is great if you want to override a macro definition in a block of code:
```
```
#pragma push_macro("GetMessage")
#undef GetMessage

// Your GetMessage usage/definition here

#pragma pop_macro("GetMessage")
```
```
I suspect this is an MS specific feature though, so keep that in mind.


Question:
When you assign a date to a named SQL parameter Hibernate automatically converts it to GMT time. How do you make it use the current server timezone for all dates?

Lets say you have a query:

Query q = session.createQuery("from Table where date_field < :now");
q.setDate("now", new java.util.Date());

"now" will be set to GMT time, while "new Date()" gets your current server time.

Thanks.

Answer:
Hibernate is ignorant of timezones. Any timezone conversion should be done prior to executing the query.
E.g., if your database server is set to CST, but the user is on EST, you'll need to add 1 hour to any timestamps which are the input to a query.


Question:
I am trying to design a location lookup in which the user can specify a location to any desired level of accuracy. eg. one of Country, State, City, Borough etc,

I have a used a common location table, which will then be used in a lookup with the table name selected dynamically, but was wondering if there is a feasible alternative way to do this.

alt text http://img386.imageshack.us/img386/3842/locationschemadh6.png

Edit The hierarchical table looks like the way to go. Thanks for the tip.

Answer:
You might consider something like:
```
```
locations
  id int
  parentId int
  name varchar(45)
```
```
From this perspective you could load any type of location with any level depth.


Question:
I embedded a swf in my html page, but I would like it to swap to another swf when I clicked on a button in html. I used swfobject.js to embed the swf, and I use prototype to write the javascript. I thought I can just do this

$('movie').value = 'swf/bhts.swf';
alert($('movie').value);

the value did change to swf/bhts.swf, but it is still playing the original swf file...
this is the code I use to embed swf

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="530" height="298" id="flashcontent">
<param id="movie" name="movie" value="swf/trailer.swf" />
</object>

thanks.

Answer:
Using swfObject:
```
```
<div id='flashContent'>
</div>

<script type='text/javascript'>
    // Setup your initial flash
    var so = new SwfObject(.....);
    so.write ('flashContent');

    // Some event handler
    someElement.onclick = function ()
    {
         // Load up the new SWF
         so = new swfObject(....);
         so.write('flashContent');
    }
</script>
```
```


Question:
I can't seem to retrieve the AlternateView from System.Net.Mail.AlternateView.

I have an application that is pulling email via POP3.  I understand how to create an alternate view for sending, but how does one select the alternate view when looking at the email.  I've have the received email as a System.Net.MailMessage object so I can easily pull out the body, encoding, subject line, etc.  I can see the AlternateViews, that is, I can see that the count is 2 but want to extract something other than the HTML that is currently returned when I request the body.

Hope this makes some amount of sense and that someone can shed some light on this.  In the end, I'm looking to pull the plaintext out, instead of the HTML and would rather not parse it myself.

Answer:
Its not immediately possible to parse an email with the classes available in the System.Net.Mail namespace; you either need to create your own MIME parser, or use a third party library instead.
This great Codeproject article by Peter Huber SG, entitled
'POP3 Email Client with full MIME Support (.NET 2.0)'
will give you an understanding of how MIME processing can be implemented, and the related RFC specification articles.
You can use the Codeproject article as a start for writing your own parser, or appraise a library like
SharpMimeTools
, which is an open source library for parsing and decoding MIME emails.
http://anmar.eu.org/projects/sharpmimetools/
Hope this helps!


Question:
Suppose I have a page that I am writing a javascript plugin for on the domain first.com.  The javascript plugin injects an iframe pointing to a login page (of domain second.com) into the first.com page and displays it as a popup so that the user can login.

Is there anyway for me to hide/close the iframe after the user logs in with it?  I can inject any javascript necessary into the first.com page and I control both the client and server side code on the login page within the iframe.

The main issue is that the iframe cannot access it's parent window to hide itself and the parent window cannot see any changes made in the contents of the iframe because of the same origin policy.  Is there anyway around this or should I just lose the iframe idea and instead open a new window?

Answer:
I think the issue you're running into is the browser stopping the cross-domain communication from happening.  There is a way to
sign your javascript
but it is pretty much breaking the browser security model and isn't suggested unless absolutely necessary.
Is there any way that the login form is based on URL submition?  You could create a simple sign in form and use AJAX to get your response back to ensure a successful login.  This solution depends on having a RESTful login and again, I'm not sure about the implementation of your second.com.
If you're wondering about how to use the ajax to submit a form, I'd check
this
out (it is in jQuery but it applies to just about any framework.)  View the source on that and see if that could work in your situation.


Question: How can I take full advantage of 64-bit architecture in my .NET 2.0 Web Applications and Console/Forms Applications?

Answer:
I think there is not too much you can optimize in your managed .NET code regarding 32bit vs. 64bit architectures. This is because most of the differences and optimizatinons are most likely already implemented by the underlying VM. As mentioned in
Programming for the 64 bit platform
, the 64bit VM may perform better on larger data types (as
```
long
```
stored in one register).


Question:
Have you ever had alternating background colors in a Jasper report and then exported it to Excel?  The Excel export seems to ignore the alternating color.

I've got a Jasper report where the rows alternating background color using the procedure referenced HERE.  When I preview it using the viewer or export to PDF it works -- but not when I export to Excel.  I've tried using JRXlsExporter and JExcelApiExporter both to no avail.

I think it might be a side-effect of how you have to make alternating row colors in Jasper, which I despise to begin with, but have found no other way.

Thanks in advance!

Answer:
Did you try the idea suggested in the
comment
of the very procedure you are referring to ?
First how to create new report style with condition:
Recent releases of JasperReports include report styles, which make this a bit easier - you no longer have to create the rectangle.
I use iReport to create my styles - there is a “styles” pane that by default is docked with the “Library” pane. If you make it visible you can create a new style in the styles library. In the screen that pops up give the style a name (say “EvenOddRowStyle” and press “Add” under “Style Conditions”. Use one of the expressions that Brian gave and press Apply. and in the “Common” section press the “…” button next to “Backcolor” and pick the background color you want. Finally, when done with your report apply that style to all the fields in the rows you want to highlight. Just drag the style from the styles pane onto the field.
Then how to define a style which will be applied when exported to Excel:
defining a new style with the condition expression:
```
```
Boolean.valueOf( $V{PAGE_COUNT}.intValue() % 2 == 0 )
```
```
on it
without using a rectangle and a print when expression on it
!


Question:
We have an advanced webpage (ASP.NET, C#), and a application which needs to be installed on the client computer in order to utilize the webpage to its fullest. The application is a tray app, and has primarily two tasks. Detect when certain events happen on the webserver (for instance invited to a meeting, or notify of an upcoming meeting). The other task the trayapp has is to use a custom protocol (trayapp://) to perform some ajax calls back to the server.

One problem we have is how to determine if the application is installed on the local machine or not. Now the user has to tick a checkbox to inform the website that the application is installed, and that it's safe to call the trayapp:// url calls.

Is there any way, for instance through a JavaScript or similar to detect if our application is installed on the local machine?

The check needs to work for IE, FF and Opera browsers.

Answer:
When installing your client-side app you could modify the browser configuration to include another request header in HTTP requests and then have the server code look for that header, for example as a supported mime type using the following registry key (for Internet explorer)
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\
                                                      Internet Settings\Accepted Documents
```
```
I am not sure if Opera and FF use this same key, but they likely have similar configuration options, but this should at least get you on the right track.


Question:
Someone posted a great little function here the other day that separated the full path of a file into several parts that looked like this:

Function BreakDown(Full As String, FName As String, PName As String, Ext As String) As Integer
 If Full = "" Then
 BreakDown = False
 Exit Function
 End If
 If InStr(Full, "\") Then
 FName = Full
 PName = ""
 Sloc% = InStr(FName, "\")
 Do While Sloc% <> 0
   PName = PName + Left$(FName, Sloc%)
   FName = Mid$(FName, Sloc% + 1)
   Sloc% = InStr(FName, "\")
 Loop
 Else
 PName = ""
 FName = Full
 End If
Dot% = InStr(Full, ".")
If Dot% <> 0 Then
 Ext = Mid$(Full, Dot%)
Else
 Ext = ""
End If
BreakDown = True

End Function

However if the line continues past that point it counts it as part of the extension, is there anyway to make this only count to 3 characters after the last period in a string?

Answer:
If you just have blank characters then just add this as the first line
```
```
Full = Trim(Full)
```
```
If you have other characters then
Change:
```
```
Ext = Mid$(Full, Dot%)
```
```
to:
```
```
Ext = Mid$(Full, Dot%, 3)
```
```


Question: I have set of names and addresses that have been entered into and excel spreadsheet, but the problem is that the many people that entered the addresses entered them in many different non-standard formats.  I want to scrub the addresses before transferring all of of them to my database.  Looking around, all I really found in the way of address scrubbers(parsers or formatters) is the one that is put out by Semaphore.  For my purposes, I don't really need all of that and I don't want to pay for the licensing fees for the software.  Is there anything out there that is Free and/or Open Source that will do the scrubbing for me?

Answer:
Most of the software that I've worked with to do this is very expensive (or to put it another way, marketing departments are naive and have huge budgets).
This sort of work is a precursor to Geo-coding.  This
linked Wiki article
includes a list of Geocoding software, some of which is free.  If you're lucky, some of the free ones may include address standardizing routines.
If you find a good one, let me know.