q:
I have a table that holds only two columns - a ListID and PersonID.  When a person is merged with another in the system, I was to update all references from the "source" person to be references to the "destination" person.

Ideally, I would like to call something simple like

UPDATE MailingListSubscription
SET PersonID = @DestPerson
WHERE PersonID = @SourcePerson

However, if the destination person already exists in this table with the same ListID as the source person, a duplicate entry will be made.  How can I perform this action without creating duplicated entries? (ListID, PersonID is the primary key)

EDIT: Multiple ListIDs are used.  If SourcePerson is assigned to ListIDs 1, 2, and 3, and DestinationPerson is assigned to ListIDs 3 and 4, then the end result needs to have four rows - DestinationPerson assigned to ListID 1, 2, 3, and 4.

[A]
```
```
--out with the bad
DELETE
FROM MailingListSubscription
WHERE PersonId = @SourcePerson
  and ListID in (SELECT ListID FROM MailingListSubscription WHERE PersonID = @DestPerson)

--update the rest (good)
UPDATE MailingListSubscription
SET PersonId = @DestPerson
WHERE PersonId = @SourcePerson
```
```


q:
I have a project at work the requires me to be able to enter information into a web page, read the next page I get redirected to and then take further action.  A simplified real-world example would be something like going to google.com, entering "Coding tricks" as search criteria, and reading the resulting page.

Small coding examples like the ones linked to at http://www.csharp-station.com/HowTo/HttpWebFetch.aspx tell how to read a web page, but not how to interact with it by submitting information into a form and continuing on to the next page.

For the record, I'm not building a malicious and/or spam related product.

So how do I go read web pages that require a few steps of normal browsing to reach first?

[A]
What you need to do is keep retrieving and analyzing the html source for each page in the chain.  For each page, you need to figure out what the form submission will look like and send a request that will match that to get the next page in the chain.
What I do is build a custom class the wraps System.Net.HttpWebRequest/HttpWebResponse, so retrieving pages is as simple as using System.Net.WebClient.  However, my custom class also keeps the same cookie container across requests and makes it a little easier to send post data, customize the user agent, etc.

s: huggingface

c: devops

d: intermediate


q:
I'm programming in C for RAM limited embedded microcontroller with RTOS.

I regularly break my code to short functions, but every function calling require to more stack memory.
Every task needs his stack, and this is one of the significant memory consumers in the project.

Is there an alternative to keep the code well organized and readable, still preserve the memory?

[A]
Turn on optimization, specifically aggressive inlining.  The compiler should be able to inline methods to minimize calls.  Depending on the compiler and the optimization switches you use, marking some methods as
```
inline
```
may help (or it may be ignored).
With GCC, try adding the "-finline-functions" (or -O3) flag and possibly the " -finline-limit=n" flag.


q:
I frequently come across Windows programs that bundle in MSVCRT (or their more current equivalents) with the program executables.  On a typical PC, I would find many copies of the same .DLL's.   My understanding is that MSVCRT is the C runtime library, somewhat analogous to glibc/libc.so under *nix.

Why do Windows programs have to bring along their C libraries with them, instead of just sharing the system-wide libc?

Update: thanks to Shog9, I started to read about SxS, which has further opened up my eyes to the DLL linkage issues (DLL Hell) - Link is one useful intro to the issue...

[A]
Programs are linked against a specific version of the runtime, and that required version is
not
guaranteed to exist on the target machine.  Also, matching up versions used to be problematic.
In the Windows world, it's very bad manners to expect your users to go out and find and install a separate library to use your application.  You make sure any dependencies not part of the host system are included with your app.
In the linux world this isn't always as simple, since there's a much larger variation for how the host system might look.


q:
In C# I could easily write the following:

string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;

Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?

[A]
In Python 2.5, there is
```
```
A if C else B
```
```
which behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case:
```
```
stringValue = otherString or defaultString
```
```


q:
When running a CherryPy app it will send server name tag something like CherryPy/version.
Is it possible to rename/overwrite that from the app without modifying CherryPy so it will show something else?

Maybe something like MyAppName/version (CherryPy/version)

[A]
This string appears to be being set in the CherrPy
Response
class:
```
```
def __init__(self):
  self.status = None
  self.header_list = None
  self._body = []
  self.time = time.time()

  self.headers = http.HeaderMap()
  # Since we know all our keys are titled strings, we can
  # bypass HeaderMap.update and get a big speed boost.
  dict.update(self.headers, {
    "Content-Type": 'text/html',
    "Server": "CherryPy/" + cherrypy.__version__,
    "Date": http.HTTPDate(self.time),
  })
```
```
So when you're creating your Response object, you can update the "Server" header to display your desired string. From the CherrPy
Response Object documentation
:
headers
A dictionary containing the headers of the response. You may set values in
  this dict anytime before the finalize phase, after which CherryPy switches
  to using header_list ...
EDIT
: To avoid needing to make this change with every response object you create, one simple way to get around this is to wrap the Response object. For example, you can create your own Response object that inherits from CherryPy's Response and updates the headers key after initializing:
```
```
class MyResponse(Response):

    def __init__(self):
        Response.__init__(self)
        dict.update(self.headers, {
            "Server": "MyServer/1.0",
        })

RespObject = MyResponse()
print RespObject.headers["Server"]
```
```
Then you can can call your object for uses where you need to create a Response object, and it will always have the Server header set to your desired string.


q:
Does anybody know if there is a built-in function in Mathematica for getting the lhs of downvalue rules (without any holding)?  I know how to write the code to do it, but it seems basic enough for a built-in

For example:

a[1]=2;
a[2]=3;

BuiltInIDoNotKnowOf[a] returns {1,2}

[A]
This seems to work; not sure how useful it is, though:
```
```
a[1] = 2
a[2] = 3
a[3] = 5
a[6] = 8
Part[DownValues[a], All, 1, 1, 1]
```
```


q:
Within an n-tier app that makes use of a WCF service to interact with the database, what is the best practice way of making use of LinqToSql classes throughout the app?

I've seen it done a couple of different ways but they seemed like they burned a lot of hours creating extra interfaces, message classes, and the like which reduces the benefit you get from not having to write your data access code.

Is there a good way to do it currently?  Are we stuck waiting for the Entity Framework?


q: When should you NOT use a singleton class although it might be very tempting to do so? It would be very nice if we had a list of most common instances of 'singletonitis' that we should take care to avoid.

[A]
I know many have answered with "when you have more than one", etc.
Since the original poster wanted a list of cases when you shouldn't use Singletons (rather than the top reason), I'll chime in with:
Whenever you're using it because you're not allowed to use a global!
The number of times I've had a junior engineer who has used a Singleton because they knew that I didn't accept globals in code-reviews.  They often seem shocked when I point out that all they did was replace a global with a Singleton pattern and they still just have a global!


q: We have a painfully slow report.I added a Response.flush and it seems a great deal better. What are some of the caveats of using this method.

[A]
If Response.Buffer is not set to true, then you'll get a run-time error.  Also, If the Flush method is called on an ASP page, the server does not honor Keep-Alive requests for that page.
You'll also want to look out if you're using a table-based design as it won't render in some browsers until the entire table is sent.. meaning if you have 10,000 rows, the user would still need to wait for all 10,000 rows to transfer before they'd actually see them.


q:
I've always struggled with how to best include classes into my php code. Pathing is usually an issue but a few minutes ago i found this question which dramatically helps that. Now I'm reading about __autoload and thinking that it could make the process of developing my applications much easier. The problem is i like to maintain folder structure to separate areas of functionality as opposed to throwing everything into a general /lib folder. So if i override autoload to do a deep search of a class folder including all subfolders, what performance hits can i expect?

Obviously this will depend on scale, depth of the folder structure and number of classes but generally I'm asking on a medium scale project will it cause problems.

[A]
__autoload is great, but the cost of stating all the files in a recursive search function is expensive. You might want to look at building a tree of files to use for autoloading.  In my framework, I consistently name files for their classes and use a map that is cached for the data.
Check out
http://trac.framewerk.org/cgi-bin/trac.fcgi/browser/trunk/index.php
[
dead link
] starting at line 68 for an idea of how this can be done.
Edit: And to more directly answer your question, without caching,  you can expect a performance hit on a site with medium to heavy traffic.


q:
There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });

In this case, GetMethod() will not return private methods. What BindingFlags do I need to supply to GetMethod() so that it can locate private methods?

[A]
I think you can pass it
```
BindingFlags.NonPublic
```
where
it
is the
```
GetMethod
```
method.


q:
How do I check if an object has a specific property in JavaScript?

Consider:

x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
    //Do this
}

Is that the best way to do it?

[A]
Yes it is :)  I think you can also do
```
Object.prototype.hasOwnProperty.call(x, 'key')
```
which should also work if
```
x
```
has a property called
```
hasOwnProperty
```
:)
But that tests for own properties.  If you want to check if it has an property that may also be inhered you can use
```
typeof x.foo != 'undefined'
```
.


q:
I want to create a list of methods to execute.  Each method has the same signature.
I thought about putting delegates in a generic collection, but I keep getting this error:

'method' is a 'variable' but is used like a 'method'

In theory, here is what I would like to do:

List<object> methodsToExecute;

int Add(int x, int y)
{ return x+y; }

int Subtract(int x, int y)
{ return x-y; }

delegate int BinaryOp(int x, int y);

methodsToExecute.add(new BinaryOp(add));
methodsToExecute.add(new BinaryOp(subtract));

foreach(object method in methodsToExecute)
{
    method(1,2);
}

Any ideas on how to accomplish this?
Thanks!

[A]
Have them all implement of common interface, say IExecuteable, and then have a List<IExecutable>
Also, using delegates:
```
```
class Example
{
    public delegate int AddDelegate(int x, int y);

    public List<AddDelegate> methods = new List<AddDelegate>();

    int Execute()
    {
        int sum = 0;
        foreach(AddDelegate method in methods)
        {
            sum+=method.Invoke(1, 2);
        }
        return sum;
    }
}
```
```


q:
Suppose I have the following code:

