Question:
When you're using Tiles with Struts and do...

request.getRequestURL()

...you get the URL to e.g. /WEB-INF/jsp/layout/newLayout.jsp instead of the real URL that was entered/clicked by the user, something like /context/action.do.

In newer Struts versions, 1.3.x and after, you can use the solution mentioned on javaranch and get the real URL using the request attribute ORIGINAL_URI_KEY.

But how to do this in Struts 1.2.x?

Answer:
I don't know if Struts 1.2.x has a similar Globals constant, but you could create your own in at least two ways:
get the original request URL in the Action and set it on the request, and call that from the JSP
use a Servlet Filter to do the same thing


Question:
Does anyone know if IE6 ever misrenders pages with hidden divs? We currently have several divs which we display in the same space on the page, only showing one at a time and hiding all others.

The problem is that the hidden divs components (specifically option menus) sometimes show through. If the page is scrolled, removing the components from view, and then scrolled back down, the should-be-hidden components then disappear.

How do we fix this?

Answer:
One hack you could use is to move your div outside the screen:
```
```
MyDiv.style.left = "-1000px";
```
```
And then put it back on its original position when you want to show it.


Question:
I wish to test a function that will generate lorem ipsum text, but it does so within html tags. So I cant know in advance the textual content, but i know the html structure. That is what I want to test. And maybe that the length of the texts are within certain limits.
So what I am wondering is if the assertTags can do this in a way paraphrased bellow:

Result = "<p>Some text</p>";
Expected = array(
   '<p' ,
   'regex',
   '/p'
);
assertTags(resutl, expected)

I am using SimpleTest with CakePHP, but I think it should be a general question.

Answer:
Extend the SimpleExpectation class and then use your new Expectation class in the assert statement
see:
http://www.lastcraft.com/expectation_documentation.php#extending
the example given is for validating an IP address but should be applicable to your problem:
```
```
class ValidIp extends SimpleExpectation {

  function test($ip) {
    return (ip2long($ip) != -1);
  }

  function testMessage($ip) {
    return "Address [$ip] should be a valid IP address";
  }
}
```
```
then in your test
```
```
$this->assert(new ValidIp(),$server->getIp());
```
```


Question: When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?

Answer:
Here is an example to boot strap spring for a Main method, simply grab the passed params as normal then make the function you call on your bean (in the case deployer.execute()) take them as Strings or via any format you feel suitable.
```
```
public static void main(String[] args) throws IOException, ConfigurationException {
    Deployer deployer = bootstrapSpring();

    deployer.execute();
}

private static Deployer bootstrapSpring()
{
    FileSystemXmlApplicationContext appContext = new FileSystemXmlApplicationContext("spring/deployerContext.xml");

    Deployer deployer = (Deployer)appContext.getBean("deployer");
    return deployer;
}
```
```


Question:
Consider this case:

dll = LoadDLL()
dll->do()

...
void do() {
    char *a = malloc(1024);
}
...

UnloadDLL(dll);

At this point, will the 1k allocated in the call to malloc() be available to the host process again?
The DLL is statically linking to the CRT.

Answer:
No, you do not leak.
If you mix dll models (static, dynamic) then you can end up with a memory error if you allocate memory in a dll, that you free in a different one (or freed in the exe)
This means that the heap created by the statically-linked CRT is not the same heap as a different dll's CRT.
If you'd linked with the dynamic version of the CRT, then you'd have a leak as the heap is shared amongst all dynamically-linked CRTs. It means you should always design your apps to use the dynamic CRTs, or ensure you never manage memory across a dll boundary (ie if you allocate memory in a dll, always provide a routine to free it in the same dll)


Question: I compile my project with VIsual Studio 2005 Express Edition, and get this linking error. Can anyone suggest how to solve that?

Answer:
That exact question is asked and answered at
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1512436&SiteID=1
.
Try re-installing.  It appears to be an install of the wrong service pack.


Question: Is there anyone using Subsonic with asp.net mvc framework? If so, can you tell us something about your experience. Are there tips and tricks that can be shared?

Answer:
If you're planning on doing database first design, and you don't need any mapping (i.e. you're in control of your db naming) then SubSonic is a decent option.
It's straight-forward, doesn't hide a lot from you.  On the same token, for advanced scenarios I have to side-step it a lot and execute raw sql (or a sproc).
If you're looking for a better object abstraction over the database, something that more closely matches your problem domain, then I'd look at NHibernate or Castle ActiveRecord.  This gives you a lot more flexibility in how you want your object model to look, and you have a powerful query API at your disposal.
None of this really has to do with ASP.NET MVC, other than you just use your objects in your web project.  I'd suggest putting the entities inside of a separate class library project anyway.


Question: We want migrate from Delphi 7.0 to Delphi 2009, to stay up with a modern IDE and current technology. Our target platform is .NET. What is best way, to achieve this goal?

Answer:
Migrating from Delphi 7 to Delphi 2009 is probably straight forward, there were only minor changes (such as the recently discussed move from ANSI to Unicode strings).
The move to .NET is not so straight forward, though. Although there's a VCL.NET which makes migrating GUIs possible, severeal other things will not work. So you might think of having Win32 code AND .NET code, bringing them together through COM.
(I hope you already know COM, otherwise this is probably not an option;-))


Question:
I have an ANSI encoded text file that should not have been encoded as ANSI as there were accented
characters that ANSI does not support. I would rather work with UTF-8.

Can the data be decoded correctly or is it lost in transcoding?

What tools could I use?

Here is a sample of what I have:

Ã§ Ã©

I can tell from context (cafÃ© should be café) that these should be these two characters:

ç é

Answer:
With vim from command line:
```
```
vim -c "set encoding=utf8" -c "set fileencoding=utf8" -c "wq" filename
```
```


Question:
My implementation of httpclient occasionally throws an exception when calling doGetConnection(). However, I have the following timeout set

_moHttpClient.setHttpConnectionFactoryTimeout(30000);

it looks almost like my timeout is not being picked up. Is there anywhere else I need to set a timeout to ensure this behaviour does not re-occur

Answer:
```
```
HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams();
    cmparams.setSoTimeout(10000);
    cmparams.setTcpNoDelay(true);
    HttpConnectionManager manager = new SimpleHttpConnectionManager();
    manager.setParams(cmparams);
    params = new HttpClientParams();
    params.setSoTimeout(5000);
    client = new HttpClient(params, manager);
```
```
I wonder why I have two different SoTimeouts set. Maybe I was trying to find out which one was actually active, as I had the same problems as you when I used it.
The above is in live code at our place right now, but I cannot say whether it works because it's correct, or because providence is smiling down on me (and the other end is usually always available).


Question: Are there any good examples (websites or books) around of how to build a full text search engine in F#?

Answer:
```
```
HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams();
    cmparams.setSoTimeout(10000);
    cmparams.setTcpNoDelay(true);
    HttpConnectionManager manager = new SimpleHttpConnectionManager();
    manager.setParams(cmparams);
    params = new HttpClientParams();
    params.setSoTimeout(5000);
    client = new HttpClient(params, manager);
```
```
I wonder why I have two different SoTimeouts set. Maybe I was trying to find out which one was actually active, as I had the same problems as you when I used it.
The above is in live code at our place right now, but I cannot say whether it works because it's correct, or because providence is smiling down on me (and the other end is usually always available).


Question: When I do an "os.execute" in Lua, a console quickly pops up, executes the command, then closes down. But is there some way of getting back the console output only using the standard Lua libraries?

Answer:
I don't know about Lua specifically but you can generally run a command as:
```
```
comd >comd.txt 2>&1
```
```
to capture the output and error to the file comd.txt, then use the languages file I/O functions to read it in.
That's how I'd do it if the language itself didn't provide for capturing stanard output and error.


Question:
Consider the following code:

void Handler(object o, EventArgs e)
{
   // I swear o is a string
   string s = (string)o; // 1
   //-OR-
   string s = o as string; // 2
   // -OR-
   string s = o.ToString(); // 3
}

What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?

Answer:
'as' is based on 'is', which is a keyword that checks at runtime if the object is polimorphycally compatible (basically if a cast can be made) and returns null if the check fails.
These two are equivalent:
Using 'as':
```
```
string s = o as string;
```
```
Using 'is':
```
```
if(o is string)
    s = o;
else
    s = null;
```
```
On the contrary, the c-style cast is made also at runtime, but throws an exception if the cast cannot be made.
Just to add an important fact:
The 'as' keyword only works with reference types. You cannot do:
```
```
// I swear i is an int
int number = i as int;
```
```
In those cases you have to use casting.


Question:
I need to perform Diffs between Java strings. I would like to be able to rebuild a string using the original string and diff versions. Has anyone done this in Java? What library do you use?

String a1; // This can be a long text
String a2; // ej. above text with spelling corrections
String a3; // ej. above text with spelling corrections and an additional sentence

Diff diff = new Diff();
String differences_a1_a2 = Diff.getDifferences(a,changed_a);
String differences_a2_a3 = Diff.getDifferences(a,changed_a);
String[] diffs = new String[]{a,differences_a1_a2,differences_a2_a3};
String new_a3 = Diff.build(diffs);
a3.equals(new_a3); // this is true

Answer:
Apache Commons has String diff
org.apache.commons.lang.StringUtils
```
```
StringUtils.difference("foobar", "foo");
```
```


Question:
I'm creating a UI that allows the user the select a date range, and tick or un-tick the days of the week that apply within the date range.

The date range controls are DateTimePickers, and the Days of the Week are CheckBoxes

Here's a mock-up of the UI:

From Date: (dtpDateFrom)

To Date:   (dtpDateTo)

[y] Monday,   [n] Tuesday,   [y] Wednesday, (etc)

What's the best way to show a total count the number of days, based not only on the date range, but the ticked (or selected) days of the week?

Is looping through the date range my only option?

Answer:
Looping through wouldn't be your only option - you could perform
subtraction
to figure out the total number of days, and subtract one for each of your "skipped" dates every week range in between that contains one of those days. By the time you figure out whether a day lands on one of the partial weeks at the beginning or end of the range and add
```
#weeks * skipped days in a week
```
, your code will be more complicated than it would be if just counted, but if you're expecting to have huge date ranges, it might perform better.
If I were you, I'd write the simple looping option and rewrite it if it turned out that profiling revealed it to be a bottleneck.


