Question:
In a static view, how can I view an old version of a file?

Given an empty file (called empty in this example) I can subvert diff to show me the old version:

    % cleartool diff -ser empty File@@/main/28

This feels like a pretty ugly hack. Have I missed a more basic command? Is there a neater way to do this?

(I don't want to edit the config spec - that's pretty tedious, and I'm trying to look at a bunch of old versions.)

Clarification: I want to send the version of the file to stdout, so I can use it with the rest of Unix (grep, sed, and so on.) If you found this question because you're looking for a way to save a version of an element to a file, see Brian's answer.

Answer:
[ Rewritten based on the first comment ]
All files in Clearcase, including versions, are available in the virtual directory structure. I don't have a lot of familiarity with static views, but I believe they still go through a virtual fs; they just get updated differently.
In that case, you can just do:
```
```
cat File@@/main/28
```
```
It can get ugly if you also have to find the right version of a directory that contained that file element. We have a PERL script at work that uses this approach to analyze historical changes made to files, and we quickly ran out of command-line space on Windows to actually run the commands!


Question: What is the best way to convert existing jar (without source) written in java 1.5 into java 1.4.x?

Answer:
You could decompile it, then recompile. You'll probably have to fix incompatibilities by hand. Here's a thread on java
decompilers
.


Question: How do I run a .jar executable java file from outside NetBeans IDE? (Windows Vista).  My project has a .jar file created by Netbeans.  We'd like to run it.  Either: how do we run the file or how do we create a 'proper' executable file in NetBeans 6.1?

Answer:
Running a jar is as simple as
```
```
java -jar filename.jar
```
```


Question:
When I want an array of flags it has typically pained me to use an entire byte (or word) to store each one, as would be the result if I made an array of bools or some other numeric type that could be set to 0 or 1. But now I wonder whether using a structure that is more space-efficient is worth it given the (albeit hopefully very slight) additional overhead of shifting and bit testing.

In my company we use Rogue Wave tools (though hopefully not for much longer) and it's their RWBitVec that I've used for this purpose up until now.

Answer:
It's mostly about saving memory.  If your array of bools is large enough that a 8x improvement on storage space is meaningful, then by all means, use a bitarray.
Note that the memory access is pretty expensive compared to the shift/and, so the bitarray approach is slightly faster than the array-of-chars.  Basically it comes down to memory versus programmer time.  Remember that premature optimization is a waste of time.  I'd use whichever approach is the easiest to develop, and then refactor only after it shows that it's a primary performance bottleneck.


Question: Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index 1?

Answer:
```
```
>>> ["foo", "bar", "baz"].index("bar")
1
```
```
Reference:
Data Structures > More on Lists
Caveats follow
Note that while this is perhaps the cleanest way to answer the question
as asked
,
```
index
```
is a rather weak component of the
```
list
```
API, and I can't remember the last time I used it in anger. It's been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. Some caveats about
```
list.index
```
follow. It is probably worth initially taking a look at the documentation for it:
```
```
list.index(x[, start[, end]])
```
```
Return zero-based index in the list of the first item whose value is equal to
x
. Raises a
```
ValueError
```
if there is no such item.
The optional arguments
start
and
end
are interpreted as in the
slice notation
and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
Linear time-complexity in list length
An
```
index
```
call checks every element of the list in order, until it finds a match. If your list is long, and you don't know roughly where in the list it occurs, this search could become a bottleneck. In that case, you should consider a different data structure. Note that if you know roughly where to find the match, you can give
```
index
```
a hint. For instance, in this snippet,
```
l.index(999_999, 999_990, 1_000_000)
```
is roughly five orders of magnitude faster than straight
```
l.index(999_999)
```
, because the former only has to search 10 entries, while the latter searches a million:
```
```
>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514
```
```
Only returns the index of the
first match
to its argument
A call to
```
index
```
searches through the list in order until it finds a match, and
stops there.
If you expect to need indices of more matches, you should use a list comprehension, or generator expression.
```
```
>>> [1, 1].index(1)
0
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> next(g)
0
>>> next(g)
2
```
```
Most places where I once would have used
```
index
```
, I now use a list comprehension or generator expression because they're more generalizable. So if you're considering reaching for
```
index
```
, take a look at these excellent Python features.
Throws if element not present in list
A call to
```
index
```
results in a
```
ValueError
```
if the item's not present.
```
```
>>> [1, 1].index(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 2 is not in list
```
```
If the item might not be present in the list, you should either
Check for it first with
```
item in my_list
```
(clean, readable approach), or
Wrap the
```
index
```
call in a
```
try/except
```
block which catches
```
ValueError
```
(probably faster, at least when the list to search is long, and the item is usually present.)


Question:
How can I get MSBuild to evaluate and print in a <Message /> task an absolute path given a relative path?

Property Group

<Source_Dir>..\..\..\Public\Server\</Source_Dir>
<Program_Dir>c:\Program Files (x86)\Program\</Program_Dir>

Task

<Message Importance="low" Text="Copying '$(Source_Dir.FullPath)' to '$(Program_Dir)'" />

Output

Copying '' to 'c:\Program Files (x86)\Program\'

Answer:
Wayne is correct that well-known metadata does not apply to properties - only to items. Using properties such as "MSBuildProjectDirectory" will work, but I'm not aware of a built in way to resolve the full path.
Another option is to write a simple, custom task that will take a relative path and spit out the fully-resolved path. It would look something like this:
```
```
public class ResolveRelativePath : Task
{
    [Required]
    public string RelativePath { get; set; }

    [Output]
    public string FullPath { get; private set; }

    public override bool Execute()
    {
        try
        {
            DirectoryInfo dirInfo = new DirectoryInfo(RelativePath);
            FullPath = dirInfo.FullName;
        }
        catch (Exception ex)
        {
            Log.LogErrorFromException(ex);
        }
        return !Log.HasLoggedErrors;
    }
}
```
```
And your MSBuild lines would look something like:
```
```
<PropertyGroup>
    <TaskAssembly>D:\BuildTasks\Build.Tasks.dll</TaskAssembly>
    <Source_Dir>..\..\..\Public\Server\</Source_Dir>
    <Program_Dir>c:\Program Files (x86)\Program\</Program_Dir>
</PropertyGroup>
<UsingTask AssemblyFile="$(TaskAssembly)" TaskName="ResolveRelativePath" />

<Target Name="Default">
    <ResolveRelativePath RelativePath="$(Source_Dir)">
    <Output TaskParameter="FullPath" PropertyName="_FullPath" />
    </ResolveRelativePath>
    <Message Importance="low" Text="Copying '$(_FullPath)' to '$(Program_Dir)'" />
</Target>
```
```


Question:
I've been looking for the answer for how to use BSWAP for lower 32-bit sub-register of 64-bit register. For example, 0x0123456789abcdef is inside RAX register, and I want to change it to 0x01234567efcdab89 with a single instruction (because of performance).

So I tried following inline function:

#define BSWAP(T) {  \
    __asm__ __volatile__ (  \
            "bswap %k0" \
            : "=q" (T)  \
            : "q" (T)); \
}

And the result was 0x00000000efcdab89. I don't understand why the compiler acts like this. Does anybody know the efficient solution?

Answer:
Check the assembly output generated by gcc!  Use the
```
gcc -s
```
flag to compile the code and generate asm output.
IIRC, x86-64 uses 32-bit integers by default when not explicitly directed to do otherwise, so this may be (part of) the problem.


Question: OK I have an array of tserversocket and am using the tag property to keep track of its index. When an event is fired off such as _clientconnect i am using Index := (Sender as TServerSocket).Tag; but i get an error that highlights that line and tells me its an invalid typecast. What am I doing wrong if all I want to do is get the tag property field? It works with other objects.

Answer:
Are you sure Sender is the TServerSocket? Isn't the event defined like below:
```
```
procedure TfrmServer.sskServerClientConnect(Sender: TObject; Socket: TCustomWinSocket);
```
```
In which case your code probably should be:
```
```
Index := (Socket as TServerSocket).Tag;
```
```
Have a look at
```
Sender.ClassName
```
to see what Sender really is.


Question:
I am having an issue setting up cURL with IIS 6.0, Windows Server 2003, PHP 5.2.6

I have installed to C:\PHP

set PHPRC = C:\PHP\php.ini

copied ssleay32.dll and libeay32.dll to C:\PHP

in php.ini, uncommented the line

extension=php_curl.dll

extension_dir="C:\PHP\ext"

c:\php\ext has the dll php_curl.dll

C:\PHP is in PATH

still getting

Fatal error: Call to undefined function curl_init()

Answer:
Make sure php_curl.dll is in the directory listed under "extension_dir" in php.ini.  If it is already, try restarting IIS (Apache always needs a restart from me when making php.ini changes).
EDIT 1:
Try opening up a command prompt to c:\php and running:
```
```
php -c . -i | find /i "curl"
```
```
Does it come back with any output?  If so, IIS is using the wrong php.ini file.
EDIT 2:
Is c:\php in your PATH?  You can check with "echo %PATH%" from the command prompt.


Question:
I have a std::string with UTF-8 characters in it.

I want to convert the string to its closest equivalent with ASCII characters.

For example:

Łódź  =>  Lodz

Assunção  =>  Assuncao

Schloß  =>  Schloss

Unfortunatly ICU library is realy unintuitive and I haven't found good documentation on its usage, so it would take me too much time to learn to use it. Time I dont have.

Could someone give a little example about how can this be done??

thanks.

Answer:
I don't know about ICU but ICONV does this and its quite easy to learn. it's only about 3-4 calls and what you need in your case is to use the
```
ICONV_SET_TRANSLITERATE
```
flag using
```
iconvctl()
```
.


Question:
In particular, I am interested in:
1) Getting up a free environment setup to do workflows.
2) How to use existing workflow items/states and what is involved in that.

Thanks!

Answer:
Are you looking for a virtual lab like this one from
MSDN
?
For some How Tos, try downloading
Hands-on Labs for Windows Workflow Foundation


Question:
I was talking to somebody a recently who mentioned it was possible to store reports created using Crystal Reports as XML files.

Upon Googling this, I can't find anything suggesting that this is the case (using data stored in XML in a report, yes, but actually storing the report, the part stored by default as a .rpt file, no.