while(TRUE) {
  pthread_t *thread = (pthread_t *) malloc(sizeof(pthread_t));
  pthread_create(thread, NULL, someFunction, someArgument);
  pthread_detach(*thread);
  sleep(10);
}

Will the detached thread free the memory allocated by malloc, or is that something I now have to do?

[A]
No.
pthread_create()
has no way of knowing that the
thread
pointer passed to it was dynamically allocated. pthreads doesn't use this value internally; it simply returns the new thread id to the caller. You don't need to dynamically allocate that value; you can pass the address of a local variable instead:
```
```
pthread_t thread;
pthread_create(&thread, NULL, someFunction, someArgument);
```
```


q:
I've created a custom list & also added a column in the Announcement List.  Question is, how can I include those newly created items when I create a fresh Web Application (like a script, feature or something)?

Additional Info: It's like when you're to deploy from your development machine to a staging or production server.  I'd like to have a script or something to update my production server to have the new column i've added to the Announcement List.  Just like SQL Server's ALTER TABLE command to update a SQL Server Table.

Is there an equivalent in Sharepoint Lists?

TIA!

[A]
Your question is not very clear but I think you may want to look at Application Templates.
Microsoft provide 40 pre-built templates in the link below and the same technology is available to you. Links from this page should lead you to information showing you how you can crate your own.
Application Templates for Windows SharePoint Services 3.0
http://technet.microsoft.com/en-us/windowsserver/sharepoint/bb407286.aspx


q: In WPF, we are creating custom controls that inherit from button with completely drawn-from-scratch xaml graphics.  We have a border around the entire button xaml and we'd like to use that as the location for updating the background when MouseOver=True in a trigger.  What we need to know is how do we update the background of the border in this button with a gradient when the mouse hovers over it?

[A]
In your
```
ControlTemplate
```
, give the
```
Border
```
a
```
Name
```
and you can then reference that part of its visual tree in the triggers. Here's a very brief example of restyling a normal
```
Button
```
:
```
```
<Style
    TargetType="{x:Type Button}">
    <Setter
        Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Name="customBorder"
                    CornerRadius="5"
                    BorderThickness="1"
                    BorderBrush="Black"
                    Background="{StaticResource normalButtonBG}">
                    <ContentPresenter
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center" />
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger
                        Property="IsMouseOver"
                        Value="True">
                        <Setter
                            TargetName="customBorder"
                            Property="Background"
                            Value="{StaticResource hoverButtonBG}" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
```
```
If that doesn't help, we'll need to know more, probably seeing your own XAML. Your description doesn't make it very clear to me what your actual visual tree is.


q:
I have an index on columns A, B, C, D of table T

I have a query that pulls from T with A, B, C in the WHERE clause.

Will the index be used or will a separate index be needed that only includes A, B, C?

[A]
in Oracle databases this is called a
Composite Index
( 12g docs but valid for earlier versions)
Composite indexes can speed retrieval of data for SELECT statements in which the WHERE clause references all of the leading portion of the columns in the composite index. Therefore, the order of the columns used in the definition is important. In general, the most commonly accessed columns go first.
so in your case, Yes. the index would/could be used.  this could be verified by using an explain plan.
if MS SQLSERVER is different (and i suspect it might) you'll need a new answer.
Edit:
Should also mention it will only
consider
the index for use.. that does not necessarily mean it WILL use it.
Edit2:
Oracle 11g and later now has an option that will allow it to skip columns in an index. so a query on A,B and D might still use the index


q: The shop that I am working part time with is new to Microsoft CRM. I just want to survey what projects have developers done to the system to extend its capabilities.

[A] I did some work with CRM 3.0. My work enhanced the program and turned it into a Document Management app, where you could scan and upload documents based on a case, contact, customer, vendor etc. The .NET SDK back then could have used a bit more work, but I hear with newer versions of CRM it has gotten better. CRM allows for attachments but not at all levels, more at the case level.


q:
I need to validate this simple pick list:

<select name="<%= key %>">
    <option value="ETC" SELECTED>Select an option...</option>
    <option value="ONE">Lorem ipsum</option>
    <option value="TWO">dolor sit amet</option>
</select>

So the user would never submit the form with the, excuse the repetition, "Select an option..." option selected. In principle I'm allowed to use JavaScript but It'd be interesting to learn how to solve it within JSP too.

[A]
You can never really satisfy the condition 'never submit a given value' because you don't have control over the client side.  The user can always manipulate HTML to submit whatever they want.
It is a good approach is to use JavaScript to do client-side validation and give the user quick feedback and catch 99%+ of the cases, then do a server-side validation of the submitted parameters to catch the minority that don't have JS enabled or who manipulate the HTML to submit non-expected values.
Just remember that the client-side validation is optional, and is good for those 'common mistakes' input validation, but the server-side validation is mandatory for all input whether or not any client-side checks have been done on the given input.


q:
I'm a PHPer, and am not writing object-oriented code.

What are the advantages of OO over procedural code, and where can I learn how to apply these ideas to PHP?

[A]
Objects help keep your code isolated between different sections, so that if you need to make a change to one section you can be confident it won't affect other sections: loose coupling.
Then, when you've done that for a while, you'll start finding that objects you created for one app are also useful in others, and you start getting better code re-use as well.  So the new app has part of the work already done, and is using time-tested code:  software is built faster with fewer bugs.


q:
When I download my program from my website to my windows 2003 machine, it has a block on it and you have to right click on the exe, then properties, then select the button "Unblock".

I would like to add detection in my installer for when the file is blocked and hence doesn't have enough permissions.

But I can't eaisly reproduce getting my exe in this state where it needs to be unblocked.

How can I get the unblock to appear on my exe so I can test this functionality?

[A]
This is done using NTFS File Streams. There is a stream named "Zone.Identifier" added to downloaded files. When IE7 downloads certain types of file that stream contains:
```
```
[ZoneTransfer]
ZoneId=3
```
```
The simplest way to set it is to create a text file with those contents in it, and use more to add it to the alternate stream.
Zone.Identifier.txt:
```
```
[ZoneTransfer]
ZoneId=3
```
```
Command:
```
```
more Zone.Identifier.txt > file.exe:Zone.Identifier
```
```
Then, the way for you to check it would be to try to open the Zone.Identifier stream and look for ZoneId=3, or simply assume that if the stream exists at all that your user will receive that warning.
It's also important to note that this has nothing to do with permissions. Administrators see the same warning; it's to do entirely with the source and type of file. The entire stream goes away when users uncheck the "Always ask before opening this file" box and then click Run.


q: I have a website where clients pay for a service but have to out the money upfront via escrow, I'm very proficient with PHP (this is what the website is coded in) how would I go about implementing an escrow system that would work automatically?

[A]
You need to break down your design into components and think about the process.
Escrow works like this:
Entity A deposits money into Escrow Account for Entity B.
Entity A and Entity B come to an agreement
The Escrow account is deposited to Entity B.
Implementation wise, I'd track escrow deposits like any transaction, I'd also track escrow payments the same way.
You need to come up with a way to store "Work Orders" in a database. These would have two columns "AcceptedByA", and "AcceptedByB", as well as the amount of money.
The process would be:
Entity A opens a workorder and pays $X into the Escrow Account
Entity B does whatever the workorder requires (Setting AcceptedByB to true)
Entity A sets "AcceptedByA" to true.
A transaction runs to pay EntityB from the Escrow Account.
This is extremely high level, but its a rather simple idea.


q:
A bunch of CSS files were pulled in and now I'm trying to clean things up a bit.

How can I efficiently identify unused CSS definitions in a whole project?

[A]
Chrome Developer Tools
has an
Audits
tab which can show unused CSS selectors.
Run an audit, then, under
Web Page Performance
see
Remove unused CSS rules


q: Let's collect some tips for evaluating the appropriate use of global.asax.

[A]
I've used it before to catch errors at the application level, and to do something when a user's session expires.
I also tend to use it a lot to provide static properties that read values from the web.config.
I think it ok for stuff like that, though I wouldn't put much more than that in there.


q:
For example, how much memory is required to store a list of one million (32-bit) integers?

alist = range(1000000) # or list(range(1000000)) in Python 3.0

[A]
"It depends."  Python allocates space for lists in such a way as to achieve
amortized constant time
for appending elements to the list.
In practice, what this means with the current implementation is... the list always has space allocated for a power-of-two number of elements.  So range(1000000) will actually allocate a list big enough to hold 2^20 elements (~ 1.045 million).
This is only the space required to store the list structure itself (which is an array of pointers to the Python objects for each element).  A 32-bit system will require 4 bytes per element, a 64-bit system will use 8 bytes per element.
Furthermore, you need space to store the actual elements.  This varies widely.  For small integers (-5 to 256 currently), no additional space is needed, but for larger numbers Python allocates a new object for each integer, which takes 10-100 bytes and tends to fragment memory.
Bottom line:
it's complicated
and Python lists are
not
a good way to store large homogeneous data structures.  For that, use the
```
array
```
module or, if you need to do vectorized math, use NumPy.
PS- Tuples, unlike lists, are
not designed
to have elements progressively appended to them.  I don't know how the allocator works, but don't even think about using it for large data structures :-)


q:
What is the proper way to modify environment variables like PATH in OS X?

I've looked on Google a little bit and found three different files to edit:

/etc/paths

~/.profile

~/.tcshrc

I don't even have some of these files, and I'm pretty sure that .tcshrc is wrong, since OS X uses bash now. Where are these variables, especially PATH, defined?

I'm running OS X v10.5 (Leopard).

