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

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


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

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

s: huggingface

c: devops

d: intermediate


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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


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

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


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

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


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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

e.g.

1.2 = 1
1.7 = 2

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


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

[A]
```
```
public enum MyEnum
{
    Yes = 0,
    No = 1,
    Maybe = 2
}

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


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

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


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

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


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

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


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


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

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


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

[A]
See the following threads:
.NET Usercontrols telerik devexpress infragistics ComponentOne whos best


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

[A]
I believe it is a simple actionscript command.
Source
```
```
fscommand( "fullscreen" ,  "true" )
```
```


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

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


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

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


q:
I always use unix timestamps for everything, but am wondering if there is a better way.

What do you use to store timestamps and why?

[A]
32 bit Unix timestamps will overflow in a few years (January 2038)
, so that might be a consideration. I generally use a DATETIME format in SQL, which is YYYY-MM-DD HH:MM:SS with the time as a 24-hour clock. I try to output to files in the same format, just to make my life easier.


q:
Trying to use an excpetion class which could provide location reference for XML parsing, found an interesting behavior - compiler could not choose between overload which consumes an interface and one which needs System.Exception when I trying to pass XmlReader as a parameter.

Detais are following:

//exception overloads:
public FilterXmlParseException(string message, Exception innerException)
        : base(message, innerException) { }
public FilterXmlParseException(string message, IXmlLineInfo lineInfo) {...}

//Usage:
XmlReader reader = ...
IXmlLineInfo lineinfo = (IXmlLineInfo)reader;

//fails
throw new FilterXmlParseException("<Filter> element expected", reader);

//ok
throw new FilterXmlParseException("<Filter> element expected", lineinfo);

And it fails since it could not select correct overload.But why? We see that XmlReader supports an interface and it is not inherited from System.Exception

[A]
The line:
```
```
//fails
throw new FilterXmlParseException("<Filter> element expected", reader);
```
```
because XmlReader doesn't implement IXmlLineInfo. I am not sure if your cast works, but the casts are not checked statically. If it actually works, it is because the concrete class (that inherits from XmlReader) implements this interface, but the compiler has no way to know it.


q:
What is tracing and how should it be done?

I have a common utilities library I am including in my projects and I want to be able to get some output from it. I have been using log4net but would rather not have my common utilities library dependent upon log4net. Does that make sense?

Edit:
Is there any correlation between logging and tracing? Would I want to put tracing and logging into the same stream for some reason?

Should I perhaps replace some of the log4net Logger.Debug(..) I have in my projects with System.Diagnostics.Trace.WriteLine(..)s?

[A]
Here are some blog posts by Mike Rousos of the .NET BCL team:
A Tracing Primer – Part I
- is a simple introduction to the tracing APIs.
A Tracing Primer – Part II (A)
- talks mainly about filtering events
A Tracing Primer – Part II (B)
- talks about developing custom trace listeners (plugins that will channel your trace events to wherever you desire).
A Tracing Primer – Part II (C)
- talks about  how the configuration files are interpreted.


q:
I have seen arguments for using explicit interfaces as a method of locking a classes usage to that interface.  The argument seems to be that by forcing others to program to the interface you can ensure better decoupling of the classes and allow easier testing.

Example:

public interface ICut
{
    void Cut();
}
public class Knife : ICut
{
    void ICut.Cut()
    {
        //Cut Something
    }
}

And to use the Knife object:

ICut obj = new Knife();
obj.Cut();

Would you recommend this method of interface implementation? Why or why not?

EDIT:
Also, given that I am using an explicit interface the following would NOT work.

Knife obj = new Knife();
obj.Cut();

[A]
If the client code doesn't care about anything other than the fact that it can use the object to
```
Cut()
```
things, then use
```
ICut
```
.


q:
Should new projects use logback instead of log4j as a logging framework ?

Or with other words :'Is logback better than log4j (leaving the SLF4J-'feature' of logback beside)?'

[A]
I'm not familiar with SLF4J, and I've only taken a brief look at logback, but two things come to mind.
First, why are you excluding a tool from examination? I think it's important to keep an open mind and examine all possibilities to choose the best one.
Second, I think that in some projects one tool is a better than another tool, and the opposite might be true in a different project. I don't think that one tool is always better than another tool. There is, after all,
no silver bullet
.
To answer your question - Yes and no. It depends on the project, and how familiar the team is with one tool. I wouldn't say "don't use log4j" if the entire team is very comfortable with it, it meets all the needs, and logback doesn't offer anything that we need to complete the task.


q:
I am looking for a regex that will find repeating letters. So any letter twice or more, for example:

booooooot or abbott

I won't know the letter I am looking for ahead of time.

This is a question I was asked in interviews and then asked in interviews. Not so many people get it correct.

[A]
Use \N to refer to previous groups:
```
```
/(\w)\1+/g
```
```


q:
Is there some simple way to calculate a Weeknumber value from a date value stored in XML?