Question:
Possible Duplicate:

  “const correctness” in C#

I have programmed C++ for many years but am fairly new to C#. While learning C# I found that the use of the const keyword is much more limited than in C++. AFAIK, there is, for example, no way to declare arguments to a function const. I feel uncomfortable with the idea that I may make inadvertent changes to my function arguments (which may be complex data structures) that I can only detect by testing.

How do you deal with this situation?

Answer:
Stephen Denne
has a Metro implementation that satisfies your requirement. My answer is provided below after a short explination as to why that is the case.
Most Web Service implementations that are built using HTTP as the message protocol are REST compliant, in that they only allow simple send-receive patterns and nothing more. This greatly improves interoperability, as all the various platforms can understand this simple architecture (for instance a Java web service talking to a .NET web service).
If you want to maintain this you could provide chunking.
```
```
boolean uploadFile(String username, String password, String fileName, int currentChunk, int totalChunks, byte[] chunk);
```
```
This would require some footwork in cases where you don't get the chunks in the right order (Or you can just require the chunks come in the right order), but it would probably be pretty easy to implement.


Question: What is the difference between overflow:hidden and display:none?

Answer: Overflow:hidden just says if text flows outside of this element the scrollbars don't show.    display:none says the element is not shown.


Question:
While developing a C++ application, I had to use a third-party library which produced a huge amount of warnings related with a harmless #pragma directive being used.

../File.hpp:1: warning: ignoring #pragma ident
In file included from ../File2.hpp:47,
                 from ../File3.hpp:57,
                 from File4.h:49,

Is it possible to disable this kind of warnings, when using the GNU C++ compiler?

Answer:
I believe you can compile with
```
```
-Wno-unknown-pragmas
```
```
to suppress these.


Question: When setting the size of fonts in CSS, should I be using a percent value (%) or em? Can you explain the advantage?

Answer:
From
http://archivist.incutio.com/viewlist/css-discuss/1408
%: Some browsers doesn't handle
  percent for font-size but interprets
  150%  as 150px. (Some NN4 versions,
  for instance.) IE also has problems
  with  percent on nested elements. It
  seems IE uses percent relative to
  viewport  instead of relative to
  parent element. Yet another problem
  (though correct  according to the W3C
  specs), in Moz/Ns6, you can't use
  percent relative to  elements with no
  specified height/width.
em: Sometimes browsers use the wrong
  reference size, but of the relative
  units it's the one with least
  problems. You might find it
  interpreted as px  sometimes though.
pt: Differs greatly between
  resolutions, and should not be used
  for  display. It's quite safe for
  print use though.
px: The only reliable absolute unit on
  screen. It might be wrongly
  interpreted in print though, as one
  point usually consist of several
  pixels, and thus everything becomes
  ridiculously small.


Question:
I have a Visual Studio (2008) solution consisting of several projects, not all in the same namespace. When I build the solution, all the DLL files used by the top level project, TopProject, are copied into the TopProject\bin\debug folder. However, the corresponding .pdb files are only copied for some of the other projects. This is a pain, for example when using NDepend.

How does Visual Studio decide which .pdb files to copy into higher level bin\debug folders? How can I get Visual Studio to copy the others too?

References are as follows: all the DLL files are copied to a central location, without their PDB files. TopProject only has references to these copied DLL files; the DLL files themselves, however, evidently know where their PDB files are, and (most of them) get copied to the debug folder correctly.

Answer:
From
MSDN
:
A program database (PDB) file holds
  debugging and project state
  information that allows incremental
  linking of a Debug configuration of
  your program. A PDB file is created
  when you compile a C/C++ program with
  /ZI or /Zi or a Visual
  Basic/C#/JScript .NET program with
  /debug.
So it looks like the "issue" here (for lack of a better word) is that some of your DLLs are being built in debug mode (and hence emitting PDB files), and some are being built in release mode (hence not emitting PDB files). If that's the case, it should be easy to fix -- go into each project and update its build settings. This would be the default scenario, if you haven't done any tweaking of command line options.
However, it will get trickier if that isn't the case. Maybe you're all in release or debug mode. Now you need to look at the command line compile options (specified in the project properties) for each project. Update them to /debug accordingly if you want the debugger, or remove it if you don't.
Edit in Response to Edit
Yes, the DLL files "know" that they have PDB files, and have paths to them, but that doesn't mean too much. Copying just DLL files to a given directory, as others have mentioned, won't clear this issue up. You need the PDB files as well.
Copying individual files in Windows, with the exception of certain "bundle"-type files (I don't know Microsoft's term for this, but "complete HTML packages" are the concept) doesn't copy associated files. DLL files aren't assembled in the "bundle" way, so copying them leaves their PDB file behind.
I'd say the only answer you're going to have is to update your process for getting the DLL files to those central locations, and include the PDB files ... I'd love to be proven wrong on that, though!


Question:
How can you you insert a newline from your batch file output?

I want to do something like:

echo hello\nworld

Which would output:

hello
world

Answer:
Use:
```
```
echo hello
echo:
echo world
```
```


Question:
I have the following layout for my test suite:

TestSuite1.cmd:

Run my program

Check its return result

If the return result is not 0, convert the error to textual output and abort the script.  If it succeeds, write out success.

In my single .cmd file, I call my program about 10 times with different input.

The problem is that the program that I run 10 times takes several hours to run each time.

Is there a way for me to parallelize all of these 10 runnings of my program while still somehow checking the return result and providing a proper output file and while still using a single .cmd file and to a single output file?

Answer:
try the command
start
, it spawns a new command prompt and you can send along any commands you want it to run.
I'd use this to spawn batch files that run the tests and then appends to a output.txt using >>  as such:
```
```
testthingie.cmd >> output.txt
```
```


Question:
I need to move entire tables from one MySQL database to another. I don't have full access to the second one, only phpMyAdmin access. I can only upload (compressed) sql files smaller than 2MB. But the compressed output from a mysqldump of the first database's tables is larger than 10MB.

Is there a way to split the output from mysqldump into smaller files? I cannot use split(1) since I cannot cat(1) the files back on the remote server.

Or is there another solution I have missed?

Edit

The --extended-insert=FALSE option to mysqldump suggested by the first poster yields a .sql file that can then be split into importable files, provided that split(1) is called with a suitable --lines option. By trial and error I found that bzip2 compresses the .sql files by a factor of 20, so I needed to figure out how many lines of sql code correspond roughly to 40MB.

Answer:
First dump the schema (it surely fits in 2Mb, no?)
```
```
mysqldump -d --all-databases
```
```
and restore it.
Afterwards dump only the data in separate insert statements, so you can split the files and restore them without having to concatenate them on the remote server
```
```
mysqldump --all-databases --extended-insert=FALSE --no-create-info=TRUE
```
```


Question:
I was wondering how i can force a user who has requested a page using Http to use the secure https version?

I am using Websphere 6.1 as my application server and Rad 7 as my development environment

Thanks
Damien

Answer:
Websphere is not a complete http server. It does have 'Transport Chains', which act like an HTTP Server.
Normally you will put a HTTP server in front. IBM provides IHS (IBM HTTP Server) which is a lightly modified Apache HTTP Server. The HTTP Server is configured with the httpd.conf file. There you add redirects in such a way that request for http are redirected to https.
Maybe you can give some detailed information about your infrastructure.


Question:
Recently I noticed my application appears to be eating memory that never gets released. After profiling with CLRProfiler I've found that the Castle Windsor container I'm using is holding onto objects. These objects are declared with the lifestyle="transient" attribute in the config xml.

I've found if I put an explicit call to IWindsorContainer.Release(hangingObject), that it will drop its references.

This is causing a problem though, I wasn't expecting that with a transient lifestyle object CastleWindsor would keep a reference and effectively create a leak. It's going to be a rather mundane and error prone task going around inserting explicit Release calls in all the appropriate places.

Have you seen this problem, and do you have any suggestions for how to get around it?

Answer:
You can set a lifestyle of singleton or transient though on objects in the container. Singleton objects I understand should last the life of the application, but I don't understand the usefulness of this behvaviour being the same for transient ones!
Custom lifestyles can be created by implementing
```
ILifestyleManager
```
. Maybe it's possible to implement this suitably to create a
```
ReallyTransient
```
lifestyle type!


Question: How do I have a script run every, say 30 minutes?  I assume there are different ways for different OSs.  I'm using OS X.

Answer:
On MacOSX, you have at least the following options:
Recurring iCal alarm with a "Run Script" action
launchd
cron (
link1
,
link2
)
From personal experience, cron is the most reliable. When I tested, launchd had a number of bugs and quirks. iCal alarms only run when you are logged in (but that might be something you prefer).


Question:
A Google search turned up software that performs the same functions as cron, but nothing built into Windows.

I'm running Windows XP Professional, but advice for any version of Windows would be potentially helpful to someone.

Is there also a way to invoke this feature (which based on answers is called the Task Scheduler) programatically or via the command line?

Answer:
For the original question, asking about Windows XP (and Windows 7):
Windows Task Scheduler
For command-line usage, you can schedule with the
AT command
.
For newer Microsoft OS versions, Windows Server 2012 / Windows 8, look at the
schtasks
command line utility.
If using PowerShell, the
Scheduled Tasks Cmdlets in Windows PowerShell
are made for scripting.


Question:
My Google-fu has failed me.

In Python, are the following two tests for equality equivalent?

n = 5
# Test one.
if n == 5:
    print 'Yay!'

# Test two.
if n is 5:
    print 'Yay!'

Does this hold true for objects where you would be comparing instances (a list say)?

Okay, so this kind of answers my question:

L = []
L.append(1)
if L == [1]:
    print 'Yay!'
# Holds true, but...

if L is [1]:
    print 'Yay!'
# Doesn't.

So == tests value where is tests to see if they are the same object?

Answer:
```
==
```
determines if the values are equal, while
```
is
```
determines if they are the exact same object.


Question:
I need to add a specific column if it does not exist. I have something like the following, but it always returns false:

IF EXISTS(SELECT *
          FROM   INFORMATION_SCHEMA.COLUMNS
          WHERE  TABLE_NAME = 'myTableName'
                 AND COLUMN_NAME = 'myColumnName')

How can I check if a column exists in a table of the SQL Server database?