[A]
Up to and including
OS X v10.7
(Lion)
you can set them in:
```
```
~/.MacOSX/environment.plist
```
```
See:
https://developer.apple.com/legacy/library/qa/qa1067/_index.html
https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/EnvironmentVars.html
For PATH in the Terminal, you should be able to set in
```
.bash_profile
```
or
```
.profile
```
(you'll probably have to create it though)
For
OS X v10.8
(Mountain Lion) and beyond
you need to use
```
launchd
```
and
```
launchctl
```
.


q:
What are the different types of indexes, what are the benefits of each?

I heard of covering and clustered indexes, are there more? Where would you use them?

[A]
OdeToCode has a good article covering the basic differences
As it says in the article:
Proper indexes are crucial for good
  performance in large databases.
  Sometimes you can make up for a poorly
  written query with a good index, but
  it can be hard to make up for poor
  indexing with even the best queries.
Quite true, too... If you're just starting out with it, I'd focus on clustered and composite indexes, since they'll probably be what you use the most.


q:
It is typical to have something like this in your cshrc file for setting the path:

set path = ( . $otherpath $path )

but, the path gets duplicated when you source your cshrc file multiple times, how do you prevent the duplication?

EDIT: This is one unclean way of doing it:

set localpaths = ( . $otherpaths )
echo ${path} | egrep -i "$localpaths" >& /dev/null
if ($status != 0) then
    set path = ( . $otherpaths $path )
endif

[A]
I always set my path from scratch in .cshrc.
That is I start off with a basic path, something like:
```
```
set path = (. ~/bin /bin /usr/bin /usr/ucb /usr/bin/X11)
```
```
(depending on the system).
And then do:
```
```
set path = ($otherPath $path)
```
```
to add more stuff


q:
Why can't I create a class in VB.NET that inherits System.IO.Directory?  According to Lutz Roeder, it is not declared as NotInheritable!

I want to create a utility class that adds functionality to the Directory class.  For instance, I want to add a Directory.Move function.

Please advise and I will send you a six pack.  OK nevermind I'm not sending you anything but if you come to the bar tonight I will hook you up and then beat you in pool.

[A]
Are you using
C# 3.0
VB.NET 2008 -- then you could add an
Extension Method


q:
A lot of my C# code follows this pattern:

void foo(string param1, string param2, string param3)
{
    try
    {
         // do something...
    }
    catch(Exception ex)
    {
        LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message));
    }
}

Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string?
OR
Do you have a more generic / better way of doing this?

[A]
When I have done this I just created a generic dictionary for the logging.
I have this LogArgs class.  And logging in a base class that I call when I have an exception.
```
```
public class LogArgs
{

    public string MethodName { get; set; }
    public string ClassName { get; set; }
    public Dictionary<string, object> Paramters { get; set; }

    public LogArgs()
    {
        this.Paramters = new Dictionary<string, object>();
    }

}
```
```
Then at the start of every method I do
```
```
LogArgs args = new LogArgs { ClassName = "ClassName", MethodName = "MethodName" };
args.Paramters.Add("Param1", param1);
args.Paramters.Add("Param2", param2);
args.Paramters.Add("Param3", param3);

base.Logger.MethodStartLog(args);
```
```
When I have an error I log it this way.
```
```
base.Logger.LogError(args, ex);
```
```


q: I am using prototype and I can't find any built in extensions to set or retrieve cookies. After googling for a little bit, I see a few different ways to go about it. I was wondering what you think is the best approach for getting a cookie in JavaScript?

[A]
I use this. It has been dependable:
```
```
function getCookie(c_name) {
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    }
  }
return ""
```
```
}


q:
System.InvalidOperationException: DragDrop registration did not
  succeed. ---> System.Threading.ThreadStateException:

What does this exception mean?  I get it at this line trying to add a panel to a panel at runtime...

splitReport.Panel1.Controls.Add(ChartPanel);

Working in VS2008 C#

[A]
This exception means that the thread that owns the Panel (the Panel being added) has been initialized using the MTA threading model. The drag/drop system requires that the calling thread use the STA thread model (particularly it requires that COM be initialized via OleInitialize). Threading models are an unfortunate vestige of COM, a predecessor of the .NET platform.
If you have the
```
[STAThread]
```
attribute on your Main function, then the main program thread should already be STA. The most likely explanation, then, is that this exception is happening on a different thread. Look at the Threads window in Visual Studio (Debug | Windows | Threads) when the exception occurs and see if you are on a thread other than the main thread. If you are, the solution is probably as simple as setting the thread model for that new thread, which you can do as follows (add this code to the thread where the control is being created):
```
Thread.CurrentThread.SetApartmentState( ApartmentState.STA )
```
(
```
Thread
```
and
```
ApartmentState
```
are members of
```
System.Threading
```
)
That code will need to happen before you actually start the new thread. As noted by @Tomer, you can also specify this declaratively using the
```
[STAThread]
```
attribute.
If you find that the exception is happening on the main thread, post back and let us know, and maybe we can help more. A stack trace at the time of the exception may help track down the problem.


q: As just stated in a recent question and answer, you can't inherit from a static class.  How does one enforce the rules that go along with static classes inside VB.NET?  Since the framework is compatible between C# and VB it would make sense that there would be a way to mark a class static, but there doesn't seem to be a way.

[A]
Module == static class
If you just want a class that you can't inherit, use a
```
NotInheritable
```
class; but it won't be static/Shared. You could mark all the methods, properties, and members as
```
Shared
```
, but that's not strictly the same thing as a static class in C# since it's not enforced by the compiler.
If you really want the VB.Net equivalent to a C# static class, use a
```
Module
```
.  It can't be inherited and all members, properties, and methods are static/shared.


q:
Does anyone know of a web site where I can find a list of 32-bit MIPS instructions/opcodes, with the following features:

Clearly distinguishes between real opcodes and assembly-language macros (pseudo-instructions)

Describes the instruction behavior including differences depending on privilege level.

Indicates in which instruction set revision the instruction was introduced/revised (e.g. MIPS I, MIPS II, MIPS32, etc.)

Includes privileged instructions such as syscall.

I am aware of numerous web sites which document "part of" the instruction set, mostly for teaching purposes.  They tend to leave out or only partially describe floating-point and privileged instructions.

In case you're wondering, I'm looking at Verilog code for a MIPS processor subset, and trying to figure out exactly to what extent it complies with the instruction sets of any real MIPS processors!

[A]
I can only partially answer the question: I'd recommend
See MIPS Run
by Dominic Sweetman, if you're not already referring to it. I have the first edition of the book, the second edition is now current.
table 8.2 lists each opcode and expected behavior, differentiating assembler macros and  listing the instructions they decompose to. Unfortunately it does not differentiate user vs kernel mode.
table 8.6 lists the ISA level where each instruction was introduced, including obscure variants like the LSI MiniRISC
syscall is present in the table, though lacking much description
The first edition mentions the kernel. supervisor, and user privilege levels but does not discuss what operations are allowed in each. I do not know what changes were made in the second edition.


q:
I'd like to just put in a comment in the block of my if-statement, but I get an error when I try. I want to be more like Steve McConnell.

declare @ConstraintName varchar(255)
set @ConstraintName = 'PK_Whatever'

IF LEFT(@ConstraintName, 2) = 'PK'
BEGIN
    --can't drop primary keys
END

The error I get is:

Incorrect syntax near 'END'.

If I add something after the comment, i.e. PRINT @ConstraintName, it works fine.

[A]
I can't say for sure in SQL Server, but in Oracle PL/SQL you would put a NULL statement in a block that you want to do nothing:
```
```
BEGIN
  -- This is a comment
  NULL;
END
```
```


q: So a column will hold some text that beforehand I won't know how long the length of this string can be. Realistically 95% of the time, it will probably be between 100-500 chars, but there can be that one case where it will 10000 chars long. I have no control over the size of this string and never does the user. Besides varchar(max), what other strategy have you guys found useful? Also what are some cons of varchar(max)?

[A]
Varchar(max) in sqlserver 2005 is what I use.
SqlServer handles large string fields weirdly, in that if you specify "text" or a large varchar, but not max, it stores part of the bits in the record and the rest outside.
To my knowledge with varchar(max) it goes ahead and stores the entire contents out of the record, which makes it less efficient than a small text input. But its more efficient than a "text" field since it does not have to look up that information 2 times by getting part inline and the rest from a pointer.


q:
I need to show a camera capture dialog in a compact framework 3.7 application by pinvoking SHCameraCapture from the dll Aygshell.dll.  I cannont use the managed object CameraCaptureDialog because of limitations with the technology I'm working with.  Instead, I need to access it by Pinvoking it.

See http://msdn.microsoft.com/en-us/library/aa454995.aspx for documentation on the function.  The function takes in a struct that defines the parameters of the dialog.  e.g. where to save the file, what resolution to use.

I would imaging that I would have to define a copy of the struct in C# and decorate the sturct with the attribute StructLayout.  I also imagine that the code would involve [DllImport("aygshell.dll")].  Any sample code of how to call this would be much appreciated.

[A]
I've not been able to test this, but your struct/function should look something like this:
```
```
struct SHCAMERACAPTURE {
  public Int32 cbSize;
  public IntPtr hwndOwner;

  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
  public string szFile;

  [MarshalAs(UnmanagedType.LPStr)]
  string pszInitialDir;

  [MarshalAs(UnmanagedType.LPStr)]
  string pszDefaultFileName;

  [MarshalAs(UnmanagedType.LPStr)]
  string pszTitle;

  Int32 StillQuality;
  Int32 VideoTypes;
  Int32 nResolutionWidth;
  Int32 nResolutionHeight;
  Int32 nVideoTimeLimit;
  Int32 Mode;
}

[DllImport("aygshell.dll")]
static extern int SHCameraCapture(ref SHCAMERACAPTURE pshcc);
```
```
AFAIK, you don't need to explicitly set StructLayout on SHCAMERCAPTURE as there's nothing unusual about its layout.
Once you get this working, you might want to post your findings to pinvoke.net for others to make use of!


q:
Stored procs in SQL Server sometimes finish with a return code, as opposed to a recordset of data.  I've seen ASP code that's able to get this return code, but I can't figure out how to get this code with PHP's mssql driver.

mssql_get_last_message() always returns nothing, and I'm thinking it's because it only returns the very last line that came from the server. When we run the proc in another application (outside PHP), there is blank line following the return code.

Has anyone figured out how to get return codes from SQL stored procs using PHP's mssql driver?