It needs to be pure XSLT solution. I cannot use any code :(

[A]
I program in Visual Basic, so I know how to do it using VB.NET.  Read your XML date into a variable (let's call it
SomeDate
).  Then you construct a new date that you
know
is the beginning of the year that contains your unknown date.  Then, you let the
DateDiff
function do its work to tell you the week number.
```
```
Dim SomeDate As Date = ReadDateFromXML()
Dim YearStart As New Date(Year(SomeDate), 1, 1)
Dim WeekNumber As Integer = DateDiff(DateInterval.WeekOfYear, YearStart, SomeDate)
```
```


q:
Is it possible to get the text of an OleDbCommand with all parameters replaced with their values? E.g. in the code below I'm looking for a way to get the query text

SELECT * FROM my_table WHERE c1 = 'hello' and c2 = 'world'

after I finished assigning the parameters.

var query = "SELECT * FROM my_table WHERE c1 = ? and c2 = ?";
var cmd = new OleDbCommand(query, connection);
cmd.Parameters.Add("@p1", OleDbType.WChar).Value = "hello";
cmd.Parameters.Add("@p2", OleDbType.WChar).Value = "world";

[A]
No:  you have to iterate through the parameters collection yourself, doing a string.Replace() to get the equivalent.  It's particularly painful when you have to use the
```
?
```
syntax rather than the
```
@parametername
```
syntax.
The reason for this is that the full string is
never
assembled.  The parameters and sent to the server and treated as data, and are never included in the string.
All the same, I for one understand your pain.  It would have been nice if they included some kind of
```
.ComposeSQL()
```
method you could call
for debugging purposes
, that perhaps also produces a compiler warning to help avoid use in production.


q:
Is it is possible, with Windows Forms in .NET, to change the opacity of a form without it automatically changing the opacity of the controls within the form?

I have a form that is running maximized, that contains a flowlayoutpanel in the centre of the form with controls inside it. I would like to lower the opacity of the form so that the "spare" part around the flowlayoutpanel is partly transparent, but the flowlayoutpanel itself remains solid (im aiming for a lightbox style effect).

[A]
Unfortunately,
```
Opacity
```
is a property of
```
Form
```
, not
```
Control
```
. The only way I can imagine this would be possible is if you custom drew the form yourself and used an alpha-component in the brush used to paint the form background.
Even then, I don't think it would work as the desktop composition manager (especially relevant on Windows Vista) needs to know how your form is supposed to be composed with the rest of the desktop, and I think the brush would only be transparent against the form background, rather than whatever is underneath it.


q:
var something = {

wtf: null,
omg: null
};

My JavaScript knowledge is still horribly patchy since I last programmed with it, but I think I've relearned most of it now.  Except for this.  I don't recall ever seeing this before.  What is it?  And where can I learn more about it?

[A]
It's object literal syntax. The 'wft' and 'omg' are property names while, null and null are the property values.
It is equivalent to:
```
```
var something = new Object();
something.wtf = null;
something.omg = null;
```
```
Check out mozilla's documentation on object literals:
http://developer.mozilla.org/En/Core_JavaScript_1.5_Guide:Literals#Object_Literals


q: What do I need to do to save an image my program has generated (possibly from the camera, possibly not) to the system photo library on the iPhone?

[A]
You can use this function:
```
```
UIImageWriteToSavedPhotosAlbum(UIImage *image,
                               id completionTarget,
                               SEL completionSelector,
                               void *contextInfo);
```
```
You only need
completionTarget
,
completionSelector
and
contextInfo
if you want to be notified when the
```
UIImage
```
is done saving, otherwise you can pass in
```
nil
```
.
See the
official documentation for
```
UIImageWriteToSavedPhotosAlbum()
```
.


q:
I have the following code in my file to load a div with HTML from an AJAX call:

$('#searchButton').click( function() {
    $('#inquiry').load('/search.php?pid=' + $('#searchValue').val());
});

This works fine in Firefox and Google Chrome, but whenever I do the search in IE I get redirected back to index.php. I grabbed the URL from Firebug and pasted that into IE and no redirection happens, I just get the output that should be returned.

I also tried changing it to a $.get() request and a full $.ajax() request but still the same redirection.

[A]
IE Handles default events differently (also beware of hitting enter in a text field).  IE is causing some default event handler to fire.  If searchButton is a  link with HREF of "" it will reload the current page.  You can try to set the href to  "javascript:void(0)"  or do something like:
```
```
$('#searchButton').click( function(e) {
    $('#inquiry').load('/search.php?pid=' + $('#searchValue').val());
    e.preventDefault();
});
```
```


q:
In the STL library some containers have iterators and it is commonly held that they are a superior way of iterating through these containers rather than simple for loops e.g.

for ( int i=0; i < vecVector.size(); i++ )
{

..

}

Can anyone tell me why and in what cases I should use iterators and in what cases the code snippet above please?

[A]
Using iterators allows your code to be agnostic about the implementation of your container.  If random access for your container is cheap, there isn't much difference performance-wise.
But in lots of cases you won't know whether that is the case.  If you try do use your method on a linked list, for example, with subscripting, the container is going to have to walk the list on every iteration to find your element.
So unless you know for sure that random access to your container is cheap, use an iterator.


q:
I have this working definition:

IDENTIFIER   [a-zA-Z][a-zA-Z0-9]*

I don't want to keep repeating the [a-zA-Z] and [0-9], so I made two new definitions

DIGIT    [0-9]
VALID    [a-zA-Z]

How can I rewrite the IDENTIFIER rule to use the DIGIT and VALID definitions?

I don't know how to do the "second" match, I'm stuck here:

IDENTIFIER {VALID}[{VALID}{DIGIT}]* // This syntax is incorrect

Thanks.

Edit: The entire test program that I'm using: http://pastebin.com/f5b64183f.

[A]
I think this will do it, but I can't test it.  Do you have sample data?
```
```
(?:[a-zA-Z])+(?:[0-9])+
```
```


q:
JavaScript post request like a form submit shows you how to submit a form that you create via POST in JavaScript. Below is my modified code.

var form = document.createElement("form");

form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");

var hiddenField = document.createElement("input");

hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form); // Not entirely sure if this is necessary
form.submit();

What I would like to do is open the results in a new window. I am currently using something like this to open a page in a new window:

onclick = window.open(test.html, '', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');

[A]
Add
```
```
<form target="_blank" ...></form>
```
```
or
```
```
form.setAttribute("target", "_blank");
```
```
to your form's definition.


q:
In the Ajax toolkit you can use a Tab Container and add TabPanels to this.

I have some controls that I want to be able to use across all tabs and the tailor the tabs with other controls as neccessary.

My question is how do I reuse a panel on multiple tabs?
Essentially I after something like this

<TabContainer>
<tabPanel1>
<contentTemplate>
<pnl1></pnl1>
//other controls here
</contentTemplate>
</tabPanel1>

<tabPanel2>
<contentTemplate>
<pnl1></pnl1>
//other controls here
</contentTemplate>
<tabPanel2>
</tabContainer>

<pnl1>
//some controls here
</pnl1>

[A]
Make the panel a user control and then drop the user control in each tab panel.
```
```
<TabContainer>
  <tabPanel1>
    <contentTemplate>
      <uc1:MyControl id="myControl" runat="server" />
    </contentTemplate>
  </tablPanel1>

  <tabPanel2>
    <contentTemplate>
      <uc1:MyControl id="myControl2" runat="server" />
    </contentTemplate>
  </tablPanel2>
</TabContainer>

<uc1:MyControl id="myControl3" runat="server" />
```
```


q:
Logging can get complicated, quickly. Considering that you have some code, how do you add logging to it? What library(ies) do you use?

What are some good code techniques for getting the most out of your logging statements while having minimal impact on your application?

[A]
Libraries:
Log4J
and
Log4Net
(for Java and .NET respectively)
From Log4J site:
Inserting log statements into your code is a low-tech method for debugging it. It may also be the only way because debuggers are not always available or applicable. This is often the case for distributed applications.
On the other hand, some people argue that log statements pollute source code and decrease legibility. (We believe that the contrary is true). In the Java language where a preprocessor is not available, log statements increase the size of the code and reduce its speed, even when logging is turned off. Given that a reasonably sized application may contain thousands of log statements, speed is of particular importance.
With log4j it is possible to enable logging at runtime without modifying the application binary. The log4j package is designed so that these statements can remain in shipped code without incurring a heavy performance cost. Logging behavior can be controlled by editing a configuration file, without touching the application binary.
Logging equips the developer with detailed context for application failures. On the other hand, testing provides quality assurance and confidence in the application. Logging and testing should not be confused. They are complementary. When logging is wisely used, it can prove to be an essential tool.


q:
How do you add a JAR file to an already existing Java library in Eclipse?  Note that this is not a user library.

That is, if you look at the Java Build Path for a Java project and click on the Libraries tab, you will see the list of libraries used by the project.  If you expand a given library, you will see a list of JAR files included in that library.  I want to add an additional JAR file to one of these libraries.

I am using Version 3.4.0 of Eclipse.

[A]
In Eclipse Ganymede (3.4.0):
Select the library and click "Edit" (left side of the window)
Click "User Libraries"
Select the library again and click "Add JARs"


q:
So, I was looking over my standard cache utility when preparing to unit test a controller and thought, hey, is accessing the HttpRuntime.Cache directly considered harmful in MVC?

I wrap the cache in a proxy class that implements a cache-like interface (tho much simpler) so that I can mock it during tests.  But I'm wondering if that's already done for me in the new framework.  I can't find anything, however.

Here's an idea of how I do it:

public ActionResult DoStuffLol(guid id)
{
  var model = CacheUtil.GetOrCreateAndStore(
                  "DoStuffLolModel",
                  () =>
                  {
                    /* construct model here; time consuming stuff */
                    return model;
                  });
  return View("DoStuffLol", model);
}

So, has the old patterns of accessing the cache changed?  Are there any better patterns for caching action results in MVC?

[A]
Add the OutputCache attribute to your controller action in order to tell the framework to cache the output for you.  You can read more about this attribute in
ScottGu's blog post on ASP.NET Preview 4
.
Don't combine this with the Authorize attribute
, however.


q:
What is the difference between creating one index across multiple columns versus creating multiple indexes, one per column?

Are there reasons why one should be used over the other?

For example:

Create NonClustered Index IX_IndexName On TableName
(Column1 Asc, Column2 Asc, Column3 Asc)

Versus:

Create NonClustered Index IX_IndexName1 On TableName
(Column1 Asc)

Create NonClustered Index IX_IndexName2 On TableName
(Column2 Asc)

Create NonClustered Index IX_IndexName3 On TableName
(Column3 Asc)

[A]
Yes.  I recommend you check out
Kimberly Tripp's articles on indexing
.
If an index is "covering", then there is no need to use anything but the index.  In SQL Server 2005, you can also add additional columns to the index that are not part of the key which can eliminate trips to the rest of the row.
Having multiple indexes, each on a single column may mean that only one index gets used at all - you will have to refer to the execution plan to see what effects different indexing schemes offer.
You can also use the tuning wizard to help determine what indexes would make a given query or workload perform the best.


q:
I want to get a System.Type given only the type name in a string.

For instance, if I have an object:

MyClass abc = new MyClass();

I can then say:

System.Type type = abc.GetType();

But what if all I have is:

string className = "MyClass";

[A]
```
```
Type type = Type.GetType("foo.bar.MyClass, foo.bar");
```
```
MSDN
.  Make sure the name is
Assembly Qualified
.


q:
I recall reading somewhere that using references to smart pointers can cause memory corruption.  Is this simply because of using the reference of the smart pointer after its been destroyed?  Or does the reference counting get messed up?

Thanks for clarifying

[A]
Assuming you are talking about shared_ptr here...
Is this simply because of using the
  reference of the smart pointer after
  its been destroyed?
This is a good answer. You may not know absolutely the lifetime of the pointer your reference refers too.
To get around this, you'd want to look into boost::weak_ptr. It doesn't participate in reference counting. When you need to use it, it gives you a shared_ptr which goes away once your done with it. It will also let you know when the refered to pointer has been collected.
From the
weak_ptr
documentation
The weak_ptr class template stores a
  "weak reference" to an object that's
  already managed by a shared_ptr. To
  access the object, a weak_ptr can be
  converted to a shared_ptr using the
  shared_ptr constructor or the member
  function lock. When the last
  shared_ptr to the object goes away and
  the object is deleted, the attempt to
  obtain a shared_ptr from the weak_ptr
  instances that refer to the deleted
  object will fail: the constructor will
  throw an exception of type
  boost::bad_weak_ptr, and
  weak_ptr::lock will return an empty
  shared_ptr.
Note the method expired() will also tell you if your ptr is still around.


q:
Say I've got two scheduled processes: A and B.

Given that B should not run until A has completed, how might I gracefully enforce this dependency?

Approaches that have been considered:

Have A schedule B upon completion. This has the downside of B never being scheduled if for some reason A failed.

When B runs, have it ping A to see if the latter has completed. How this might be accomplished (network, file, database record, message queue) could be messy and problematic introducing a third dependency.

Combine A and B into a single process.  This has the downside of tightly binding the two, making it harder to re-run one or the other in isolation if need be.

Thoughts?

[A]
Your option 1 directly answers your question: if B is dependent on A, and A fails, A not scheduling B means that B can't happen.
Unless B merely has to run after A does, whether or not A was successful.
In that case, something like the following (in bash) would work:
```
```
A && B
```
```


q:
I'm starting a project which requires reading outlook msg files in c#.  I have the specs for compound documents but am having trouble reading them in c#.  Any pointers would be greatly appreciated.

Thanks.

[A]
Outlook Interop
.  While I have never used the outlook interop, you
SHOULD
be able to open the email messages with it.
MailItem Interface
should be the interface that you need to access it.
Also, make sure that you release the
com references
after you are done with them


q:
I have an XmlDocument that already exists and is read from a file.

I would like to add a chunk of Xml to a node in the document. Is there a good way to create and add all the nodes without cluttering my code with many .CreateNote and .AppendChild calls?

I would like some way of making a string or stringBuilder of a valid Xml section and just appending that to an XmlNode.

ex:
Original XmlDoc:

<MyXml>
   <Employee>
   </Employee>
</MyXml>

and, I would like to add a Demographic (with several children) tag to Employee:

<MyXml>
   <Employee>
      <Demographic>
         <Age/>
         <DOB/>
      </Demographic>
   </Employee>
</MyXml>

[A]
I suggest using
XmlDocument.CreateDocumentFragment
if you have the data in free form strings. You'll still have to use AppendChild to add the fragment to a node, but you have the freedom of building the XML in your StringBuilder.
```
```
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(@"<MyXml><Employee></Employee></MyXml>");

XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment();
xfrag.InnerXml = @"<Demographic><Age/><DOB/></Demographic>";

xdoc.DocumentElement.FirstChild.AppendChild(xfrag);
```
```


q:
Is there an easy way to create a table in SQL Server (2005) from an Excel spreadsheet. I'm thinking maybe some tool?

Thanks in advance.

[A]
If the data is not that big and if it is a simple table, easiest way is to create and open the table in SQL Server Management Studio and copy paste the excel data into it.
Other solutions are using DTS or using
SSIS
..


q:
I want to add my own member to the StringBuilder class, but when I go to create it IntelliSense doesn't bring it up.

public class myStringBuilder()
    Inherits System.Text.[StringBuilder should be here]
    ....
end class

Is it even possible? thanks

[A]
No,
StringBuilder
is a
NotInheritable
class.  You could try wrapping a
StringBuilder
instance, but can't inherit from it.  You can also use
extension methods
, if you're using .NET 3.5.


q:
If I have an Address object which implements IEditableObject, I might have EndEdit implementation like this:

public void EndEdit()
{
    // BeginEdit would set _editInProgress and update *Editing fields;
    if (_editInProgress)
    {
        _line1 = _line1Editing;
        _line2 = _line2Editing;
        _city = _cityEditing;
        _state = _stateEditing;
        _postalCode = _postalCodeEditing;
        _editInProgress = false;
    }
}

If there is an exception updating _state, for example, then all 5 properties should reset.  This atomic update issue probably isn't limited to EndEdit.

[A]
First off, Kent is correct in wondering why setting a field would throw an exception.
Ignoring that question; you could just use a simple:
```
```
try {
  //do stuff
}
catch (Exception ex) {
  //reset

  //rethrow exception
  throw;
}
```
```
The complications come in with regards to what constitutes the reset value for each field?
The last value
A default value
Some token value denoting an invalid state
A mix of the above
If you need to "reset" to the last value then you'll likely want some way to easily store the object state before doing something to it, along with the ability to easily restore that state should something go wrong.  Check out the
Momento Pattern
on a nifty way to deal with that problem.


q:
Let's say I have an existing trivial XML file named 'MyData.xml' that contains the following:

<?xml version="1.0" encoding="utf-8" ?>
<myElement>foo</myElement>

I want to change the text value of 'foo' to 'bar' resulting in the following:

<?xml version="1.0" encoding="utf-8" ?>
<myElement>bar</myElement>

Once I am done, I want to save the changes.

What is the easiest and simplest way to accomplish all this?

[A]
For quick, non-critical XML manipulations, i really like
P4X
. It let's you write like this:
```
```
import p4x
doc = p4x.P4X (open(file).read)
doc.myElement = 'bar'
```
```


q:
I'm looking to call a subprocess with a file descriptor opened to a given pipe such that the open() call does not hang waiting for the other side of the pipe to receive a connection.

To demonstrate:

$ mkfifo /tmp/foobar.pipe
$ some_program --command-fd=5 5</tmp/foobar.pipe

In this case, some_program is not run until some process has /tmp/foobar.pipe open for write; however, some_program has useful effects even when it isn't receiving commands, so desired behavior is for some_program to be immediately executed.

Mechanisms to do this by exec'ing through an alternate scripting language (python, perl, etc) or a C wrapper which open /tmp/foobar.pipe with the O_NONBLOCK flag are obvious; I'm looking for a pure-bash solution, should one be possible.

[A]
The only way I know getting this kind of result is a hack:
```
```
mkfifo /tmp/foobar.in
mkfifo /tmp/foobar.out
( cat </tmp/foobar.in ) >/tmp/foobar.out &
some_program --command-fd=5 5</tmp/foobar.out
```
```
perhaps this helps :-)