Am I correct in assuming that there was in fact some sort of misunderstanding between us and it in fact not possible to do this?

Answer: At least in version 8.5 XML-file is one of the supported export destinations just like PDF, Excel or Word. Seems unlikely they'd have removed the support in later versions.


Question:
How do I get the list of open file handles by process id in C#?

I'm interested in digging down and getting the file names as well.

Looking for the programmatic equivalent of what process explorer does.

Most likely this will require interop.

Considering adding a bounty on this, the implementation is nasty complicated.

Answer:
You can P/INVOKE into the
```
NtQuerySystemInformation
```
function to query for all handles and then go from there. This
Google groups discussion
has details.


Question:
I need to get just the first item (actually, just the first key) off a rather large associative array in JavaScript. Here's how I'm doing it currently (using jQuery):

getKey = function (data) {
    var firstKey;
    $.each(data, function (key, val) {
        firstKey = key;
        return false;
    });
    return firstKey;
};

Just guessing, but I'd say there's got to be a better (read: more efficient) way of doing this. Any suggestions?

UPDATE: Thanks for the insightful answers and comments! I had forgotten my JavaScript 101, wherein the spec says you're not guaranteed a particular order in an associative array. It's interesting, though, that most browsers do implement it that way. I'd prefer not to sort the array before getting that first key, but it may be unavoidable given my use case.

Answer:
There isn't really a
first
or
last
element in associative arrays (i.e. objects). The only order you can hope to acquire is the order the elements were saved by the parser -- and no guarantees for consistency with that.
But, if you want
the first to come up
, the classic manner might actually be a bit easier:
```
```
function getKey(data) {
  for (var prop in data)
    return prop;
}
```
```
Want to avoid inheritance properties?
```
```
function getKey(data) {
  for (var prop in data)
    if (data.propertyIsEnumerable(prop))
      return prop;
}
```
```


Question:
I have an single threaded, embedded application that allocates and deallocates lots and lots of small blocks (32-64b). The perfect scenario for a cache based allocator. And although I could TRY to write one it'll likely be a waste of time, and not as well tested and tuned as some solution that's already been on the front lines.

So what would be the best allocator I could use for this scenario?

Note: I'm using a Lua Virtual Machine in the system (which is the culprit of 80+% of the allocations), so I can't trivially refactor my code to use stack allocations to increase allocation performance.

Answer:
In a past project in C I worked on, we went down the road of implementing our own memory management routines for a library ran on a wide range of platforms including embedded systems.  The library also allocated and freed a large number of small buffers.  It ran relatively well and didn't take a large amount of code to implement.  I can give you a bit of background on that implementation in case you want to develop something yourself.
The basic implementation included a set of routines that managed buffers of a set size.  The routines were used as wrappers around malloc() and free().   We used these routines to manage allocation of structures that we frequently used and also to manage generic buffers of set sizes.  A structure was used to describe each type of buffer being managed.  When a buffer of a specific type was allocated, we'd malloc() the memory in blocks (if a list of free buffers was empty).  IE, if we were managing 10 byte buffers, we might make a single malloc() that contained space for 100 of these buffers to reduce fragmentation and the number of underlying mallocs needed.
At the front of each buffer would be a pointer that would be used to chain the buffers in a free list.  When the 100 buffers were allocated, each buffer would be chained together in the free list.  When the buffer was in use, the pointer would be set to null.  We also maintained a list of the "blocks" of buffers, so that we could do a simple cleanup by calling free() on each of the actual malloc'd buffers.
For management of dynamic buffer sizes, we also added a size_t variable at the beginning of each buffer telling the size of the buffer.  This was then used to identify which buffer block to put the buffer back into when it was freed.  We had replacement routines for malloc() and free() that did pointer arithmetic to get the buffer size and then to put the buffer into the free list.  We also had a limit on how large of buffers we managed.  Buffers larger than this limit were simply malloc'd and passed to the user.  For structures that we managed, we created wrapper routines for allocation and freeing of the specific structures.
Eventually we also evolved the system to include garbage collection when requested by the user to clean up unused memory.  Since we had control over the whole system, there were various optimizations we were able to make over time to increase performance of the system.  As I mentioned, it did work quite well.


Question: c# + sql server: I have to import a few tables from Access into sql server. The new sql server tables are already defined and created. The Access tables have primary key - foreign key relationships that have to be maintained. I would like to have the new sql tables use identity values for the primary keys, but I can't easily load the legacy rows and maintain the relationships if I do that. I could possibly load the data using identity_insert but I have to back way out of my ORM software (subsonic) to do that. Perhaps I can make my new primary keys non-identity types, but then there is the hassle of generating unique ids for all the rows I add later. I'm sure this has a decent solution out there somewhere.

Answer:
In a past project in C I worked on, we went down the road of implementing our own memory management routines for a library ran on a wide range of platforms including embedded systems.  The library also allocated and freed a large number of small buffers.  It ran relatively well and didn't take a large amount of code to implement.  I can give you a bit of background on that implementation in case you want to develop something yourself.
The basic implementation included a set of routines that managed buffers of a set size.  The routines were used as wrappers around malloc() and free().   We used these routines to manage allocation of structures that we frequently used and also to manage generic buffers of set sizes.  A structure was used to describe each type of buffer being managed.  When a buffer of a specific type was allocated, we'd malloc() the memory in blocks (if a list of free buffers was empty).  IE, if we were managing 10 byte buffers, we might make a single malloc() that contained space for 100 of these buffers to reduce fragmentation and the number of underlying mallocs needed.
At the front of each buffer would be a pointer that would be used to chain the buffers in a free list.  When the 100 buffers were allocated, each buffer would be chained together in the free list.  When the buffer was in use, the pointer would be set to null.  We also maintained a list of the "blocks" of buffers, so that we could do a simple cleanup by calling free() on each of the actual malloc'd buffers.
For management of dynamic buffer sizes, we also added a size_t variable at the beginning of each buffer telling the size of the buffer.  This was then used to identify which buffer block to put the buffer back into when it was freed.  We had replacement routines for malloc() and free() that did pointer arithmetic to get the buffer size and then to put the buffer into the free list.  We also had a limit on how large of buffers we managed.  Buffers larger than this limit were simply malloc'd and passed to the user.  For structures that we managed, we created wrapper routines for allocation and freeing of the specific structures.
Eventually we also evolved the system to include garbage collection when requested by the user to clean up unused memory.  Since we had control over the whole system, there were various optimizations we were able to make over time to increase performance of the system.  As I mentioned, it did work quite well.


Question:
I know how to load themes dynamically when they are stored locally. Is it possible to store theses themes in the database yet still apply them programmatically as described in referenced MSDN article?

Also - If you do store them in the filesystem, is it possible to change the path of the App_Themes directory to a different location? Like Amazon S3?

Apply Themes Programattically

Answer:
In your example you've created the same index twice - this would give an error so I'm assuming that was a mistake in pasting, not the actual code you tried.
I tried it with
```
```
CREATE INDEX idx_person_upper_surname ON person (UPPER(surname));

SELECT * FROM person WHERE UPPER(surname) LIKE 'P%';
```
```
and it produced the expected query plan:
```
```
Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=1 Card=1 Bytes=67)
   1    0   TABLE ACCESS (BY INDEX ROWID) OF 'PERSON' (TABLE) (Cost=1
          Card=1 Bytes=67)

   2    1     INDEX (RANGE SCAN) OF 'IDX_PERSON_UPPER_SURNAME' (INDEX)
           (Cost=1 Card=1)
```
```
To answer your question, yes it should work. Try double checking that you do have the second index created correctly.
Also try an explicit hint:
```
```
SELECT /*+INDEX(PERSON IDX_PERSON_UPPER_SURNAME)*/ *
FROM person
WHERE UPPER(surname) LIKE 'P%';
```
```
If that works, but only with the hint, then it is likely related to CBO statistics gone wrong, or CBO related init parameters.


Question:
Whenever I start our Apache Felix (OSGi) based application under SUN Java ( build 1.6.0_10-rc2-b32 and other 1.6.x builds) I see the following message output on the console (usually under Ubuntu 8.4):

Warning:  The encoding 'UTF-8' is not supported by the Java runtime.

I've seen this message display occasionally when running both Tomcat and Resin as well.  If java supports unicode and UTF-8, what causes this message?  I've yet to find any reference, or answer to this anywhere else.

Answer:
According
the documentation
"Every implementation of the Java platform is required to support the following standard charsets... US-ASCII, ISO-8859-1, UTF-8, UTF-16BE, UTF-16LE, UTF-16."  So I doubt that Sun have released a build without UTF-8 support.
The actual error message appears to be from
here
, which is part of the Xerces XML parser.  I imagine it is the XML parser where the problem is occurring.


Question:
Possible Duplicate:

  Unit Testing C Code

I've seen a few questions specific to C++, but I'm really curious about C. I'm trying to add a standard unit test framework into our build environment. My primary goals are to encourage our developers to write unit tests, and to standardize those test so others can run them. Ideally I'd like to run the unit tests as part of our nightly build.

We started some work with CUnit, which worked except that everything ran in one thread and any memory faults caused the unit tests to stop running, which was rather annoying. I also found it incredibly difficult to write the tests, but that might just be unit testing for you.

Does anybody know of good alternatives? Has anybody had any experience with the C++ Unit Testers with C-only code?

Answer:
We started some work with CUnit, which worked except that everything ran in one thread and any memory faults caused the unit tests to stop running, which was rather annoying.
There one C unit testing framework that forks and executes each test cases in a separate process so that all the tests are executed even in the presence of tests that core dump :
Check
However, I'm afraid of the performance penalty all these forks bring (and to be honest, I didn't give it a try). But I won't live long with any single test core dumping : I usually fix it immediately.
One trick to prevent the unit tests to core is the
assertion guard
, for instance: use an assertion to prevent using a NULL pointer (example with
minunit
).
```
```
void test_function_returning_a_pointer(void)
{
    struct_t *theStruct = function_returning_a_pointer();
    MU_ASSERT(theStruct != NULL);

    //--- now you can use the pointer
    MU_ASSERT(theStruct->field1 == 0);

    return MU_PASSED;
}
```
```
By the way, I'm not aware of any C++ unit test framework that won't crash in case of segmentation violation.
I also found it incredibly difficult to write the tests, but that might just be unit testing for you.
Could you elaborate on your difficulties ? Are you trying to put legacy code under tests ?