[A]
Are you talking about SQL Server error codes, e.g. RAISERRROR or other failures? If so, last time I checked in PHP you need to ask for @@ERROR (e.g. select @@error) instead.
If it is a return code, you must explicitly catch it, e.g.
```
```
DECLARE @return_code INT
EXEC @return_code = your_stored_procedure 1123
SELECT @return_code
```
```


q:
I've looked around for a good example of this, but I haven't run into one yet.  I want to pass a custom string array from java to oracle and back, using the IBATIS framework.  Does anyone have a good link to an example?  I'm calling stored procs from IBATIS.

Thanks

[A]
You've got to start with a custom instance of
```
TypeHandler
```
.  We'd prefer to implement the simpler
```
TypeHandlerCallback
```
, but in this scenario we need access to the underlying
```
Connection
```
.
```
```
public class ArrayTypeHandler implements TypeHandler {

    public void setParameter(PreparedStatement ps, int i, Object param, String jdbcType)
            throws SQLException {
        if (param == null) {
            ps.setNull(i, Types.ARRAY);
        } else {
            Connection conn = ps.getConnection();
            Array loc = conn.createArrayOf("myArrayType", (Object[]) param);
            ps.setArray(i, loc);
        }
    }

    public Object getResult(CallableStatement statement, int i)
            throws SQLException {
        return statement.getArray(i).getArray();
    }
    ...
}
```
```
Then, to wire it up in the iBATIS config:
```
```
<?xml version="1.0"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="arrayTest">

    <parameterMap id="storedprocParams" class="map">
        <parameter property="result" mode="OUT" jdbcType="ARRAY" typeHandler="ArrayTypeHandler"/>
        <parameter property="argument" mode="IN" jdbcType="ARRAY" typeHandler="ArrayTypeHandler"/>
    </parameterMap>

    <procedure id="storedproc" parameterMap="arrayTest.storedprocParams">
        {? = call My_Array_Function( ? )}
    </procedure>

</sqlMap>
```
```
Hope this helps!


q:
It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.

Now, this sometimes leads to unnecessary repetitive code, for example:

try
{
    WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
    WebId = Guid.Empty;
}
catch (OverflowException)
{
    WebId = Guid.Empty;
}

I wonder: Is there a way to catch both exceptions and only call the WebId = Guid.Empty call once?

The given example is rather simple, as it's only a GUID. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the object. However, if there is an unexpected exception, I still want to throw that higher.

[A]
Note that I did find one way to do it, but this looks more like material for
The Daily WTF
:
```
```
catch (Exception ex)
{
    switch (ex.GetType().Name)
    {
        case "System.FormatException":
        case "System.OverflowException":
            WebId = Guid.Empty;
            break;
        default:
            throw;
    }
}
```
```


q:
I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook.

I found a page on microsoft.com that says there's a 'Remove line breaks' "feature" in Outlook so does this mean there's no solution to get around that other than un-checking that setting?

Thanks

[A]
Try
```
\r\c
```
instead of
```
\n
```
.
EDIT:
I think @Robert Wilkinson had it right.
```
\r\n
```
. Memory just isn't what it used to be.


q:
I am working on a web app that uses Perl and I need to look into speeding up portions of the app.

I thought I'd start profiling the particular calls for the portion I wish to investigate.  I've done some searching on profiling Perl code, but unfortunately most of what I find says that I should run my perl code with -d:DProf myapp from the command line.  That doesn't quite work for me since my code is within a web app.  I did find a way to get the profiling to work with apache, but unfortunately, the "most used" modules that came back from the profiler were all CPAN modules -- Class::xyz, etc etc etc.  Not terribly helpful.

Does anyone know of a good way besides me injecting "timer" code into the methods I wish to profile to target just these methods?  I've thought of writing a test script and profiling that but due to the nature of the code I'm working on that would require a bit more work than I'm hoping to have to do.

[A]
You can use the
Benchmark
core module with the
:hireswallclock
option if you really want to time things internally.   But really, you should be able to profile from the command line.  You might have to write test scripts to emulate certain portions of a CGI request, but DProf can be
extremely
useful when looking for performance bottlenecks.
In particular, look for where your code is calling the CPAN module code.  You may be doing this in loops far more than necessary, so while the time is spent in the CPAN module, refactoring your code can fix the problem.


q: What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?

[A]
A
staticmethod
is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.
A
classmethod
, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how
```
dict.fromkeys()
```
, a classmethod, returns an instance of the subclass when called on a subclass:
```
```
>>> class DictSubclass(dict):
...     def __repr__(self):
...         return "DictSubclass"
...
>>> dict.fromkeys("abc")
{'a': None, 'c': None, 'b': None}
>>> DictSubclass.fromkeys("abc")
DictSubclass
>>>
```
```


q:
Browsing to a dynamic web page built using Grails version 1.0.3 the console log shows the following errors for each page request:

[Fatal Error] :-1:-1: Premature end of file.

How do I stop this error from appearing for each request?

[A]
This bug was already fixed:
http://jira.codehaus.org/browse/GRAILS-3088
Premature end of file
Affects Version/s:  1.0.3
Fix Version/s:
1.0.4
...Just a few implementation notes. We were defaulting to a q value of 0, which is incorrect according to the spec. So we now default to 1.0 which gives the correct precedence order in Firefox 3, but incorrect in Firefox 2. However, more specific XML types like application/xhtml+xml now take precendence over less specific ones if they have the same q value so this fixes the issue in Firefox 2...


q: Why isn't Visual Studio 2005 generating a serialization setting when I set the project setting "Generate Serialization Assembly" to "On"?

[A]
It turns out that Dev Studio only honors this setting for Web Services.
For non-web services you can get this to work by adding an AfterBuild target to your project file:
```
```
<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)"  Outputs="$(OutputPath)$(_SGenDllName)">
      <SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)"  References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)">
          <Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
      </SGen>
  </Target>
```
```
See also:
SGen MSBuild Task
AfterBuild Event


q:
Examples:

"1"     yes
"-1"    yes
"- 3"   no
"1.2"   yes
"1.2.3" no
"7e4"   no  (though in some cases you may want to allow scientific notation)
".123"  yes
"123."  yes
"."     no
"-.5"   yes
"007"   yes
"00"    yes

[A]
This allows for optional "+" and "-" in front.  And allows trailing or initial whitespace.
```
```
/^\s*[+-]?(?:\d+\.?\d*|\d*\.\d+)\s*$/
```
```


q:
Not really getting the point of the map function. Can anyone explain with examples its use?

Are there any performance benefits to using this instead of a loop or is it just sugar?

[A]
Any time you want to generate a list based another list:
```
```
# Double all elements of a list
my @double = map { $_ * 2 } (1,2,3,4,5);
# @double = (2,4,6,8,10);
```
```
Since lists are easily converted pairwise into hashes, if you want a hash table for objects based on a particular attribute:
```
```
# @user_objects is a list of objects having a unique_id() method
my %users = map { $_->unique_id() => $_ } @user_objects;
# %users = ( $id => $obj, $id => $obj, ...);
```
```
It's a really general purpose tool, you have to just start using it to find good uses in your applications.
Some might prefer verbose looping code for readability purposes, but personally, I find
```
map
```
more readable.


q:
I need to write an SNMP agent for my application.

I read the CodeProject article on how to write an SNMP extension agent DLL using win32, but would like to know if it is possible to do it with managed code.

Also, is it possible to write my own SNMP agent in managed code and run it along windows SNMP service?
windows SNMP service is required to run on my server to provide the basic operating system management info.

What C# SNMP library would you recommend? I found a few C# SNMP protocol implementations, but could not find sample code on how to implement an SNMP agent - most samples are only about querying other agents or sending traps.

[A]
the best library I have used in 8
years of NMS development -
adventnet
you can write your own, but you need to understand
ASN
. Good luck with that.
SNMP agents do 2 things: query for data, send and receive traps. What else you want
them to do? wash your laundry?! (sorry couldn't resist that! :) ).
What are you trying to do with your SNMP agent?! Does you app need to send traps?! or query for data from a node?!


q:
OK, first let me state that I have never used this control and this is also my first attempt at using a web service.

My dilemma is as follows. I need to query a database to get back a certain column and use that for my autocomplete. Obviously I don't want the query to run every time a user types another word in the textbox, so my best guess is to run the query once then use that dataset, array, list or whatever to then filter for the autocomplete extender...

I am kinda lost any suggestions??

[A]
This question depends upon how transactional your data store is. Obviously if you are looking for US states (a data collection that would not change realistically through the life of the application) then I would either cache a System.Collection.Generic List<> type or if you wanted a DataTable.
You could easily set up a cache of the data you wish to query to be dependent upon an XML file or database so that your extender always queries the data object casted from the cache and the cache object is only updated when the datasource changes.


q:
Right now, I have two Eclipse projects - they both use Maven 2 for all their jar-dependency goodness.

Inside Eclipse, I have project Foo included in project Bar's build path, so that I can use Foo's classes from project Bar.  This works really well in Eclipse land, but when I try:

mvn compile

inside Bar's directory, it fails because Maven doesn't know about the project-to-project relationship in Eclipse's build path.

If I were using Ant, I would just use it to do something silly like copy foo.jar into project Bar's classpath, but as far as I can tell, things are done a lot less hackishly in Maven-land.

I'm wondering if there's a standard workaround for this type of problem - it seems like it would be fairly common, and I'm just missing something basic about how Maven works.

[A]
I think the best way to handle it is to make Bar a Maven project just like Foo, and then
```
mvn install
```
it so it is available in your local Maven repository. The drawback is that you have to install that project every time you want Maven to see the changes you make to Bar.


q: I need to determine the current year in Java as an integer. I could just use java.util.Date(), but it is deprecated.

[A]
For Java 8 onwards:
```
```
int year = Year.now().getValue();
```
```
For older version of Java:
```
```
int year = Calendar.getInstance().get(Calendar.YEAR);
```
```


q:
How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used?

It would also be nice if the back button would reload the original URL.

I am trying to record JavaScript state in the URL.

[A]
I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look
just like the real bank
!
Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches...
[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an
HTML5 technique
that allows the URL to be modified as long as it is from the same origin]


q:
I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution:

Vector itemsVector = getItems();

Collections.shuffle(itemsVector);
itemsVector.setSize(5);

While this has the advantage of being nice and simple, I suspect it's not going to scale very well, i.e. Collections.shuffle() must be O(n) at least. My less clever alternative is

Vector itemsVector = getItems();

Random rand = new Random(System.currentTimeMillis()); // would make this static to the class

List subsetList = new ArrayList(5);
for (int i = 0; i < 5; i++) {
     // be sure to use Vector.remove() or you may get the same item twice
     subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size())));
}