Answer:
Try this...
```
```
IF NOT EXISTS(
  SELECT TOP 1 1
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE
    [TABLE_NAME] = 'Employees'
    AND [COLUMN_NAME] = 'EmployeeID')
BEGIN
  ALTER TABLE [Employees]
    ADD [EmployeeID] INT NULL
END
```
```


Question: The CSS rules visibility:hidden and display:none both result in the element not being visible. Are these synonyms?

Answer:
```
display:none
```
removes the element from the layout flow.
```
visibility:hidden
```
hides it but leaves the space.


Question:
In MS SQL 2000 and 2005, given a datetime such as '2008-09-25 12:34:56' what is the most efficient way to get a datetime containing only '2008-09-25'?

Duplicated here.

Answer:
```
```
Select DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)
```
```
DateDiff(Day, 0, GetDate()) is the same as DateDiff(Day, '1900-01-01', GetDate())
Since DateDiff returns an integer, you will get the number of days that have elapsed since Jan 1, 1900.  You then add that integer number of days to Jan 1, 1900.  The net effect is removing the time component.
I should also mention that this method works for any date/time part (like year, quarter, month, day, hour, minute, and second).
```
```
Select  DateAdd(Year, DateDiff(Year, 0, GetDate()), 0)
Select  DateAdd(Quarter, DateDiff(Quarter, 0, GetDate()), 0)
Select  DateAdd(Month, DateDiff(Month, 0, GetDate()), 0)
Select  DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)
Select  DateAdd(Hour, DateDiff(Hour, 0, GetDate()), 0)
Select  DateAdd(Second, DateDiff(Second, '20000101', GetDate()), '20000101')
```
```
The last one, for seconds, requires special handling.  If you use Jan 1, 1900 you will get an error.
Difference of two datetime columns caused overflow at runtime.
You can circumvent this error by using a different reference date (like Jan 1, 2000).


Question:
I need to increment a number in a source file from an Ant build script. I can use the ReplaceRegExp task to find the number I want to increment, but how do I then increment that number within the replace attribute?

Heres what I've got so far:

<replaceregexp file="${basedir}/src/path/to/MyFile.java"
    match="MY_PROPERTY = ([0-9]{1,});"
    replace="MY_PROPERTY = \1;"/>

In the replace attribute, how would I do

replace="MY_PROPERTY = (\1 + 1);"

I can't use the buildnumber task to store the value in a file since I'm already using that within the same build target. Is there another ant task that will allow me to increment a property?

Answer:
You can use something like:
```
<propertyfile file="${version-file}">
 <entry key="revision" type="string" operation="=" value="${revision}" />
 <entry key="build" type="int" operation="+" value="1" />
```
so the ant task is propertyfile.


Question:
I want to make a .NET Form as a TopMost Form for another external App (not .NET related, pure Win32) so it stays above that Win32App, but not the rest of the apps running.

I Have the handle of the Win32App (provided by the Win32App itself), and I've tried Win32 SetParent() function, via P/Invoke in C#, but then my .NET Form gets confined into the Win32App and that's not what I want.

Answer:
I think you're looking for is to P/Invoke
```
SetWindowLongPtr(win32window, GWLP_HWNDPARENT, formhandle)
```
Google Search


Question: I use Eclipse 3.3 in my daily work, and have also used Eclipse 3.2 extensively as well.  In both versions, sometimes the Search options (Java Search, File Search, etc) in the menu get disabled, seemingly at random times.  However, with Ctrl+H, I am able to access the search functionality.  Does anyone know why this happens?  Has it been fixed in Eclipse 3.4?

Answer: I don't have an exact answer.  I will recommend that you try to correlate the disablement with which perspective is active.  Likewise, which view is active.  I have been using 3.4 and not experienced this issue.


Question:
I have inherited a project that uses LLBLGen Pro for the DB layer. The DB model requires that when a entry is deleted a flag (DeletedDate is set to the current time). The last programmer ignored this requirement and has used regular deletes throughout the entire application.

Is there a way to set the code generator to do this automatically or do I have to overload each delete operator for the Entities that requires it?

Answer:
I implemented this in SQL Server 2005 using INSTEAD OF triggers on delete for any soft delete table. The triggers set the delete flag and perform clean-up. The beauty of this solution is that it correctly handles deletes issued by any system that accesses the database. INSTEAD OF is relatively new in SQL Server, I know there's an Oracle equivalent.
This solution also plays nicely with our O/R mapper -- I created views that filter out soft deleted records and mapped those. The views are also used for all reporting.


Question:
While normally it's good to always choose the right language for the job, it can sometimes be instructive to try and do something in a language which is wildly inappropriate.

It can help you understand the problem better.  Maybe you don't have to solve it the way you thought you did.

It can help you understand the language better.  Maybe it supports more features than you realized.

And pushing this idea to it's illogical conclusion...how would you implement quicksort in a batch file?  Is it even possible?

Answer:
Turns out, it's not as hard as you might think.  The syntax is ugly as hell, but the batch  syntax is actually capable of some surprising things, including recursion, local variables, and some surprisingly sophisticated parsing of strings.  Don't get me wrong, it's a terrible language, but to my surprise, it isn't completely crippled.  I don't think I learnt anything about quicksort, but I learned a lot about batch files!
In any case, here's quicksort in a batch file - and I hope you have as much fun trying to understand the bizarre syntax while reading it as I did while writing it.  :-)
```
```
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

call :qSort %*
for %%i in (%return%) do set results=!results! %%i
echo Sorted result: %results%
ENDLOCAL
goto :eof

:qSort
SETLOCAL
    set list=%*
    set size=0
    set less=
    set greater=
    for %%i in (%*) do set /a size=size+1
    if %size% LEQ 1 ENDLOCAL & set return=%list% & goto :eof
    for /f "tokens=2* delims== " %%i in ('set list') do set p=%%i & set body=%%j
    for %%x in (%body%) do (if %%x LEQ %p% (set less=%%x !less!) else (set greater=%%x !greater!))
    call :qSort %less%
    set sorted=%return%
    call :qSort %greater%
    set sorted=%sorted% %p% %return%
ENDLOCAL & set return=%sorted%
goto :eof
```
```
Call it by giving it a set of numbers to sort on the command line, seperated by spaces.  Example:
```
```
C:\dev\sorting>qsort.bat 1 3 5 1 12 3 47 3
Sorted result:  1 1 3 3 3 5 12 47
```
```
The code is a bit of a pain to understand.  It's basically standard quicksort.  Key bits are that we're storing numbers in a string - poor man's array.  The second for loop is pretty obscure, it's basically splitting the array into a head (the first element) and a tail (all other elements).  Haskell does it with the notation x:xs, but batch files do it with a for loop called with the /f switch.  Why?  Why not?
The SETLOCAL and ENDLOCAL calls let us do local variables - sort of.  SETLOCAL gives us a complete copy of the original variables, but all changes are completely wiped when we call ENDLOCAL, which means you can't even communicate with the calling function using globals.  This explains the ugly "ENDLOCAL & set return=%sorted%" syntax, which actually works despite what logic would indicate.  When the line is executed the sorted variable hasn't been wiped because the line hasn't been executed yet - then afterwards the return variable isn't wiped because the line has already been executed.  Logical!
Also, amusingly, you basically can't use variables inside a for loop because they can't change - which removes most of the point of having a for loop.   The workaround is to set ENABLEDELAYEDEXPANSION which works, but makes the syntax even uglier than normal.  Notice we now have a mix of variables referenced just by their name, by prefixing them with a single %, by prefixing them with two %, by wrapping them in %, or by wrapping them in !.  And these different ways of referencing variables are almost completely NOT interchangeable!
Other than that, it should be relatively easy to understand!


Question:
In a previous job we had a classic ASP application that no one wanted to migrate to ASP.NET.  The things that it did, it did very well.

However there was some new functionality that needed to be added that just seemed best suited to ASP.NET.  The decision was made to allow the system to become a weird hybrid of ASP and ASP.NET.

Our biggest sticking point was session management and we hacked together a solution to pass session values through form variables.  I've talked to others that handled this same problem through cookies.

Both methods seem a horrible kluge (in addition to being terribly insecure).

Is there a better or cleaner way or is this just such a bad idea to begin with that discussion on the topic is pointless?

Answer: I have had to deal with the same problem. In my case, I encrypted a key into a cookie and used the database for any other information.  I wrote the encryption in .NET and inter-op'd to decrypt the id on the ASP side.  There is some weirdness dealing with base-64 string in that ASP will not get the same string as .NET, so you may have to do as I did and rewrite the base-64 string to hex equivalent or some similar lowest-common-denominator tactic.  It is relatively secure (save a XSS attack).


Question:
How do I get a list of the files checked out by users (including the usernames) using P4V or P4?

I want to provide a depot location and see a list of any files under that location (including sub folders) that are checked out.

Answer:
From the command line:
```
```
p4 opened -a //depot/Your/Location/...
```
```
The ... indicates that sub folders should be included.


Question: I want to discover all xml files that my ClassLoader is aware of using a wildcard pattern.  Is there any way to do this?

Answer:
Well, it is not from within Java, but
```
jar -tvf jarname | grep xml$
```
will show you all the XMLs in the jar.


Question:
I am wanting to store the "state" of some actions the user is performing in a series of different ASP.Net webforms.  What are my choices for persisting state, and what are the pros/cons of each solution?

I have been using Session objects, and using some helper methods to strongly type the objects:

    public static Account GetCurrentAccount(HttpSessionState session)
    {
        return (Account)session[ACCOUNT];
    }

    public static void SetCurrentAccount(Account obj, HttpSessionState session)
    {
        session[ACCOUNT] = obj;
    }

I have been told by numerous sources that "Session is evil", so that is really the root cause of this question.  I want to know what you think "best practice", and why.

Answer:
As for "Session being evil" ... if you were developing in classic ASP I would have to agree, but ASP.NET/IIS does a much better job.
The real question is what is the best way to maintain state.  In our case, when it comes to the current logged in user, we store that object in Session, as we are
constantly
referring to it for their name, email address, authorization and so forth.
Other little
tidbits
of information that doesn't need any long-term persistence we use a combination of cookies and viewstate.