Question:
Please can someone help me make sense of the Batch madness?

I'm trying to debug an Axapta 3.0 implementation that has about 50 Batch Jobs. Most of the batched classes do not implement the description() method, so when you look at the Batch List form (Basic>>Inquiries>>Batch list) the description field is blank. You can see the Batch Group and the Start Time, etc. but you can't tell which class is actually being called.

The Batch table contains a hidden field called ClassNum which identifies the ID property of the class. Can anyone tell me how I can find the corresponding class from the ID? Once I've identified the culprits I can add descriptions.

I tried using the standard Find function on the AOT but it doesn't pick them up.

Any suggestions would be most welcome!

Many thanks,
Mike

Answer:
Jay's answer provides two comprehensive solutions.
I've just discovered that the global class
ClassId2Name
does the same thing, so you can simply have:
```
```
display str Classname()
{
   return ClassId2Name(this.ClassNum);
}
```
```


Question: Always was interested why are Array.Sort() and Array.IndexOf() methods made static and similar ArrayList.Sort() and ArrayList.IndexOf() are designed as member methods. Thank you for any ideas.

Answer:
In my view Array class is basically a class representation of the fixed size arrays that we declare using [] in program (you can draw the analogy like int has it's class (structure) representation as System.Int32).
Also Array class does not contain the actually array data in any instance variables but it provides just static utility functions which can be utilized to do sorting and searching in the declared fixed size arrays.
On the other hand, ArrayList is a collection class, which provides dynamic size array implementation and it has it's own data-structure to contain the data. Therefore the said methods are instance methods, so that they can work on the that particular instance's data.


Question:
Can anyone provide some pseudo code for a roulette selection function? How would I implement this:

I don't really understand how to read this math notation. I never took any probability or statistics.

Answer:
It's been a few years since i've done this myself, however the following pseudo code was found easily enough on google.
```
for all members of population
    sum += fitness of this individual
end for

for all members of population
    probability = sum of probabilities + (fitness / sum)
    sum of probabilities += probability
end for

loop until new population is full
    do this twice
        number = Random between 0 and 1
        for all members of population
            if number > probability but less than next probability
                then you have been selected
        end for
    end
    create offspring
end loop
```
The site where this came from can be found
here
if you need further details.


Question:
I have a TreeView control in my WinForms .NET application that has multiple levels of childnodes that have childnodes with more childnodes, with no defined depth. When a user selects any parent node (not necessarily at the root level), how can I get a list of all the nodes beneith that parent node?

For example, I started off with this:

Dim nodes As List(Of String)

For Each childNodeLevel1 As TreeNode In parentNode.Nodes
    For Each childNodeLevel2 As TreeNode In childNodeLevel1.Nodes
        For Each childNodeLevel3 As TreeNode In childNodeLevel2.Nodes
            nodes.Add(childNodeLevel3.Text)
        Next
    Next
Next

The problem is that this loop depth is defined and I'm only getting nodes burried down three levels. What if next time the user selects a parent node, there are seven levels?

Answer:
you need a recursive function to do this [or a loop equivalent, but the recursive version is simpler] - pseudocode:
```
```
function outputNodes(Node root)
    writeln(root.Text)
    foreach(Node n in root.ChildNodes)
        outputNodes(n)
    end
end
```
```


Question:
Is it possible to produce an alert similar to JavaScript's alert("message") in python, with an application running as a daemon.

This will be run in Windows, Most likely XP but 2000 and Vista are also very real possibilities.

Update:

This is intended to run in the background and alert the user when certain conditions are met, I figure that the easiest way to alert the user would be to produce a pop-up, as it needs to be handled immediately, and other options such as just logging, or sending an email are not efficient enough.

Answer:
what about this:
```
```
import win32api

win32api.MessageBox(0, 'hello', 'title')
```
```
Additionally:
```
```
win32api.MessageBox(0, 'hello', 'title', 0x00001000)
```
```
will make the box appear on top of other windows, for urgent messages. See
MessageBox function
for other options.


Question:
What is the most efficient way to read the last row with SQL Server?

The table is indexed on a unique key -- the "bottom" key values represent the last row.

Answer:
You'll need some sort of uniquely identifying column in your table, like an auto-filling primary key or a datetime column (preferably the primary key). Then you can do this:
```
```
SELECT * FROM table_name ORDER BY unique_column DESC LIMIT 1
```
```
The
```
ORDER BY column
```
tells it to rearange the results according to that column's data, and the
```
DESC
```
tells it to reverse the results (thus putting the last one first). After that, the
```
LIMIT 1
```
tells it to only pass back one row.


Question:
I've been experimenting with Adobe Flex recently. Being a long-time server-side web app developer, I'm faced with difficulties that I last experienced when I dabbled in Java Swing development a long time ago. It mainly revolves around the flow of control between my code and the framework's code. Most things are asynchronous as to not freeze the UI.

So, I'm looking for all the seasoned developers out there who have seen it all to put into words the shifts in thinking required to make the transition from traditional web apps to RIAs.

Update: Moved the distracting parts to another question.

Answer:
There's two models I'm seeing in the market right now:
Blended UI. The server is still involved in the UI construction effort, but a lot of it is offloaded to javascript. This is how a lot of the javascript toolkits work (except dojo, extjs, ...).
Separated concerns. The server is treated as a data storage and synchronization method only. The app runs entirely client-side, possibly even with local storage. This is how flex works.
I think we're going to be migrating towards the second model, because it means that you don't have to track UI state on the server, which dramatically simplifies the architecture. I've been toying with ExtJS and Flex, and the development experience is a lot like building a desktop app, only without the fancy drag-and-drop IDE's. It's hard to think of large differences between a three-tier desktop app and a web app in this fashion.
So my advice would be: stop thinking you're building web apps, always put into doubt whether something belongs on the server, because in the new model it often won't. Also, use gears or the browser cache effectively, because if your app is client-side, downloading all that code every time will be too slow.


Question: In sql server does it make a difference if I define a varchar column to be of length 32 or 128?

Answer:
There should be no noticeable difference as the backend will only store the amount of data you insert into that column. It's not padded out to the full size of the field like it is with a char column.
Edit: For more info, this
link
should be useful.


Question:
This question will expand on: Best way to open a socket in Python

When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail.

Edit:
I tried this:

try:
    s.connect((address, '80'))
except:
    alert('failed' + address, 'down')

but the alert function is called even when that connection should have worked.

Answer:
It seems that you catch not the exception you wanna catch out there :)
if the
```
s
```
is a
```
socket.socket()
```
object, then the right way to call
```
.connect
```
would be:
```
```
import socket
s = socket.socket()
address = '127.0.0.1'
port = 80  # port number is a number, not string
try:
    s.connect((address, port))
    # originally, it was
    # except Exception, e:
    # but this syntax is not supported anymore.
except Exception as e:
    print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
    s.close()
```
```
Always try to see what kind of exception is what you're catching in a try-except loop.
You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate
```
except
```
statement for each one of them - this way you'll be able to react differently for different kind of problems.


Question:
I have seen recent updates in term of record sets being updated so that we can scroll back and forth through the data it points to.

Why they were initially designed for a forward only traversal. Is there any impact using the new version?

Answer:
"new version" is about 5 years old.
forward only : it is the easiest way to implement. It is easiest to implement a Queue(FIFO) rather than a deque or linked list. Since the JDBC driver has to read the record from the DB, it can make them EASILY available to the ResultSet reader FIRST COME FIRST SERVE.
Later on, they realized that some desktop applications and some rich web based apps might want to scroll forward and backward without having to store the intermediate representations, they decided to implement it.
Then came the updatable ResultSets where you can update the columns/rows of a ResultSet.


Question: How can i go about programaticaly getting the IP address of my network as seen from the Internet? Its obviously a property that my router has access to when it connects to the ISP. Is there any way to get this info from a router using a standard protocol. My only other option is to either find a WS which returns my IP address (suprisingly difficult to do), or just go to something like whatismyip.com and strip out all the HTML (very dirty and susceptable to change). Is there any other way???

Answer:
I don't see a language specifacation but I did it here in python:
Finding a public facing IP address in Python?
Basicly there is no way of doing it without relying on an external server, in this case I use
http://www.whatismyip.com/automation/n09230945.asp
which only provide the ip address.
Alternatively you could use your own script which in PHP would look like:
```
```
<?php
echo $_SERVER['REMOTE_ADDR'];
?>
```
```


Question:
const static int foo = 42;

I saw this in some code here on StackOverflow and I couldn't figure out what it does. Then I saw some confused answers on other forums. My best guess is that it's used in C to hide the constant foo from other modules. Is this correct? If so, why would anyone use it in a C++ context where you can just make it private?

Answer:
It's missing an 'int'.  It should be:
```
```
const static int foo = 42;
```
```
In C and C++, it declares an integer constant with local file scope of value 42.
Why 42?  If you don't already know (and it's hard to believe you don't), it's a refernce to the
Answer to Life, the Universe, and Everything
.


Question:
I am primary a web developer but I do have a very good understanding of C++ and C#. However, recently I have writing a GUI application and I have started to get lost in how to handle the relationship between my controller and view logic. In PHP it was very easy - and I could write my own MVC pattern with my eyes closed - mainly because of how PHP is stateless and you regenerate the entire form per request. But in application programming languages I get lost very quickly.

My question is: how would I separate my controller from view? Should the view attach to events from the controller - or should the view implement an interface that the controller interacts with?

Answer:
Imagine this GUI:
The Zergling unit is presented to the user as an alien icon. You can see that it is in its idle animation. Call this the View.
The player moves the unit by clicking on it and a target location. You can subtitute the player for an AI if you want. Call this the Controller.
The HP and attack range of the unit is calculated every game frame when the unit is in combat. You can change this data to make the Zergling into a range unit. Call this the Model.
Keep this analogy in mind and extend it for your MVC designs.


Question:
double r = 11.631;
double theta = 21.4;

In the debugger, these are shown as 11.631000000000000 and 21.399999618530273.

How can I avoid this?