Any suggestions on better ways to draw out a random subset from a Collection?

[A]
Your second solution of using Random to pick element seems sound, however:
Depending on how sensitive your data is, I suggest using some sort of hashing method to scramble the random number seed.  For a good case study, see
How We Learned to Cheat at Online Poker
(but this link is 404 as of 2015-12-18). Alternative URLs (found via a Google search on the article title in double quotes) include:
How We Learned to Cheat at Online Poker
— apparently the original publisher.
How We Learned to Cheat at Online Poker
How We Learned to Cheat at Online Poker
Vector is synchronized.  If possible, use ArrayList instead to improve performance.


q:
I'm trying to wrap my head around SharePoint.  Why is it good?  Why is it bad?

At a glance it appears to offer some incredible collaboration tools.  However, the cost looks astronomical and it seems to be rigid & difficult to customize.

To those who've worked with SharePoint; please describe something good and something bad about it.

[A]
It has pretty good Office 2007 integration. As an example, Excel understands when you have a file checked out and will let you check it in (with comments) when you close it. The document management features simplistic version control (although it's not required; you can go with a single version for each file).
In SharePoint, everything is essentially a list internally and it's very easy to create a custom one. On a related note, I haven't used either yet, but it supposedly works well with workflows and InfoPath.
On the downside, it's pretty much a resource beast. It requires multiple machines with powerful specs, particularly if you want to "really" use it for document management and to be the backbone of your intranet/internet site. It scales to an extent, but it's not pretty from my vantage point.
Customizing it presents it's own challenges. You really need people focused on it full time, as both administration and customization require their own impressive learning curves.
Lastly, some of the out of the box parts are poorly implemented. The wiki is a prime example; it's basically useless in my opinion. So one thing to keep in mind is that some may consider SharePoint as a whole package as "best in class" (not saying I do!), its individual features often are not.


q: I need to generate a new interface at run-time with all the same members as an existing interface, except that I will be putting different attributes on some of the methods (some of the attribute parameters are not known until run-time). How can it be achieved?

[A]
Your question isn't very specific.  If you update it with more information, I'll flesh out this answer with additional detail.
Here's an overview of the manual steps involved.
Create an assembly with DefineDynamicAssembly
Create a module with DefineDynamicModule
Create the type with DefineType.  Be sure to pass
```
TypeAttributes.Interface
```
to make your type an interface.
Iterate over the members in the original interface and build similar methods in the new interface, applying attributes as necessary.
Call
```
TypeBuilder.CreateType
```
to finish building your interface.


q:
Is there a way through the .net framework to determine if a folder is shared or not?

Neither Diretory, DirectoryInfo or FileAttributes seem to have any corresponding field.

One thing I forgot to mention was that I want to be checking for network shares.  But I'll investigate the WMI stuff.

[A]
Try using WMI and doing a
```
SELECT * FROM Win32_ShareToDirectory
```
query.


q:
In C++ you can initialize a variable in an if statement, like so:

if (CThing* pThing = GetThing())
{
}

Why would one consider this bad or good style? What are the benefits and disadvantages?

Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this:

if (CThing* pThing = GetThing() && pThing->IsReallySomeThing())
{
}

If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why.

Question borrowed from here, similar topic but PHP.

[A]
This
should
doesn't work in C++
since
even though it supports
short circuiting evaluation
.
Maybe
Don't try the following:
```
```
if ((CThing* pThing = GetThing()) && (pThing->IsReallySomeThing()))
{
}
```
```
err.. see
Wesley Tarle's answer


q:
I'm trying to get an expect script to work, and when I use the -re flag (to invoke regular expression parsing), the 'timeout' keyword seems to no longer work. When the following script is run, I get the message 'timed out at step 1', then 'starting step 2' and then it times out but does NOT print the 'timed out at step 2' I just get a new prompt.

Ideas?

#!/usr/bin/expect --

spawn $env(SHELL)
match_max 100000

set timeout 2

send "echo This will print timed out\r"
expect  {
    timeout { puts "timed out at step 1"  }
    "foo " { puts "it said foo at step 1"}
}

puts "Starting test two\r"

send "echo This will not print timed out\r"
expect  -re {
    timeout { puts "timed out at step 2" ; exit }
    "foo " { puts "it said foo at step 2"}
}


q: Is there a way to keep the "Loading..." graphic from appearing when cfdiv refreshes?  I'd like to prevent the flicker of loading the graphic then loading the new html.

[A]
I don't think there is currently a way to do this programmatically within the
```
cfdiv
```
tag. If you really want to get rid of that "Loading..." message and the image, there are a couple places you can look.
You can rename or delete the image, which is located at:
CFIDE\scripts\ajax\resources\cf\images\loading.gif
That only gets rid of the animation. The "Loading..." text can be blanked out to an empty string, and is defined in:
CFIDE\scripts\ajax\messages\cfmessage.js
Making these changes will obviously have an impact on tags other than
```
cfdiv
```
, but if you are looking to eliminate this behavior in one place, I'm sure you won't mind killing it everywhere else too. :)
I'd love to see a cleaner way to do this if anybody else has any ideas.


q: What the difference between Application("some-object") and Cache("some-object") in ASP.NET?

[A]
Application is an application wide, no timeout (except when the pool restarts) dictionary.  The cache is a temporary repository for common cache storage.
This
And
This
might help clarify the differences and usages.
Here
is another one.


q: How can I programmatically determine if I have access to a server (TCP) with a given IP address and port using C#?

[A]
Assuming you mean through a TCP socket:
```
```
IPAddress IP;
if(IPAddress.TryParse("127.0.0.1",out IP)){
    Socket s = new Socket(AddressFamily.InterNetwork,
    SocketType.Stream,
    ProtocolType.Tcp);

    try{
        s.Connect(IPs[0], port);
    }
    catch(Exception ex){
        // something went wrong
    }
}
```
```
For more information:
http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4


q:
How do I programmatically force an onchange event on an input?

I've tried something like this:

var code = ele.getAttribute('onchange');
eval(code);

But my end goal is to fire any listener functions, and that doesn't seem to work.  Neither does just updating the 'value' attribute.

[A]
if you're using jQuery you would have:
```
```
$('#elementId').change(function() { alert('Do Stuff'); });
```
```
or MS AJAX:
```
```
$addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });
```
```
Or in the raw HTML of the element:
```
```
<input type="text" onchange="alert('Do Stuff');" id="myElement" />
```
```
After re-reading the question I think I miss-read what was to be done. I've never found a way to update a DOM element in a manner which will force a change event, what you're best doing is having a separate event handler method, like this:
```
```
$addHandler($get('elementId'), 'change', elementChanged);
function elementChanged(){
  alert('Do Stuff!');
}
function editElement(){
  var el = $get('elementId');
  el.value = 'something new';
  elementChanged();
}
```
```
Since you're already writing a JavaScript method which will do the changing it's only 1 additional line to call.
Or, if you
are
using the Microsoft AJAX framework you can access all the event handlers via:
```
```
$get('elementId')._events
```
```
It'd allow you to do some reflection-style workings to find the right event handler(s) to fire.


q:
I have a model and two views set up like this:

Model ---> OSortFilterProxyModel ---> OListView
Model ------------------------------> OTableView

When the user selects something in one of the views, I want the other view to mirror that selection. So I thought I'd use a QSelectionModel to link them together. But this does not work. I have a feeling it is because the views think they have two different models, when in fact they have the same model. Is there a way to get this to work?

[A]
What is probably happening is that the views do have two different models.  One is your original model, the other is the sort filter model.
I'm not sure if this would work, and it depends on what Qt considers "activated", but you could connect a function to each of the view's activated slots.  These will pass you a model index.  You'll have to send the model index through the proxy model in the appropriate direction (mapFromSource and mapToSource).  Then, call the setCurrentIndex on the other view.
The documentation for the activated signal states that what is considered "activated" varies by platform.  There might be other signals you could latch onto, such as the selection model's selection changed signal.  You might have to do a different call to change the selection as seen by the user.  And finally, it might be possible or even easier to do in a derived QSelectionModel, as long as you remember about mapping to/from the source model.


q:
We have a .NET 2.0 application which we normally run on IIS6, and used to run fine on IIS7, but recently after installing SP1 for Vista  IIS7 seems to be choking on a line in the Web.Config file:

<system.web AllowLocation="true">

Is it safe to remove the AllowLocation attribute? What does this attribute do?

[A]
Having this set to true should enable any
```
<location>
```
sections in your web.config, so you should be fine to remove it if there's none in there.


q:
I'm having trouble coming up with the correct regex string to remove a sequence of multiple ? characters. I want to replace more than one sequential ? with a single ?, but which characters to escape...is escaping me.

Example input:

Is this thing on??? or what???

Desired output:

Is this thing on? or what?

I'm using preg_replace() in PHP.

[A]
```
```
preg_replace('{\?+}', '?', 'Is this thing on??? or what???');
```
```
That is, you only have to escape the question mark, the plus in "\?+" means that we're replacing every instance with one or more characters, though I suspect "\?{2,}" might be even better and more efficient (replacing every instance with two or more question mark characters.


q:
I'm looking for a few talking points I could use to convince coworkers that it's NOT OK to run a 24/7 production application by simply opening Visual Studio and running the app in debug mode.

What's different about running a compiled console application vs. running that same app in debug mode?

Are there ever times when you would use the debugger in a live setting?  (live: meaning connected to customer facing databases)