Question:
I want to have a UIScrollView with a set of subviews where each of these subviews has a UITextView with a different text. For this task, I have modified the PageControl example from the apple "iphone dev center" in order to add it a simple UITextView to the view which is used to generate the subviews of the scroll view. When I run the app (both on the simulator and the phone), NO Text is seen but if i activate the "user interaction" and click on it, the text magically appears (as well as the keyboard).

Does anyone has a solution or made any progress with UITextView inside a UIScrollView? Thanks.

Answer:
I think the problem stems from the fact that
```
UITextView
```
is a subclass of
```
UIScrollView
```
, so you basically have scroll views embedded within
```
UIScrollViews
```
.  Even if the text displayed properly, you would have usability problems, as it would never be clear if a finger swipe was supposed to scroll the outer view or the text view.
Yeah, Safari sort of does this, but it has to, and it's not the most pleasant part of using Safari.
I think this is one of those times where the difficulty indicates you are working against the system.  I strongly recommend going back and re-thinking the UI.


Question:
I'm new to CodeIgniter, and I need some help. I'd like to implement the following:

View a user's profile via:
http://localhost/profile/johndoe

Administrate a user's profile via:
http://localhost/admin/profile/johndoe

Be able to accomplish even further processing via:
http://localhost/admin/profile/create
...and...
http://localhost/admin/profile/edit/johndoe

I've already created the admin object and secured it. Do I have to create a profile function under admin, and work with the URI to process accordingly? Is there a better way?

Answer:
This is not such a good idea.
If you want to implement those URLs, you need two controllers:
Profile, with the function
```
index
```
Admin, with the function
```
profile
```
In Admin, the
```
profile
```
function has to read the first argument (create/edit/[userid]) and then do something accordingly. (You also must make sure that no user can call himself "create" or "edit".)
I would instead use only one controller with the functions
```
show
```
,
```
edit
```
, and
```
create
```
(or
```
add
```
). Much easier. Then you would get these URLs:
http://localhost/profile/show/johndoe
http://localhost/profile/edit/johndoe
http://localhost/profile/create/johndoe


Question:
I have a JavaScript widget which provides standard extension points. One of them is the beforecreate function. It should return false to prevent an item from being created.

I've added an Ajax call into this function using jQuery:

beforecreate: function (node, targetNode, type, to) {
  jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),

  function (result) {
    if (result.isOk == false)
        alert(result.message);
  });
}

But I want to prevent my widget from creating the item, so I should return false in the mother-function, not in the callback. Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?

Answer:
From the
jQuery documentation
: you specify the
asynchronous
option to be
false
to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.
Here's what your code would look like if changed as suggested:
```
```
beforecreate: function (node, targetNode, type, to) {
    jQuery.ajax({
        url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
        success: function (result) {
            if (result.isOk == false) alert(result.message);
        },
        async: false
    });
}
```
```


Question:
I remember reading that one abstracts the low level calls into a data agnostic framework (eg. ExecuteCommand methods etc), and the other usually contains business specific methods (eg. UpdateCustomer).

Is this correct?  Which is which?

Answer:
To me this is a personal design decision on how you want to handle your project design.  At times data access and data service are one and the same.  For .NET and LINQ that is the case.
To me the data service layer is what actually does the call to the database.  The data access layer receives the objects and creates them or modify them for the data service layer to make the call to the database.
In my designs the Business Logic Layer manipulates the objects based on the business rules, then passes them to the data access layer which will format them to go into the database or the objects from the database, and the data service layer handles the actual database call.


Question:
How do I find the name of the namespace or module 'Foo' in the filter below?

class ApplicationController < ActionController::Base
  def get_module_name
    @module_name = ???
  end
end

class Foo::BarController < ApplicationController
  before_filter :get_module_name
end

Answer:
This should do it:
```
```
def get_module_name
    @module_name = self.class.to_s.split("::").first
  end
```
```


Question:
I'm trying to install a service using InstallUtil.exe but invoked through Process.Start. Here's the code:

ProcessStartInfo startInfo = new ProcessStartInfo (m_strInstallUtil, strExePath);
System.Diagnostics.Process.Start (startInfo);

where m_strInstallUtil is the fully qualified path and exe to "InstallUtil.exe" and strExePath is the fully qualified path/name to my service.

Running the command line syntax from an elevated command prompt works; running from my app (using the above code) does not. I assume I'm dealing with some process elevation issue, so how would I run my process in an elevated state? Do I need to look at ShellExecute for this?

This is all on Windows Vista. I am running the process in the VS2008 debugger elevated to admin privilege.

I also tried setting startInfo.Verb = "runas"; but it didn't seem to solve the problem.

Answer:
You should use Impersonation to elevate the state.
```
```
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
```
```
Don't forget to undo the impersonated context when you are done.


Question:
I am developing a Joomla component and one of the views needs to render itself as PDF. In the view, I have tried setting the content-type with the following line, but when I see the response, it is text/html anyways.

header('Content-type: application/pdf');

If I do this in a regular php page, everything works as expected. It seems that I need to tell Joomla to use application/pdf instead of text/html. How can I do it?

Note: Setting other headers, such as Content-Disposition, works as expected.

Answer:
Since version 1.5 Joomla has the JDocument object. Use
JDocument::setMimeEncoding()
to set the content type.
```
```
$doc =& JFactory::getDocument();
$doc->setMimeEncoding('application/pdf');
```
```
In your special case, a look at
JDocumentPDF
may be worthwile.


Question:
Our server application is listening on a port, and after a period of time it no longer accepts incoming connections.  (And while I'd love to solve this issue, it's not what I'm asking about here;)

The strange this is that when our app stops accepting connections on port 44044, so does IIS (on port 8080).  Killing our app fixes everything  - IIS starts responding again.

So the question is, can an application mess up the entire TCP/IP stack?  Or perhaps, how can an application do that?

Senseless detail: Our app is written in C#, under .Net 2.0, on XP/SP2.

Clarification: IIS is not "refusing" the attempted connections.  It is never seeing them.  Clients are getting a "server did not respond in a timely manner" message (using the .Net TCP Client.)

Answer:
You haven't maxed out the available port handles have you ?
```
netstat -a
```
I saw something similar when an app was opening and closing ports (but not actually closing them correctly).


Question:
Does IPsec in Windows XP Sp3 support AES-256 encryption?

Update:

Windows IPsec FAQ says that it's not supported in Windows XP, but maybe they changed it in Service Pack 3?

http://www.microsoft.com/technet/network/ipsec/ipsecfaq.mspx

Question: Is Advanced Encryption Standard (AES) encryption supported?

origamigumby, please specify where, because I cannot find it.

Answer:
You haven't maxed out the available port handles have you ?
```
netstat -a
```
I saw something similar when an app was opening and closing ports (but not actually closing them correctly).


Question:
Wanted to convert

<br/>
<br/>
<br/>
<br/>
<br/>

into

<br/>

Answer:
Use a regular expression to match
```
<br/>
```
one or more times, then use preg_replace (or similar) to replace with
```
<br/>
```
such as levik's reply.


Question:
Is there a way to make a Radio Button enabled/disabled (not checked/unchecked) via CSS?

I've need to toggle some radio buttons on the client so that the values can be read on the server, but setting the 'enabled' property to 'false' then changing this on the client via javascript seems to prevent me from posting back any changes to the radio button after it's been enabled.

See: ASP.NET not seeing Radio Button value change

It was recommended that I use control.style.add("disabled", "true") instead, but this does not seem to disable the radio button for me.

Thanks!

Answer:
Disabled is a html attribute, not a css attribute.
Why can't you just use some jQuery
```
```
$('#radiobuttonname').attr('disabled', 'true');
```
```
or plain old javascript
```
```
document.getElementById(id).disabled = true;
```
```


Question: I want to know if responsetimes are good, not just if it scales. Anyone with experiences?

Answer:
A scalable architecture like GAE is not the same as one based on optimizing speed. A different approach is needed.
The DataStore isn't designed to be super fast at the small scale, but rather handle large amounts of data, and be distributed.  We could say that database access is "very slow" at the small scale (compared with a standard relational database).
Take a look at:
google-appengine-second-look
and
how-i-learned-stop-worrying-and-love-using-lot-disk-space-scale
Some
experimental results
.


Question:
Ok, this is another one in the theory realm for the CS guys around.

In the 90's I did fairly well in implementing BST's. The only thing I could never get my head around was the intricacy of the algorithm to balance a Binary Tree (AVL).

Can you guys help me on this?

Answer:
I don't think it's good to post complete codes for node balancing algorithms here since they get quite big. However, the Wikipedia article on
red-black trees
contains a complete C implementation of the algorithm and the article on
AVL trees
has several links to high-quality implementations as well.
These two implementations are enough for most general-purpose scenarios.


Question:
I am using Vim for windows installed in Unix mode. Thanks to this site I now use the gf command to go to a file under the cursor.

I'm looking for a command to either:

return to the previous file (similar
to Ctrl+T for ctags), or

remap gf
to automatically launch the new file
in a new window.

Answer:
Ctrl
-
Shift
-
6
is one.
```
:e#↲
```
is another.


Question: I want to insert say 50,000 records into sql server database 2000 at a time. How to accomplish this?

Answer:
Do you mean for a test of some kind?
```
```
declare @index integer
set @index = 0
while @index < 50000
begin
   insert into table
   values (x,y,z)
   set @index = @index + 1
end
```
```
But I expect this is not what you mean.
If you mean the best way to do a bulk insert, use
```
BULK INSERT
```
or something like
```
bcp
```


Question:
In my ASP.net MVC app I have a view that looks like this:

...
<label>Due Date</label>
<%=Html.TextBox("due")%>
...

I am using a ModelBinder to bind the post to my model (the due property is of DateTime type). The problem is when I put "01/01/2009" into the textbox, and the post does not validate (due to other data being input incorrectly). The binder repopulates it with the date and time "01/01/2009 00:00:00".

Is there any way to tell the binder to format the date correctly (i.e. ToShortDateString())?

Answer:
In order to get strongly typed access to your model in the code behind of your view you can do this:
```
```
public partial class SomethingView : ViewPage<T>
{
}
```
```
Where T is the ViewData type that you want to pass in from your Action.
Then in your controller you would have an action :
```
```
public ActionResult Something(){
    T myObject = new T();
    T.Property = DateTime.Today();

    Return View("Something", myObject);
}
```
```
After that you have nice strongly typed model data in your view so you can do :
```
```
<label>My Property</label>
<%=Html.TextBox(ViewData.Model.Property.ToShortDateString())%>
```
```


Question:
When I am using Bitvise Tunnelier and I spawn a new xterm window connecting to our sun station everything works nicely. We have visual slick edit installed on the sun station and I have been instructed to open it using the command vs&. When I do this I get the following:

fbm240-1:/home/users/ajahn 1 % vs&
[1] 4716
fbm240-1:/home/users/ajahn 2 % Visual SlickEdit: Can't open connection to X. DIS
PLAY='<Default Display>'

I would rather not go jumping through hoops ftping my material back and forth to the server.
Advice?

Answer:
What is your DISPLAY environment variable in the shell where you run vs? Is it really "<Default Display>"? If yes, try setting it up to ":0" or "
yourhostname
:0" and then running vs again (you might need to use
```
xhost +
```
on your host).
That's only a fraction of the clarifications needed to help you with this.


