q:
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:

ç é

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


q:
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

[A]
```
```
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).

s: huggingface

c: devops

d: intermediate


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


q: 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?

[A]
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.


q:
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?

[A]
'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.


q:
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

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


q:
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?

[A]
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.


q:
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?

[A]
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.


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

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


q:
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?

[A]
I believe you can compile with
```
```
-Wno-unknown-pragmas
```
```
to suppress these.


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

[A]
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.


q:
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.

[A]
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!


q:
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

[A]
Use:
```
```
echo hello
echo:
echo world
```
```


q:
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?

[A]
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
```
```


q:
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.

[A]
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
```
```


q:
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

[A]
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.


q:
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?

[A]
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!


q: 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.

[A]
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).


q:
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?

[A]
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.


q:
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?

[A]
```
==
```
determines if the values are equal, while
```
is
```
determines if they are the exact same object.


q:
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?

[A]
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
```
```


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

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


q:
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.

[A]
```
```
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).


q:
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?

[A]
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.


q:
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.

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


q: 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?

[A] 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.


q:
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?

[A]
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.


q:
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?

[A]
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!


q:
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?

[A] 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).


q:
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.

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


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

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


q:
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.

[A]
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.


q:
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.

[A]
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.


q:
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?

[A]
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


q:
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?

[A]
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
    });
}
```
```


q:
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?

[A]
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.


q:
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

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


q:
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.

[A]
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.


q:
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.

[A]
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.


q:
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.)

[A]
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).


q:
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.


q:
Wanted to convert

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

into

<br/>

[A]
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.


q:
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!

[A]
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;
```
```


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

[A]
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
.


q:
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?

[A]
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.


q:
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.

[A]
Ctrl
-
Shift
-
6
is one.
```
:e#↲
```
is another.


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