Am I wrong in assuming that it's always a bad idea to run a live configuration via the debugger?

[A]
I can't speak for everyone's experience, but for me Visual Studio crashes a lot. It not only crashes itself, but it crashes explorer. This is exacerbated by add-ons and plugins. I'm not sure if its ever been tested to run for 24/7 over days and days and days the same way the OS has.
Your essentially putting the running of your app at the mercy of this huge behemoth of a second app that sounds like its easily orders-of-magnitude larger and more complex than your app. Youre just going to get bug reports and most of them are going to involve visual studio crashing.
Also, are you paying for visual studio licenses for production machines?


q:
I've got a code like this :

Dim Document As New mshtml.HTMLDocument
Dim iDoc As mshtml.IHTMLDocument2 = CType(Document, mshtml.IHTMLDocument2)
iDoc.write(html)
iDoc.close()

However when I load an HTML like this it executes all Javascripts in it as well as doing request to some resources from "html" code.

I want to disable javascript and all other popups (such as certificate error).

My aim is to use DOM from mshtml document to extract some tags from the HTML in a reliable way (instead of bunch of regexes).

Or is there another IE/Office DLL which I can just load an HTML wihtout thinking about IE related popups or active scripts?

[A]
If you have the 'html' as a string already, and you just want access to the DOM view of it, why "render" it to a browser control at all?
I'm not familiar with .Net technology, but there has to be some sort of StringToDOM/StringToJSON type of thing that would better suit your needs.
Likewise, if the 'html' variable you are using above is a URL, then just use wget or similar to retrieve the markup as a string, and parse with an applicable tool.
I'd look for a .Net XML/DOM library and use that. (again, I would figure that this would be part of the language, but I'm not sure)
PS after a quick Google I found this (
source
).  Not sure if it would help, if you were to use this in your HTMLDocument instead.
```
```
if(typeof(DOMParser) == 'undefined') {
      DOMParser = function() {}
      DOMParser.prototype.parseFromString = function(str, contentType) {
      if(typeof(ActiveXObject) != 'undefined') {
        var xmldata = new ActiveXObject('MSXML.DomDocument');
        xmldata.async = false;
        xmldata.loadXML(str);
        return xmldata;
     } else if(typeof(XMLHttpRequest) != 'undefined') {
        var xmldata = new XMLHttpRequest;
        if(!contentType) {
          contentType = 'application/xml';
        }
        xmldata.open('GET', 'data:' + contentType + ';charset=utf-8,' + encodeURIComponent(str), false);
        if(xmldata.overrideMimeType) {
          xmldata.overrideMimeType(contentType);
        }
        xmldata.send(null);
        return xmldata.responseXML;
     }
  }
}
```
```


q:
Is it possible to make it appear to a system that a key was pressed, for example I need to  make A key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.

A better way to put it, I need to emulate a key press, I.E. not capture a key press.

More Info (as requested):
I am running windows XP and need to send the keys to another application.

[A]
AutoHotKey
is perfect for this kind of tasks (keyboard automation / remapping)
Script to send "A" 100 times:
```
```
Send {A 100}
```
```
That's all
EDIT
: to send the keys to an specific application:
```
```
WinActivate Word
Send {A 100}
```
```


q:
How can I drop sql server agent jobs, if (and only if) it exists?

This is a well functioning script for stored procedures. How can I do the same to sql server agent jobs?

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[storedproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
    drop procedure [dbo].[storedproc]
GO
CREATE PROCEDURE [dbo].[storedproc] ...

[A]
Try something like this:
```
```
DECLARE @jobId binary(16)

SELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name = N'Name of Your Job')
IF (@jobId IS NOT NULL)
BEGIN
    EXEC msdb.dbo.sp_delete_job @jobId
END

DECLARE @ReturnCode int
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'Name of Your Job'
```
```
Best to read the docs on all the parameters required for
'sp_add_job'
and
'sp_delete_job'


q:
I have a datetime column in MySQL.

How can I convert it to the display as mm/dd/yy H:M (AM/PM) using PHP?

[A]
An easier way would be to format the date directly in the MySQL query, instead of PHP.  See the
MySQL manual entry for DATE_FORMAT
.
If you'd rather do it in PHP, then you need the
date
function, but you'll have to convert your database value into a timestamp first.


q:
Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: http://gist.github.com/12978. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seconds. The machine is a standard 15" MacBook Pro (2.4ghz C2D, 2GB RAM)

Is it possible for this to go faster or is that a limitation on the language/database?

[A]
Use bind variables instead of literal values in the sql statements and create a cursor for
each unique sql statement so that the statement does not need to be reparsed the next time it is used.  From the python db api doc:
Prepare and execute a database
  operation (query or command).
  Parameters may be provided as sequence
  or mapping and will be bound to
  variables in the operation. Variables
  are specified in a database-specific
  notation (see the module's paramstyle
  attribute for details). [5]
A reference to the operation will be
  retained by the cursor.  If the same
  operation object is passed in again,
  then the cursor can optimize its
  behavior.  This is most effective for
  algorithms where the same operation is
  used, but different parameters are
  bound to it (many times).
ALWAYS ALWAYS ALWAYS use bind variables.


q:
I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name):

people = []
info = 'a' # must fill variable with something, otherwise loop won't execute

while not info.empty?
    info = gets.chomp
    people += [Person.new(info)] if not info.empty?
end

This code would look much nicer in a do ... while loop:

people = []

do
    info = gets.chomp
    people += [Person.new(info)] if not info.empty?
while not info.empty?

In this code I don't have to assign info to some random string.

Unfortunately this type of loop doesn't seem to exist in Ruby. Can anybody suggest a better way of doing this?

[A]
I found the following snippet while reading the source for
```
Tempfile#initialize
```
in the Ruby core library:
```
```
begin
  tmpname = File.join(tmpdir, make_tmpname(basename, n))
  lock = tmpname + '.lock'
  n += 1
end while @@cleanlist.include?(tmpname) or
  File.exist?(lock) or File.exist?(tmpname)
```
```
At first glance, I assumed the while modifier would be evaluated before the contents of begin...end, but that is not the case. Observe:
```
```
>> begin
?>   puts "do {} while ()"
>> end while false
do {} while ()
=> nil
```
```
As you would expect, the loop will continue to execute while the modifier is true.
```
```
>> n = 3
=> 3
>> begin
?>   puts n
>>   n -= 1
>> end while n > 0
3
2
1
=> nil
```
```
While I would be happy to never see this idiom again, begin...end is quite powerful. The following is a common idiom to memoize a one-liner method with no params:
```
```
def expensive
  @expensive ||= 2 + 2
end
```
```
Here is an ugly, but quick way to memoize something more complex:
```
```
def expensive
  @expensive ||=
    begin
      n = 99
      buf = ""
      begin
        buf << "#{n} bottles of beer on the wall\n"
        # ...
        n -= 1
      end while n > 0
      buf << "no more bottles of beer"
    end
end
```
```
Originally written by
Jeremy Voorhis
.  The content has been copied here because it seems to have been taken down from the originating site.  Copies can also be found in the
Web Archive
and at
Ruby Buzz Forum
.  -Bill the Lizard


q:
I didn't know I would be getting too many replies so fast. I can provide more details. It is definitely for use within the company. I was looking for some info on whether I should be more careful or anything to watch out for...

My boss is asking me to put some tracking info on what users do with their application. It is not about collecting sensitive data but there might be some screenshots involved and I am not sure if this is a breach of privacy.

Would love to hear any thoughts on this or if you handled something similar.

[A]
At work, there is no privacy.  Think of it this way, if you work for a financial institution, or a government one, monitoring users may be the difference between keeping sensitive information secret and not.  (I want my personal information kept private).  They are paid to do work at work.  If they are afraid about what they are doing is wrong, then they shouldn't be doing it.
A comment brought up a good point.  If you are selling the product and spying on end users, that is totally different.  That is highly unethical to take screen shots and report them back to the company.  Actually where I work, we'd have you arrested for it if we found out. (yes, you'd be violating a federal law, and I guarantee we'd go after everyone and sort out the mistakes later.) That is a very slippery slope.


q:
After reading this answer:
best way to pick a random subset from a collection?

It got me wondering, how does one pick a random seed in Java?

And don't say use System.currentTimeMillis() or System.nanoTime().  Read the article to see why not.