Question:
I am developing a web application which has Chart Controls.
I have developed a common chart User Control to  use across the application.

I am looking for an elegent way to set the Chart control's along with other control's width, height based on the screen(browser size).

Please help me
Thanks
Shaik

Answer:
Generally speaking, the easiest way to size an element relative to the client screen is to give it a width specified as a percentage (e.g. 25%).  You can also size an object relative to the font size by specifying the width in terms of ems (e.g. 10em).
If percentages won't work, then the alternative is to use JavaScript to resize the object dynamically in the client's browser.  The downside to this is that JavaScript has to interact with the HTML elements that make up the control, rather than acting on the control directly.


Question:
I've created a new C++ project in Visual Studio 2008.  No code has been written yet;  Only project settings have been changed.

When I compile the project, I receive the following fatal error:

fatal error LNK1104: cannot open file 'C:\Program.obj'

Answer:
This particular issue is caused by specifying a dependency to a lib file that had spaces in its path.  The path needs to be surrounded by quotes for the project to compile correctly.
On the
Configuration Properties -> Linker -> Input
tab of the project’s properties, there is an
Additional Dependencies
property.  This issue was fixed by adding the quotes. For example, changing this property from:
C:\Program Files\sofware
sdk\lib\library.lib
To:
"C:\Program Files\sofware
sdk\lib\library.lib"
where I added the quotes.


Question:
When I use the  task, the property is only set to TRUE if the resource (say file) is available. If not, the property is undefined.

When I print the value of the property, it gives true if the resource was available, but otherwise just prints the property name.

Is there a way to set the property to some value if the resource is not available? I have tried setting the property explicitly before the available check, but then ant complains:

[available] DEPRECATED -  used to override an existing property.
[available]   Build file should not reuse the same property name for different values.

Answer:
You can use a condition in combination with not:
http://ant.apache.org/manual/Tasks/condition.html
```
```
<condition property="fooDoesNotExist">
    <not>
      <available filepath="path/to/foo"/>
    </not>
  </condition>
```
```


Question:
I am running Ruby and MySQL on a Windows box.

I have some Ruby code that needs to connect to a MySQL database a perform a select. To connect to the database I need to provide the password among other things.

The Ruby code can display a prompt requesting the password, the user types in the password and hits the Enter key. What I need is for the password, as it is typed, to be displayed as a line of asterisks.

How can I get Ruby to display the typed password as a line of asterisks in the 'dos box'?

Answer:
Poor man's solution:
```
```
system "stty -echo"
# read password
system "stty echo"
```
```
Or using
http://raa.ruby-lang.org/project/ruby-password/
The target audience for this library is system administrators who need to write Ruby programs that prompt for, generate, verify and encrypt passwords.
Edit:
Whoops I failed to notice that you need this for Windows :(


Question:
Lately I've be moving source files around in our source tree. For example placing a bunch of files into a common assembly.  I've been doing this my deleting the file from CVS and then adding it again in the new spot. The problem is the revision number of the file resets back to 1.1. Is there some simple way to move things without having the number reset.

I probably should have mentioned that I don't have access to the repository so anything that requires that doesn't help me but it might help others.

Answer:
The
online CVS manual
has some detail on how to do this:
The normal way to move a file is to issue a cvs rename command.
$ cvs rename old new
$ cvs commit -m "Renamed old to new"
This is the simplest way to move a file. It is not error prone, and it preserves the history of what was done. CVSNT clients can retrieve the original name by checking out an older version of the repository.
This feature is only supported on CVSNT servers 2.0.55 and later.


Question:
I am using RRDTool (http://oss.oetiker.ch/rrdtool/) as a graphing back-end for storing performance metrics.  This is done via the RRDTool CLI from a Python script.

My problem is that the script is multithreaded and each thread updates the RRD at a pretty rapid pace.  Sometimes an update fails because one thread is accessing the RRD file while another one tries to access it also.

I was under the impression that this is OK to try since RRDTool uses its own locking mechanism, but I guess that isn't true.

Does anyone have a good approach for concurrent access to an RRD?

I can think of a few ways to go:

have 1 thread create a queue and only feed the RRD from a single thread.

create my own locking mechanism inside the Python script. (how would I do this?)

got anything better or have you run into this issue before?

Answer:
An exclusive lock ought to be enough for this problem :
Python doc page
Use example
Define your lock object at the main level, not at the thread level, and you're done.
Edit in Response to comment :
if you define your lock (
```
lock = new Lock()
```
) at the thread level, you will have one lock object per running thread, and you really want a single lock for the file rrdtool updates, so this definition must be at the main level.


Question: What might be the best way to start programming using boost lambda libraries.

Answer:
Depends. Are you already well versed in functional programming concepts? If not, I'd suggest that you start in a language that is designed for functional programming instead of a procedural language with functional features stapled on. If you aren't used to coding in a functional style (it's not
harder
necessarily, but it's definitely different), then you'll spend more time fighting the syntax and not enough time learning to get stuff done.
As for where to start, I cut my functional teeth on Scheme, but there are plenty of good options.


Question: When developing an app that will listen on a TCP/IP port, how should one go about selecting a default port?  Assume that this app will be installed on many computers, and that avoiding port conflicts is desired.

Answer:
Go
here
and pick a port with the description
```
Unassigned
```


Question: How can I script a bat or cmd to stop and start a service reliably with error checking (or let me know that it wasn't successful for whatever reason)?

Answer:
Using the return codes from
```
net start
```
and
```
net stop
```
seems like the best method to me. Try a look at this:
Net Start return codes
.


Question:
I need to create a multi-dimensional (nested) hashtable/dictionary so that I can use syntax like

val = myHash("Key").("key")

I know I need to use Generics but I can't figure out the correct syntax using VB in ASP.NET 2.0, there are plenty of c# examples on the net but they aren't helping much.

Cheers!

Answer:
OK, I'm better at C# than vb.net, but I'll give this a go....
```
```
Dim myHash as Dictionary(Of string, Dictionary(Of string, Integer));
```
```


Question:
I have a line that I draw in a window and I let the user drag it around. So, my line is defined by two points: (x1,y1) and (x2,y2). But now I would like to draw "caps" at the end of my line, that is, short perpendicular lines at each of my end points. The caps should be N pixels in length.

Thus, to draw my "cap" line at end point (x1,y1), I need to find two points that form a perpendicular line and where each of its points are N/2 pixels away from the point (x1,y1).

So how do you calculate a point (x3,y3) given it needs to be at a perpendicular distance N/2 away from the end point (x1,y1) of a known line, i.e. the line defined by (x1,y1) and (x2,y2)?

Answer:
You need to compute a unit vector that's perpendicular to the line segment.  Avoid computing the slope because that can lead to divide by zero errors.
```
```
dx = x1-x2
dy = y1-y2
dist = sqrt(dx*dx + dy*dy)
dx /= dist
dy /= dist
x3 = x1 + (N/2)*dy
y3 = y1 - (N/2)*dx
x4 = x1 - (N/2)*dy
y4 = y1 + (N/2)*dx
```
```


Question:
This is a super basic question but I'm trying to execute a Query that I'm building via some form values against the MS Access database the form resides in.  I don't think I need to go through ADO formally, but maybe I do.

Anyway, some help would be appreciated.  Sorry for being a n00b. ;)

Answer:
You can use the following DAO code to query an Access DB:
```
```
Dim rs As DAO.Recordset
Dim db As Database

Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM Attendance WHERE ClassID = " & ClassID)

do while not rs.EOF
  'do stuff
  rs.movenext
loop

rs.Close
Set rs = Nothing
```
```
In my case, ClassID is a textbox on the form.


Question:
For example, if I have an echo statement, there's no guarantee that the browser might display it right away, might display a few dozen echo statements at once, and might wait until the entire page is done before displaying anything.

Is there a way to have each echo appear in a browser as it is executed?

Answer:
Start your investigation here:
http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts


Question: What are the best/most popular ways to do aspect-oriented programming (AOP) in C#/.Net?

Answer:
I've played around with rolling my own, for several different types of things.  I've had some luck.  In general, I make an interface, implement it with a class, and then make a proxy which implements the interface, does whatever precondition steps I want, calls the real object's method, and then does whatever postcondition steps I want.  One of the main annoyances of mine with this approach is that you can't have constructors in an interface, and you also can't have static methods in an interface, so there's no real obvious place to put that type of code.  The hard part is the code generation - because you're either going to emit IL, or you're going to emit C# that you have to compile.  But that's just been my approach.  And it forced me to think about one aspect at a time, really - I hadn't gotten to the point where I could abstract out the "Aspect" and think in those terms.  In short: roll your own or find a toolset you like, probably from
Eric Bodden's list
.


Question:
In VB6, I used a call to the Windows API, GetAsyncKeyState, to determine if the user has hit the ESC key to allow them to exit out of a long running loop.

Declare Function GetAsyncKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer

Is there an equivalent in pure .NET that does require a direct call to the API?

Answer:
You can find the P/Invoke declaration for GetAsyncKeyState from
http://pinvoke.net/default.aspx/user32/GetAsyncKeyState.html
Here's the C# signature for example:
```
```
[DllImport("user32.dll")]
static extern short GetAsyncKeyState(int vKey);
```
```


Question: Does anyone have a good set of Visio Stencils for MS SQL Server?

Answer:
I haven't tried it myself but there is one at
http://visiotoolbox.com/downloads.aspx?resourceid=1&aid=562


Question:
I need to be able to load the entire contents of a text file and load it into a variable for further processing.

How can I do that?

Here's what I did thanks to Roman Odaisky's answer.

SetLocal EnableDelayedExpansion
set content=
for /F "delims=" %%i in (test.txt) do set content=!content! %%i

echo %content%
EndLocal

Answer:
Use
```
for
```
, something along the lines of:
```
```
set content=
for /f "delims=" %%i in ('filename') do set content=%content% %%i
```
```
Maybe you’ll have to do
```
setlocal enabledelayedexpansion
```
and/or use
```
!content!
```
rather than
```
%content%
```
. I can’t test, as I don’t have any MS Windows nearby (and I wish you the same :-).
The best batch-file-black-magic-reference I know of is at
http://www.rsdn.ru/article/winshell/batanyca.xml
. If you don’t know Russian, you still could make some use of the code snippets provided.


Question:
I am thinking about buying an iPod touch to make some money on developing apps for the iPhone. I like the concept of the App Store and had a quick look at it with iTunes.
Looks like applications are categorized, to be iPhone OR iPod applications.
Some apps which are free for the iPod seem to cost for iPhone users.

What is the difference of both platforms, or why is the App Store separating them ?
Does it make sense to develop for the iPhone using an iPod touch (beside phone/location related apps) ?

On developer.apple.com I can sign up for selling my Applications on the AppStore for 99$.
Do I have to expect any further costs ?
Is it a problem to develop from outside the US (in my case Germany) ?

Answer:
The iPod touch is missing:
GPS
Bluetooth
(iPod Touch 4G has Bluetooth)
Cellular network
Camera
(iPod Touch 4G has front and back cameras)
Microphone (thanks
John Topley
)
(iPod Touch 4G has headset with microphone)
Vibration
The 1G is lacking a speaker
On the plus side it weighs a bit less and is a bit smaller.. Other than that they are pretty much identical (no sarcasm here; it still has the same processor, OS, control system, and display) Personally I would get an iPhone, as you will probably end up getting one later on anyway. I have an iPod touch (bought first) and an iPhone. I never use the iPod anymore.
The iPod touch is obviously cheaper than the iPhone, and there is no contract necessary. However, at least in the UK you can get a contract-free iPhone, and you should be able to do so soon on AT&T in the USA.
There are no extra costs besides the $99 for application development (which is a yearly fee)
We are developing from the UK. One issue to be aware of when you eventually sell your application is tax withholding - Apple will retain 30% of your revenues. There are some forms you need to fill out - I dealt with this in
another thread
. Here's what I wrote there:
You need to fill out a
W-8BEN
and give it to Apple to avoid a 30% tax withholding. This requires that you have a SSN (Social Security Number). If, and only if, you do not have an SSN, you may supply  an ITIN (Individual Taxpayer Identification Number) or an EIN (Employer ID Number).
To get an ITIN, you need to fill out form
W7
and submit that to the IRS.


Question:
Why are 'out' parameters in .NET a bad idea?

I was recently asked this, but I had no real answer besides it's simply unnecessarily complicating an application. What other reasons are there?

Answer:
I would say the answer you gave is about the best there is. You should always design away from
```
out
```
parameters if possible, because it usually makes the code needlessly complex.
But this is true of just about any pattern. If there is no need for it, don't use it.


Question:
On occasion, I find myself wanting to search the text of changelist descriptions in Perforce.  There doesn't appear to be a way to do this in P4V.  I can do it by redirecting the output of the changes command to a file...

p4 changes -l > p4changes.txt

...(the -l switch tells it to dump the full text of the changelist descriptions) and then searching the file, but this is rather cumbersome.  Has anyone found a better way?

Answer:
I use
p4sql
and run a query on the "changes" database. Here's the
perforce database schema
The query looks something like this (untested)
```
```
select change from changes where description like '%text%' and p4options = 'longdesc'
```
```
edit: added the p4options to return more than 31 characters in the description.


Question:
I have three divs:

<div id="login" />
<div id="content" />
<div id="menu" />

How would I define the CSS styles (without touching the HTML) to have the menu-div as the left column, the login-div in the right column and the content-div also in the right column but below the login-div.

The width of every div is fixed, but the height isn't.

Answer:
```
```
#menu {
  position:absolute;
  top:0;
  left:0;
  width:100px;
}
#content, #login {
  margin-left:120px;
}
```
```
Why this way?  The menu coming last in the markup makes it tough.  You might also be able to float both content and login right, and added a clear:right to content, but I think this might be your best bet.  Without seeing the bigger picture, it is hard to give a solution that will definitely work in your case.
EDIT: This seems to work as well:
```
```
#content, #login {
  float:right;
  clear:right
}
```
```
More thoughts:  The absolute positioning won't work (or won't work well) if you want to have the columns in a centered layout.  The float seems to work - as long as you can get any border-between-columns type requirements to pan out with the float solution, you might be better off choosing that.  Then again, if the site is supposed to be left align, I think that the absolute method would work very well for your needs.