Answer:
These
accuracy problems
are due to the
internal representation
of floating point numbers and there's not much you can do to avoid it.
By the way, printing these values at run-time often still leads to the correct results, at least using modern C++ compilers. For most operations, this isn't much of an issue.


Question: Does anyone know of a sample distributed application (.NET or J2EE) using RMI or Web Services?

Answer:
As often, Sun has an excellent tutorial on RMI:
http://java.sun.com/docs/books/tutorial/rmi/index.html


Question:
Every time I need to do something N times inside an algorithm using C# I write this code

for (int i = 0; i < N; i++)
{
    ...
}

Studying Ruby I have learned about method times() which can be used with the same semantics like this

N.times do
    ...
end

Code fragment in C# looks more complex and we should declare useless variable i.

I tried to write extension method which returns IEnumerable, but I am not satisfied with the result because again I have to declare a cycle variable i.

public static class IntExtender
{
    public static IEnumerable Times(this int times)
    {
        for (int i = 0; i < times; i++)
            yield return true;
    }
}

...

foreach (var i in 5.Times())
{
    ...
}

Is it possible using some new C# 3.0 language features to make N times cycle more elegant?

Answer:
It is indeed possible with C# 3.0:
```
```
public interface ILoopIterator
{
    void Do(Action action);
    void Do(Action<int> action);
}

private class LoopIterator : ILoopIterator
{
    private readonly int _start, _end;

    public LoopIterator(int count)
    {
        _start = 0;
        _end = count - 1;
    }

    public LoopIterator(int start, int end)
    {
        _start = start;
        _end = end;
    }

    public void Do(Action action)
    {
        for (int i = _start; i <= _end; i++)
        {
            action();
        }
    }

    public void Do(Action<int> action)
    {
        for (int i = _start; i <= _end; i++)
        {
            action(i);
        }
    }
}

public static ILoopIterator Times(this int count)
{
    return new LoopIterator(count);
}
```
```
Usage:
```
```
int sum = 0;
5.Times().Do( i =>
    sum += i
);
```
```
Shamelessly stolen from
http://grabbagoft.blogspot.com/2007/10/ruby-style-loops-in-c-30.html


Question: While estimating straight row and table sizes are fairly simple math, we find it challenging to guess just how much space each index will occupy (for a given table size). What areas can we learn to calculate a better estimate and growth rate for indexes?

Answer:
An index leaf has a preamble identifying the data page (7 bytes plus some directory information for variable length columns, if any) plus a copy of the key value (s) which will be the same size as the table data for those columns.  There's one for each row in the table.  The higher up levels of the index are much smaller, usually less than 1% of the leaves unless you are indexing a very wide key.
The fill factor leaves some space free so that updates and inserts do not generate excessive leaf splitting traffic.
EDIT:
This MSDN link
describes the page-level structures, although it's a bit light on the format of the individual index rows.
This presentation
goes into the physical format of disk log entries and data pages to some extent.
This one
more detail and includes the index data structures.  Numeric and fixed length columns have the size it says on the box; you would have to estimate the average size of varchar columns.
For reference, some documents on Oracle's block format can be found
Here
and
Here
.


Question:
Something like this is on my mind: I put one or a few strings in, and the algorithm shows me a matching regex.

Is there an "easy" way to do this, or does something like this already exist?

Edit 1: Yes, I'm trying to find a way to generate regex.

Edit 2: Regulazy is not what I am looking for. The common use for the code I want is to find a correct RegEx; for example, article numbers:

I put in 123456, the regex should be \d{6}

I put in nb-123456, the regex should be \w{2}-\d{6}

Answer:
It sounds like you want an algorithm to generate a regular grammar based on some samples. In a lot of cases, there are many possible grammars for a given set of examples--there can even be infinite possible grammars. Of course, the possibilities can be limited by a second set of required
non
-matches, which can limit it to zero possibilities if the non-matching strings are too inclusive.
txt2re
does something like this.


Question:
This is something that's been bothering me a while and there just has to be a solution to this. Every time I call ShellExecute to open an external file (be it a document, executable or a URL) this causes a very long lockup in my program before ShellExecute spawns the new process and returns. Does anyone know how to solve or work around this?

EDIT: And as the tags might indicate, this is on Win32 using C++.

Answer:
I don't know what is causing it, but Mark Russinovich (of sysinternal's fame) has a really great blog where he explains how to debug these kinds of things. A good one to look at for you would be
The Case of the Delayed Windows Vista File Open Dialogs
, where he debugged a similar issue using only process explorer (it turned out to be a problem accessing the domain). You can of course do similar things using a regular windows debugger.
You problem is probably not the same as his, but using these techniques may help you get closer to the source of the problem. I suggest invoking the
```
CreateProcess
```
call and then capturing a few stack traces and seeing where it appears to be hung.
The Case of the Process Startup Delays
might be even more relevant for you.


Question:
I have an app written in C# that lies on a network share. When I run it from a local drive, everything works fine. When I start it from the remote share, calls like

try
{
    System.Reflection.Assembly.GetExecutingAssembly();
    System.IO.Directory.GetCurrentDirectory();
}

throw a SecurityException 'Request failed'.

What causes this, what is the difference between an app that is started locally and one that is started from a remote location?

Answer:
This is due to
CAS
; code started from the local machine has much more trust than code in the intranet, which in turn has more trust that code from the internet.
IIRC, with the latest SP (3.5SP1?) if you have
mapped
the share (i.e. as F:) it is trusted; otherwise you will need to either:
a: apply a
caspol
change to all clients (yeuck)
b: use
ClickOnce
to deploy the app, and run the .application instead (yay!)
The point is that ClickOnce allows you to sign the app and state your security policy (even if you demand full trust).


Question:
I have Eclipse 3.3.2 with PDT doing PHP development.
All projects that I create, even SVN projects have code completion.
Now I just opened another SVN project and it has no code completion or PHP templates (CTRL-space does nothing in that project).
However, I can open the other projects and code completion all work in them.

Why would code completion and templates be "off" in just one project and how can I turn it back on?

Answer:
Maybe Eclipse doesn't understand the project has a "PHP nature".
Try comparing the .project file on both projects to look for differences. It should contain something like:
```
```
<natures>
  <nature>org.eclipse.php.core.PHPNature</nature>
 </natures>
```
```
The .project file will be in your workspace under the project directories.


Question: Consider a regular web application doing mostly form-based CRUD operations over SQL database. Should there be explicit transaction management in such web application? Or should it simply use autocommit mode? And if doing transactions, is "transaction per request" sufficient?

Answer:
You should use transactions given that different users will be hitting the database at the same time. I would recommend you do
not
use autocommit. Use explicit transaction brackets. As to the resolution of each transaction, you should bracket a particular unit of work (whatever that means in your context).
You might also want to look into the different transaction isolation levels that your SQL database supports. They will offer a range of behaviours in terms of what reading users see of partially updated records.


Question: What is the differences and similarities between Domain Specific Languages (DSL) and Domain Driven Design (DDD)?

Answer:
Domain Driven Design (DDD) is a way of thinking and communicating about the problems and its solutions.
Domain Specific Language (DSL) is a way of writing code.
They're similar because they both start with the word "domain". That's it, I guess. :-)


Question:
I had a little discussion with a friend about the usage of collections in return/input values of a method. He told me that we have to use
- the most derived type for return values.
- the least derived type for input parameters.

So, it means that, for example, a method has to get a ReadOnlyCollection as parameter, and as return a List.

Moreover, he said that we must not use List or Dictionary in publics API, and that we have to use, instead Collection, ReadOnlyCollection, ... So, in the case where a method is public, its parameters and its return values must be Collection, ReadOnlyCollection, ...

Is it right ?

Answer:
Regarding input parameters, it's generally more flexible to use the least specific type.  For example, if all your method is going to do is enumerate the items in a collection passed as an argument, it's more flexible to accept IEnumerable<T>.
For example, consider a method "ProcessCustomers" that accepts a parameter that is a collection of customers:
```
```
public void ProcessCustomers(IEnumerable<Customer> customers)
{
   ... implementation ...
}
```
```
If you declare the parameter as IEnumerable<Customer>, your callers can easily pass in a subset of a collection, using code like the following (pre-NET 3.5: with .NET 3.5 you could use lambda expressions):
```
```
private IEnumerable<Customer> GetCustomersByCountryCode(IEnumerable<Customer> customers, int countryCode)
{
    foreach(Customer c in customers)
    {
        if (c.CountryCode == countryCode) yield return c;
    }
}

...
ProcessCustomers(GetCustomersByCountryCode(myCustomers, myCountryCode);
...
```
```
In general MS guidelines recommend not exposing List<T>.  For a discussion of why this is so, see
this blog entry
from the Code Analysis (FxCop) team.


Question:
I have a strongly-typed MVC View Control which is responsible for the UI where users can create and edit Client items.  I'd like them to be able to define the ClientId on creation, but not edit, and this to be reflected in the UI.

To this end, I have the following line:

<%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, new
 { @readonly =
   (ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0
      ? "readonly" : "false")
 } )
%>

It seems that no matter what value I give the readonly attribute (even "false" and ""), Firefox and IE7 make the input read-only, which is annoyingly counter-intuitive.  Is there a nice, ternary-operator-based way to drop the attribute completely if it is not required?

Answer:
Tough problem... However, if you want to define only the
```
readonly
```
attribute, you can do it like this:
```
```
<%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId,
  ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0
    ? new { @readonly =  "readonly" }
    : null)