That's a hard question, but let me make it harder.  Let's say you need to generate a random seed without connecting to the internet, without using user input (IE, there's no gui), and it has to be cross platform (therefore no JNI to access hardware).

Is there some JVM variables we can monitor as a source of our randomness?

Can this be done?  Or is it impossible?

[A]
Take a look at
Uncommons Maths
(full disclosure: I wrote it).  It should solve most of the problems you'll ever have with random numbers in Java.
Even, if you don't use it you should be able to get some ideas from the various
SeedGenerator
implementations it provides.  Basically, it defaults to using
/dev/random
.  If that doesn't exist (e.g. Windows) it either tries to download data from
random.org
or it uses
SecureRandom.generateSeed
.
I think SecureRandom.generateSeed is the best that you can do without relying on anything platform specific or on the Internet.


q:
What is the slickest way to initialize an array of dynamic size in C# that you know of?

This is the best I could come up with

private bool[] GetPageNumbersToLink(IPagedResult result)
{
   if (result.TotalPages <= 9)
      return new bool[result.TotalPages + 1].Select(b => true).ToArray();

   ...

[A]
Untested, but could you just do this?
```
```
return result.Select(p => true).ToArray();
```
```
Skipping the "new bool[]" part?


q: Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes?  That is to say when the browser is not communicating with the server or reloading the page.

[A]
```
onLocationChange
```
may also be useful.  Not sure if this is a Mozilla-only thing though, appears that it might be.


q:
What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?

For example, when should one use

enum {BUFFER = 1234};

over

#define BUFFER 1234

[A]
```
enum
```
defines a syntactical element.
```
#define
```
is a pre-preprocessor directive, executed
before
the compiler sees the code, and therefore is not a language element of C itself.
Generally enums are preferred as they are type-safe and more easily discoverable.  Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a
```
#define
```
made by another.  This can be hard to track down.


q:
2 tables:

Employees
- EmployeeID
- LeadCount

Leads
- leadID
- employeeID

I want to update the Employees.LeadCount column by counting the # of leads in the Leads table that have the same EmployeeID.

Note:  There may be more than 1 lead with the same employeeID, so I have to do a DISTINCT(SUM(employeeID)).

[A]
```
```
UPDATE Employees SET LeadCount = (
  SELECT Distinct(SUM(employeeID)) FROM Leads WHERE Leads.employeeId = Employees.employeeId
)
```
```


q: What is the best way to take a given PHP object and serialize it as XML? I am looking at simple_xml and I have used it to parse XML into objects, but it isn't clear to me how it works the other way around.

[A]
Use a dom function to do it:
http://www.php.net/manual/en/function.dom-import-simplexml.php
Import the SimpleXML object and then save. The above link contains an example. :)
In a nutshell:
```
```
<?php
$array = array('hello' => 'world', 'good' => 'morning');

$xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><foo />");
foreach ($array as $k=>$v) {
  $xml->addChild($k, $v);
}
?>
```
```


q:
How does one do this?

If I want to analyze how something is getting compiled, how would I get the emitted assembly code?

[A]
Use the
-S
switch:
```
```
g++ -S main.cpp
```
```
Or also with
```
gcc
```
:
```
```
gcc -S main.c
```
```
Also see
this
.


q:
I'm working on a MS Access database.  I've made some changes to one of the modules.  I want to go out for lunch, but when I try closing the database, I get the following message:

"You do not have exclusive access to the database.  Your design changes cannot be saved at this time.  Do you want to close without saving your changes?"

I'm pretty sure nobody else on the network has the database file open, and I don't have any other Access databases open.  I'm probably missing something obvious, but would really appreciated some help!

Update:

In the end I copied all the code, closed the database without saving, re-opened it and pasted the code back in.  I was then able to save the database.  I'm not sure if this was a one off, but I'll report back if it happens again.

[A]
If you close the database and are sure nobody else has it opened, check to see if there is a .ldb file (it will have the same name as your database file).  If the file is there, then there is a  good chance it is still in use.
Is it being access by a service, like a website?
You could copy the database to another sub-directory and make your changes.  If that doesn't work, I will have to look that up.  Of course there is always the database tool, "repair and compress database..."
Is the file located on a file server?  If so check to see if any users have a file handle to it.
If it still doesn't work, update your post with your new information and we'll go further.
UPDATE (9/26):
Another thing I do when having strange issues with access databases with contain vba code is decompile.  I don't know if this is documented yet, I haven't looked in years, but it's was (at least) an undocumented switch to msaccess.
From a cmd line:
change directory to where msaccess.exe is located.
Run the following command
msaccess \path to access file\databasefile.mdb /decompile
usually runs very quick then opens the database.  Open any module and compile.
Doesn't always work, but sometimes can remove strange happenings.
Did you ever trying to copy the database to another directory and making your edits?  That should of worked; you could then rename the original and copy the file back.
Anyway, I am glad you are working again.


q:
Whats the best way to round in VBA Access?

My current method utilizes the Excel method

Excel.WorksheetFunction.Round(...

But I am looking for a means that does not rely on Excel.

[A]
Int and Fix are both useful rounding functions, which give you the integer part of a number.
Int always rounds down - Int(3.5) = 3, Int(-3.5) = -4
Fix always rounds towards zero - Fix(3.5) = 3, Fix(-3.5) = -3
There's also the coercion functions, in particular CInt and CLng, which try to coerce a number to an integer type or a long type (integers are between -32,768 and 32,767, longs are between-2,147,483,648 and 2,147,483,647).  These will both round towards the nearest whole number, rounding away from zero from .5 - CInt(3.5) = 4, Cint(3.49) = 3, CInt(-3.5) = -4, etc.


q: I need to rebuild an apache server, but the original source is no longer available. Is there any way ( command line switch to httpd? ) to get the build options which were originally used?

[A]
Try -V which "Print the version and build parameters of httpd, and then exit."
```
```
httpd -V
```
```
Also, you can see the options for httpd via:
```
```
httpd -h
```
```


q:
What are the patterns you use to determine the frequent queries?

How do you select the optimization factors?

What are the types of changes one can make?

[A]
Your question is a bit vague. Which DB platform?
If we are talking about SQL Server:
Use the Dynamic Management Views. Use SQL Profiler. Install the SP2 and the performance dashboard reports.
After determining the most costly queries (i.e. number of times run x cost one one query), examine their execution plans, and look at the sizes of the tables involved, and whether they are predominately Read or Write, or a mixture of both.
If the system is under your full control (apps. and DB) you can often re-write queries that are badly formed (quite a common occurrance), such as deep correlated sub-queries which can often be re-written as derived table joins with a little thought. Otherwise, you options are to create covering non-clustered indexes and ensure that statistics are kept up to date.


q: How can I list all the types that are declared by a module in Ruby?

[A]
Use the
constants
method defined in the
Module
module. From the Ruby documentation:
Module.constants => array
Returns an array of the names of all
  constants defined in the system. This
  list includes the names of all modules
  and classes.
p Module.constants.sort[1..5]
produces:
["ARGV", "ArgumentError", "Array",
  "Bignum", "Binding"]
You can call
constants
on any module or class you would like.
```
```
p Class.constants
```
```


q: I first encountered the concept of lazy registration the Ajax Patterns site, where they define it as accumulating "bits of information about the user as they interact, with formal registration occurring later on." I'm looking at doing something similar for my website, but I'd like to know a little bit more about best practices before I start implementing it. My site is about web development, but general best practices are great too. How have you implemented lazy registration on your sites or projects? Where have you seen it in the wild? What do you like or dislike about it?

[A]
I say this not as a person who has designed such a site before, but as a person that might visit that site.  :)
With that said, the thing that I would be the most concerned about is knowing what kind of information is being collected about me.  And I think that there should be an option to opt out of collecting the information and instead entering it all during formal registration.
But other than that, if it makes registering for a website easier, I'd be all for it.  I leave 9 out of 10 sites that require me to register to do stuff.


q: How can I determine if a remote drive has enough space for me to upload a given file using C# in .Net?

[A]
Are you talking about mapping a network share to a logical drive on you computer?
If so you can use DriveInfo.
```
DriveInfo info = new DriveInfo("X:");

    info.AvailableFreeSpace;
```
DriveInfo only works with logical drives so if you are just using the full share (UNC) name I don't think the above code will work.


q:
What is the best way to read an HTTP response from GetResponseStream ?

Currently I'm using the following approach.

Using SReader As StreamReader = New StreamReader(HttpRes.GetResponseStream)
   SourceCode = SReader.ReadToEnd()
End Using

I'm not quite sure if this is the most efficient way to read an http response.

I need the output as string, I've seen an article with a different approach but I'm not quite if it's a good one. And in my tests that code had some encoding issues with in different websites.

How do you read web responses?

[A]
I use something like this to download a file from a URL:
```
```
if (!Directory.Exists(localFolder))
{
    Directory.CreateDirectory(localFolder);
}

try
{
    HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(Path.Combine(uri, filename));
    httpRequest.Method = "GET";

    // if the URI doesn't exist, an exception will be thrown here...
    using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
    {
        using (Stream responseStream = httpResponse.GetResponseStream())
        {
            using (FileStream localFileStream =
                new FileStream(Path.Combine(localFolder, filename), FileMode.Create))
            {
                var buffer = new byte[4096];
                long totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    totalBytesRead += bytesRead;
                    localFileStream.Write(buffer, 0, bytesRead);
                }
            }
        }
    }
}
catch (Exception ex)
{
    // You might want to handle some specific errors : Just pass on up for now...
    // Remove this catch if you don't want to handle errors here.
    throw;
}
```
```


q:
I've got a CAkePHP 1.2 site. I've got three related Models/tables:
A Comment has exactly one Touch, a Touch has exactly one Touchtype.

In each model, I have a belongs to, so I have
Comments belongs to Touch, Touch belongs to Touchtype.

I'm trying to get a list of comments that includes information about the touch stored in the touchtype table.

$this->Comment->find(...)

I pass in a fields list to the find(). I can grab fields from Touch and Comment, but not TouchType. Does the model connection only go 1 level? I tried tweaking recursive, but that didn't help.

[A]
Pipe output to:
```
```
cut -b 1-LIMIT
```
```
Where LIMIT is the desired line width.


q: How do you embed a SWF file in an HTML page?

[A]
```
```
<object width="100" height="100">
    <param name="movie" value="file.swf">
    <embed src="file.swf" width="100" height="100">
    </embed>
</object>
```
```


q:
The question posed came about during a 2nd Year Comp Science lecture while discussing the impossibility of generating numbers in a deterministic computational device.

This was the only suggestion which didn't depend on non-commodity-class hardware.

Subsequently nobody would put their reputation on the line to argue definitively for or against it.

Anyone care to make a stand for or against.  If so, how about a mention as to a possible implementation?

[A]
Eh, I find that this kind of question leads into discussions about the meaning of 'truly random' pretty quickly.
I think that measuring pings would yield decent-quality random bits, but at an insufficient rate to be of much use (unless you were willing to do some serious DDOSing).
And I don't see that it would be any more random than measuring analogue/mechanical properties of the computer, or the behaviour of the meatbag operating it.
(edit) On a practical note, this approach opens you up to the possibility of someone on your network manipulating your 'random' number generator.


q:
A couple of months ago I've coded a tiny tool that we needed at work for a specific task, and I've decided to share it on CodePlex. It's written in C# and honestly it's not big deal but since it's the first project I've ever built from scratch in that language and with the goal of opening it from the very beginning, one ends getting sort of emotionally attached to it, I mean you'd wish that the people will actually participate, be it criticism, bug reporting, or what have you.

So my question is, what can I do to actually encourage participation, stimulate curiosity or just recieve more feedback about it?

By the way this is the project I'm talking about: http://www.codeplex.com/winxmlcook/