q:
I'm implementing a class that wraps around an xml document with a very strictly defined schema.  I don't control the schema.

One of the properties in the class is for an element value that the schema indicates must match a certain regular expression.  In the setter for the property, if a string doesn't match the expression I'm throwing an exception.

My question is, how can I better communicate to users of my class the requirements for this field?  Is there an attribute I can use?  Xml comments (so it shows up in intellisense)?  Should I do something other than thrown an exception?  What other options do I have?

[A]
Document it in the XML comments, and throw an exception.  Make the message explicit:
```
```
Element <elementname> must match /regex/
```
```


q:
I am sure there is a simple answer to this one.

I have a docx file that I get an error when trying to download(document cannot be found).... .doc is fine .txt is also fine. I am sure this is just an iis setting, the permissions on the server are all the same for all files.

[A]
When there is no mime type associated with an extension in IIS (6.0 and up), it will give you 404. See
Requests for static files return 404 error (IIS 6.0)
. (
Edit:
The original MSDN link is dead as of mid-2017,
the Internet Archive has a copy
. Even though it was written for IIS6, the information still applies to modern IIS versions.)
Other than that, and just because you did not specify
where
the error shows up: When you forbid caching in a header, similar behavior may occur on the client. But that is a general issue, and not bound to .docx.


q: How do you delete all the cookies for the current domain using JavaScript?