%>
```
```
If you want to define more attributes then you must define two anonymous types and have multiple copies of the attributes. For example, something like this (which I don't like anyway):
```
```
ClientId.Length > 0
  ? (object)new { @readonly = "readonly", @class = "myCSS" }
  : (object)new { @class = "myCSS" }
```
```


Question:
I am trying to uncompress some data created in VB6 using the zlib API.

I have read this is possible with the qUncompress function:
http://doc.trolltech.com/4.4/qbytearray.html#qUncompress

I have read the data in from QDataStream via readRawBytes into a char
array, which I then converted to a QByteArray for decompression. I
have the compressed length and the expected decompressed length but am not getting
anything back from qUncompress.

However I need to prepend the expected decompressed length in big endian format. Has anybody done this and have an example?

Answer:
I haven't used VB6 in
ages
, so I hope this is approximately correct.  I
think
that vb6 used () for array indexing.  If I got anything wrong, please let me know.
Looking at the qUncompress docs, you should have put your data in your QByteArray starting at byte 5 (I'm going to assume that you left the array index base set to 1 for this example).
Let's say the array is named qArr, and the expected uncompressed size is Size.
In a "big-endian" representation, the first byte is at the first address.
```
```
qArr(1) = int(Size/(256*256*256))
qArr(2) = 255 And int(Size/256*256)
qArr(3) = 255 And int(Size/256)
qArr(4) = 255 And int(Size)
```
```
Does that make sense?
If you needed little endian, you could just reverse the order of the indexes (qArr(4) - qArr(1)) and leave the calculations the same.


Question:
Provide Used: Microsoft OLE DB Provider for SQL Server. Can anyone help me with this..
I was trying to connect with LLBLgen

Answer:
I used to get this error sometimes when connecting to my local SQL Server with Windows Authentication. I never fixed it unfortunately - it went away when I reinstalled windows.
I think a reboot used to fix it - have you tried that? Not exactly the best solution, I know :P


Question:
I'm trying to get a case-insensitive search with two strings in JavaScript working.

Normally it would be like this:

var string="Stackoverflow is the BEST";
var result= string.search(/best/i);
alert(result);

The /i flag would be for case-insensitive.

But I need to search for a second string; without the flag it works perfect:

var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(searchstring);
alert(result);

If I add the /i flag to the above example it would search for searchstring and not for what is in the variable "searchstring" (next example not working):

var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(/searchstring/i);
alert(result);

How can I achieve this?

Answer:
Yeah, use
```
.match
```
, rather than
```
.search
```
. The result from the
```
.match
```
call will return the actual string that was matched itself, but it can still be used as a boolean value.
```
```
var string = "Stackoverflow is the BEST";
var result = string.match(/best/i);
// result == 'BEST';

if (result){
    alert('Matched');
}
```
```
Using a regular expression like that is probably the tidiest and most obvious way to do that in JavaScript, but bear in mind it
is
a regular expression, and thus can contain regex metacharacters. If you want to take the string from elsewhere (eg, user input), or if you want to avoid having to escape a lot of metacharacters, then you're probably best using
```
indexOf
```
like this:
```
```
matchString = 'best';
// If the match string is coming from user input you could do
// matchString = userInput.toLowerCase() here.

if (string.toLowerCase().indexOf(matchString) != -1){
    alert('Matched');
}
```
```


Question:
Perl has several built-in functions for accessing /etc/passwd on Unix systems (and elsewhere when supported) for user and group information. For instance,

my $name = getpwuid($uid);

will return the user name given the user ID, or undef if there is no such user.

If a Perl script needs to be portable and run on Unices and Windows, how should one access user and group information? ActivePerl seems to support User::grent and User::pwent modules, which provide by-field access to /etc/passwd -- even in Windows. Curiously they do not support the built-in functions getpw* and getgr*. What other alternatives are there?

Answer:
You could use the
```
Win32::NetAdmin
```
module
.
```
UserGetAttributes
```
and
```
GroupIsMember
```
look like they do what you need.


Question:
I got a simple page with a HtmlInputHidden field. I use a javascript to update that value and when posting back the page i want to read the value of that HtmlInputHidden field.

The Value property of that HtmlInputHidden field is on postback the default value (the value it had when the page got created, not the value reflected through the javascript).

I also tried to Register the HtmlInputHidden field with ScriptManager.RegisterHiddenField(Page, "MyHtmlImputHiddenField", "initialvalue") but it still only lets me read the 'initialvalue' even though i (through javascript) can inspect that the value has changed.

Answer:
You ideally want to use the asp.net HiddenField control
```
```
<asp:HiddenField id="myHiddenField" runat="server" />
```
```
Then you will be able to read the value from the code behind when the page is processing.
```
```
string value = myHiddenField.Value; // retrieve the value in hidden field
```
```
ref;
HiddenField Web Server Control Overview
Be careful about the DOM name of the control (
```
control.ClientID
```
) on the client side (ie when you are accessing from javascript) as it may change depending where on the page you have declared the control.


Question:
When I add &nbsp; or &eacute; to a text value of a listitem, it display the code of the HTML entity instead of the result (a space or é).

I can add "physical" non-breaking spaces or special chars, but I would like to avoid that if possible. Sometimes the data stored in database is encoded, and I don't want to always process data before displaying it.

Any solution ?

Thanks

Edit note : previous description noted it was about a dropdownlist simulating a treeview, but it was merely an example ; I can't and don't want to replace the dropdownlist by anything else.

Answer:
Standard drop down lists are very poor at representing treeviews .
They can handle going one level deep if the top level is not selectable (see the
optgroup
element[1]), but beyond that I suggest taking a regular list (ordered or unordered) with as much nesting as you need (remember sublists go inside list items in their parent list) and including a checkbox or radio button with each selectable list item.
Some JavaScript could then be added to manipulate classes to create a drop down effect if desired.
[1] Optgroup should be able to go deeper but, IIRC, browser support is sucky.


Question:
I am trying to get some XML data with LINQ, but running into a problem.

I am using a schema, which is set in the attribute xmlns ...

<CarsForSale xmlns="http://schemas.sharplogic.net/CarSales.xsd">
  <CarForSale>

There are many CarForSale elements.

When the schema is set and I do this...

XElement doc = XElement.Load(HttpContext.Current.Server.MapPath("App_Data/XML/CarsForSale.xml"));

var cars2 = from d in doc.Descendants("CarForSale")
            select d;

Then I get in the results i get Enumeration yielded no results

Strip the xmlns out of the XML file and the data comes back as expected??

Any ideas?

Thx

Answer:
You need to prepend the namespace:
```
```
var ns    = "http://schemas.sharplogic.net/CarSales.xsd";
var cars2 = from d in doc.Descendants(ns + "CarForSale")
            select d;
```
```
otherwise search by local name:
```
```
var cars2 = from d in doc.Descendants()
            where d.Name.LocalName == "CarForSale"
            select d;
```
```


Question:
When developing a database of articles in a Knowledge Base (for example) - what are the best ways to sort and display the most relevant answers to a users' question?

Would you use additional data such as keyword weighting based on whether previous users found the article of help, or do you find a simple keyword matching algorithm to be sufficient?

Answer:
That's a hard question, and companies like Google are pushing a lot of efforts to address this question. Have a look at
Google Enterprise Search Appliance
or
Exalead Enterprise Search
.
Then, as a personal opinion, I don't think that any "naive" approach is going to improve much the result compared to naive keyword search and ordering by the number of views on the documents.
If you have the possibility to expose your knowledge base to the web, then, just do it, and let your favorite search engine handles the search for you.


Question:
Is there guide out there that will help me, A .Net developer whose been using Visual studio for some time, get to grips with Eclipse?

Even just a quick guide to eclipse.

Has anyone else made the transition, and if so how did you cope. Any Tips?

Answer:
Not sure if it will help you, but Eric Sink ran a nice four part series some time ago on his move from VS to Eclipse:
From C# to Java - Part 1
From C# to Java - Part 2
From C# to Java - Part 3
From C# to Java - Part 4


Question:
Trying to perform a single boolean NOT operation, it appears that under MS SQL Server 2005, the following block does not work

DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = NOT @MyBoolean;
SELECT @MyBoolean;

Instead, I am getting more successful with

DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = 1 - @MyBoolean;
SELECT @MyBoolean;

Yet, this looks a bit a twisted way to express something as simple as a negation.

Am I missing something?

Answer:
Your solution is a good one...  you can also use this syntax to toggle a bit in SQL...
```
```
DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = @MyBoolean ^ 1;
SELECT @MyBoolean;
```
```


Question:
I am trying to set the background color for a double spin box, and I am not sure what function I should use.

I saw some function called SetBackgroundRole which accepts a Qt::ColorRole, but I am not sure how to use this one as well.

Kindly let me know, what's the simple way to change the background color of a QComboBox or QDoubleSpinBox?

Answer:
I'd try something like
```
```
QPalette pal = widget.palette();
pal.setColor(QPalette::Window, Qt::blue);
widget.setPalette(pal);
```
```


Question: I am changing a GET to a POST. Currently I have .jsp?id=a,b,c,d. When changing this to a post I am still sitting the id parameter a,b,c,d . This is not working for me. Can I submit a comma separated list to a post parameter?

Answer:
You can do it like a select form input:
url?param=value1&param=value2&param=value3
Depending on you language and library you should be able to get an array of values for param.
For example with asp.net mvc i do this to get an array of strings:
```
```
string[] values = Request.Form.GetValues("param");
```
```


Question:
I have a lot of classes in the App_Code directory could this be a problem? Would it build faster if it was in a separate library?

Any other tips?

Answer:
There's a decent article
here
. Items listed there are:
Do not disable batch compilation
Leverage Server-side Compilation
Move App_Code files into a separate class library project
Check for conflicting dependencies
Turn off AutoToolboxPopulate in the Windows Forms Designer options.
Disable validation for HTML editing


Question:
One of our unit tests is to populate properties within our business objects with random data.

These properties are of different intrinsic types and therefore we would like to use the power of generics to return data of the type you pass in. Something along the lines of:

public static T GetData<T>()

How would you go about approaching this? Would a low level interface work? (IConvertible)

Answer:
You could keep the "easy to use" GetData interface you've got there, but internally have a Dictionary<Type, object> where each value is a Func<T> for the relevant type. GetData would then have an implementation such as:
```
```
public static T GetData<T>()
{
    object factory;
    if (!factories.TryGet(typeof(T), out factory))
    {
         throw new ArgumentException("No factory for type " + typeof(T).Name);
    }
    Func<T> factoryFunc = (Func<T>) factory;
    return factoryFunc();
}
```
```
You'd then set up the factory dictionary in a static initializer, with one delegate for each type of random data you wanted to create. In some cases you could use a simple lambda expression (e.g. for integers) and in some cases the delegate could point to a method doing more work (e.g. for strings).
You may wish to use my
StaticRandom
class for threads-safe RNG, by the way.


Question: I would like to be able to trap Ctrl+C in a C# console application so that I can carry out some cleanups before exiting. What is the best way of doing this?

Answer:
See MSDN:
Console.CancelKeyPress Event
Article with code samples:
Ctrl-C and the .NET console application


Question:
What's the best delimiter to use when exporting data?

What's the best way to work with NULL data if you have an INT field in the table?

Answer:
I would do whatever
bcp
with the -c option (character instead of binary) does by default, overriding it only if you see a specific problem with your data. I'd even try to use bcp, if possible.
To do this from MSSQL itself you'd need to enable xp_cmdshell support, which may not be a possibility due to security concerns. But if you want to do it in an external tool, there should be no problem.
Directly answering your questions:
The best delimiter is the character that does not appear in your data
Use a blank in those columns, any integer will have a character or even a null character
All this and more is why you should use the ready made tool, all the hard choices have been thought out and made already for you.


Question:
I need to copy data values from one element to another, but jQuery's clone() method doesn't clone the data. And I can't iterate over the data either:

element.data().each

because data() is a function and not a jQuery object. It seems I have to keep a separate list of attribute names and reference those but that seems too hacky. So how can I do either of these:

a) Iterate over data items

OR

b) clone() an element with its data.