Question:
I've recently installed the MVC CTP5 and VS is now crashing on me when I try to open an aspx, I get the following error in event viewer:

.NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506)

I was able to find This post on the asp.net forums relating to the same issue but nobody has had a working solution yet (at least not for me).

Just wondering if anyone else has run into this issue and what they have done to resolve it?

EDIT: Wanted to add that I have tried all the tips in the article and can open the markup with a code editor but was wondering an actual solution had been found to resolve this issue.. Thanks!

EDIT: I don't have this issue on my Vista box, seems to only occur on my XP VM.

Answer:
Here are a steps to work around from
the post
that work for me:
1.Open project based on CTP5
2.IN solution Explorer, enable "Show All files"
3.Open "bin" folder and delete "Microsoft.Web.Mvc.dll", "System.Web.Mvc.dll", "System.Web.Abstractions.dll", "System.Web.Routing.dll"
4.Open "References" folder, click ONCE "System.Web.Abstractions" and in Properties window change "Copy Local" to true. Repeat same with System.Web.Routing.
5.Build application (Ctrl+Shift+B)
6.Open site.master in designer. VS will not crash.


Question: I've been hearing conflicting facts about this topic. What is correct?

Answer:
You've been hearing conflicting views because it's a topic of great confusion, even among senior engineers. In short, simply placing an assembly in the GAC does implicitly give it full trust, but this can be overriden via security policy.
EDIT1: Let me add that a common thought is if you don't trust an assembly fully, why are you placing it in the GAC?
EDIT2: I had a link in here to a blog post from Michelle Bustamante, but as you can see in the comment below, it's no longer available so I removed it from this answer.


Question:
Please, provide code examples in a language of your choice.

Update:
No constraints set on external storage.

Example: Integers are received/sent via network. There is a sufficient space on local disk for intermediate results.

Answer:
1 million 32-bit integers = 4 MB of memory.
You should sort them using some algorithm that uses external storage. Mergesort, for example.


Question:
I need your advice regarding migration. I want to migrate existing project to ASP.NET MVC and I can figure out the proccess except of url rewriting issue:

for example how can I make following route:

http://www.eireads.com/ireland/mayo/cars-3/1263-used-cars-citroen-c5-for-sale.aspx

Or maybe I could somehow keep supporting legacy routes.

Answer:
I think you should really re-write your question and try to detail exactly what you are attempting to accomplish here.
If you are asking how to migrate an existing
WebForm
project into ASP.NET MVC keeping the same URL rewrite, the answer is; not easily. The models are too different.
Yet, you mention "routes" in the end, which make me think you are speaking like those of the System.Web.Routing namespace. So are you dealing with an existing MVC app and want it too look like that URL path? I can't tell. I am confused.


Question:
Here's the code that I'm attempting to do:

public IList<IOperator> GetAll()
{
      using (var c = new MyDataContext())
      {
          return c.Operators.ToList();
      }
}

Operator implements IOperator, but I'm getting the following compilation error:

Cannot implicitly convert type 'System.Collections.Generic.List<MyProject.Core.Operator>' to 'System.Collections.Generic.IList<MyProject.Core.Model.IOperator>'. An explicit conversion exists (are you missing a cast?)

How do I cast this to get what I need?

Answer:
Try the
```
Cast<>()
```
method:
```
```
return c.Operators.Cast<IOperator>().ToList();
```
```


Question:
I'm trying to use the this keyword in a static method, but the compiler won't allow me to use it.

Why not?

Answer:
That's an easy one. The keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class. There is a much more
in depth explanation
of what static members are and why/when to use them in the MSDN docs.


Question:
We need to make our enterprise ASP.NET/NHibernate browser-based application able to function when connected to or disconnected from the customer's server. Has anyone done this? If so, how did you do it? (Technology, architecture, etc.)

Background:

We develop and sell an enterprise browser-based application used by construction field personnel to enter timesheet information. Currently, it requires a connection to the server back in the customer's office and we'd like to build an occasionally-connected version of the application for those clients without wireless Internet availability.

Our application is an ASP.NET application using NHibernate for O/R mapping. Being a Microsoft shop, the Microsoft Sync Framework is attractive, but we don't know whether it "plays well" with NHibernate.

Any insight would be greatly appreciated.

Dave T

Answer:
Maybe you could operate some kind of offline version using a small version database (I hear good things about vistadb -
http://www.vistadb.net/
which I believe does play well with NHibernate). With a syncing tool to copy data in when they are back on line. A click-once launcher could handle installation and integration.
Want to be careful with anything involving syncing though - if it is just single user timesheets that might be OK - but if there are any chances of conflicts in the online-offline data you might be better considering the problem from a different angle for pain-avoidance...


Question:
Currently Tomcat's login support redirects users back to where they initially were when the application figured out they weren't logged in.

For this particular application I need to force them to always go back to index.jsp.

I'm pretty sure this is a simple configuration option in the WAR's web.xml, but I haven't found the answer in google.