[A]
As far as I know there's no way to do a blanket delete of any cookie set on the domain. You can clear a cookie if you know the name and if the script is on the same domain as the cookie.
You can set the value to empty and the expiration date to somewhere in the past:
```
```
var mydate = new Date();
mydate.setTime(mydate.getTime() - 1);
document.cookie = "username=; expires=" + mydate.toGMTString();
```
```
There's an
excellent article here
on manipulating cookies using javascript.


q:
Can anyone explain what this mod_rewrite rule is doing?

I'm trying to comment the file, but the code seems to state the opposite of what I think it's doing

# Enable rewriting of URLs
RewriteEngine on

# Allow specified file types to be accessed
# Thing to test = URL
# Condition = not starting with
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt)

# RewriteRule will only be performed if the preceeding RewriteCond is fulfilled
# Remove index.php from all URLs
# Pattern = anything (0 or more of any character)
# Substitution = index.php + the rest of the URL
RewriteRule ^(.*)$ /index.php/$1 [L]

[A]
If the URL does not start with index.php or images or css or js or robots.txt, the string "/index.php/" is prefixed.
As index.php is probably an executable php app, the index.php then can read the rest of the URL from its cgi environment. (it is stored in ${PATH_INFO})


q:
Assuming we always use a Sun JVM (say, 1.5+), is it always safe to cast a Graphics reference to Graphics2D?

I haven't seen it cause any problems yet and, to my understanding, the Graphics class is legacy code but the Java designers didn't want to change the interfaces for Swing and AWT classes in order to preserver backwards compatibility.

[A]
According to the discussion
here
, it
is always safe to cast from
```
Graphics
```
to
```
Graphics2D
```
. However I am not able to quickly find the official Sun statement on this.
The reason it is valid to cast from
  Graphics to Graphics2D, is because Sun
  have said that all Graphics objects
  returned by the API in Java 1.2 or
  above will be a subclass of
  Graphics2D.
Another hint
here
with the same conclusion.
Graphics Object can always be cast
  Graphics2D g2d = (Graphics2D)g;


q:
I checked out a project from SVN and did not specify the project type, so it checked out as a "default" project.  What is the easiest way to quickly convert this into a "Java" project?

I'm using Eclipse version 3.3.2.

[A]
Open the .project file and add java nature and builders.
```
```
<projectDescription>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
</projectDescription>
```
```
And in .classpath, reference the Java libs:
```
```
<classpath>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>
```
```


q:
Can VBA code instantiate and use .NET objects? The specific class I'm interested in is System.IO.Compression.GZipStream.

For Info GAC is the .NET Global Assembly Cache

[A]
VBA can make use of any .NET objects that are exposed to COM. I don't know if GZipStream is or not, but I would guess that it would be easier for you to create a separate .NET object that is a wrapper around the functionality of GZipStream that you want to use. You can then expose your object to COM, and then VBA should make use of it.
Note that the assembly containing your COM object (and its type library too, I think, although I'm not positive on that) need to either be in the same directory as the main executable (winword.exe, or whatever) or in the GAC. This is due to the CLR's loading rules for assemblies.


q:
I'm creating a self updating app where I have the majority of the code in a seperate DLL. It's command line and will eventually be run on Mono. I'm just trying to get this code to work in C# on windows at the command line.

How can I create a c# application that I can delete a supporting dll while its running?

AppDomain domain = AppDomain.CreateDomain("MyDomain");
ObjectHandle instance = domain.CreateInstance( "VersionUpdater.Core", "VersionUpdater.Core.VersionInfo");
object unwrap = instance.Unwrap();
Console.WriteLine(((ICommand)unwrap).Run());
AppDomain.Unload(domain);
Console.ReadLine();

at the ReadLine the VersionUpdater.Core.dll is still locked from deletion

The ICommand interface is in VersionUpdater.Common.dll which is referenced by both the Commandline app and VersionUpdater.Core.dll

[A]
The only way I've ever managed something similar is to have the DLL in a separate AppDomain to the assembly that is trying to delete it. I unload the other AppDomain and then delete the DLL from disk.
If you're looking for a way to perform the update, off the top of my head I would go for a stub exe that spawns the real AppDomain. Then, when that stub exe detects an update is to be applied, it quits the other AppDomain and then does the update magic.
EDIT: The updater cannot share DLLs with the thing it is updating, otherwise it will lock those DLLs and therefore prevent them from being deleted. I suspect this is why you still get an exception. The updater has to be standalone and not reliant on anything that the other AppDomain uses, and vice versa.


q:
What I want to do is set the focus to a specific control (specifically a TextBox) on a tab page when that tab page is selected.

I've tried to call Focus during the Selected event of the containing tab control, but that isn't working. After that I tried to call focus during the VisibleChanged event of the control itself (with a check so that I'm not focusing on an invisible control), but that isn't working either.

Searching this site, I've come across this question but that isn't working either. Although after that, I did notice that calling the Focus of the control does make it the ActiveControl.

[A]
I did this and it seems to work:
Handle the
```
SelectedIndexChanged
```
for the
```
tabControl
```
.
Check if
```
tabControl1.SelectedIndex
```
== the one I want and
call
```
textBox.Focus();
```
I'm using VS 2008, BTW.
Something like this worked:
```
```
private void tabControl1_selectedIndexChanged(object sender, EventArgs e)
{
   if (tabControl1.SelectedIndex == 1)
   {
      textBox1.Focus();
   }
}
```
```


q:
I need to export a SL DataGrid to HTML so my users can then print it. Can someone put me in the right direction?

Upate: After reading Rob's answer I am changing my question. Instead of Silverlight Grid to HTML, I now just want to export it to PDF. Has anyone used any 3rd party PDF generators with Silverlight?


q:
Is there a list somewhere on common Attributes which are used in objects like Serializable?

Thanks

Edit ~ The reason I asked is that I came across an StoredProcedure attribute in ntiers ORMS.

[A]
Yes, look msdn has you covered please look
here
.
EDIT: This link only answer sucked. Here is a working extractor for all loadable types (gac) that have Attribute in the name.
```
```
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var process = new Process();
            //your path may vary
            process.StartInfo.FileName = @"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\gacutil.exe";
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.Arguments = "/l";
            process.Start();

            var consoleOutput = process.StandardOutput;

            var assemblyList = new List<string>();
            var startAdding = false;
            while (consoleOutput.EndOfStream == false)
            {
                var line = consoleOutput.ReadLine();
                if (line.IndexOf("The Global Assembly Cache contains the following assemblies", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    startAdding = true;
                    continue;
                }

                if (startAdding == false)
                {
                    continue;
                }

                //add any other filter conditions (framework version, etc)
                if (line.IndexOf("System.", StringComparison.OrdinalIgnoreCase) < 0)
                {
                    continue;
                }

                assemblyList.Add(line.Trim());
            }

            var collectedRecords = new List<string>();
            var failedToLoad = new List<string>();

            Console.WriteLine($"Found {assemblyList.Count} assemblies");
            var currentItem = 1;

            foreach (var gacAssemblyInfo in assemblyList)
            {
                Console.SetCursorPosition(0, 2);
                Console.WriteLine($"On {currentItem} of {assemblyList.Count} ");
                Console.SetCursorPosition(0, 3);
                Console.WriteLine($"Loading {gacAssemblyInfo}");
                currentItem++;

                try
                {
                    var asm = Assembly.Load(gacAssemblyInfo);

                    foreach (Type t in asm.GetTypes())
                    {
                        if (t.Name.EndsWith("Attribute", StringComparison.OrdinalIgnoreCase))
                        {
                            collectedRecords.Add($"{t.FullName} - {t.Assembly.FullName}");
                        }
                    }

                }
                catch (Exception ex)
                {
                    failedToLoad.Add($"FAILED to load {gacAssemblyInfo} - {ex}");
                    Console.SetCursorPosition(1, 9);
                    Console.WriteLine($"Failure to load count: {failedToLoad.Count}");
                    Console.SetCursorPosition(4, 10);
                    Console.WriteLine($"Last Fail: {gacAssemblyInfo}");
                }
            }

            var fileBase = System.IO.Path.GetRandomFileName();
            var goodFile = $"{fileBase}_good.txt";
            var failFile = $"{fileBase}_failedToLoad.txt";
            System.IO.File.WriteAllLines(goodFile, collectedRecords);
            System.IO.File.WriteAllLines(failFile, failedToLoad);
            Console.SetCursorPosition(0, 15);
            Console.WriteLine($"Matching types: {goodFile}");
            Console.WriteLine($"Failures: {failFile}");
            Console.WriteLine("Press ENTER to exit");
            Console.ReadLine();
        }
    }
}
```
```