[A]
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
```


q:
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())?

[A]
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())%>
```
```


q:
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?

[A]
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.


q:
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

[A]
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.


q:
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'

[A]
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.


q:
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.

[A]
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>
```
```


q:
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'?

[A]
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 :(


q:
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.

[A]
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.


q:
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?

[A]
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.


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

[A]
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.


q: 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.

[A]
Go
here
and pick a port with the description
```
Unassigned
```


q: 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)?

[A]
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
.


q:
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!

[A]
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));
```
```


q:
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)?

[A]
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
```
```


q:
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. ;)

[A]
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.


q:
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?

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


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

[A]
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
.


q:
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?

[A]
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);
```
```


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

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


q:
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

[A]
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.


q:
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) ?

[A]
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.


q:
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?

[A]
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.


q:
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?

[A]
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.


q:
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.

[A]
```
```
#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.


q:
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.

[A]
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.


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

[A]
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.


q:
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.

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


q:
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.

[A]
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.


q:
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?

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


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

Why not?

[A]
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.


q:
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

[A]
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...


q:
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.

[A]
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.


q:
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?

[A]
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.


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

Does running multiple instances offer any benifits?

[A]
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.


q:
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?

[A]
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...


q:
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.

[A]
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.


q:
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.


q:
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?

[A]
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.


q: 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?

[A]
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;
```
```


q: 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.

[A]
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


q: 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?

[A]
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.


q:
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?

[A]
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.


q: 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.

[A]
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.


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

[A]
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.


q:
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;
    }
}

[A]
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.


q:
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

[A]
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


q:
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..

[A]
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.


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

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


q: 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?

[A]
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
```
```


q:
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?

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

ans =

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


q:
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?

[A]
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.


q:
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)

[A]
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>
```
```


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

[A]
I don't believe there is one.
```
bool
```
is just an alias for
```
System.Boolean
```


q: 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?

[A]
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.


q:
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?

[A]
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.


q:
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?

[A]
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.


q:
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.

[A]
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
```
```


q:
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?

[A]
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"


q: What is the best way to return XML from a controller's action in ASP.NET MVC?  There is a nice way to return JSON, but not for XML.  Do I really need to route the XML through a View, or should I do the not-best-practice way of Response.Write-ing it?

[A]
Use
MVCContrib
's XmlResult Action.
For reference here is their code:
```
```
public class XmlResult : ActionResult
{
    private object objectToSerialize;

    /// <summary>
    /// Initializes a new instance of the <see cref="XmlResult"/> class.
    /// </summary>
    /// <param name="objectToSerialize">The object to serialize to XML.</param>
    public XmlResult(object objectToSerialize)
    {
        this.objectToSerialize = objectToSerialize;
    }

    /// <summary>
    /// Gets the object to be serialized to XML.
    /// </summary>
    public object ObjectToSerialize
    {
        get { return this.objectToSerialize; }
    }

    /// <summary>
    /// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream.
    /// </summary>
    /// <param name="context">The controller context for the current request.</param>
    public override void ExecuteResult(ControllerContext context)
    {
        if (this.objectToSerialize != null)
        {
            context.HttpContext.Response.Clear();
            var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType());
            context.HttpContext.Response.ContentType = "text/xml";
            xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize);
        }
    }
}
```
```


q:
Is there a command or an existing script that will let me view all of a *NIX system's scheduled cron jobs at once? I'd like it to include all of the user crontabs, as well as /etc/crontab, and whatever's in /etc/cron.d. It would also be nice to see the specific commands run by run-parts in /etc/crontab.

Ideally, I'd like the output in a nice column form and ordered in some meaningful way.

I could then merge these listings from multiple servers to view the overall "schedule of events."

I was about to write such a script myself, but if someone's already gone to the trouble...

[A]
You would have to run this as root, but:
```
```
for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done
```
```
will loop over each user name listing out their crontab.  The crontabs are owned by the respective users so you won't be able to see another user's crontab w/o being them or root.
Edit
if you want to know which user a crontab belongs to, use
```
echo $user
```
```
```
for user in $(cut -f1 -d: /etc/passwd); do echo $user; crontab -u $user -l; done
```
```


q:
We will need to call out to a 3rd party to retrieve a value using REST, however if we do not receive a response within 10ms, I want to use a default value and continue processing.

I'm leaning towards using an asynchronous WebRequest do to this, but I was wondering if there was a trick to doing it using a synchronous request.

Any advice?

[A]
If you are doing a request and waiting on it to return I'd say stay synchronous - there's no reason to do an async request if you're not going to do anything or stay responsive while waiting.
For a sync call:
```
```
WebRequest request = WebRequest.Create("http://something.somewhere/url");
WebResponse response = null;
request.Timeout = 10000; // 10 second timeout
try
{
    response = request.GetResponse();
}
catch(WebException e)
{
  if( e.Status == WebExceptionStatus.Timeout)
  {
    //something
  }
}
```
```
If doing async:
You will have to call Abort() on the request object - you'll need to check the timeout yourself, there's no built-in way to enforce a hard timeout.


q:
I like to keep my source files on a USB drive for the portability. To date I have been using Visual SourceSafe for this purpose. What is a good alternative to VSS that fulfils these criteria:

Entire database can be held on a USB "pen" drive

Code / documentation duplicated on local drives

Does not require a central server

Easy to backup and restore using standard backup tools

Integrates with Visual Studio

Has a small footprint

Easy to clean the database and keep small

Compatible with Windows XP, Vista and Vista x64

A good reference on setup would be good too.

[A]
Don't use SourceSafe.  There's major problems with it.  See this:
Article1
Article2
I'd recommend using SubVersion instead.
If you're using Windows, you can use
TortoiseSVN
.
If you're working on Linux or other Unix variants, try
RapidSVN
.


q:
How would I be able to get N results for several groups in
an oracle query.

For example, given the following table:

|--------+------------+------------|
| emp_id | name       | occupation |
|--------+------------+------------|
|      1 | John Smith | Accountant |
|      2 | Jane Doe   | Engineer   |
|      3 | Jack Black | Funnyman   |
|--------+------------+------------|

There are many more rows with more occupations.  I would like to get
three employees (lets say) from each occupation.

Is there a way to do this without using a subquery?

[A]
I'm not sure this is very efficient, but maybe a starting place?
```
```
select *
from people p1
    join people p2
        on p1.occupation = p2.occupation
    join people p3
        on p1.occupation = p3.occupation
        and p2.occupation = p3.occupation
where p1.emp_id != p2.emp_id
    and p1.emp_id != p3.emp_id
```
```
This should give you rows that contain 3 distinct employees all in the same occupation.  Unfortunately, it will give you ALL combinations of those.
Can anyone pare this down please?


q: In Ruby, is there the equivalent of the __str__() method that you can define on Python classes?

[A]
On the core classes it is typically 'inspect'.
Eg:
```
```
irb(main):001:0> puts "array is: #{[1,2,3].inspect}"
array is: [1, 2, 3]
=> nil
irb(main):002:0> puts "array is: #{[1,2,3]}"
array is: 123
=> nil
irb(main):003:0>
```
```


q:
I have a problem with stopping a service and starting it again and want to be notified when the process runs and let me know what the result is.

Here's the scenario,
I have a text file output of an "sc" command. I want to send that file but not as an attachment.  Also, I want to see the initial status quickly in the subject of the email.

Here's the 'servstop.txt' file contents:

[SC] StartService FAILED 1058:

The service cannot be started, either
  because it is disabled or because it
  has no enabled devices associated with
  it.

I want the subject of the email to be "Alert Service Start: [SC] StartService FAILED 1058"
and the body to contain the entire error message above.

I will put my current method in an answer below using a program called blat to send me the result.

[A]
If the
```
<loner>
```
element in your sample XML didn't have the
```
xmlns
```
default namespace declaration on it, then it would be in the
```
whatever:name-space-1.0
```
namespace rather than being in no namespace. If that's what you want, you need to create the element in that namespace:
```
```
xml.CreateElement("loner", "whatever:name-space-1.0")
```
```
If you want the
```
<loner>
```
element to be in no namespace, then the XML that's been produced is exactly what you need, and you shouldn't worry about the
```
xmlns
```
attribute that's been added automatically for you.


q: In ruby the library path is provided in $:, in perl it's in @INC - how do you get the list of paths that Python searches for modules when you do an import?

[A]
```
```
import sys
sys.path
```
```


q: Why or why not?

[A]
```
xrange()
```
is more efficient because instead of generating a list of objects, it just generates one object at a time. Instead of 100 integers, and all of their overhead, and the list to put them in, you just have one integer at a time. Faster generation, better memory use, more efficient code.
Unless I specifically need a list for something, I always favor
```
xrange()
```


q:
This may be a matter of style, but there's a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter...

Basically, we have some debug print statements which we turn off during normal development. Personally I prefer to do the following:

//---- SomeSourceFile.cpp ----

#define DEBUG_ENABLED (0)

...

SomeFunction()
{
    int someVariable = 5;

#if(DEBUG_ENABLED)
    printf("Debugging: someVariable == %d", someVariable);
#endif
}

Some of the team prefer the following though:

// #define DEBUG_ENABLED

...

SomeFunction()
{
    int someVariable = 5;

#ifdef DEBUG_ENABLED
    printf("Debugging: someVariable == %d", someVariable);
#endif
}

...which of those methods sounds better to you and why? My feeling is that the first is safer because there is always something defined and there's no danger it could destroy other defines elsewhere.

[A]
```
#if
```
gives you the option of setting it to 0 to turn off the functionality, while still detecting that the switch is there.
Personally I always
```
#define DEBUG 1
```
so I can catch it with either an #if or #ifdef


q:
I seem to be seeing more 'for' loops over iterators in questions & answers here than I do for_each(), transform(), and the like.  Scott Meyers suggests that stl algorithms are preferred, or at least he did in 2001.  Of course, using them often means moving the loop body into a function or function object.  Some may feel this is an unacceptable complication, while others may feel it better breaks down the problem.

So... should STL algorithms be preferred over hand-rolled loops?

[A]
It depends on:
Whether high-performance is required
The readability of the loop
Whether the algorithm is complex
If the loop isn't the bottleneck, and the algorithm is simple (like for_each), then for the current C++ standard, I'd prefer a hand-rolled loop for readability.  (Locality of logic is key.)
However, now that C++0x/C++11 is supported by some major compilers, I'd say use STL algorithms because they now allow lambda expressions — and thus the locality of the logic.