Answer:
To give another alternative, i.e. instead of cloning the whole object you can copy the data object to a new array containing name/value pairs followingly:
```
```
function getOriginalElementData(domElementJQueryObject){
    var originalElementData = new Array();
    $.each(domElementJQueryObject.data(),function(name,value) {
       originalElementData.push({"name":name,"value":value});
    });

    return originalElementData;
}
```
```
To restore the data to another object:
```
```
function restoreOriginalElementData(domElementJQueryObject,originalElementData){
    for(var i=0;i<originalElementData.length;i++){
        domElementJQueryObject.data(originalElementData[i].name,originalElementData[i].value);
    }
}
```
```
The part to iterate through the data items is copied from this answer:
jQuery loop through data() object


Question: is it possible to include a servlet in a jsp page? if so how?

Answer:
To give another alternative, i.e. instead of cloning the whole object you can copy the data object to a new array containing name/value pairs followingly:
```
```
function getOriginalElementData(domElementJQueryObject){
    var originalElementData = new Array();
    $.each(domElementJQueryObject.data(),function(name,value) {
       originalElementData.push({"name":name,"value":value});
    });

    return originalElementData;
}
```
```
To restore the data to another object:
```
```
function restoreOriginalElementData(domElementJQueryObject,originalElementData){
    for(var i=0;i<originalElementData.length;i++){
        domElementJQueryObject.data(originalElementData[i].name,originalElementData[i].value);
    }
}
```
```
The part to iterate through the data items is copied from this answer:
jQuery loop through data() object


Question:
If you have a domain object, and you want to do something useful and central to that domain object's responsibility like ensure it is valid, you sometimes need to access the state of related objects in order to perform this validation.

How to avoid the domain object needing to call out to a Repository or Data Access Layer? You can't always walk the collection relationships, even with lazy loading, because of performance, and you often want to execute queries in the domain object. You can dependency inject repository implementation into the domain, but not really pure and complicates testing.

I've always relaxed things and allowed access out from domain to a repository using DI. I have seen no clear examples of how to have a 'pure' domain layer in a complex application which is not also anemic and has a service/application layer doing all the grunt and messing with what should be innards of the domain objects.

Answer:
If the object is a value object, it
should be immutable and validated
during construction.
If the object
is a root aggregate, and that its
own state is sufficient to tell you
if it is valid or not, you could add
a validation method on it, which
cascades through the aggregation.
Lastly, and I think it is your main
concern, if you need to access
several related objects (that are
not in the same aggregate) to ensure
one of them is valid, you
definitively needs to deport this
logic in a specific validation service.
I really think that injecting services and repositories into entities are not the best choice. Creating dedicated services seems more appropriate, and I don't see why it will leads you to have anemic domain objects.
In short, if you can validate you object state without relying on services or repositories, let the object takes care of it, at the aggregate root level. When you need to query services or repositories, or when you need other entities, then strongly consider moving this logic outside the object.


Question:
I've produced a python egg using setuptools and would like to access it's metadata at runtime. I currently got working this:

import pkg_resources
dist = pkg_resources.get_distribution("my_project")
print(dist.version)

but this would probably work incorrectly if I had multiple versions of the same egg installed. And if I have both installed egg and development version, then running this code from development version would pick up version of the installed egg.

So, how do I get metadata for my egg not some random matching egg installed on my system?

Answer:
I am somewhat new to Python as well, but from what I understand:
Although you can install multiple versions of the "same" egg (having the same name), only one of them will be available to any particular piece of code at runtime (based on your discovery method).  So if your egg is the one calling this code, it must have already been selected as
the
version of
```
my_project
```
for this code, and your access will be to your own version.


Question:
What is the best way to convert an int or null to boolean value in an SQL query, such that:

Any non-null value is TRUE in the results

Any null value is FALSE in the results

Answer:
```
```
isnull(column - column + 1, 0) != 0
```
```


Question:
How can I test sending email from my application without flooding my inbox?

Is there a way to tell IIS/ASP.NET how to deliver email to a local folder for inspection?

Answer:
Yes there is a way.
You can alter web.config like this so
  that when you send email it will
  instead be created as an .EML file in
  c:\LocalDir.
```
```
<configuration>
     <system.net>
      <mailSettings>
       <smtp deliveryMethod="SpecifiedPickupDirectory">
        <specifiedPickupDirectory pickupDirectoryLocation="c:\LocalDir"/>
       </smtp>
      </mailSettings>
     </system.net>
    </configuration>
```
```
You can also create an instance of the
```
SmtpClient
```
class with these same settings, if you don't want to/can't change the web.config.  In C# that looks something like this:
```
```
var smtpClient = new SmtpClient();
smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
var emailPickupDirectory = HostingEnvironment.MapPath("~/EmailPickup");
if (!Directory.Exists(emailPickupDirectory)) {
    Directory.CreateDirectory(emailPickupDirectory)
}
smtpClient.PickupDirectoryLocation = emailPickupDirectory;
```
```


Question:
This a bit of strange one.... We have an internal web app that runs on server (A) and a document repository that runs on server (B).

I have simple link on a page and I want to enable the user to download a document(From IIS Server (A)). However this document does not exist on Server (A) until the user clicks the button(because there is 40+ documents to display cannot load them all when the page loads)

When the user clicks the link(at which point I would like then to be prompted to download)
The  document is copied to server (A) and then redirected to a page where the browser prompts them to download. I believe I have set up the content header correctly and it works in FireFox.

IE(7) just pops up a window and then the window disappears, If I turn down the security settings it works OK but that is not an option.

Any Ideas how to solve this. I cannot point directly to the document on Server(B)

ADDITION: Yes Server B is also a Web Server

Answer:
Can you use ajax? For example, the user clicks the button sending a request to get the file from B to A and a spinner shows up on the page. Then when the copy is done, you disable the spinner and give the user a download link.
I was voted down and don't have comment privileges, so I figured I would elaborate here (perhaps this is just a terrible solution and I cannot see it):
User requests file by clicking link
Request is sent to server A and it disables the link via ajax
Server A copies the file to a temporary directory from server B
Server A sends back a link to the file in the temporary folder
This would work if the document server was not a webserver (SMB, AFS, NFS, etc).


Question:
Is there any easier solution in porting a windows manual-reset event to pthread,
than a pthread conditional-variable + pthread mutex + a flag if event is set or unset?

Answer:
Pthreads are low level constructs.  No, there isn't a simpler mechanism;
```
pthread_cond__*
```
is conceptually similar to an auto-reset event.  Be careful,
```
pthread_cond_wait
```
may have spurious wakeups, so it should never be used without some sort of external flag regardless of the situation.
Building your own wouldn't be too hard, though.
```
```
#include <pthread.h>
#include <stdbool.h>

struct mrevent {
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    bool triggered;
};

void mrevent_init(struct mrevent *ev) {
    pthread_mutex_init(&ev->mutex, 0);
    pthread_cond_init(&ev->cond, 0);
    ev->triggered = false;
}

void mrevent_trigger(struct mrevent *ev) {
    pthread_mutex_lock(&ev->mutex);
    ev->triggered = true;
    pthread_cond_signal(&ev->cond);
    pthread_mutex_unlock(&ev->mutex);
}

void mrevent_reset(struct mrevent *ev) {
    pthread_mutex_lock(&ev->mutex);
    ev->triggered = false;
    pthread_mutex_unlock(&ev->mutex);
}

void mrevent_wait(struct mrevent *ev) {
     pthread_mutex_lock(&ev->mutex);
     while (!ev->triggered)
         pthread_cond_wait(&ev->cond, &ev->mutex);
     pthread_mutex_unlock(&ev->mutex);
}
```
```
This may not fit your usage, as you will often have a different lock that you'd want to use in place of
```
ev->mutex
```
, but this is the gist of how it's typically used.


Question:
Let's say I have to implement a piece of T-SQL code that must return a table as result. I can implement a table-valued function or else a stored procedure that returns a set of rows. What should I use?

In short, what I want to know is:

Which are the main differences between functions and stored procedures? What considerations do I have to take into account for using one or the other?

Answer:
If you're likely to want to combine the result of this piece of code with other tables, then obviously a table-valued function will allow you to compose the results in a single SELECT statement.
Generally, there's a hierarchy (View < TV Function < Stored Proc). You can do more in each one, but the ability to compose the outputs, and for the optimizer to get really involved decreases as the functionality increases.
So use whichever one minimally allows you to express your desired result.


Question:
Originally I thought to ask if there would be an easy way to provide an automatically managed last update field with MS Access.

After some googling I found following approach:

Private Sub Form_Dirty(Cancel As Integer)

   Me.Last_Update = Date()

End Sub

Which seems to do the job. I thought I'd share it with others too (and if somebody has some good points that should be considered, feel free to share them)

Answer:
That might be your best choice on an access database with an access back end- but if you've got a MS-SQL back end, put an update trigger on the table so that you can catch edits regardless of where they come from.
```
```
CREATE TRIGGER [Table_stampUpdates] ON [dbo].[Table]
 FOR Update