q: F# is derived from OCaml, but what major items are missing or added? Specifically I'm curious as to whether the resources available for learning OCaml are also useful to someone who wants to learn F#.

[A]
F# supports OCaml syntax directly.  It might not be 100% compatible, but I think it's pretty close.
http://plus.kaist.ac.kr/~shoh/fsharp/html/index.html
Here is a list of differences (not sure how up-to-date it is)
http://plus.kaist.ac.kr/~shoh/fsharp/html/fsharp-vs-ocaml.html


q:
I've seen a lot of questions around that use improperly the expression "C/C++".
The reasons in my opinion are:

Newbie C and C++ programmers probably don't understand the difference between the two languages.

People don't really care about it since they want a generic, quick and "dirty" answer

While C/C++ could sometimes be interpreted as "either C or C++", I think it's a big error. C and C++ offer different approaches to programming, and even if C code can be easily implemented into C++ programs I think that referring to two separate languages with that single expression ( C/C++ ) is wrong.

It's true that some questions can be considered either as C or C++ ones, anyway.
What do you think about it?

[A]
C/C++ is a holdout from the early days of C++, where they were much more similar than they were today. It's something that wasn't really wrong at first, but is getting more-so all the time.
The basic structure is similar enough that most simple questions do still work between the two, though. There is an entire Wikipedia article on this topic:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
The biggest fallacy that comes from this is that because someone is well-versed in C, they will be equally good at C++.


q: Is there a way to get rid of the selection rectangle when clicking a link which does not refresh the current page entirely?

[A]
Try adding this:
```
```
onclick="this.blur()"
```
```
Discussed here as well
(CSS?) Eliminating browser's 'selected' lines around a hyperlinked image?


q:
If I have $var defined in Page1.php and in Page2.php I have

//Page2.php
include('Page1.php');

echo $var;

For what reasons will it not print the value of $var to the screen?  The files are in the same directory so paths shouldn't be the issue.   I've checked the php.ini file and nothing really jumps out at me.  Any ideas?

[A]
Possible causes:
The current working path isn't always the same as the file's. For example, if Page2.php is being included at a higher level, that higher level will be the path. Either make sure you've loaded Page2.php directly or move Page1.php accordingly.
Make sure
```
$var
```
is really what you expect it to be. Echo it in Page1.php to confirm. (this also checks the right file is being included)
If the source isn't really this simple, make sure you're not undefining/clearing
```
$var
```
anywhere.


q: I am sure to become a scrum master could really add value to the process I am following, however I believe that the background of the area of the application I am working on help more to get better planning and scheduling done for the project

[A]
Becoming a CSM doesn't really qualify you for running a Scrum project either.  Practice is the only preparation you can ever hope for.
The CSM class/cert
is
valuable still, though.  At the very least, if you don't have a mentor/coach to lean on, you should read..
Agile Project Management with Scrum (Schwaber)
Agile Estimation and Planning (Cohn)
User Stories Applied (Cohn)
and take the CSM course.  You'll be moderately prepared to run a Scrum project.
The biggest thing you can take away from this is:  you'll make mistakes if you're new to this.  If you can learn some pitfalls and see what to avoid, then you can avoid the cost of making/learning from these mistakes.


q: Like the title says, If I place an app_offline.htm in the application root, will it cut off currently running requests, or just new ones?

[A]
From ScottGu's blog:
Basically, if you place a file with
  this name in the root of a web
  application directory,
ASP.NET 2.0
  will shut-down the application, unload
  the application domain from the
  server, and stop processing any new
  incoming requests for that
  application
.  ASP.NET will also then
  respond to all requests for dynamic
  pages in the application by sending
  back the content of the
  app_offline.htm file (for example: you
  might want to have a “site under
  construction” or “down for
  maintenance” message).
App_Offline.htm - ScottGu's Blog
So, it seems like it will continue processing current request, but stop new incoming requests.


q:
If yes, on which operating system, shell or whatever?