[A]
You should:
Promote it where you think it would be relevant (forums,mailing lists etc.). Try not to spam though - it will create a backlash.
continue to provide updates as to create the appearance of an active project until more people pick it up.
Find project leaders, they are the sort of contributors that encourage others to contribute as well.
Blog about it and link to relevant blogs (creating ping-backs). Also leave comments at relevant blog posts.
Basically, your generic Internet marketing tactics ;)


q:
I'm converting an old app that records folder sizes on a daily basis. The legacy app uses the Scripting.FileSystemObject library:

Set fso = CreateObject("Scripting.FileSystemObject")
Set folderObject = fso.GetFolder(folder)
size = folderObject.Size

There isn't an equivalent mechanism on the System.IO.Directory and System.IO.DirectoryInfo classes.

To achieve the same result in .NET do I actually have to recursively walk the whole folder structure keeping a running total of file sizes?

Update: @Jonathon/Ed - thanks....as I thought. I think I'll just reference the Scripting.FileSystemObject COM library. Works just as well even if breaking the .NET purity of my app. It's for an internal reporting app so it's not such a big deal.

[A]
Sadly, yes...who knows why.
```
```
public static long DirSize(DirectoryInfo d)
{
    long Size = 0;
    // Add file sizes.
    FileInfo[] fis = d.GetFiles();
    foreach (FileInfo fi in fis)
    {
        Size += fi.Length;
    }
    // Add subdirectory sizes.
    DirectoryInfo[] dis = d.GetDirectories();
    foreach (DirectoryInfo di in dis)
    {
        Size += DirSize(di);
    }
    return(Size);
}
```
```
As seen at:
http://msdn.microsoft.com/en-us/library/system.io.directory.aspx


q:
I'm sick of remembering all the passwords for different logins. Lately I found the interesting tool password composer which lets you generate passwords base on the hostname and a secret master password. But I don't want to use a website or installing software to generate my passwords.

So I'm looking for a simple one way hashing alogorithm which I can execute without computer aid to generate my passwords. Something in the spirit of the solitare cipher without the need for cards.

Using a PW store is not an option.

[A]
Why don't you just use the exact same algorithm as the password composer?
Pick a master password
Take the application/machine name for which you want a password
Concatenate the two (or shuffle)
Apply a code you can do in your head, like
Caesar's cipher
Take the first X characters (15 is usually a good length for secure passwords)
Example:
```
```
Master Password: kaboom
Machine Name: hal9000
Shuffle: khaablo9o0m00
Transposition table: shift 5 left
abcdefghijklmnopqrstuvwxyz 1234567890
vwxyzabcdefghijklmnopqrstu 6789012345

Result: fcvvwgj4j5h55
```
```
You could use as complex a substitution as your head can do reliably (with or without a paper). You could also use a different table for each password (say, deduce the table from the first letter of each machine name). As long as your master password is secure, there's nothing to fear about the simplicity of the algorithm.


q:
I have a SQL query (MS Access) and I need to add two columns, either of which may be null. For instance:

SELECT Column1, Column2, Column3+Column4 AS [Added Values]
FROM Table

where Column3 or Column4 may be null. In this case, I want null to be considered zero (so 4 + null = 4, null + null = 0).

Any suggestions as to how to accomplish this?

[A]
Since ISNULL in Access is a boolean function (one parameter), use it like this:
```
```
SELECT Column1, Column2, IIF(ISNULL(Column3),0,Column3) + IIF(ISNULL(Column4),0,Column4) AS [Added Values]
FROM Table
```
```


q:
Looking at the processmodel element in the Web.Config there are two attributes.

maxWorkerThreads="25"
maxIoThreads="25"

What is the difference between worker threads and I/O threads?

[A]
Fundamentally not a lot, it's all about how ASP.NET and IIS allocate I/O wait objects and manage the contention and latency of communicating over the network and transferring data.
I/O threads are set aside as such because they will be doing I/O (as the name implies) and may have to wait for "long" periods of time (hundreds of milliseconds).  They also can be optimized and used differently to take advantage of I/O completion port functionality in the Windows kernel.  A single I/O thread may be managing multiple completion ports to maintain throughput.
Windows has a lot of capabilities for dealing with I/O blocking whereas ASP.NET/.NET has a plain concept of "Thread".  ASP.NET can optimize for I/O by using more of the unmanaged threading capabilities in the OS. You wouldn't want to do this all the time for every thread as you lose a lot of capabilities that .NET gives you which is why there is a distinction between how the threads are intended to be used.
Worker threads are threads upon which regular "work" or just plain code/processing happens.  Worker threads are unlikely to block a lot or wait on anything and will be short running and therefore require more aggressive scheduling to maximize processing power and throughput.
[Edit]: I also found this link which is particularly relevant to this question:
http://blogs.msdn.com/ericeil/archive/2008/06/20/windows-i-o-threads-vs-managed-i-o-threads.aspx


q:
When do we use client side reporting and when do we use server side reporting?

Which reporting is best practice (client/server)?

This pertains to SSRS reporting.

[A]
Well... client side reporting you'd use if you've got something like a winforms client that you can't guarantee will have constant access to the data source. It might have a set of data cached on the client side which you need to report on even if the connection to the server is unavailable.
Server side reporting you'd use in the scenario where you either need to simplify the report distribution and deployment as you just deploy the reports to one place and everyone can access them. This has the downfall of always requiring a connection be available to the server


q:
Take the following snippet:

List<int> distances = new List<int>();

Was the redundancy intended by the language designers? If so, why?

[A]
You could always say:
```
```
var distances = new List<int>();
```
```


q:
I have a draggable div element with a hover style. This works fine, but the div contains some form elements (label, input). The problem is that when the mouse is over these child elements the hover is disabled.

<div class="app_setting">
  <label">Name</label>
  <input type="text" name="name"/>
</div>

.app_setting:hover {
  cursor:move;
}

Any ideas how to get the hover to apply also to the child elements?

[A]
```
```
.app_setting *:hover { cursor:move }
```
```


q:
I am told that good developers can spot/utilize the difference between Null and False and 0 and all the other good "nothing" entities.

What is the difference, specifically in PHP?  Does it have something to do with ===?

[A]
The differences between these values always come down to detailed language-specific rules. What you learn for PHP isn't necessarily true for Python, or Perl, or C, etc. While it is valuable to learn the rules for the language(s) you're working with, relying on them too much is asking for trouble. The trouble comes when the next programmer needs to maintain your code and you've used some construct that takes advantage of some little detail of Null vs. False (for example). Your code should look correct (and conversely,
wrong code should look wrong
).


q: In Oracle, is there an easy way to fully unwrap a view? eg: If I have a view which is made up of selects on more views, is there some way to unwrap it to just select directly on real tables?

[A]
Get the query text of your view.
```
```
SELECT text FROM dba_views
WHERE owner = 'the-owner' AND view_name = 'the-view-name';
```
```
Parse.  Search for view names within the query text.
Get the query text for each view name found.  (see item 1.)
Replace each view name in the query with the related query text.
Do this recursively until there are no more views found.
Easy?
EDIT:
The above instructions do not do everything required.  Thinking about this a little more it gets hairy, grows legs, and maybe another arm.  Finding column names, and column names that might be elaborate functions and subqueries.  Bringing it all back together with the joins and clauses.  The resulting query might look very ugly.
Somewhere within Oracle there may be something that is actually unwrapping a view.  I don't know.  I am glad I didn't use views that much in Oracle.


q:
My Invoice model has an address_id attribute, and I don't want this address_id to change FOREVER. So I don't want this to happen outside the class:

invoice.address_id = 1
invoice.address = some_address

Rails automatically adds this address_id attribute to the model from the invoice table, so how can I declare this attribute private/protected? Calling

attr_protected :address_id

is most likely not the solution since based on the documentation it only prevents mass assignments.

Thanks!

[A]
Not as pretty as a one liner, but code below should work (and you could always do some metaprogramming to write an 'immutable' method)
```
```
def address_id=(id)
  if new_record?
    write_attribute(:address_id, id)
  else
    raise 'address is immutable!'
  end
end
```
```


q:
I was reading about output buffering in JavaScript here, and was trying to get my head around the script the author says was the fastest at printing 1 to 1,000,000 to a web page. (Scroll down to the header "The winning one million number script".) After studying it a bit, I have a few questions:

What makes this script so efficient compared to other approaches?

Why does buffering speed things up?

How do you determine the proper buffer size to use?

Does anyone here have any tricks up her/his sleeve that could optimize this script further?

(I realize this is probably CS101, but I'm one of those blasted, self-taught hackers and I was hoping to benefit from the wisdom of the collective on this one. Thanks!)

[A]
I would bet the slowest thing in printing 1m numbers is the browser redrawing the page, so the fewer times you call document.write(), the better.  Of course this needs to be balanced against large string concatenations (because they involve allocating and copying).
Determining the right buffer size is found through experimentation.
In other examples, buffering helps align along natural boundaries. Here are some examples
32 bit CPUs can transfer 32 bits more efficiently.
TCP/IP packets have maximum sizes.
File I/O classes have internal buffers.
Images, like TIFFs, may be stored with their data in strips.
Aligning with the natural boundaries of other systems can often have performance benefits.


q:
I know how to do a HEAD request with httplib, but I have to use mechanize for this site.

Essentially, what I need to do is grab a value from the header (filename) without actually downloading the file.

Any suggestions how I could accomplish this?

[A]
Mechanize itself only sends GETs and POSTs, but you can easily extend the Request class to send HEAD. Example:
```
```
import mechanize

class HeadRequest(mechanize.Request):
    def get_method(self):
        return "HEAD"

request = HeadRequest("http://www.example.com/")
response = mechanize.urlopen(request)

print response.info()
```
```


q: How do you render primitives as wireframes in OpenGL?

[A]
From
http://cone3d.gamedev.net/cgi-bin/index.pl?page=tutorials/ogladv/tut5
```
```
// Turn on wireframe mode
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);

// Draw the box
DrawBox();

// Turn off wireframe mode
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);
```
```