AS
BEGIN
UPDATE Table
SET
modified_by = right(system_user, len(system_user) - charindex('\', system_user)), modified_on = getdate()
FROM Table inner join inserted on Table.PrimaryKey = Inserted.PrimaryKey
 END
```
```


Question: I have an application in C# (2.0 running on XP embedded) that is communicating with a 'watchdog' that is implemented as a Windows Service. When the device boots, this service typically takes some time to start. I'd like to check, from my code, if the service is running. How can I accomplish this?

Answer:
I guess something like this would work:
Add
```
System.ServiceProcess
```
to your project references (It's on the .NET tab).
```
```
using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}
```
```
Edit: There is also a method
```
sc.WaitforStatus()
```
that takes a desired status and a timeout, never used it but it may suit your needs.
Edit: Once you get the status, to get the status again you will need to call
```
sc.Refresh()
```
first.
Reference:
ServiceController
object in .NET.


Question:
I'd like to calculate the age of the messages in an Exchange mailbox to make sure they sit there for at least a minute before our program (C++, MAPI) processes them. This way the spam filter we use should have enough time to do its job.

Because the time on the PC where our program runs might be different from the time used by the Exchange server, our program has to read the server time via MAPI.

Is there an elegant solution to it? One way I can think of is to modify some Item and immediately read its PR_LAST_MODIFICATION_TIME, but I'd like to avoid that.

Edit:

Our program is a batch job that runs every 10 minutes and reads the journal mailbox.

Answer:
You can use
```
PR_MESSAGE_DELIVERY_TIME
```
.
As per
MSDN
:
The
```
PR_MESSAGE_DELIVERY_TIME
```
property describes the time the message was stored at the server, rather than the download time when the transport provider copied the message from the server to the local store.
Other than that - when your solution runs on the client anyway - why not use the client time in the first place? Incorrect clock or not, for relative times (e.g. "one minute after ...") this should make no difference.


Question:
In PHP I can name my array indices so that I may have something like:

$shows = Array(0 => Array('id' => 1, 'name' => 'Sesame Street'),
               1 => Array('id' => 2, 'name' => 'Dora The Explorer'));

Is this possible in Python?

Answer:
Yes,
```
```
a = {"id": 1, "name":"Sesame Street"}
```
```


Question:
When designing business objects I have tried several different methods of writing the data access layer.  Some have worked out better than others but I have always felt there must be a "better" way.

I would really just like to see the different ways people have handled the DAL in different situations and their opinon of how the technique worked or didn't work well.

Answer:
Unfortunately I don't think there is a "better way", it's too dependent on the specific situation as to what DAL approach you use.
A great discussion of the "state of the art" is
Patterns of Enterprise Application Architecture
by Martin Fowler.
Chapter 10, Data Source Architectural Patterns specifically talks about most of the most commonly used patterns for business applications.
In general though, I've found using the simplest approach that meets the basic maintainability and adaptability requirements is the best choice.
For example on a recent project a simple "Row Data Gateway" was all I needed.  (This was simply code generated classes for each relevant database table, including methods to perform the CRUD operations).  No endless debates about ORM versus stored procs, it just worked, and did the required job well.


Question:
We are building a multi-tenant website in ASP.NET, and we must let each customer configure their own security model.  They must be able to define their own roles, and put users in those roles.  What is the best way to do this?

There are tons of simple examples of page_load events that have code like:

  if (!user.InGroup("Admin")
       Response.Redirect("/NoAccess.aspx");

But that hard codes the groups and permissions in the code.  How can I make it user configurable?

Answer:
I would create a configuration system for the website that is easily managed in config-files. Where you could get typed members and use like this.
```
```
foreach(var group in ThisPageConfiguration.AcceptedRoleNames)
if (user.IsInRole(group))
...
```
```
Each customer could then configure their site in their configuration files... And every other type of things you'd want to configure.


Question:
We are using log4j behind a selfmade wrapper. We plan to use much more features of it now.

Should we update to logback ?

(I mean the framework not a facade like SLF4J)

Answer:
Not exactly answering your question, but if you could move away from your self-made wrapper then there is
Simple Logging Facade for Java (SLF4J)
which Hibernate has now switched to (instead of commons logging).
SLF4J suffers from none of the class loader problems or memory leaks observed with Jakarta Commons Logging (JCL).
SLF4J supports JDK logging, log4j and logback. So then it should be fairly easy to switch from log4j to logback when the time is right.
Edit: Aplogies that I hadn't made myself clear. I was suggesting using SLF4J to isolate yourself from having to make a hard choice between log4j or logback.


Question:
In Informix, how can I cast a char(8) type into a money type, so that I can compare it to another money type?

Using "tblAid.amt::money as aid_amt" did not work.
Using "(tblAid.amt * 1) AS aid_amt" did not work.

Answer:
try this -->
```
```
select (disb_amt::NUMERIC) disb_amt from tmp_kygrants;
```
```
You may be able to compare the amounts as numeric.


Question: Most, if not all architecture documents I've seen (and developed) have been presented as a series of views (Logical, Physical, Use-case etc).  Is this the preferred layout?  What other styles are there?

Answer:
Since it's complex, it's hard to do otherwise.
I like to start with the one-paragraph summary of the overall requirements.  If there isn't a one-paragraph summary, that's -- perhaps -- the most important thing to build.
Once the summary is out of the way, there's an overview of architectural features.  And after that, no one will read a single word.
It isn't a novel.  There's no story arc.  No drama.  No conflict.  No characters.  At least, I can't find a way to make an architecture readable.
The best you can hope for is a reference work with enough indexes, cross references, overviews and sidebars that people use it.
Indeed, it's the pull-outs that matter.  The picture are all anyone will ever use.  And those will get put into PPT's for presentation internally and externally.
So, don't waste a lot of time on writing.  Invest time in overviews, summaries, feature lists and pictures people want to use every day.


Question:
I have minified my javascript and my css.

Now, Which is better?

<script type="text/javascript">
<?
  $r = file_get_contents('min.js');
  if($r) echo $r;
?>
</script>

OR

<script type="text/javascript" src="min.js"></script>

Same question for CSS.

If the answer is 'sometimes because browsers fetch files simultaneously?'  Which browsers, and what are examples of the times in either scenario.

Answer:
```
```
<script type="text/javascript" src="min.js"></script>
```
```
...is better, as the user's browser can cache the file.
Adding a parameter to the
```
src
```
such as the file's last modified timestamp is even better, as the user's browser will cache the file but will always retrieve the most up to date version when the file is modified.
```
```
<script type="text/javascript" src="min.js?version=20081007134916"></script>
```
```


Question:
Today at work we came across the following code (some of you might recognize it):

#define GET_VAL( val, type ) \
    {                                                   \
        ASSERT( ( pIP + sizeof(type) ) <= pMethodEnd ); \
        val = ( *((type *&)(pIP))++ );                  \
    }

Basically we have a byte array and a pointer. The macro returns a reference to a variable of type and advance the pointer to the end of that variable.

It reminded me of the several times that I needed to "think like a parser" in order to understand C++ code.

Do you know of other code examples that caused you to stop and read it several times till you managed to grasp what it was suppose to do?

Answer:
C, but present in C++, I find the comma operator really obfuscates code, take this...
```
```
ihi = y[0]>y[1] ? (inhi=1,0) : (inhi=0,1);
```
```
Terse and quite elegant, but very easy to miss or misunderstand.


Question:
When you're passing variables through your site using GET requests, do you validate (regular expressions, filters, etc.) them before you use them?

Say you have the URL http://www.example.com/i=45&p=custform. You know that "i" will always be an integer and "p" will always contain only letters and/or numbers. Is it worth the time to make sure that no one has attempted to manipulate the values and then resubmit the page?

Answer:
Yes.  Without a doubt.  Never trust user input.
To improve the user experience, input fields can (and IMHO should) be validated on the client. This can pre-empt a round trip to the server that only leads to the same form and an error message.
However, input must
always
be validated on the server side since the user can just change the input data manually in the GET url or send crafted POST data.
In a worst case scenario you can end up with an
SQL injection
, or even worse, a
XSS
vulnerability.
Most frameworks already have some builtin way to clean the input, but even without this it's usually very easy to clean the input using a combination of regular exceptions and lookup tables.
Say you know it's an integer, use int.Parse or match it against the regex "^\d+$".
If it's a string and the choices are limited, make a dictionary and run the string through it. If you don't get a match change the string to a default.
If it's a user specified string, match it against a strict regex like "^\w+$"


Question:
How do I toggle the visibility of an element using  .hide(), .show(), or .toggle()?

How do I test if an element is visible or hidden?

Answer:
```
```
if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
    // 'element' is hidden
}
```
```
The above method does not consider the visibility of the parent. To consider the parent as well, you should use
```
.is(":hidden")
```
or
```
.is(":visible")
```
.
For example,
```
```

Div2

```
```
The above method will consider
```
div2
```
visible while
```
:visible
```
not. But the above might be useful in many cases, especially when you need to find if there is any error divs visible in the hidden parent because in such conditions
```
:visible
```
will not work.


Question:
I have an MFC app which I have been working on for a few weeks now, I want to manually set the dimensions of the main frame when it is loaded, can someone give me a hand with this, specifically where to put the code as well?

Thanks!

Answer:
Find your screen size with ..
```
```
CRect rect;
SystemParametersInfo(SPI_GETWORKAREA,0,&rect,0);
screen_x_size=rect.Width();
screen_y_size=rect.Height();
```
```
use these values to calculate the X and Y size of your window then ..
```
```
::SetWindowPos(m_hWnd,HWND_TOPMOST,0,0,main_x_size,main_y_size,SWP_NOZORDER);
```
```
Where
```
main_x_size
```
and
```
main_y_size
```
are your sizes.


Question:
OK, another road bump in my current project.

I have never had form elements in both my master and content pages, I tend to have all the forms in the content where relevant.

In the current project however, we have a page where they want both. A login form at the top right, and a questions form in the content.

Having tried to get this in, I have run in to the issue of ASP.NET moaning about the need for a single form element in a master page. TBH, I really dont get why this is a requirement on ASP.NET's part, but hey ho.

Does anyone know if/how I can get the master and content pages to contain form elements that work independantly?

If not, can you offer advice on how to proceed to get the desired look/functionality?

Answer:
no, you can only have one asp.net form per page.
That has been the rule since 1.0
They should both share the same form


Question: Can MySql 5.0 views use tables that are located on another server?  What is the syntax for creating such a view?

Answer:
Yes, you can create objects in one database that reference another database and even another host. The syntax to do so works something like this:
```
```
USE localhost.myDB;

SELECT * FROM host2.db.tableName;
```
```


Question:
Say I have the following:

<ul>
 <li>First item</li>
 <li>Second item</li>
 <li>Third item</li>
</ul>

How would I select all the child elements after the first one using jQuery?  So I can achieve something like:

<ul>
 <li>First item</li>
 <li class="something">Second item</li>
 <li class="something">Third item</li>
</ul>

Answer:
http://docs.jquery.com/Traversing/slice
```
```
$("li").slice(1).addClass("something");
```
```


Question:
Is it better to do this:

try
{
    ...
}
catch (Exception ex)
{
    ...
    throw;
}

Or this:

try
{
    ...
}
catch (Exception ex)
{
    ...
    throw ex;
}

Do they do the same thing? Is one better than the other?

Answer:
You should always use the following syntax to rethrow an exception. Else you'll stomp the stack trace:
```
```
throw;
```
```
If you print the trace resulting from
```
throw ex
```
, you'll see that it ends on that statement and not at the real source of the exception.
Basically, it should be deemed a criminal offense to use
```
throw ex
```
.
If there is a need to rethrow an exception that comes from somewhere else (AggregateException, TargetInvocationException) or perhaps another thread, you also shouldn't rethrow it directly. Rather there is the
ExceptionDispatchInfo
that preserves all the necessary information.
```
```
try
{
    methodInfo.Invoke(...);
}
catch (System.Reflection.TargetInvocationException e)
{
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw();
    throw; // just to inform the compiler that the flow never leaves the block
}
```
```


Question: Answers to a recent post (Any chances to imitate times() Ruby method in C#?) use the => operator in the usage examples.  What does this operator do?  I can't locate it in my C# book, and it is hard to search for symbols like this online.  (I couldn't find it.)

Answer:
It's not really an operator as such, it's part of the syntax for lambda expressions. In particular => is the bit which separates the parameters from the body of the lambda expression.
Does your book cover C# 3.0? If not, it won't include lambda expressions. If it does, it should really cover them! Hopefully with the right terminology, you'll be able to find it in the TOC or index.
EDIT: A bit more information: A lambda expression is a piece of syntactic sugar to either create an instance of a delegate
or
an expression tree (the latter being new to .NET 3.5). Lambda expressions almost entirely replace anonymous methods (from C# 2.0) although they don't support the notion of "I don't care about the parameters" in the way that anonymous methods do.


Question: I'm just starting with CodeIgniter, and I am not sure where things such as css, js, and images should go. Outside the whole system folder seems ok, but that means everything is seperate. Inside means the filepaths are longer, and I'm worried that it might mess things up. What's the best practice on this issue?

Answer:
I usually put separate folders at the root level, so I end up with a directory structure like this:
```
```
/system
/css
/js
/img
```
```
Seems to work for me - when you use
```
site_url(url)
```
, the URL it generates is from the root, so you can use
```
site_url('css/file.css')
```
to generate URLs to your stylesheets etc.


Question:
How can I round a decimal number (floating point) to the nearest integer?

e.g.

1.2 = 1
1.7 = 2

Answer:
You can either use a module like
Math::Round
:
```
```
use Math::Round;
my $rounded = round( $float );
```
```
Or you can do it the crude way:
```
```
my $rounded = sprintf "%.0f", $float;
```
```


Question:
I have the following VB.net interface that I need to port to C#.  C# does not allow enumerations in interfaces.  How can I port this without changing code that uses this interface?

Public Interface MyInterface

    Enum MyEnum
        Yes = 0
        No = 1
        Maybe = 2
    End Enum

    ReadOnly Property Number() As MyEnum

End Interface

Answer:
```
```
public enum MyEnum
{
    Yes = 0,
    No = 1,
    Maybe = 2
}

public interface IMyInterface
{
    MyEnum Number { get; }
}
```
```


Question:
I'm using Webbrowser control to login to HTTPS site with "untrusted certificate".
but I get popup such standart window "Security Alert" about untrusted certificate:

I have to find this window by title and send it Alt+Y to press Yes:

int iHandle = NativeWin32.FindWindow(null, "Security Alert");
NativeWin32.SetForegroundWindow(iHandle);
System.Windows.Forms.SendKeys.Send("Y%");

but user can see a flickering of this window.

How can I ignore this alert?

Or disable this "untrusted certificate" check in Webbrowser control?

Answer:
This should do it:
```
```
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return true;
}

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
```
```
Obviously, blindingly allowing certificates is a security risk.  Be careful.


Question:
We are trying to bind a Linux machine (debian 4.0) to W2k3 AD.  We have configured kerberos properly so that we can get TGTs.  And users authenticate properly.  However, PAM seems to be the sticky wicket.  For example when we try to SSH to the linux machine as one of the AD users, the authentication succeeds (as per the auth.log) but I never get shell.  The default environment is configured properly and PAM even creates the Homedir properly.  As a reference we were loosely following:

https://help.ubuntu.com/community/ActiveDirectoryHowto

Answer:
If you're confident everything but PAM works correctly, I suggest passing the debug option to pam_krb5.so to see if that gives a clue to what's happening.
I'd also suggest verifying that nss-ldap is set up correctly using
```
```
getent passwd avalidusername
```
```


Question:
<div spry:region="ds1" spry:repeatchildren="ds1">
  <b spry:if=" '{title}'!='' ">
    <!-- this is the first if -->
    <a href="#"  spry:if=" '{author}'!='' ">{author}
      <!-- this is the second if -->
    </a>
  </b>
</div>

I wonder if there is any method as simple as

if(x==y && i>j)

in

<b>spry</b>

region.
I can't find any information in spry docs  (labs.adobe.com/technologies/spry/)

Answer:
The syntax inside the
```
spry:if
```
attribute is Javascript, so you can use
```
&&
```
:
```
```
<b spry:if="'{title}' != '' && '{author}' != ''">
<!-- ... -->
</b>
```
```


Question:
When Instantiating a class, Windsor by default treats all public properties of the class as optional dependencies and tries to satisfy them.  In my case, this creates a rather complicated circular dependency which causes my application to hang.

How can I explicitly tell Castle Windsor that it should not be trying to satisfy a public property?  I assume there must be an attribute to that extent.  I can't find it however so  please let me know the appropriate namespace/assembly.

If there is any way to do this without attributes (such as Xml Configuration or configuration via code) that would be preferable since the specific library where this is happening has to date not needed a dependency on castle.


Question:
There is some magic going on with WCF deserialization.  How does it instantiate an instance of the data contract type without calling its constructor?

For example, consider this data contract:

[DataContract]
public sealed class CreateMe
{
   [DataMember] private readonly string _name;
   [DataMember] private readonly int _age;
   private readonly bool _wasConstructorCalled;

   public CreateMe()
   {
      _wasConstructorCalled = true;
   }

   // ... other members here
}

When obtaining an instance of this object via DataContractSerializer you will see that the field _wasConstructorCalled is false.

So, how does WCF do this?  Is this a technique that others can use too, or is it hidden away from us?

Answer:
```
FormatterServices.GetUninitializedObject()
```
will create an instance without calling a constructor.  I found this class by using
Reflector
and digging through some of the core .Net serialization classes.
I tested it using the sample code below and it looks like it works great:
```
```
using System;
using System.Reflection;
using System.Runtime.Serialization;

namespace NoConstructorThingy
{
    class Program
    {
        static void Main()
        {
            // does not call ctor
            var myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass));

            Console.WriteLine(myClass.One); // writes "0", constructor not called
            Console.WriteLine(myClass.Two); // writes "0", field initializer not called
        }
    }

    public class MyClass
    {
        public MyClass()
        {
            Console.WriteLine("MyClass ctor called.");
            One = 1;
        }

        public int One { get; private set; }
        public readonly int Two = 2;
    }
}
```
```
http://d3j5vwomefv46c.cloudfront.net/photos/large/687556261.png


Question: Am looking for commercial/free recommended c# winform controls packs

Answer:
See the following threads:
.NET Usercontrols telerik devexpress infragistics ComponentOne whos best


Question: How can i make my flash applications in a browser in full screen mode? I know that the stage can be put in that mode, but when i run the application in any browser this doesn't work. So, this can be done, but how?

Answer:
I believe it is a simple actionscript command.
Source
```
```
fscommand( "fullscreen" ,  "true" )
```
```


Question:
Basically I have a bunch of unmanaged VC++ static libraries. And the VC++ GUI application which uses those and it is based on MFC.
The goal is to replace the GUI app with the one done in C# instead but using all the same static libraries.
The question is if this even possible, and if yes, then what is the right way to accomplish that?

Suggestions, anybody?
Thanks.

Answer:
Yes, it is possible using C++/CLI for managed C++ code.  You would write a C++/CLI WinForms app and simply link in your static lib as per normal.
However, if there is a lot of tight coupling between the GUI code and the libraries then this can get a bit messy.  You will need to worry about converting some data types between the managed and unmanaged world, particularly strings.  If you need to pass managed objects/arrays
There is a good introduction on
Wikipedia
and lots of documentation on
MSDN
.


Question:
I've got the following JavaScript on my web page...

64    var description = new Array();
65    description[0] = "..."
66    description[1] = "..."
...
78    function init() {
79        document.getElementById('somedivid').innerHTML = description[0];
80    }
81
82    window.onload = init();

In Microsoft Internet Explorer it causes the following error...

A Runtime Error has occurred.

  Do you wish to debug?

Line: 81

  Error: Not implemented

Line 79 executes as expected.

If line 79 is commented out, it still throws the error.

If I comment out line 82, then the function does not execute and there is no error.

Answer:
Try to add an envent listener for 'load' instead, or use the declarative syntax
```
<body onload="init()">
```
.
EDIT: Additionally, saying
```
window.onload = init();
```
sets window.onload to the result of calling
```
init()
```
. What you mean is
```
window.onload = init;
```
(a lambda expression). This is bad practice still, as it overwrites other things that might be bound to
```
window.onload
```
.