Consider the following java program (I'm using java just as an example, any language would be good for this question, which is more about operation systems):

public class ExitCode {
    public static void main(String args[]) {
        System.exit(Integer.parseInt(args[0]));
    }
}

Running it on Linux and bash, it returns always values less equal 255, e.g. (echo $? prints the exit code of the previous executed command)

> java ExitCode 2; echo $?
2

> java ExitCode 128; echo $?
128

> java ExitCode 255; echo $?
255

> java ExitCode 256; echo $?
0

> java ExitCode 65536; echo $?
0

EDITED: the (only, so far) answer below fully  explain what happens on UNIXes. I'm still wondering about other OSes.

[A]
Using
```
wait()
```
or
```
waitpid()
```
It is not possible on Unix and derivatives using POSIX functions like
```
wait()
```
and
```
waitpid()
```
.  The exit status information returned consists of two 8-bit fields, one containing the exit status, and the other containing information about the cause of death (0 implying orderly exit under program control, other values indicating that a signal killed it, and indicating whether a core was dumped).
Using
```
sigaction()
```
with
```
SA_SIGINFO
```
If you work hard, and read the POSIX specification of
```
sigaction()
```
and
```
<signal.h>
```
and
Signal Actions
, you will find that you can get hold of the 32-bit value passed to
```
exit()
```
by a child process.   However, it is not completely straight-forward.
```
```
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

static siginfo_t sig_info = { 0 };
static volatile sig_atomic_t sig_num = 0;
static void *sig_ctxt = 0;

static void catcher(int signum, siginfo_t *info, void *vp)
{
    sig_num = signum;
    sig_info = *info;
    sig_ctxt = vp;
}

static void set_handler(int signum)
{
    struct sigaction sa;
    sa.sa_flags = SA_SIGINFO;
    sa.sa_sigaction = catcher;
    sigemptyset(&sa.sa_mask);

    if (sigaction(signum, &sa, 0) != 0)
    {
        int errnum = errno;
        fprintf(stderr, "Failed to set signal handler (%d: %s)\n", errnum, strerror(errnum));
        exit(1);
    }
}

static void prt_interrupt(FILE *fp)
{
    if (sig_num != 0)
    {
        fprintf(fp, "Signal %d from PID %d (status 0x%.8X; UID %d)\n",
                sig_info.si_signo, (int)sig_info.si_pid, sig_info.si_status,
                (int)sig_info.si_uid);
        sig_num = 0;
    }
}

static void five_kids(void)
{
    const int base = 0xCC00FF40;
    for (int i = 0; i < 5; i++)
    {
        pid_t pid = fork();
        if (pid < 0)
            break;
        else if (pid == 0)
        {
            printf("PID %d - exiting with status %d (0x%.8X)\n",
                   (int)getpid(), base + i, base + i);
            exit(base + i);
        }
        else
        {
            int status = 0;
            pid_t corpse = wait(&status);
            if (corpse != -1)
                printf("Child: %d; Corpse: %d; Status = 0x%.4X - waited\n", pid, corpse, (status & 0xFFFF));
            struct timespec nap = { .tv_sec = 0, .tv_nsec = 1000000 }; // 1 millisecond
            nanosleep(&nap, 0);
            prt_interrupt(stdout);
            fflush(0);
        }
    }
}

int main(void)
{
    set_handler(SIGCHLD);
    five_kids();
}
```
```
When run (program
```
sigexit73
```
compiled from
```
sigexit73.c
```
), this produces output like:
```
```
$ sigexit73
PID 26599 - exiting with status -872349888 (0xCC00FF40)
Signal 20 from PID 26599 (status 0xCC00FF40; UID 501)
Child: 26600; Corpse: 26599; Status = 0x4000 - waited
PID 26600 - exiting with status -872349887 (0xCC00FF41)
Signal 20 from PID 26600 (status 0xCC00FF41; UID 501)
Child: 26601; Corpse: 26600; Status = 0x4100 - waited
PID 26601 - exiting with status -872349886 (0xCC00FF42)
Signal 20 from PID 26601 (status 0xCC00FF42; UID 501)
Child: 26602; Corpse: 26601; Status = 0x4200 - waited
PID 26602 - exiting with status -872349885 (0xCC00FF43)
Signal 20 from PID 26602 (status 0xCC00FF43; UID 501)
Child: 26603; Corpse: 26602; Status = 0x4300 - waited
PID 26603 - exiting with status -872349884 (0xCC00FF44)
Signal 20 from PID 26603 (status 0xCC00FF44; UID 501)
$
```
```
With the one millisecond call to
```
nanosleep()
```
removed, the output is apt to look like:
```
```
$ sigexit73
sigexit23
PID 26621 - exiting with status -872349888 (0xCC00FF40)
Signal 20 from PID 26621 (status 0xCC00FF40; UID 501)
Child: 26622; Corpse: 26621; Status = 0x4000 - waited
PID 26622 - exiting with status -872349887 (0xCC00FF41)
PID 26623 - exiting with status -872349886 (0xCC00FF42)
Signal 20 from PID 26622 (status 0xCC00FF41; UID 501)
Child: 26624; Corpse: 26623; Status = 0x4200 - waited
Signal 20 from PID 26623 (status 0xCC00FF42; UID 501)
Child: 26625; Corpse: 26622; Status = 0x4100 - waited
PID 26624 - exiting with status -872349885 (0xCC00FF43)
PID 26625 - exiting with status -872349884 (0xCC00FF44)
$
```
```
Note that there are only three lines starting
```
Signal
```
here, and also only three lines ending
```
waited
```
; some of the signals and exit statuses are lost.  This is likely to be because of timing issues between the
```
SIGCHLD
```
signals being set to the parent process.
However, the key point is that 4 bytes of data can be transmitted in the
```
exit()
```
status when the code uses
```
sigaction()
```
,
```
SIGCHLD
```
,
```
SA_SIGINFO
```
to track the status.
Just for the record, the testing was performed on a MacBook Pro running macOS Mojave 10.14.6, using GCC 9.2.0 and XCode 11.3.1.  The code is also available in my
SOQ
(Stack Overflow Questions) repository on GitHub as file
```
sigexit73.c
```
in the
src/so-1843-7779
sub-directory.


q:
I'm primarily interested in pgsql for this, but I was wondering if there is a way in any RDBMS to do an insert operation, without disabling and re-enabling any FOREIGN KEY or NOT NULL constraints, on two tables that refer to each other.  (You might think of this as a chicken that was somehow born from its own egg.)

For a practical example, if you had a multiple-choice quiz system, with tables "question" and "answer", where question.correct_answer refers to answer.id, and answer.question refers to question.id, is it possible to add a question and its answers simultaneously?

(For the record, I'm aware that you can do the disabling and re-enabling in a transaction block, and that another solution is to not have a correct_answer column but instead have answer.correct as a boolean and have a check constraint making sure there's exactly one correct answer per question.  But I'm not curious about alternative solutions here.)

[A]
I think that you answered your own question - you have to make a transaction block. In PostgreSQL this should work:
```
```
BEGIN;
  SET CONSTRAINTS ALL DEFERRED;
INSERT INTO questions (questionid, answerid, question)
  VALUES (1, 100, 'How long are Abraham Lincoln\'s legs?');
INSERT INTO answers (answerid, questionid, answer)
  VALUES (100, 1, 'Long enough to reach the ground.');
COMMIT;
```
```
It has to be in a transaction block because if either INSERT statement failed the database would be in an invalid state (table constraints not met).


q:
Does anyone know a way to convert from VB6 code to C#?

Is there a tool that can do this for me?

Is there any migration process that I can follow to do this?

[A] VisualStudio offers (or at least offered) a wizard to do a conversion from VB6 to VB.NET (which could then be converted to C# with a bit of work, possibly helped by #develop's VB.NET <-> C# converter), but when last I used it, for anything non-trivial there was a lot of manual work needing to be done so I suspect you're probably better rewriting or porting by hand if this is a large and/or important application.


q:
Why is it that there are two kinds of references in xaml.

One looks like this:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

But mine look like this:

xmlns:WPFToolKit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"

Why can't I do this:

xmlns:local="http://myschema.mydomain.com/MyControlNamespace

Thanks to ixlettervariables for the answer. Here's a detailed explanation here

[A]
The second instance is basically an unmapped, but explicit reference to a namespace in an assembly. The first instance is a mapped reference to a namespace in some assembly referenced by your project.
XAML Namespaces and Namespace Mapping
, over at MSDN explains this in more detail:
WPF defines a CLR attribute that is consumed by XAML processors in order to map multiple CLR namespaces to a single XML namespace. This attribute,
XmlnsDefinitionAttribute
, is placed at the assembly level in the source code that produces the assembly. The WPF assembly source code uses this attribute to map the various common namespaces, such as System.Windows and System.Windows.Controls, to the
http://schemas.microsoft.com/winfx/2006/xaml/presentation
namespace.
Therefore, by adding the following to your assembly you could do just that:
```
```
[assembly:XmlnsDefinition("http://myschema.mydomain.com/MyControlNamespace", "My.Control.Namespace")]
```
```


q: I've used XNA and Visual Studio 2005 integrated with Flash.  I'm curious to see what environments other people use and prefer.

[A]
Same. XNA 2.0 in VS2005 or XNA 3.0 in VS2008.
I've also dabbled in darkGDK when I feel like some C++.


q:
In SQL Server 2017, you can use this syntax, but not in earlier versions:

SELECT Name = TRIM(Name) FROM dbo.Customer;

[A]
```
```
SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer
```
```


q:
I want to take the value stored in a 32 bit unsigned int, put it into four chars and then store the integer value of each of these chars in a string.

I think the first part goes like this:

char a = orig << 8;
char b = orig << 8;
char c = orig << 8;
char d = orig << 8;

[A]
Not quite:
```
```
char a = orig & 0xff;
orig >>= 8;
char b = orig & 0xff;
orig >>= 8;
char c = orig & 0xff;
orig >>= 8;
char d = orig & 0xff;
```
```
Not exactly sure what you mean by "store the integer values of each of these values into a string.  Do you want turn
```
0x10111213
```
into
```
"16 17 18 19"
```
, or what?


q:
I have an array NSMutableArray with happy objects. These objects viciously turn on (leak) me whenever I try to clear the array of all the objects and repopulate it.

It's allocated in the init function like so

self.list = [NSMutableArray array];

The different methods I have used to clear it out include:

self.list = nil;
self.list = [NSMutableArray array];

and

[self.eventList removeAllObjects];

Explicitly allocating and releasing the array doesn't work either. The leak ONLY occurs when I try to reset the list.

Am I missing a step when resetting or is this a different problem?

[A]
what does your
```
@property
```
declaration look like? are you synthesizing the accessors? If so, you need
```
@property(retain)
```
. I'm assuming that when you say the objects are turning on you, you're referring to a core dump
```
(EXC\_BAD\_ACCESS)
```
.


q: What is the best way to get a file (in this case, a .PDF, but any file will do) from a WebResponse and put it into a MemoryStream?  Using .GetResponseStream() from WebResponse gets a Stream object, but if you want to convert that Stream to a specific type of stream, what do you do?

[A]
Copied this from the web a year or so ago.
```
```
//---------- Start HttpResponse
if(objHttpWebResponse.StatusCode == HttpStatusCode.OK)
    {
        //Get response stream
        objResponseStream = objHttpWebResponse.GetResponseStream();

        //Load response stream into XMLReader
        objXMLReader = new XmlTextReader(objResponseStream);

        //Declare XMLDocument
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(objXMLReader);

        //Set XMLResponse object returned from XMLReader
        XMLResponse = xmldoc;

        //Close XMLReader
        objXMLReader.Close();
    }

    //Close HttpWebResponse
    objHttpWebResponse.Close();
}
```
```


q:
There are some updates with .NET 3.0 concerning how to create and use add-ins for your own applications. I read about some "pipeline" you have to create for the communication between add-in and host-application but couldn't find further information about it.

How would you made an add-in functionality in an application with .NET 3.0/3.5?

Additional information if necessary: The host application is made with WPF and some general functionality. Each add-in should add a own register-tab to a given container with their own content (buttons, textfields, ...) and methods to extend the host-application.

[A]
In addition to
Daniels
codeplex link, Jason He also has a nice wee series on using the System.AddIn namespace when developing Paint.NET starting here -
http://blogs.msdn.com/zifengh/archive/2007/01/04/addin-model-in-paint-net-1-introduction.aspx