Answer:
It's something you can't configure in web.xml as it is not part of the standard. For Tomcat (tested on version 6.0.14) you can force users back to index.jsp by adding the next code on top of your login.jsp. It redirects every request that does not have a parameter with the name 'login' in the url to the /index.jsp?login page. Because the redirect does have the 'login' parameter the user will be presented the login page.
It's not a secure solution. If someone requests for a page and adds the login parameter, he will be redirected. So:
/showPerson?id=1234 will redirect to /index.jsp?login
/showPerson?id=1234?login will NOT redirect to /index.jsp?login
The code that goes on top of your login.jsp:
```
```
<%
if (request.getParameter("login") == null) {
    response.sendRedirect(request.getContextPath() + "/index.jsp?login");
    return;
}
%>
```
```
Instead of using the 'login' parameter you probably could use a cookie. You can make it more secure by creating a random value for the login parameter (login=randomvalue) and store the value in the session object for comparison.


Question:
After reading the answers to the question "Calculate Code Metrics" I installed the tool SourceMonitor and calculated some metrics.

But I have no idea how to interpret them.

What's a "good" value for the metric

"Percent Branch Statements"

"Methods per Class"

"Average Statements per Method"

"Maximum Method or Function
Complexity"

I found no hints in the documentation, can anybody help me?

Answer:
SourceMonitor is an awesome tool.
"Methods Per Class" is useful to those who wish to ensure their classes follow good OO principles (too many methods indicates that a class could be taking on more than it should).
"Average Statements per Method" is useful for a general feel of how big each method is.  More useful to me is the info on the methods with too many statements (double click on the module for finer grain detail).
Function Complexity is useful for ascertaining how nasty the code is.  Truly I use this info more than anything else.  This is info on how complicated the nastiest function in a module is (at least according to cyclomatic complexity).  If you double click on the module / file you can find out which particular method is so bad.


Question:
Is there any difference between having 4 .5GB memcache servers running or one 2GB instance?

Does running multiple instances offer any benifits?

Answer:
High availability is nice, and memcached will automatically distribute your cache across the 4 servers. If one of those servers dies for some reason, you can handle that error by either just continuing as if the cache was blank, redirecting to a different server, or any sort of custom error handling you want. If your 1x 2gb server dies, then your options are pretty limited.
The important thing to remember is that you do not have 4 copies of your cache, it is 1 cache, split amongst the 4 servers.
The only downside is that it's easier to run out of 4x .5 than it is to run out of 1x 2gb memory.


Question:
I would like to listen to method calls.

For example, when an element is appended by anything to the document, I would like to be passed that element to act on it, like:

//somewhere

aParent.appendChild(aChild);

//when the former, a function I defined as listener is called with the aChild as argument

Does anybody know how to do that?

Answer:
don't know if that's possible with the core functions, but you could always create your own functions, for the actions you want to monitor:
```
```
function AppendChild(oParent, oChild) {

   // your stuff on oParent

   // append oChild
   oParent.appendChild(oChild)
}
```
```
or, maybe, modify the actual appendChild(), but that would be tricky...


Question:
Every indication I have, based on my experience in embedded computing is that doing something like this would require expensive equipment to get access to the platform (ICE debuggers, JTAG probes, I2C programmers, etc, etc), but I've always wondered if some ambitious hacker out there has found a way to load native code on a Blackberry device.   Anyone?

Edit: I'm aware of the published SDK and it's attendant restrictions.  I'm curious if anyone has attempted to get around them, and if so, how far they got.

Answer:
Unfortunately the official
SDK website
only seems to mention Java.  According to
wikipedia
, different versions of the BlackBerry use different processors.  Combined with the fact that RIM uses a proprietary operating system for the devices, it becomes pretty difficult to develop native code without official tools.  There is also a partial API-level security restriction which would further prohibit advanced tinkering.


Question:
I have a JSP that allows users to dynamically create additional form fields to create multiple objects. Perhaps I want to allow users to be able to submit as many line items as they want when submitting an invoice form.

How do I create a Struts 2 Action that will be able to take in an ArrayList populated with objects created from those dynamically generated fields.

Answer:
Unfortunately the official
SDK website
only seems to mention Java.  According to
wikipedia
, different versions of the BlackBerry use different processors.  Combined with the fact that RIM uses a proprietary operating system for the devices, it becomes pretty difficult to develop native code without official tools.  There is also a partial API-level security restriction which would further prohibit advanced tinkering.


Question:
I'm refactoring "spaghetti code" C module to work in multitasking (RTOS) environment.

Now, there are very long functions and many unnecessary global variables.

When I try to replace global variables that exists only in one function with locals, I get into dilemma. Every global variable is behave like local "static" - e.g. keep its value even you exit and re-enter to the function.

For multitasking "static" local vars are worst from global. They make the functions non reentered.

There are a way to examine if the function is relay on preserving variable value re-entrancing without tracing all the logical flow?

Answer:
Please give examples of what you call 'global' and 'local' variables
```
```
int global_c; // can be used by any other file with 'extern int global_c;'

static int static_c; // cannot be seen or used outside of this file.

int foo(...)
{
   int local_c; // cannot be seen or used outside of this function.
}
```
```
If you provide some code samples of what you have and what you changed we could better answer the question.


Question: I am using a popup menu in Delphi.  I want to use it in a "radio group" fashion where if the user selects an item it is checked and the other items are not checked.  I tried using the AutoCheck property, but this allows multiple items to be checked.  Is there a way to set the popup menu so that only one item can be checked?

Answer:
Zartog is right, but if you want to keep the checkbox, assign this event to every item in the popup menu.
Note that this code is a little hairy looking because it does not depend on knowing the name of your popup menu (hence, looking it up with "GetParentComponent").
```
```
procedure TForm2.OnPopupItemClick(Sender: TObject);
var
  i : integer;
begin
  with (Sender as TMenuItem) do begin
    //if they just checked something...
    if Checked then begin
      //go through the list and *un* check everything *else*
      for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin
        if i <> MenuIndex then begin  //don't uncheck the one they just clicked!
          (GetParentComponent as TPopupMenu).Items[i].Checked := False;
        end;  //if not the one they just clicked
      end;  //for each item in the popup
    end;  //if we checked something
  end;  //with
end;
```
```
You can assign the event at runtime to every popup box on your form like this (if you want to do that):
```
```
procedure TForm2.FormCreate(Sender: TObject);
var
  i,j: integer;
begin
  inherited;

  //look for any popup menus, and assign our custom checkbox handler to them
  if Sender is TForm then begin
    with (Sender as TForm) do begin
      for i := 0 to ComponentCount - 1 do begin
        if (Components[i] is TPopupMenu) then begin
          for j := 0 to (Components[i] as TPopupMenu).Items.Count - 1 do begin
            (Components[i] as TPopupMenu).Items[j].OnClick := OnPopupItemClick;
          end;  //for every item in the popup list we found
        end;  //if we found a popup list
      end;  //for every component on the form
    end;  //with the form
  end;  //if we are looking at a form
end;
```
```
In response to a comment below this answer: If you want to require at least one item to be checked, then use this instead of the first code block.  You may want to set a default checked item in the oncreate event.
```
```
procedure TForm2.OnPopupItemClick(Sender: TObject);
var
  i : integer;
begin
  with (Sender as TMenuItem) do begin
    //go through the list and make sure *only* the clicked item is checked
    for i := 0 to (GetParentComponent as TPopupMenu).Items.Count - 1 do begin
      (GetParentComponent as TPopupMenu).Items[i].Checked := (i = MenuIndex);
    end;  //for each item in the popup
  end;  //with
end;
```
```


Question: I have two controllers which share most of their code (but must be, nonetheless, different controllers). The obvious solution (to me, at least) is to create a class, and make the two controllers inherit from it. The thing is... where to put it? Now I have it in app_controller.php, but it's kind of messy there.

Answer:
In cake, components are used to store logic that can be used by multiple controllers.  The directory is /app/controllers/components.  For instance, if you had some sharable utility logic, you would have an object called UtilComponent and a file in /app/controlers/components called UtilComponent.php.
```
```
<?php
class UtilComponent extends Object {
    function yourMethod($param) {
        // logic here.......

        return $param;
    }
}
?>
```
```
Then, in your controller classes, you would add:
```
```
var $components = array('Util');
```
```
Then you call the methods like:
```
```
$this->Util->yourMethod($yourparam);
```
```
More Info:
Documentation


Question: I wasn't aware of a difference, but a coworker says there is, although he can't back it up. What's the difference if any?

Answer:
There is a difference, yes.
XML that adheres to the
XML standard
is considered well formed, while xml that adheres to a
DTD
is considered valid.


Question:
I distribute software online, and always wonder if there is a proper way to better define version numbers.

Let's assume A.B.C.D in the answers.  When do you increase each of the components?

Do you use any other version number tricks such as D mod 2 == 1 means it is an in house release only?

Do you have beta releases with their own version numbers, or do you have beta releases per version number?

Answer:
I use V.R.M  e.g. 2.5.1
V (version) changes are a major rewrite
R (revision) changes are significant new features or bug fixes
M (modification) changes are minor bux fixes (typos, etc)
I sometimes use an SVN commit number on the end too.


Question: Does anyone know how in ASP.Net's TreeView control, to have a custom style applied to an Expanded node? I have many root nodes and want the Expanded nodes to have a different background.

Answer:
There is no way of doing this with out of the box controls and this goes for alot of MS ASP.NET controls, however there is an adapters project on codeplex that makes your ASP.NET controls CSS-friendly:
http://www.codeplex.com/cssfriendly
Its pretty straight forward but ask again if you need any help setting it up.


Question: It should be hands-on, complete, targeted to programmers and detailed on layout techniques!

Answer:
Are you looking for a free screen cast? If not, Eric Meyer (one of the gods of web standards)  has a video called
CSS Web Design
which will tell you everything you need to be fluent with CSS.
It also covers some advanced CSS techniques like
Sliding Doors
. He also goes and refactors some HTML on some well known websites to take advantage of CSS.
If you are a fast learner,
W3School's CSS
section has more than enough information to get you started. CSS is actually very easy to learn.


Question:
I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a std::string pointer?

Here's what I was looking forward to doing:

void Foo::Bar() {
    if(!QueryPerformanceTimer(&m_baz)) {
        throw new std::string("it's the end of the world!");
    }
}

void Foo::Caller() {
    try {
        this->Bar(); // should throw
    }
    catch(std::string *caught) { // not quite sure the syntax is OK here...
        std::cout << "Got " << caught << std::endl;
    }
}

Answer:
It works, but I wouldn't do it if I were you.  You don't seem to be deleting that heap data when you're done, which means that you've created a memory leak.  The C++ compiler takes care of ensuring that exception data is kept alive even as the stack is popped, so don't feel that you need to use the heap.
Incidentally, throwing a
```
std::string
```
isn't the best approach to begin with.  You'll have a lot more flexibility down the road if you use a simple wrapper object.  It may just encapsulate a
```
string
```
for now, but maybe in future you will want to include other information, like some data which caused the exception or maybe a line number (very common, that).  You don't want to change all of your exception handling in every spot in your code-base, so take the high road now and don't throw raw objects.


Question:
I've been searching on SO on how to do i18n support on my little application...

I know that Microsoft offers 'culture' classes, but you have to re-compile your application to include any new string you add. So, all I'm trying to do is to put all my strings in a external file and offers users the choice to translate the app without the need to recompile.

Is there an easy way to handle this ? Use XML, or INI-like ? any Tutorial available ?
P.S: Trying to do this on C#... Don't bother if other languages

Answer:
if you include a new string in your app, you have to recompile it anyway, do you not?
if you add languages often, resource files and/or satellite DLLs are probably your best bet
failing that, you can write your own provider. Here are some links I found useful, your mileage may vary:
http://en.csharp-online.net/Localization_Like_the_Pros
http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=211
http://www.codeproject.com/KB/aspnet/DeclarativeGlobalization.aspx
MS toolkit for web pages
CE solution


Question:
I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior.

Here are some trivial examples where they functionally do the same thing if either were found within another function:

Lambda function

>>> a = lambda x : 1 + x
>>> a(5)
6

Nested function

>>> def b(x): return 1 + x

>>> b(5)
6

Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.)

Does it even matter? If it doesn't then does that violate the Pythonic principle:

There should be one-- and preferably only one --obvious way to do it..

Answer:
If you need to assign the
```
lambda
```
to a name, use a
```
def
```
instead.
```
def
```
s are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable.
```
lambda
```
s can be used for
use once, throw away
functions which won't have a name.
However, this use case is very rare. You rarely need to pass around unnamed function objects.
The builtins
```
map()
```
and
```
filter()
```
need function objects, but
list comprehensions
and
generator expressions
are generally more readable than those functions and can cover all use cases, without the need of lambdas.
For the cases you really need a small function object, you should use the
```
operator
```
module functions, like
```
operator.add
```
instead of
```
lambda x, y: x + y
```
If you still need some
```
lambda
```
not covered, you might consider writing a
```
def
```
, just to be more readable. If the function is more complex than the ones at
```
operator
```
module, a
```
def
```
is probably better.
So, real world good
```
lambda
```
use cases are very rare.


Question: What is your preferred method for reading through the contents of zipped directories with Perl ?

Answer:
There are several modules on CPAN for working with various archive formats (zip, tar, etc.), the one you're probably after is
Archive::Zip
.


Question: I have a DataGrid, with an ItemTemplate that has an image and label.  In the EditItemTemplate the label is replaced by a textbox.  My problem is that the edit template only shows when I click the Edit button the second time.  What gives?

Answer:
Make sure you check for Page.IsPostback before binding your datagrid. It may be the case that you are binding during every page load.
```
```
If Not Page.IsPostBack() Then
    DoDataBinding()
End If
```
```


Question:
I would like to sort a matrix according to a particular column. There is a sort function, but it sorts all columns independently.

For example, if my matrix data is:

 1     3
 5     7
-1     4

Then the desired output (sorting by the first column) would be:

-1     4
 1     3
 5     7

But the output of sort(data) is:

-1     3
 1     4
 5     7

How can I sort this matrix by the first column?

Answer:
I think the
sortrows
function is what you're looking for.
```
```
>> sortrows(data,1)

ans =

    -1     4
     1     3
     5     7
```
```


Question:
Whilst refactoring some code I came across some getter methods that returns a std::string.  Something like this for example:

class foo
{
private:
    std::string name_;
public:
    std::string name()
    {
        return name_;
    }
};

Surely the getter would be better returning a const std::string&?  The current method is returning a copy which isn't as efficient.  Would returning a const reference instead cause any problems?

Answer:
I'd change it to return const std::string&.  The caller will probably make a copy of the result anyway if you don't change all the calling code, but it won't introduce any problems.
One potential wrinkle arises if you have multiple threads calling name().  If you return a reference, but then later change the underlying value, then the caller's value will change.  But the existing code doesn't look thread-safe anyway.
Take a look at Dima's answer for a related potential-but-unlikely problem.


Question:
I have a data table with a variable number of columns and a data scroller. How can I enable server side sorting? I prefer that it be fired by the user clicking the column header.

<rich:datascroller for="instanceList" actionListener="#{pageDataModel.pageChange}"/>
<rich:dataTable id="instanceList" rows="10" value="#{pageDataModel}"
                var="fieldValues" rowKeyVar="rowKey">
  <rich:columns value="#{pageDataModel.columnNames}" var="column" index="idx">
    <f:facet name="header">
      <h:outputText value="#{column}"/>
    </f:facet>
    <h:outputText value="#{classFieldValues[idx]}" />
  </rich:columns>
</rich:dataTable>

I already have a method on the bean for executing the sort.

public void sort(int column)

Answer:
I ended up doing it manually. I adding a support tag to the header text tag, like so.
```
```
<h:outputText value="#{column}">
  <a4j:support event="onclick" action="#{pageDataModel.sort(idx)}"
               eventsQueue="instancesQueue"
               reRender="instanceList,instanceListScroller"/>
</h:outputText>
```
```
To get the ascending/descending arrows, I added a css class.
```
```
<h:outputText value="#{column}" styleClass="#{pageDataModel.getOrderClass(idx)}" >
  <a4j:support event="onclick" action="#{pageDataModel.sort(idx)}"
               eventsQueue="instancesQueue"
               reRender="instanceList,instanceListScroller"/>
</h:outputText>
```
```


Question: What is the difference between bool and Boolean types in C#?

Answer:
I don't believe there is one.
```
bool
```
is just an alias for
```
System.Boolean
```


Question: I work for a product development company.We first do internal releases,and then public release.I was wondering, how other product developing companies manage their release? How do you give release number? Tag the source control?

Answer:
We use SubVersion, where tags and branches are cheap to create.
As far as releases go, we follow this convention:
(Major Release).(Minor Release).(Patch Release).(SVN revision)
Patch Release = bug fixes
Minor Release = binary compatible /
interface compatible
Major Release = includes breaking
changes.
Does that make sense?  If you need more information, add a comment and I'll edit my post to clarify.


Question:
Stateless beans in Java do not keep their state between two calls from the client. So in a nutshell we might consider them as objects with business methods. Each method takes parameters and return results. When the method is invoked some local variables are being created in execution stack. When the method returns the locals are removed from the stack and if some temporary objects were allocated they are garbage collected anyway.

From my perspective that doesn’t differ from calling method of the same single instance by separate threads. So why cannot a container use one instance of a bean instead of pooling a number of them?

Answer:
Pooling does several things.
One, by having one bean per instance, you're guaranteed to be threads safe (Servlets, for example, are not thread safe).
Two, you reduce any potential startup time that a bean might have. While Session Beans are "stateless", they only need to be stateless with regards to the client. For example, in EJB, you can inject several server resources in to a Session Bean. That state is private to the bean, but there's no reason you can't keep it from invocation to invocation. So, by pooling beans you reduce these lookups to only happening when the bean is created.
Three, you can use bean pool as a means to throttle traffic. If you only have 10 Beans in a pool, you're only going to get at most 10 requests working simultaneously, the rest will be queued up.


Question:
I have an index.php file which has to process many different file types. How do I guess the filetype based on the REQUEST_URI?

If I request http://site/image.jpg, and all requests redirect through index.php, which looks like this

<?php
   include('/www/site'.$_SERVER['REQUEST_URI']);
?>

How would I make that work correctly?

Should I test based on the extension of the file requested, or is there a way to get the filetype?

Answer:
If you are sure you're only ever working with images, you can check out the
exif_imagetype()
PHP function, which attempts to return the image MIME type.
If you don't mind external dependencies, you can also check out the excellent
getID3
library which can determine the MIME type of many different file types.
Lastly, you can check out the
mime_content_type()
function - but it has been deprecated for the
Fileinfo
PECL extension.


Question:
How do I easily undo a git rebase? A lengthy manual method is:

checkout the commit parent to both of the branches

create and checkout a temporary branch

cherry-pick all commits by hand

reset the faulty rebased branch to point to the temporary branch

In my current situation, this works because I can easily spot commits from both branches (one was my stuff, the other was my colleague's stuff). However, my approach strikes me as suboptimal and error-prone (let's say I had just rebased with two of my own branches).

Clarification: I am talking about a rebase during which multiple commits were replayed, not only one.

Answer:
The easiest way would be to find the head commit of the branch as it was immediately before the rebase started in the
reflog
...
```
```
git reflog
```
```
and to reset the current branch to it (with the usual caveats about being absolutely sure before reseting with the
```
--hard
```
option).
Suppose the old commit was
```
HEAD@{2}
```
in the ref log:
```
```
git reset --hard HEAD@{2}
```
```
In Windows, you may need to quote the reference:
```
```
git reset --hard "HEAD@{2}"
```
```
You can check the history of the candidate old head by just doing a
```
git log HEAD@{2}
```
(
Windows:
```
git log "HEAD@{2}"
```
).
If you've not disabled per branch reflogs you should be able to simply do
```
git reflog branchname@{1}
```
as a rebase detaches the branch head before reattaching to the final head. I would double check this, though as I haven't verified this recently.
Per default, all reflogs are activated for non-bare repositories:
```
```
[core]
    logAllRefUpdates = true
```
```


Question:
After making it through the major parts of an introductory Lisp book, I still couldn't understand what the special operator (quote) (or equivalent ') function does, yet this has been all over Lisp code that I've seen.

What does it do?

Answer:
It says "don't evaluate me".  For example, if you wanted to use a list as data, and not as code, you'd put a quote in front of it.  For example,
```
(print '(+ 3 4))
```
prints "(+ 3 4)", whereas
```
(print (+ 3 4))
```
prints "7"