Question:
In my vb.net program, I am using a webbrowser to show the user an HTML preview.  I was previously hitting a server to grab the HTML, then returning on an asynchronous thread and raising an event to populate the WebBrowser.DocumentText with the HTML string I was returning.

Now I set it up to grab all of the information on the client, without ever having to hit the server, and I'm trying to raise the same event.  I watch the code go through, and it has the HTML string correct and everything, but when I try to do

browser.DocumentText = _emailHTML

the contents of DocumentText remain as "<HTML></HTML>"

I was just wondering why the DocumentText was not being set.  Anyone have any suggestions?

Answer:
Try the following:
```
```
browser.Navigate("about:blank");
HtmlDocument doc = browser.Document;
doc.Write(String.Empty);
browser.DocumentText = _emailHTML;
```
```
I've found that the
```
WebBrowser
```
control usually needs to be initialized to
```
about:blank
```
anyway. The same needs to be done between navigates to different types of content (like text/xml to text/html) because the renderer is different (mshtml for text/html, something else for text/xml).
See Also
:
C# 2.0 WebBrowser control - bug in DocumentText?


Question:
I'm having trouble figuring out how to access a cookie from a compiled object. I'm trying to make a compiled (DLL) object that will check the users cookie and then compare that to a database to confirm they have the correct access.

I can pass in the cookie info fine and the component will work, but I'm trying to have the component check the users cookie as well. I'm not even sure what object to use. I've been searching all weekend and I've seen references to httprequest, httpcookie, cookie, and cookiecollection.

I can look up cookie values on the page itself using Request.Cookies("inet")("user_id") but this doesn't work in the component.

Answer:
Objects (App_Code/ compiled dlls) can only access Request via the static HttpContext.Current object
```
```
HttpCookie cookie = HttpContext.Current.Request.Cookies["CookieName"];
```
```
(If it's not called from a web app, HttpContext.Current is null, so you may want to check for that when running in unit testing)
(If this isn't App_Code, you'll need to reference System.Web)


Question:
I have about 200 Excel files that are in standard Excel 2003 format.

I need them all to be saved as Excel xml - basically the same as opening each file and choosing Save As... and then choosing Save as type: XML Spreadsheet

Would you know any simple way of automating that task?

Answer:
You could adapt the code I posted here:
http://www.atalasoft.com/cs/blogs/loufranco/archive/2008/04/01/loading-office-documents-in-net.aspx
It shows how to save as PDF (Word is shown in the blog, but if you download the solution, it has code for Excel and PPT).
You need to find the function for saving as the new format instead of exporting (probably the easiest way is to record a macro of yourself doing it in Excel and then looking at the code).


Question:
I have a table that records a sequence of actions with a field that records the sequence order:

user    data    sequence
1       foo     0
1       bar     1
1       baz     2
2       foo     0
3       bar     0
3       foo     1

Selecting the first item for each user is easy enough with WHERE sequence = '0' but is there a way to select the last item for each user in SQL?

The result I am after should look like this:

user    data    sequence
1       baz     2
2       foo     0
3       foo     1

I'm using MySQL if there are any implementation specific tricksters answering.

Answer:
This sql will return the record with the highest sequence value for each user:
```
```
select a.user, a.data, a.sequence
from table as a
    inner join (
        select user, max(sequence) as 'last'
        from table
        group by user) as b
    on a.user = b.user and
       a.sequence = b.last
```
```


Question: What is the simplest way (least error-prone, least lines of code, however you want to interpret it) to open a file in C and read its contents into a string (char*, char[], whatever)?

Answer:
I tend to just load the entire buffer as a raw memory chunk into memory and do the parsing on my own. That way I have best control over what the standard lib does on multiple platforms.
This is a stub I use for this. you may also want to check the error-codes for fseek, ftell and fread. (omitted for clarity).
```
```
char * buffer = 0;
long length;
FILE * f = fopen (filename, "rb");

if (f)
{
  fseek (f, 0, SEEK_END);
  length = ftell (f);
  fseek (f, 0, SEEK_SET);
  buffer = malloc (length);
  if (buffer)
  {
    fread (buffer, 1, length, f);
  }
  fclose (f);
}

if (buffer)
{
  // start to process your data / extract strings here...
}
```
```


Question:
I recently inherited a database on which one of the tables has the primary key composed of encoded values (Part1*1000 + Part2).

I normalized that column, but I cannot change the old values.
So now I have

select ID from table order by ID
ID
100001
100002
101001
...

I want to find the "holes" in the table (more precisely, the first "hole" after 100000) for new rows.

I'm using the following select, but is there a better way to do that?

select /* top 1 */ ID+1 as newID from table
where ID > 100000 and
ID + 1 not in (select ID from table)
order by ID

newID
100003
101029
...

The database is Microsoft SQL Server 2000. I'm ok with using SQL extensions.

Answer:
```
```
SELECT (ID+1) FROM table AS t1
LEFT JOIN table as t2
ON t1.ID+1 = t2.ID
WHERE t2.ID IS NULL
```
```


Question:
How can you depend on test code from another module in Maven?

Example, I have 2 modules:

Base

Main

I would like a test case in Main to extend a base test class in Base.  Is this possible?

Update: Found an acceptable answer, which involves creating a test jar.

Answer:
Yep ... just include the Base module as a dependency in Main.  If you're only inheriting test code, then you can use the scope tag to make sure Maven doesn't include the code in your artifact when deployed.  Something like this should work:
```
```
<dependency>
    <groupId>BaseGroup</groupId>
    <artifactId>Base</artifactId>
    <version>0.1.0-SNAPSHOT</version>
    <scope>test</scope>
</dependency>
```
```


Question:
If I wish to simply rename a column (not change its type or constraints, just its name) in an SQL database using SQL, how do I do that?  Or is it not possible?

This is for any database claiming to support SQL, I'm simply looking for an SQL-specific query that will work regardless of actual database implementation.

Answer:
Specifically for SQL Server, use
```
sp_rename
```
```
```
USE AdventureWorks;
GO
EXEC sp_rename 'Sales.SalesTerritory.TerritoryID', 'TerrID', 'COLUMN';
GO
```
```


Question: In Eclipse, I often include all project-related material (including documents in PDF, Microsoft, and OpenDocument formats) in the project. Is this possible with Visual Studio, especially to the point where if I attempt to open the file from inside Visual Studio, it will open in the external application?

Answer:
Yes, just right-click your project in the solution explorer and goto Add > Existing Item...
Though -- I'd recommend making a new folder to keep this in.
Yes, you can make sure that when you open it it opens with the correct application.  Just right-click the file once it's added into the solution explorer and select Open With... and make sure you set the default application that way from that point forward you can just double-click your files.
If you have access to use Sharepoint Services with your source control than that would also make life much easier, thanks for reminding me Chris!


Question: What is the difference between ROWNUM and ROW_NUMBER  ?

Answer:
ROWNUM is a "pseudocolumn" that assigns a number to each row returned by a query:
```
```
SQL> select rownum, ename, deptno
  2  from emp;

    ROWNUM ENAME          DEPTNO
---------- ---------- ----------
         1 SMITH              99
         2 ALLEN              30
         3 WARD               30
         4 JONES              20
         5 MARTIN             30
         6 BLAKE              30
         7 CLARK              10
         8 SCOTT              20
         9 KING               10
        10 TURNER             30
        11 FORD               20
        12 MILLER             10
```
```
ROW_NUMBER is an analytic function that assigns a number to each row according to its ordering within a group of rows:
```
```
SQL> select ename, deptno, row_number() over (partition by deptno order by ename) rn
  2  from emp;

ENAME          DEPTNO         RN
---------- ---------- ----------
CLARK              10          1
KING               10          2
MILLER             10          3
FORD               20          1
JONES              20          2
SCOTT              20          3
ALLEN              30          1
BLAKE              30          2
MARTIN             30          3
TURNER             30          4
WARD               30          5
SMITH              99          1
```
```


Question:
I am trying to get in place editing working but I am running into this error:

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken)

I understand that rails now wants to protect against forgery and that I need to pass a form authenticity token but I am not clear on how to do this with the in_place_edit plugin.

Answer:
This isn't a
complete
tested answer, but I took a look at the
plugin code
, and it looks like you could use the
```
:with
```
option to tack the authenticity token onto the end of the request parameters.  Something along the lines of:
```
```
in_place_editor("my_element", :with => "form.serialize() + '&authenticity_token=#{form_authenticity_token}';")
```
```
(I have not tested the above code).


Question:
I'd like to  use the Wiimote (accelerometers, gyroscopes, infrared camera, etc, etc, etc) on various applications.

It's a bluetooth device, and I know others have connected it to their computer.

What's the easiest way to start using it in my software - are there libraries for C#, for instance?

I want my software to be usable and easily installable - what's the current easiest way to connect a wiimote to the computer?  Can I make that process part of my software installation?

-Adam

Answer:
Coding4Fun had a managed C# library up that would allow you to interface with it but it seems their site is down right now.  Though I think they used the Robotics Studio so that may be a place to start.
Found it...
http://www.codeplex.com/WiimoteLib
Oh and I forgot to post a link to these videos I saw quite some time ago.
http://www.cs.cmu.edu/~johnny/projects/wii/


Question:
Oracle FAQ defines temp table space as follows:

Temporary tablespaces are used to
  manage space for database sort
  operations and for storing global
  temporary tables. For example, if you
  join two large tables, and Oracle
  cannot do the sort in memory, space
  will be allocated in a temporary
  tablespace for doing the sort
  operation.

That's great, but I need more detail about what exactly is using the space. Due to quirks of the application design most queries do some kind of sorting, so I need to narrow it down to client executable, target table, or SQL statement.

Essentially, I'm looking for clues to tell me more precisely what might be wrong with this (rather large application). Any sort of clue might be useful, so long as it is more precise than "sorting".

Answer:
I'm not sure exactly what information you have to hand already, but using the following query will point out which program/user/sessions etc are currently using your temp space.
```
```
SELECT   b.TABLESPACE
       , b.segfile#
       , b.segblk#
       , ROUND (  (  ( b.blocks * p.VALUE ) / 1024 / 1024 ), 2 ) size_mb
       , a.SID
       , a.serial#
       , a.username
       , a.osuser
       , a.program
       , a.status
    FROM v$session a
       , v$sort_usage b
       , v$process c
       , v$parameter p
   WHERE p.NAME = 'db_block_size'
     AND a.saddr = b.session_addr
     AND a.paddr = c.addr
ORDER BY b.TABLESPACE
       , b.segfile#
       , b.segblk#
       , b.blocks;
```
```
Once you find out which session is doing the damage, then have a look at the SQL being executed, and you should be on the right path.


Question:
I have a form that I would like to style. specifcally I would like to chnage the background color of the form item's label. (the backgorundColor attribute changes both the label and the inputs background color)

i.e.

<mx:Form>
    <mx:FormItem label="username:">
        <mx:TextInput />
    </mx:FormItem>
</mx:Form>

I would like to make the label with 'username:' have a different background color, but have the text input still be the default background color.

is this possible with a FormItem ?

Answer:
Try using the flex style explorers to create your desired style:
Flex 3 Style Explorer
Flex 2 Style Explorer
I used the TextArea in the style explorer and formatted the background color which gave the following css output:
```
```
TextArea {
   backgroundColor: #0000ff;
}
```
```
You can change this to the following to include in you stylesheet:
```
```
.formLabel {
   backgroundColor: #0000ff;
}
```
```
Then in the FormItem tag:
```
```
<FormItem label="Label" styleName="formLabel" />
```
```
More info on Flex Style Sheets:
Flex Style Sheets
These examples will show that you can declare styles within the mxml Style tags rather than an external style sheet if you would like.


Question: just wanted to gather different ideas and perspectives as to which layer should (and why) LINQ fall into?

Answer:
I think LINQ should be the very lower-level (DAL) and I think it should be wrapped into a BLL.
I know a lot of people like to use the partial accessibility of the models that LINQ to SQL generates but I think you should have clear separation of interests (see what I did there?).  I think if you're going to have business logic it needs to be decoupled completely from your data access logic.
I think what makes it tricky is the fact that you can keep chaining those LINQ extension methods anywhere you have a using System.Linq line in your code.  Again though I think LINQ belongs with the definition and should be at the lowest possible level.  It also makes TDD/Unit Testing much, much easier when you wrap the usage of LINQ in a BLL.


Question: What is a typical estimate for coding unit tests given an estimate for coding new functionality? Is this different for estimates to maintain code?

Answer:
My time is about equal between time for unit testing and time for functional code.
Some people would look at this and say that is a waste of time, but if your only other option is to run the app and step through all the possible paths the app can take, then the time spent on unit testing is actually less than the time you would spend on developer testing. Of course if you don't do much developer testing, then you will spend the time in fixing bugs that come back from QA.
Either way the time spent writing unit test actually saves time from the amount I would spend on the project.
When it comes time to maintain the code (slight changes, small additions in functionality), there might be a difference. If the code being changed is already fully covered and your changes do not require changes to the tests, then your time is 0. Otherwise obviously it is not, probably closer to equal again.
But, your time savings in testing time is MUCH larger; you've already created the tests to cover the rest of the code, so you would uncover any incidental changes flowing from your change without any new code or walking the app.


Question:
I've got this code:

rs1 = getResults(sSQL1)
rs2 = getResults(sSQL2)

rs1 and rs2 and 2D arrays.  The first index represents the number of columns (static) and the second index represents the number of rows (dynamic).

I need to join the two arrays and store them in rs3.  I don't know what type rs1 and rs2 are though.

Answer:
Are you sure that the columns will match up?  Because if that's not the case I don't know how you'd do it in a generic way in any language.  If it is the case, then you could probably do it
very
simply like this:
```
```
rs1 = getResults(sSQL1 & " UNION " sSQL2)
```
```


Question:
I've discovered that cElementTree is about 30 times faster than xml.dom.minidom and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.

Can it be done?

Answer:
It's not possible AFAIK... which is a pity.  Basically, ElementTree modules assume that the reader is 100% XML compliant, so it shouldn't matter if they output a section as CDATA or some other format that generates the equivalent text.
See
this thread
on the Python mailing list for more info.  Basically, they recommend some kind of DOM-based XML library instead.


Question: I'm specifying my doctype as xhtml strict, but it's being sent over the wire as a content type of text/html.  I'd like to specify that the content type is application/xhtml+xm, but I can't figure out where, or if, I can configure this from within my application

Answer:
You can specify it in the @ page attributes section, like this:
```
```
<%@ Page ContentType="application/xhtml+xm" %>
```
```
...more on
MSDN
.


Question:
How can I get a single keyboard character from the terminal with Ruby without pressing enter?
I tried Curses::getch, but that didn't really work for me.

Answer:
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/2999
```
```
#!/usr/bin/ruby

begin
  system("stty raw -echo")
  str = STDIN.getc
ensure
  system("stty -raw echo")
end
p str.chr
```
```
(Tested on my OS X system, may not be portable to all Ruby platforms). See
http://www.rubyquiz.com/quiz5.html
for some additional suggestions, including for Windows.


Question:
A colleague once told me that the last option when everything has failed to debug on Linux was to use strace.

I tried to learn the science behind this strange tool, but I am not a system admin guru and I didn’t really get results.

So,

What is it exactly and what does it do?

How and in which cases should it be used?

How should the output be understood and processed?

In brief, in simple words, how does this stuff work?

Answer:
strace lists all
system calls
done by the process it's applied to.  If you don't know what system calls mean, you won't be able to get much mileage from it.
Nevertheless, if your problem involves files or paths or environment values, running strace on the problematic program and redirecting the output to a file and then grepping that file for your path/file/env string may help you see what your program is
actually
attempting to do, as distinct from what you expected it to.


Question: Is there any IDE for coding mono on windows platform?

Answer:
SharpDevelop
and Visual Studio will both work. You can also use the Windows version of
MonoDevelop
.


Question:
I create a TextArea in actionscript:

var textArea:TextArea = new TextArea();

I want it to have a black background.  I've tried

textArea.setStyle("backgroundColor", 0x000000);

and I've tried

textArea.opaqueBackground = 0x000000;

but the TextArea stays white.  What should I do?

Answer:
TextArea is a UI component built from TextField and other Flash built-in classes and UIComponents. As with most of the Adobe UI components, nothing is as it seems when setting properties. To set the color of the area behind the text in the TextArea, you need to actually set the opaque background of its internal TextField using the textField property:
```
```
var textArea:TextArea = new TextArea()
textArea.textField.opaqueBackground = 0x000000;
```
```
Of course now that the background is black, the text can't also be black, so we change its color using a new TextFormat:
```
```
var myFormat:TextFormat = new TextFormat();
myFormat.color = 0xffffff;
textArea.setStyle("textFormat",myFormat);
```
```
then just set the text and add to stage:
```
```
textArea.text = "hello";
addChild(textArea);
```
```
Also, if you want a little more control, there's a nice extension class here that fixes a lot of the problems with TextArea:
http://blog.bodurov.com/Post.aspx?postID=14


Question:
I have this solution for a single button:

myButton.Attributes.Add("onclick", "this.disabled=true;" + GetPostBackEventReference(myButton).ToString());

Which works pretty well for one button, any ideas on how to expand this to 2 buttons?

Answer:
You could add an clientside onSubmit handler, or you could do this:
```
```
myButton.Attributes.Add("onclick", "this.disabled=true; document.getElementById('"
+ button2.ClientID + "').disabled = true;"
+ GetPostBackEventReference(myButton).ToString());
```
```


Question:
I could write this, but before I do, I wanted to check to see if there are existing solutions out there since it seems a lot of websites already do this, so I was wondering if there was a quick way to do this.

Also, I am talking about "popout" windows, not "popup" windows.  All JavaScript libraries support "popup" windows, but I want ones where they originally open as "popup" windows in the same browser window, but there is also a link to open them up in a brand new browser window.

Answer:
Check out Cappuccino, it's more of a windowing framework than a web 2.0 framework. It's based off of Apples Cocoa, and uses a Superset of Javascript called Objective-J. Superset meaning that any JS is valid, but it extends on the language with additional syntax that is similar to Cocoa and Objetive-C.
http://cappuccino.org


Question:
I'm trying to host a PHP web site that was given to me.  I see this warning:

Warning: Unknown: Your script possibly
  relies on a session side-effect which
  existed until PHP 4.2.3. Please be
  advised that the session extension
  does not consider global variables as
  a source of data, unless
  register_globals is enabled. You can
  disable this functionality and this
  warning by setting
  session.bug_compat_42 or
  session.bug_compat_warn to off,
  respectively. in Unknown on line 0

What does this mean?  How might I track down the source of this problem within the code?

Answer:
basically you have a variable with the same name as your session. ex:
```
```
$_SESSION['var1'] = null;
$var1 = 'something';
```
```
which will reproduce this error. you can stop PHP from trying to find existing variables and warning you about them by adding these lines to your script:
```
```
ini_set('session.bug_compat_warn', 0);
ini_set('session.bug_compat_42', 0);
```
```
these values can be set in php.ini or .htaccess as well


Question: Is there a portable way of getting thread and/or process identifier (string, int, ...) with C++?

Answer:
You have a few ways, but all imply the use of an external library abstracting the thread for you.
Among the popular choices, two are:
The
Boost.Thread
library. This is the most portable but imply working with Boost, which is a HUGE library
The
Qt
library. This is less portable and imply to work with Qt, a big library.
If you already use any on these two libraries, I would recommend sticking with it. Otherwise, look at what other tools they provide and make a choice.


Question:
I'm doing some research into using log4net, and I found the IObjectRenderer interface interesting.  It would allow us to control how types are logged and provide a different, possibly more user-friendly ToString() implementation.  I just started looking at log4net though, and can't seem to find a logical way to programmatically set up the association between types and renderers.

I found that this can be set up in the XML configuration file by reading the manual, but it didn't give me any hints about programmatically adding these.  It seems to me that you'd rather have a programmatic object renderer in some cases, so I'm curious how to do this.

Answer:
I poked around with it some while writing the question and came up with this:
```
```
using System.IO;
using log4net;
using log4net.Config;
using log4net.ObjectRenderer;
using log4net.Util;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            BasicConfigurator.Configure();

            ILog log = LogManager.GetLogger(typeof(Program));
            var repo = LogManager.GetRepository();
            repo.RendererMap.Put(typeof(Foo), new FooRenderer());

            var fooInstance = new Foo() { Name = "Test Foo" };
            log.Info(fooInstance);
        }
    }

    internal class Foo
    {
        public string Name { get; set; }
    }

    internal class FooRenderer : log4net.ObjectRenderer.IObjectRenderer
    {
        public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer)
        {
            if (obj == null)
            {
                writer.Write(SystemInfo.NullText);
            }

            var fooInstance = obj as Foo;
            if (fooInstance != null)
            {
                writer.Write("", fooInstance.Name);
            }
            else
            {
                writer.Write(SystemInfo.NullText);
            }
        }
    }
}
```
```
I am not certain if this is the correct way to do this, but I do know that it worked.


Question:
For obvious productivity reasons, I make an effort of learning and using as many of the keyboard shortcuts for the various Re# commands.

However, it seems that the unit test runner does not have any associated shortcut keys. I want to be able to select certain tests and be able to run or debug them without resorting to grabbing the mouse each time. Is using the mouse my only option?

Answer:
ReSharper adds items to Visual Studio's keyboard settings dialog box.
Go to:
Tools -> Options, Environment ->
  Keyboard
In the search bar, type "resharper" and see the vast options that you can control with the keyboard.
Specifically, there is one to launch the unit test explorer window, and there's a couple called
ReSharper.ReSharper_UnitTest_RunSolution
ReSharper.ReSharper_UnitTest_RunContext
that are likely what you need.


Question:
I am using SimpleTest, a PHP-based unit testing framework. I am testing new code that will handle storing and retrieving website comments from a database. I am at a loss for how to structure the project to test the database access code.

I am looking for any suggestions as to best practices for testing db code in a PHP application. Examples are really great. Sites for further reading are great.

Thank you kindly. :)

Answer:
I had a local database dedicated to unit testing with a known name and database username/password.  The unit tests were hard-coded to that location but different developers could override those variables if they wanted.
Then before each test you
```
TRUNCATE
```
each table.  This is
much
faster than dropping/creating tables or the database itself.
Note: Do
not
truncate after the tests!  That way if a test fails you have the current state of the database which often helps diagnose the problem.


Question: What function can I use in Excel VBA to slice an array?

Answer:
Application.WorksheetFunction.Index(array, row, column)
If you specify a zero value for row or column, then you'll get the entire column or row that is specified.
Example:
Application.WorksheetFunction.Index(array, 0, 3)
This will give you the entire 3rd column.
If you specify both row and column as non-zero, then you'll get only the specific element.
There is no easy way to get a smaller slice than a complete row or column.
Limitation
: There is a limit to the array size that
```
WorksheetFunction.Index
```
can handle if you're using a newer version of Excel. If
```
array
```
has more than 65,536 rows or 65,536 columns, then it throws a "Type mismatch" error. If this is an issue for you, then see
this more complicated answer
which is not subject to the same limitation.
Here's the function I wrote to do all my 1D and 2D slicing:
```
```
Public Function GetArraySlice2D(Sarray As Variant, Stype As String, Sindex As Integer, Sstart As Integer, Sfinish As Integer) As Variant

' this function returns a slice of an array, Stype is either row or column
' Sstart is beginning of slice, Sfinish is end of slice (Sfinish = 0 means entire
' row or column is taken), Sindex is the row or column to be sliced
' (NOTE: 1 is always the first row or first column)
' an Sindex value of 0 means that the array is one dimensional 3/20/09 ljr

Dim vtemp() As Variant
Dim i As Integer

On Err GoTo ErrHandler

Select Case Sindex
    Case 0
        If Sfinish - Sstart = UBound(Sarray) - LBound(Sarray) Then
            vtemp = Sarray
        Else
            ReDim vtemp(1 To Sfinish - Sstart + 1)
            For i = 1 To Sfinish - Sstart + 1
                vtemp(i) = Sarray(i + Sstart - 1)
            Next i
        End If
    Case Else
        Select Case Stype
            Case "row"
                If Sfinish = 0 Or (Sstart = LBound(Sarray, 2) And Sfinish = UBound(Sarray, 2)) Then
                    vtemp = Application.WorksheetFunction.Index(Sarray, Sindex, 0)
                Else
                    ReDim vtemp(1 To Sfinish - Sstart + 1)
                    For i = 1 To Sfinish - Sstart + 1
                        vtemp(i) = Sarray(Sindex, i + Sstart - 1)
                    Next i
                End If
            Case "column"
                If Sfinish = 0 Or (Sstart = LBound(Sarray, 1) And Sfinish = UBound(Sarray, 1)) Then
                    vtemp = Application.WorksheetFunction.Index(Sarray, 0, Sindex)
                Else
                    ReDim vtemp(1 To Sfinish - Sstart + 1)
                    For i = 1 To Sfinish - Sstart + 1
                        vtemp(i) = Sarray(i + Sstart - 1, Sindex)
                    Next i
                End If
        End Select
End Select
GetArraySlice2D = vtemp
Exit Function

ErrHandler:
    Dim M As Integer
    M = MsgBox("Bad Array Input", vbOKOnly, "GetArraySlice2D")

End Function
```
```


Question:
Consider the following code:

$("a").attr("disabled", "disabled");

In IE and FF, this will make anchors unclickable, but in WebKit based browsers (Google Chrome and Safari) this does nothing. The nice thing about the disabled attribute is that it is easily removed and does not effect the href and onclick attributes.

Do you have any suggestions on how to get the desired result. Answers must be:

Easily be revertable, since I want to disable form input controls while I have an AJAX call running.

Must work in IE, FF, and WebKit

Answer:
I assume that you have an onclick event handler bound to these anchor elements. Just have your event handler check the "disabled" attribute and cancel the event if it is set. Your event handler would look something like this:
```
```
$("a").click(function(event){
  if (this.disabled) {
    event.preventDefault();
  } else {
    // make your AJAX call or whatever else you want
  }
});
```
```
You can also set a stylesheet rule to change the cursor.
```
```
a[disabled=disabled] { cursor: wait; }
```
```
Edit - simplified the "disabled" check as suggested in comments.


Question: We are considering using ClearCase Multisite to enable the offshore development team. The other option is the ClearCase Remote Client using the local (onshore) ClearCase installation. Has anyone had experiences using Multisite? Is the synchronization and management hassle worth offshore being able to use the fat client?

Answer: That is a good question.  I belive it is worth using multisite so long as you can figure out the mastership of elements.  If an element is mastered at site A  you can't edit it at site B until you have transfered the mastership.  So if each site is working on the same pieces of code then multisite is going to be more trouble than it is worth, if the coverage is disjoint then multisite is a good call.  Clearcase is very chatty on the network and keeping as much local as possible is a good idea.


Question:
I use a 3rd party tool that outputs a file in Unicode format.  However, I prefer it to be in ASCII. The tool does not have settings to change the file format.

What is the best way to convert the entire file format using Python?

Answer:
I think this is a deeper issue than you realize
. Simply changing the file from Unicode into ASCII is easy, however, getting all of the Unicode characters to translate into reasonable ASCII counterparts (many letters are not available in both encodings) is another.
This Python Unicode tutorial may give you a better idea of what happens to Unicode strings that are translated to ASCII:
http://www.reportlab.com/i18n/python_unicode_tutorial.html
Here's a useful quote from the site:
Python 1.6 also gets a "unicode"
  built-in function, to which you can
  specify the encoding:
```
```
> >>> unicode('hello') u'hello'
> >>> unicode('hello', 'ascii') u'hello'
> >>> unicode('hello', 'iso-8859-1') u'hello'
> >>>
```
```
All three of these return the same
  thing, since the characters in 'Hello'
  are common to all three encodings.
Now let's encode something with a
  European accent, which is outside of
  ASCII. What you see at a console may
  depend on your operating system
  locale; Windows lets me type in
  ISO-Latin-1.
```
```
> >>> a = unicode('André','latin-1')
> >>> a u'Andr\202'
```
```
If you can't type an acute letter e,
  you can enter the string 'Andr\202',
  which is unambiguous.
Unicode supports all the common
  operations such as iteration and
  splitting. We won't run over them
  here.


Question:
I am trying to create a custom control that a "gridview" like control but specifcally for business objects that implement certain custom interfaces.

In doing this I have come across the following problem.

I have a control that I have disabled viewstate on (and I don't want to re-enable it) and it has a child control that I want viewstate enabled on.  I can't seem to get the viewstate on the child control to work since its parents is disabled.  Does anyone have any ideas of how to get that to work?

Answer:
You cannot enable viewstate on a control which is within another control that has viewstate disabled.
Your only option is to enable it for the outer control, and then turn it off for all of the controls within it, except for the control you need viewstate.
EnableViewState property on any container will override the behavior of all controls within that containter.
Good Luck!
EDIT:
You may want to look at your
CreateChildContols()
method and enumerate the controls disabling viewstate from there for each of the controls within the custom control using the
EnableViewState
property.


Question:
Possible Duplicate:

  Internationalization in SSRS

We use SQL Server Reporting Services for our web reports. At the moment, our clients are all in the UK, so for each report, we set the Language property for the report to "English (United Kingdom)".

But now we have US and French clients. So, we'll need to change the language and currency for the French, and the date format and currency for the Americans. We want to keep one set of reports for all our clients.

What is the best way to do this?

Answer:
The report will be rendered with the web browsers language in regard to formatting of dates, currencies and so on if the report's language has not been set. See
MSDN documentation
:
If the language of the report is not set, the language of the Web browser is used. If the language of the Web browser is not set, the language of the operating system of the report server is used. For example, if you set a specific language on a text box that displays date information, then that text box is always displayed with the date format for that language even if the report, Web browser or server is set to a different language.


Question:
I have a program I've written in VB.NET 2005, it saves statistics in an XML file.

I use this program on multiple computers.   I'd like to set up a webserver where I can upload my XML file, or just the data, and add it to the server ignoring duplicate entries already on the server.

What do I need for to learn for this? SQL?

Any ideas would be appriecated!

Answer:
I did something like this a long time ago to send back HFNetChk XML reports from around the world back to a central server.
I set up a service endpoint on the server (webservice, TCP, whatever fits your req's), and had the client app send the finished XML back to the central server when it was done with its processing.  The webserver would send back a "data received OK" message to let the client know it could move on, and then the server would go about processing the data, and entering it from the XML into a SQL database.
So, to answer your question,
learn how to create a WCF service (aim for webservices for now - ASMX is ok if WCF seems to be too much for now), and learn how to parse the incoming XML and insert it into meaningful SQL tables.
/fark can be useful


Question: What is the best way to get the names of all of the tables in a specific database on SQL Server?

Answer:
```
```
exec sp_msforeachtable 'print ''?'''
```
```


Question:
In few months I start a project in PHP and I am hesitating to do like usual : develop on my Windows Vista 64bits machine. Since I know few things on Linux, I think it can be a good way to learn by working on a Linux distribution.

Do you think it's a good idea or not? I would run a VirtualBox with Ubuntu (on my Vista64bits). I was thinking to install XAMPP to be able to develop in PHP.

If you think it's a good idea, feel free to suggest me some tutorial about what I should know with Virtualizing an OS, or Linux/dev.

Update
I have build many website in PHP with Windows, the question is more about if it's a good way to start learning Linux by developing on it via a Virtual machine? I have 4 gigs rams, will it be smooth if I install Eclipse in the Virtual Machine? etc.

Answer:
PHP
should
be the same on any platform - so
where
you develop shouldn't matter.
However, in my experience and observation,more sites running PHP are running on Linux than Windows.
Getting Apache and PHP setup on something like Ubuntu or Fedora is a cinch, and testing everything is pretty simple, too.
Also, when you go live with your site, what platform will it be running on? I prefer to do development on the platform it will be running on whenever possible.


Question:
How do you prepare your SQL deltas? do you manually save each schema-changing SQL to a delta folder, or do you have some kind of an automated diffing process?

I am interested in conventions for versioning database schema along with the source code. Perhaps a pre-commit hook that diffs the schema?

Also, what options for diffing deltas exist aside from DbDeploy?

EDIT: seeing the answers I would like to clarify that I am familiar with the standard scheme for running a database migration using deltas. My question is about creating the deltas themselves, preferably automatically.

Also, the versioning is for PHP and MySQL if it makes a difference. (No Ruby solutions please).

Answer:
See
Is there a version control system for database structure changes?
How do I version my MS SQL database in SVN?
and Jeff's article
Get Your Database Under Version Control
I feel your pain, and I wish there were a better answer.  This might be closer to what you were looking for.
Mechanisms for tracking DB schema changes
Generally, I feel there is no adequate, accepted solution to this, and I roll my own in this area.


Question:
What are the main reasons for having ridiculously long export times for a simple flash movie to swf? I have no unnecessary images or symbols, everything possible is set to lower than low and it still takes 10 minutes and upwards to export a 30 second animation at 24 fps. I have even created a new fla and pasted everything in there, to find out if it isn't maybe just a bug in flash. All other animations I've exported take a normal amount of time.

System specifications:
1GB DDR2 RAM
Intel Pentium D 3.4GHz

Should I upgrade my system?

Could it have something to do with having many symbols within symbols?

EDIT: Filesize of fla is 1.3 MB and swf is 500 KB. So not too big.

Answer:
unfortunately this is pretty average with flash.
You can check out this post on
actionscript.org
which talks about splitting up your project so save on compile time.
Back in the AS2 days an open source compiler called
MTASC
which dramatically reduced the
compile time
.  It has since turned into
Haxe
with AS2, AS3, Javascript, PHP, and Neko virtual machine all using the same syntax. The syntax used is similar to C++.
** EDIT **
Sorry I read the above as 10 seconds, not 10 minutes... sorry. ^_^


Question:
I have an application where whenever a file is uploaded to a directory, I have to call SSIS to parse the XML file.

Can I call a SSIS directly from a .NET Windows service?

Answer:
Running SSIS package programmatically
.
I prefer the second method:
Start DTEXEC.EXE process. DTEXEC is command line utility for executing SSIS packages. See its command line options here:
http://msdn2.microsoft.com/en-us/library/ms162810.aspx
Benefits: running package out of process gains reliability. Can be used from any programming language (including .NET 1.1 :)). Easy to pass parameters by setting variables values.
Drawbacks: Also local only. Harder to get information about package progress (but SSIS logging can give you most functionality). Some overhead on starting new process (likely minimal compared to execution time for big packages).
ASP.NET specific: Win32 CreateProcess function ignores the thread impersonation. So if you want DTEXEC to run under account different from ASP.NET process account, you should either make user enter name/password and pass it to Process.Start, or use method described in the following KB to run child process under impersonated account
http://support.microsoft.com/kb/889251
.


Question:
I'm trying to write a tennis reservation system and I got stucked with this problem.
Let's say you have players with their prefs regarding court number, day and hour.
Also every player is ranked so if there is day/hour slot and there are several players
with preferences for this slot the one with top priority should be chosen.
I'm thinking about using some optimization algorithms to solve this problem but I'am not sure what would be the best cost function and/or algorithm to use.
Any advice?
One more thing I would prefer to use Python but some language-agnostic advice would be welcome also.
Thanks!

edit:

some clarifications-

the one with better priority wins and loser is moved to nearest slot,
rather flexible time slots question
yes, maximizing the number of people getting their most highly preffered times

Answer:
This is an NP-complete problem, I think, so it'll be impossible to have a very fast algorithm for any large data sets.
There's also the problem where you might have a schedule that is impossible to make. Given that that's not the case, something like this pseudocode is probably your best bet:
```
```
sort players by priority, highest to lowest
start with empty schedule
for player in players:
    for timeslot in player.preferences():
        if timeslot is free:
            schedule.fillslot(timeslot, player)
            break
    else:
        #if we get here, it means this player couldn't be accomodated at all.
        #you'll have to go through the slots that were filled and move another (higher-priority) player's time slot
```
```


Question:
How you fix the following Hibernate error:

What does "Use of the same entity name twice".

Answer:
I think it means you have declared the same entity in more than one configuration file.
Without more information, I would try commenting out chunks of your config file so that you don't see the error, and then slowly adding sections back in until you encounter the error?
If its only a few config files, then why not post them here? When posting, if you add 4 spaces to the front of your XML, then it will be:
```
```
<xml>nicely formatted</xml>
```
```
Hope this helps.


Question:
What are they and how do they work?

Context happens to be SQL Server

Answer:
According to
Wikipedia
:
[...] A traditional pipe is "unnamed" because it exists anonymously and persists only for as long as the process is running. A named pipe is system-persistent and exists beyond the life of the process and must be "unlinked" or deleted once it is no longer being used. Processes generally attach to the named pipe (usually appearing as a file) to perform IPC (inter-process communication).


Question:
I want completely automated integration testing for a Maven project.  The integration tests require that an external (platform-dependent) program is started before running.  Ideally, the external program would be killed after the unit tests are finished, but is not necessary.

Is there a Maven plugin to accomplish this?  Other ideas?

Answer:
You could use the
antrun
plugin. Inside you would use ant's
exec
apply
task.
Something like this.
```
```
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.2</version>
    <executions>
      <execution>
        <phase> <!-- a lifecycle phase --> </phase>
        <configuration>

          <tasks>
            <apply os="unix" executable="cmd">
              <arg value="/c"/>
              <arg value="ant.bat"/>
              <arg value="-p"/>
            </apply>
            <apply os="windows" executable="cmd.exe">
              <arg value="/c"/>
              <arg value="ant.bat"/>
              <arg value="-p"/>
            </apply>
          </tasks>

        </configuration>
        <goals>
          <goal>run</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
```
```
Ant support os specific commands of course through the
condition task
.


Question:
I'm working on a project where I have 2 web services that need the same entity. The 2 web services are on the same server so on the back-end, they share the same classes.

On the front-end side, my code consumes both web services and sees the entities from both services as separate (in different namespaces) so I can't use the entity across both services.

Does anyone know of a way to allow this to work in .NET 2.0?

I've done this with my entity:

[XmlType(TypeName = "Class1", Namespace = "myNamespace")]
public class Class1
{
    public int field;
}

Hoping that my IDE would somehow "know" that the class is the same on both web services so that it wouldn't create separate entities for both classes, but no luck.

Is this possible to do with .NET 2.0 web services?

Answer:
I'm not sure about the implementation details with .NET 2.0, but I believe what you want to do is put the common classes in a seperate XSD file and refer to it from within your two WSDL's. This way, the common types have the same namespace between the two services.
Now, how you do this in .NET 2.0 I couldn't give you the specifics on...


Question:
I have currently 200+ GB database that is using the DB2 built in backup to do a daily backup (and hopefully not restore - lol) But since that backup now takes more than 2.5 hours to complete I am looking into a Third party Backup and Restore utility.  The version is 8.2 FP 14 But I will be moving soon to 9.1 and I also have some 9.5 databases to backup and restore.  What are the best tools that you have used for this purpose?

Thanks!

Answer:
It's not a "third-party" product but anyone that I have ever seen using DB2 is using
Tivoli Storage Manager
to store their database backups.
Most shops will set up archive logging to TSM so you only have to take the "big" backup every week or so.
Since it's also an IBM product you won't have to worry about it working with all the different flavors of DB2 that you have.
The downside is it's an IBM product.  :)   Not sure if that ($) makes a difference to you.


Question: I know I could just ask, but that would involve bureaucratic entanglements.

Answer:
I believe that on an AD network that is DNS enabled the root zone points at all the AD servers.  So, for instance, if your official AD username is joebloe@company.ad, doing an nslookup of company.ad from cmd.exe will tell you all the IPs of the controllers (and hence all the IPs you could use for LDAP).
This is edited to change the zone name, but one my work system:
```
```
C:\Documents and Settings\jj33>nslookup companyname.ad
Server:  palpatine.companyname.ad
Address:  172.19.1.3

Name:  companyname.ad
Addresses:  172.16.3.2, 172.16.6.2, 172.19.1.3, 172.16.7.9
          172.19.1.14, 172.19.1.11
C:\Documents and Settings\jj33>
```
```
On my (XP) machine, this shows me my AD domain:
Right click "My Computer"
Select "Computer Name" tab
See "Domain:" field


Question:
How can I represent the following in XSD.

<price-update>
    <![CDATA[
      arbitrary data goes here
    ]]>
</price-update>

Answer:
A CDATA tag is merely a means of escaping data as a text node.  Therefore you cannot stipulate that you require a CDATA node.
From a DOM perspective, the following documents are identical:
```
```
<doc>value</doc>
```
```
and
```
```
<doc><![CDATA[value]]></doc>
```
```


Question: I'm looking for the class name of the popup/message windows on the iPhone (it's a blueish window that comes up when you have a missed call, or a message comes in for example.)

Answer:
The class is called
```
UIAlertView
```
. From the documentation:
Use the UIAlertView class to display an alert message to the user. An alert view functions similar to but differs in appearance from an action sheet (an instance of UIActionSheet).
Use the properties and methods defined in this class to set the title, message, and delegate of an alert view and configure the buttons. You must set a delegate if you add custom buttons. The delegate should conform to the UIAlertViewDelegate protocol. Use the show method to display an alert view once it is configured.


Question:
This is something that I have never fully grasped in .NET as to the correct application of the .dispose() method.

Say I have something like

Public Class someClass()
  sub someMethod
    ' do some stuff tying up resources
  end sub
End Class

public class mainApp
  dim _class as new SomeClass
  _class.someMethod()
End Class

In all cases is it good practice to implement a dispose method, and if so what should go in there?

If it is not the case that every class should have dispose method (which my gut feeling says the shouldn't) what classes should? I have always thought anything which may tie up a resource (i.e. connection, datareader etc) should have a .dispose() which would unallocate these resources.

Also how would you enforce a calling into calling the .dispose() method?

Answer:
The
```
Dispose()
```
method is used for cleaning up any resources early. Although the garbage collector reclaims any unused memory for you, it's up to you to do deal with things like network/database connections and file handles. Normally, you'd want these things freed up as soon as they're no longer needed, so you implement the disposable pattern and take advantage of the
```
Using
```
statment for calling it within a try/finally block behind the scenes.


Question:
I have a form where controls are dynamically added to a Panel.  However, when they do so, they are many times added below the fold (bottom of the container).  It's nice that the .NET Framework provides this ScrollControlIntoView method, however, for added usability, it would also be nice if there was an easy way to animate so that it is easy for the user to understand that the Panel was automatically scrolled.

Has anyone ever encountered this or have any ideas as to how to tackle it?

Answer:
The
```
Dispose()
```
method is used for cleaning up any resources early. Although the garbage collector reclaims any unused memory for you, it's up to you to do deal with things like network/database connections and file handles. Normally, you'd want these things freed up as soon as they're no longer needed, so you implement the disposable pattern and take advantage of the
```
Using
```
statment for calling it within a try/finally block behind the scenes.


Question: c# windows forms: How do you create new settings at run time so that they are permanently saved as Settings.Default.-- values?

Answer: Since the Settings class is generated at build time (or, actually, whenever you update the settings file from within the designer), you can't use this mechanism for dynamic scenarios. You can, however, add some collection or dictionary to the application settings and modify that dynamically.


Question: I'm hoping there's something in the same conceptual space as the old VB6 IsNumeric() function?

Answer:
Try the
isNan function
:
The isNaN() function determines whether a value is an illegal number (Not-a-Number).
This function returns true if the value equates to NaN. Otherwise it returns false.
This function is different from the Number specific
Number.isNaN()
method.
The global isNaN() function, converts the tested value to a Number, then tests it.
Number.isNan() does not convert the values to a Number, and will not return true for any value that is not of the type Number...


Question:
I want to allocate a 2 D Array in Java Script.

I want do some thing similar to this in JavaScript

typedef struct
{
   int  itemA,
   int  itemB,
   string testC
} myStruc;

myStruct MyArray [100];

How to do this ?

Answer:
There are  a few ways of creating arrays in Javascript, the method closest to what you want to do should be:
```
```
var myArray = new Array("someString1", "someString2", "someString3", ...);
```
```
You can replace
```
"someString1"
```
with actual objects.
You can also use the Array constructor to set up the initial length:
```
```
var myArray = new Array(5);
myArray[0] = ...;
myArray[1] = ...;
```
```
Arrays in Javascript are pretty loose actually - you don't even need to define the length before you access an element that would normally be outside the bounds of the array.
Take a look at
the Mozilla documentation on Arrays
.


Question: When using the .NET WebBrowser control how do you open a link in a new window using the the same session (ie.. do not start a new ASP.NET session on the server), or how do you capture the new window event to open the URL in the same WebBrowser control?

Answer:
I just spent an hour looking for the answer, so I though I would post the results here. You can use the SHDocVwCtl.WebBrowser_V1 object to capture the NewWindow event.
NOTE: Code from
http://www.experts-exchange.com/Programming/Languages/Visual_Basic/Q_21484555.html#discussion
```
```
//-------------------------------VB.NET Version:-------------------------------

Dim WithEvents Web_V1 As SHDocVwCtl.WebBrowser_V1

Private Sub Form_Load()
    Set Web_V1 = WebBrowser1.Object
End Sub

Private Sub Web_V1_NewWindow(ByVal URL As String, ByVal Flags As Long, ByVal TargetFrameName As String, PostData As Variant, ByVal Headers As String, Processed As Boolean)
    Processed = True
    WebBrowser1.Navigate URL
End Sub

//-------------------------------C# Version-------------------------------

private SHDocVw.WebBrowser_V1 Web_V1; //Interface to expose ActiveX methods

private void Form1_Load(object sender, EventArgs e)
{
    //Setup Web_V1 interface and register event handler
    Web_V1 = (SHDocVw.WebBrowser_V1)this.webBrowser1.ActiveXInstance;
    Web_V1.NewWindow += new SHDocVw.DWebBrowserEvents_NewWindowEventHandler(Web_V1_NewWindow);
}

private void Web_V1_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData,string Headers, ref bool Processed)
{
    Processed = true; //Stop event from being processed

    //Code to open in same window
    this.webBrowser1.Navigate(URL);

    //Code to open in new window instead of same window
    //Form1 Popup = new Form1();
    //Popup.webBrowser1.Navigate(URL);
    //Popup.Show();
}
```
```


Question:
How do you protect your commercial application from being installed on multiple computers from people who only own one license?

Do you think it's a good idea to have more than just a serial based scheme?

Answer:
You can always use a USB dongle if the software is worth it. Of course, all dongle manufacturers claim that their copy protection cannot be broken.
The advantage of this method is that it allows the user to use the software on multiple computers, but only run on one at a time, and it is actually not such hassle like some sort of product activation. The disadvantage, of course, is that you cannot deploy your application completely electronically. Even though you might think the opposite, actually many customers seem to accept the use of a dongle, at least in the field I work in. It's especially useful if you expect your customers to use (and also install!) the software in a place where no internet connection is available.
Edit: I overread the serial-based thing in the original question. Note that even that may annoy users more than having to put in a dongle, and it's easier for you too because neither the customer nor you have to deal with that numbers. Plug in the dongle and the app works. However, the serial-only method is by far the cheapest.


Question:
It appears that our implementation of using Quartz - JDBCJobStore along with Spring, Hibernate and Websphere is throwing unmanaged threads.

I have done some reading and found a tech article from IBM stating that the usage of Quartz with Spring will cause that.  They make the suggestion of using CommnonJ to address this issue.

I have done some further research and the only examples I have seen so far all deal with the plan old JobStore that is not in a database.

So, I was wondering if anyone has an example of the solution for this issue.

Thanks

Answer:
We have a working solution for this (two actually).
1) Alter the quartz source code to use a WorkManager daemon thread for the main scheduler thread.  It works, but requires changing quarts.  We didn't use this though since we didn't want maintain a hacked version of quartz.  (That reminds me, I was going to submit this to the project but completely forgot)
2) Create a WorkManagerThreadPool to be used as the quartz threadpool.  Implement the interface for the quartz ThreadPool, so that each task that is triggered within quartz is wrapped in a commonj Work object that will then be scheduled in the WorkManager.  The key is that the WorkManager in the WorkManagerThreadPool has to be initialized before the scheduler is started, from a Java EE thread (such as servlet initialization).  The WorkManagerThreadPool must then create a daemon thread which will handle all the scheduled tasks by creating and scheduling the new Work objects.  This way, the scheduler (on its own thread) is passing the tasks to a managed thread (the Work daemon).
Not simple, and unfortunately I do not have code readily available to include.


Question:
I have a few databases that I always use SQL Server Management Studio with. I'd like to be able to create a toolbar button or keyboard shortcut that automatically opens a new query window (in the current SSMS instance) and connects to a given (registered, perhaps) database.  That's it.  That's all I need.  And this ashtray, and the paddle game, and the remote control.  That's all I need.

As it is now, I have to expand the Object Explorer, collapse/expand two to eight trees, right-click on my database, and choose "New Query".  I see no way to do it, this would probably save me 30-60 seconds a day.

Answer:
You could create a shortcut to launch SQL Server Management studio using command line parameters, as follows:
SQLWB.EXE
- launches SQL Server Management Studio from the Command Prompt or Start -> Run text box. Through its switches, you can specify which type of server (-t S, -t A, or -t C for SQL Server, Analysis Server, or SQL Server Mobile Edition, respectively), server name (-S), and database (-d) you want to connect to, provide authentication information, or designate which queries, projects, or solutions to open (-i filename). The defaults (in absence of switches) are defined in the Tools -> Options menu of the SQL Server Management Studio.
[Source]


Question:
I am currently trying to import a semi-colon delimited text file into a database in c# using OleDb where I don't know the type (SQL Server, Access, Oracle, MySQL, postgreSQL, etc.)  Currently I'm reading in the file as a database using the Jet text reader then creating a prepared insert statement, populating the fields, then commiting at the end.  While that works, it's slow and for millions of rows, it takes way too long.

So my question:  Does anybody have any other thoughts on how to best import a text file to a generic database, or comments on my approaches that will lead to a faster import?

I cannot use 3rd party libraries or software to do this as it is part of a larger project

Answer:
Your best bet is to buy an off the shelf application for doing this.
Professional Off The Shelf applications use native drivers and fine tune for each type of datasource they will hit against.  This is always under the covers so you don't see how they go about it.  For example, bulkcopy is used against SQL Server; Oracle has a Data Pump.
The problem with rolling your own is that you can either spend the money to fine tune your application to work with each of the source types you're likely to encounter OR you take a huge performance hit by using the generic ODBC / ADO / Whatever drivers.
At the end of the day, you are better off either leaving this out of your product or just dealing with the inevitable slow approach that you are forced to take.  In this case that means using single insert statements for everything.
So, how much money do you have for development resources?


Question:
List<tinyClass> ids = new List<tinyClass();
ids.Add(new tinyClass(1, 2));

bool b = ids.IndexOf(new tinyClass(1, 2)) >= 0; //true or false?

If it compares by value, it should return true; if by reference, it will return false.

If it compares by reference, and I make tinyClass a struct - will that make a difference?

Answer:
From MSDN:
This method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list.
The Default property checks whether type T implements the System.IEquatable<T> generic interface and if so returns an EqualityComparer<T> that uses that implementation. Otherwise it returns an EqualityComparer<T> that uses the overrides of Object.Equals and Object.GetHashCode provided by T.
It seems like it uses the Equals method, unless the stored class implements the IEquatable<T> interface.


Question:
How can I have a dynamic variable setting the amount of rows to return in SQL Server? Below is not valid syntax in SQL Server 2005+:

DECLARE @count int
SET @count = 20

SELECT TOP @count * FROM SomeTable

Answer:
```
```
SELECT TOP (@count) * FROM SomeTable
```
```
This will only work with SQL 2005+


Question: I have a .net project (MySolution.Common) that uses the app.config. I am using the project MySolution.Common in an InteropUserControl project called MySolution.InteropCtrl. MySolution.InteropCtrl is embedded into a VB6 project. When the MySolution.InteropCtrl is in the VB6 project, It cannot find the app.config file. Everything in the InteropControl works in VB6 except for what depends on the information in the app.config file. What do I need to change so the MySolution.InteropCtrl can see the app.config file while in VB6?

Answer:
I'm not 100% sure on this.  But I'll throw out some possibilities.  First of all, app.config is not the correct name for the file.  While it is app.config in your project, it gets auto-renamed to
binary
.exe.config or
binary
.dll.config (depending on project type) where
binary
is the name of the project.
Secondly, I'm not 100% sure if dll.config files are always properly loaded and read by .NET when the application loads.  I don't believe it happens automatically, and that there is an extra call you have to make to read the config file if its for the dll.  If you reneame the config file to match your exe, then it will definitely load and be available to you.


Question:
After making some changes in my models (eg. new field in a model and a new model) what is the best way of reflecting these changes to my populated database?

PS: I wanted to see many solutions in one place rated. Apparently more solutions are already listed here.

Answer:
Depends on the scope of the changes.  If it's beyond an ALTER, you're doing major surgery.  Make backups of model as well as database so you can go back.
My preference is to put your new (revised, corrected, expanded) model in as a NEW application.  It won't have URL's or anything, just a model.
Creating the new model as a new application.  Create tests, just to be sure it works.
syncdb to build this interim implementation of the new model.
Write a little one-time utility to query your old model, and load your new model.  You might want to try this in pure SQL.  I prefer to write a simple query, build and save loop.
After the new model is loaded, you can dump this to a JSON file.
Once you've pulled the data out of your old model, you can rebuild your DB in the preferred new format.
Move the new model into your existing application.
Drop the old versions of the application's tables.
syncdb to build the new tables.
Load the JSON file with the data.


Question:
When setting up a Home Directory on IIS6 properties for a web site there's an option to "Index this resource" which is checked on by default.

Microsoft's site says:

Grant this
  permission to allow Microsoft Indexing
  Service to include this folder in a
  full-text index of the Web site. When
  you grant this permission, users can
  perform queries on this resource.

Can someone give me more information on when you would check this option on? What sort of queries would a user perform on this resource? What are the pro's and con's of having this set to on/off for a web site?

Answer:
This is for using the indexing service which used to drive the Search. I don't think anyone uses this anymore. It's pretty intensive against the HD. Check to see if the indexing service is even enabled on your server. We would disable by default.
If you open the indexing service mmc there will be a system and a web scope. Checking this box would add the web site to the web scope. If you were writing your own search algorithm, you would write a search query against the Web scope. Since it's 2008, you will use Google.


Question: I'm trying to access the Reporting Services via Web Services in my Visual Studio 2008 Application.  How/where can I find my WSDL?

Answer:
The following example shows the format of the URL to the Reporting Services management WSDL file:
http://server/reportserver/ReportService2005.asmx?wsdl


Question:
Is it possible to open an HTML page using navigateToURL and specifying a named frame in your HTML document? For instance, if you have an iframe on the page called "Steven", can you call

navigateToURL("someURL","Steven");

instead of something like

navigateToURL("someURL","_self");

I have tried this and it opens the URL in a new window.

Answer:
I'm not sure, but you can use JavaScript:
```
```
navigateToURL("javascript:loadFrame(someURL)");
```
```
Then in your HTML page:
```
```
function loadFrame(url) {
  documents.frames[1].src=url
}
```
```


Question:
I need to be able to validate a string against a list of the possible United States Postal Service state abbreviations, and Google is not offering me any direction.

I know of the obvious solution: and that is to code a horridly huge if (or switch) statement to check and compare against all 50 states, but I am asking StackOverflow, since there has to be an easier way of doing this. Is there any RegEx or an enumerator object out there that I could use to quickly do this the most efficient way possible?

[C# and .net 3.5 by the way]

List of USPS State Abbreviations

Answer:
Here's a regex.  Enjoy!
```
```
^(?-i:A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$
```
```


Question:
The project I'm on is using a 3rd party component to build dynamic PDFs in a VB.Net web system called ABCpdf.Net.  (not a terrible tool, but not a great one either.)

Every now and then, for reasons I can't fathom, the document object throws a SEHException.  Digging futher, it turns out this is caused by a custom exception in the document object of the type WebSupergoo.ABCpdf6.Internal.PDFException.  The contents contains only the not -terribly-helpful title "Unable to get image data. Out Of Memory" Usually this happens when trying to add an image to the PDF.  Since these images are PNGs of less than 100k, I'm guessing their size isn't the issue.

Also, the really strange thing is that once this issue starts happening, the only way to get it to stop seems to be to reboot the web server, which is clearly a little sub-par.

Has anyone ever had this problem (or even used this tool?)

Answer:
I haven't specifically seen this error before, but we've had memory issues with ABC PDF before.
Long story short is that it is NOT a completely managed code base, but simply a .NET wrapper around their COM version.  That being said, we traced our memory usage problem to not disposing of their objects properly.
So, instead of:
```
```
Dim doc As New Doc()
'etc...
```
```
do this:
```
```
Dim doc as Doc
    Using doc As New Doc()
      'etc...
    End Using
```
```


Question:
New school datastore paradigms like Google BigTable and Amazon SimpleDB are specifically designed for scalability, among other things. Basically, disallowing joins and denormalization are the ways this is being accomplished.

In this topic, however, the consensus seems to be that joins on large tables don't necessarilly have to be too expensive and denormalization is "overrated" to some extent
Why, then, do these aforementioned systems disallow joins and force everything together in a single table to achieve scalability? Is it the sheer volumes of data that needs to be stored in these systems (many terabytes)?

Do the general rules for databases simply not apply to these scales?
Is it because these database types are tailored specifically towards storing many similar objects?

Or am I missing some bigger picture?

Answer:
I'm not too familiar with them (I've only read the same blog/news/examples as everyone else) but my take on it is that they chose to sacrifice a lot of the normal relational DB features in the name of scalability - I'll try explain.
Imagine you have 200 rows in your data-table.
In google's datacenter, 50 of these rows are stored on server A, 50 on B, and 100 on server C. Additionally server D contains redundant copies of data from server A and B, and server E contains redundant copies of data on server C.
(In real life I have no idea how many servers would be used, but it's set up to deal with many millions of rows, so I imagine quite a few).
To "select * where name = 'orion'", the infrastructure can fire that query to all the servers, and aggregate the results that come back. This allows them to scale pretty much linearly across as many servers as they like (FYI this is pretty much what mapreduce is)
This however means you need some tradeoffs.
If you needed to do a relational join on some data, where it was spread across say 5 servers, each of those servers would need to pull data from eachother
for each row
. Try do that when you have 2 million rows spread across 10 servers.
This leads to tradeoff #1 - No joins.
Also, depending on network latency, server load, etc, some of your data may get saved instantly, but some may take a second or 2. Again, when you have dozens of servers, this gets longer and longer, and the normal approach of 'everyone just waits until the slowest guy has finished' no longer becomes acceptable.
This leads to tradeoff #2 - Your data may not always be immediately visible after it's written.
I'm not sure what other tradeoffs there are, but off the top of my head those are the main 2.


Question: There are tons of free wysiwyg editors you can embed in web pages. I'm looking for something that is easiest to embed into an adobe air app. Means something that works in webkit and is easy to get the content from with javascript.

Answer:
TinyMCE
is nice. It's quite popular, even used with the
Symfony PHP framework
. Not sure how it will work out with AIR, but chances are really good. Works with Chrome & Safari like a charm.
EDIT: ... and there's also a
lightweight jQuery editor plug-in
. And the
wmd editor from Attacklab
(WYSIWYM) that is used here, on StackOverflow.


Question:
Is it possible to create an STL-like container, or even just an STL-style iterator, for an existing array of POD-type elements?

For example, suppose I have an array of ints.  It would be convenient to be able to call some of the STL functions, such as find_if, count_if, or sort directly on this array.

Non-solution: copying the entire array, or even just references to the elements.  The goal is to be very memory- and time-saving while hopefully allowing use of other STL algorithms.

Answer:
You can use
Boost.Array
to create a C++ array type with STL semantics.
using arrays:
```
```
int a[100];
for (int i = 0; i < 100; ++i)
    a[i] = 0;
```
```
using boost.arrays:
```
```
boost::array<int,100> a;
for (boost::array<int,100>::iterator i = a.begin(); i != a.end(); ++i)
    *i = 0;
```
```
Update:
With C++11, you can now use
```
std::array
```
.


Question:
In most modern IDEs, you can have Debug and Release build configurations, and you can quickly switch between them.

In Delphi 7, this does not seem to be possible. I have to go to Project Settings and toggle optimization and all the debug information stuff manually.

It would be great if there was a plugin or some such that handled this for me.

Does anyone know of one? Any other suggestions?

Edit: I can't upgrade to Delphi 2007 or 2009 as we have a large Delphi 7 codebase which would have to be converted. I agree that would be the best solution in theory though :P

Answer:
I don't know of any build-configurations plugin for Delphi 7, but you could however simulate this;
Just apply an include-file in every unit of your project(s) (which is a smart thing to do anyways) and let it adjust itself to one single define, like this :
--- ExampleIncludeFile.inc ---
```
```
{$IFDEF DEBBUG}

{$OPTIMIZATION OFF}
{$RANGECHECKING ON}
// etc

{$ELSE}

{$OPTIMIZATION ON}
{$RANGECHECKING OFF}

{$ENDIF}
```
```
Now, if you add DEBUG to the Compiler defines in your .dof project settings, you'll get a Debug-build, and if you remove it, you get a release build. Other setups are entirely possible too ofcourse.
Delphi 2005 does have Build Configurations embedded in the Project Manager (Release and Debug only), and Delphi 2009 add even more to this, with nice little things like 'Option sets' and custom 'Configurations' (that you could even mark as Default for all new projects). Give it a look, it's a really great product!


Question:
I need to find a good Lua to JavaScript converter; lua2js on luaforge.org is out of date (3 or so years old and looks like it doesn't work on Lua 5.1) and I haven't yet found anything on Google.

Does anyone have any experience with any other converters out there? It should work on Lua 5.1 and preferably be .NET based, but .NET is not a requirement.  A javascript lua interpreter would work as well.

Answer:
This is a recurrent question on the Lua list, i guess because of the superficial similarity of the two languages.
Unfortunately, there are many important differences that are not so obvious.  Making it work need either a full-blown compiler targeting JS instead of Lua's bytecode, or rewriting the Lua VM in JavaScript.
I don't know the original goals of Lua2js; but if it was simply a limited 'translator', then writing Lua code intended to be translated would deny most (all?) of the nice things about Lua.  For instance, i don't think you could use a function as a table key, since in JavaScript the keys are only strings (and numbers? i'm not sure).
The .NET choice is more reasonable, it could be done changing the existing compiler to emit CLR bytecode instead of standard Lua bytecode.  Even if CLR is designed and optimised for other kind of languages, it's definitely generic enough to run very well.  The main hurdle would be the availability of libraries.
Another option I just found is
this paper
by Roberto Ierusalmschy and Fabio Mascarenhas, where they explore translating LuaVM bytecode into CLR bytecode.
As is usual on academic papers, there's no indication about the date when it was written, so i have no idea if it's new and revolutionary or old and forgotten.


Question:
Is it possible to suppress warnings in Eclipse for JDK1.4 project?

EDIT:
Longer version. There is a project which requires JDK1.4 (no annotations). Only way of suppressing warnings I know is using annotation @SuppressWarnings - no can do in JDK1.4. Is there any way to remove some warning notifications in some specific method/class (not whole project) ?

Answer: Setting the compiler to 1.4 compliance in the properties of the project should do the trick. Just right click your project and select "Properties" at the bottom and then search for "Compiler".


Question:
Im looking for a method (or function) to strip out the domain.ext part of any URL thats fed into the function. The domain extension can be anything (.com, .co.uk, .nl, .whatever), and the URL thats fed into it can be anything from http://www.domain.com to www.domain.com/path/script.php?=whatever

Whats the best way to go about doing this?

Answer:
You can use
parse_url()
to do this:
```
```
$url = 'http://www.example.com';
$domain = parse_url($url, PHP_URL_HOST);
$domain = str_replace('www.','',$domain);
```
```
In this example, $domain should contain example.com, irrespective of it having www or not. It also works for a domain such as .co.uk


Question:
I've tried these, and they did not work (Access opens, but it does not wait:

start "C:\program files\Microsoft Office\Office\MSACCESS.EXE" filename.mdb

start /WAIT "C:\program files\Microsoft Office\Office\MSACCESS.EXE" filename.mdb

start /W "C:\program files\Microsoft Office\Office\MSACCESS.EXE" filename.mdb

start filename.mdb

start msaccess.exe filename.mdb

Answer:
```
```
start /WAIT msaccess.exe filename.mdb
```
```
does the trick.
I don't know why adding the full path makes it fail.


Question:
I would like to make the update of the web application as automated as possible.

I'm looking for a tool that can compare two instances of a database and generate an update script for me. As part of the build process create a instance of the last version of the database (ie currently in production) and compare that to what has been changed on the development version.

Any input is appreciated.

Answer:
See
Mechanisms for tracking DB schema changes
I believe the
profluence
of this question on SO speaks to the lack of a standard solution to this problem.
The great divide in approach is
- write delta scripts
- automate script generation from a "master" instance
It sounds like you want something in the latter camp.
Several such solutions and tools are noted in the above question.


Question:
Is there a way to get the SearchPath API to not search in c:\windows when using the default search path (passing NULL as the first param)? I can't modify the caller to send in a specific path.

I have a system with an application ini file in c:\windows (which I don't want it to use, but for legacy reasons has to remain there). I put my copy of the same ini file in c:\users\public, and put c:\users\public at the front of my system path environment variable, but a call to SearchPath still finds the c:\windows version. If I delete that version, it then finds the c:\users\public version, so I know the path was set correctly.

Answer:
According to
MSDN
, there's nothing you can do about this bar changing a system level (HKLM) registry entry (Which is a "bad thing"). The registry change would cause the search order to start with the current working directory, which you could set to the desired folder in a shortcut. (Again, I'm going to say; changing a Machine Level registry entry to do this - is potentially dangerous!)
Have you looked into
application shims
? This may be something that could work for you.


Question:
Perl 6 seems to have an explosion of equality operators. What is =:=? What's the difference between leg and cmp? Or eqv and ===?

Does anyone have a good summary?

Answer:
=:=
tests if two containers (variables or items of arrays or hashes) are aliased, ie if one changes, does the other change as well?
```
```
my $x;
my @a = 1, 2, 3;
# $x =:= @a[0] is false
$x := @a[0];
# now $x == 1, and $x =:= @a[0] is true
$x = 4;
# now @a is 4, 2, 3
```
```
As for the others:
===
tests if two references point to the same object, and
eqv
tests if two things are structurally equivalent. So
```
[1, 2, 3] === [1, 2, 3]
```
will be false (not the same array), but
```
[1, 2, 3] eqv [1, 2, 3]
```
will be true (same structure).
```
leg
```
compares strings like Perl 5's
```
cmp
```
, while Perl 6's
```
cmp
```
is smarter and will compare numbers like
```
<=>
```
and strings like
```
leg
```
.
```
```
13 leg 4   # -1, because 1 is smaller than 4, and leg converts to string
13 cmp 4   # +1, because both are numbers, so use numeric comparison.
```
```
Finally
```
~~
```
is the "smart match", it answers the question "does
```
$x
```
match
```
$y
```
". If
```
$y
```
is a type, it's type check. If
```
$y
```
is a regex, it's regex match - and so on.


Question:
I read some of the answers on here re: testing views and controllers, and mocking, but I still can't figure out how to test an ASP.NET MVC controller that reads and sets Session values (or any other context based variables.)
How do I provide a (Session) context for my test methods? Is mocking the answer? Anybody have examples?
Basically, I'd like to fake a session before I call the controller method and have the controller use that session. Any ideas?

Answer:
The ASP.NET MVC framework is not very mock-friendly (or rather, requires too much setup to mock properly, and causes too much friction when testing, IMHO) due to it's use of abstract base classes instead of interfaces.  We've had good luck writing abstractions for per-request and session-based storage. We keep those abstractions very light and then our controllers depend upon those abstractions for per-request or per-session storage.
For example, here's how we manage the forms auth stuff. We have an ISecurityContext:
```
```
public interface ISecurityContext
{
    bool IsAuthenticated { get; }
    IIdentity CurrentIdentity { get; }
    IPrincipal CurrentUser { get; set; }
}
```
```
With a concrete implementation like:
```
```
public class SecurityContext : ISecurityContext
{
    private readonly HttpContext _context;

    public SecurityContext()
    {
        _context = HttpContext.Current;
    }

    public bool IsAuthenticated
    {
        get { return _context.Request.IsAuthenticated; }
    }

    public IIdentity CurrentIdentity
    {
        get { return _context.User.Identity; }
    }

    public IPrincipal CurrentUser
    {
        get { return _context.User; }
        set { _context.User = value; }
    }
}
```
```


Question:
Suppose I have a set of values, stored in a std::set:

{1, 2, 6, 8}

and I have a search key, say, 3. I want to put 3 into a function and get the first value greater than or equal to 3, in this case I would want to get 6.

The find() function provided in map/set/multimap/and set will, of course, return the end iterator for this case. Is there a similar function to find that would return 6 in this case?

Answer:
You want the
upper_bound
function.
```
```
map<int, int> mymap = { 1,2,6,8 };
map<int,int>::iterator i = mymap.upper_bound(3); // returns an iterator to the '6' element.
```
```


Question:
A question about different methods of outputting html from PHP; what are the performance differences between these:

Method 1 - variable concatenation

$html = '';
$html .= '<ul>';
for ($k = 1; $k < = 1000; $k++){
    $html .= '<li> This is list item #'.$k.'</li>';
}
$html .= '</ul>';
echo $html;

Method 2 - output buffering

ob_start();
echo '<ul>';
for ($k = 1; $k < = 1000; $k++){
    echo '<li> This is list item #',$k,'</li>';
}
echo '</ul>';

I suspect you get some performance hit from continually modifying and enlarging a variable; is that correct?

Cheers!

Thanks GaryF, but I don't want an answer about architecture - this question is about performance. There seem to be some different opinions / testing about which one is faster, which is why there is not an accepted answer as yet.

Answer:
I typically use method #1 so I can put that HTML any where in a template file that contains static HTML. I try to keep as much HMTL out of my PHP. It makes for much cleaner and shorter PHP, as the template is usually a separate file.
Regarding speed/performance, I'm thinking the difference will be very minor. With output buffering, it's also enlarging a variable all the time, although that variable isn't accessible, but it has to be stored somewhere.
I have often wondered if open and closing
```
<?php
```
is slower than just putting it all inside
```
<?php
```
and then echo'ing all at once.
I think in the end we are talking milliseconds in extremely complex scripts.
Oh yeah, method #1 is a lot more flexible as you can
```
echo $html;
```
anywhere.


Question:
I have a filter in a combobox with a number of entries. Instead of filtering the datagrid with an exact match, I would like to take the selected value and only display records where the selected value is contained in the datafield.
For example: the user selects a value of "New" and the datagrid displays records where the contents of the record could be "New User", "New Person", "This one is New" etc.
I think that I need to use RegExp, but I cant work out how to get it to work.
Thanks in advance,
S...

Answer:
Something like this should work:
```
```
public function filter(item:Object):Boolean{
        var result:Boolean=false;
        if (item.name.toUpperCase().indexOf(cbo.selectedLabel.toUpperCase()) >= 0)
             result=true;
        return result;
 }
```
```
This filter function will search the name attribute(or whatever you want to filter on) of the object passed in with the combobox's currently selected label and if it finds that value it will return true.  So if it finds the word "New" anywhere in the string it will show up in the datagrid. IE: "New Person", "New User" will both show up once filtered.
Hope this is what you are looking for.


Question:
Why do I get compiler errors with this Java code?

1  public List<? extends Foo> getFoos()
2  {
3    List<? extends Foo> foos = new ArrayList<? extends Foo>();
4    foos.add(new SubFoo());
5    return foos;
6  }

Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface.

Errors I get with this code:

On Line 3: "Cannot instantiate ArrayList<? extends Foo>"

On Line 4: "The method add(capture#1-of ? extends Foo) in the type List<capture#1-of ? extends Foo> is not applicable for the arguments (SubFoo)"

Update: Thanks to Jeff C, I can change Line 3 to say "new ArrayList<Foo>();".  But I'm still having the issue with Line 4.

Answer:
Use this instead:
```
```
1  public List<? extends Foo> getFoos()
2  {
3    List<Foo> foos = new ArrayList<Foo>(); /* Or List<SubFoo> */
4    foos.add(new SubFoo());
5    return foos;
6  }
```
```
Once you declare foos as
```
List<? extends Foo>
```
, the compiler doesn't know that it's safe to add a SubFoo. What if an
```
ArrayList<AltFoo>
```
had been assigned to
```
foos
```
? That would be a valid assignment, but adding a SubFoo would pollute the collection.


Question:
Our system dynamically generates a large report by converting many HTML pages into a single PDF.  The resulting PDF is sent back (via the HTTP request) to the calling browser. When the report is sufficiently large (200+ pages) IE 7 intermittently chokes.  The result issue is the calling PC locks up and must be rebooted.  When using an alternative browser such as Mozilla Firefox (run on the same PC) executes the report, all works properly w/out any issues.

Any ideas or workarounds (other than to tell the user to use Firefox)?

Answer:
I beleive there are a few ways you can do this:
1)  Stream the pdf binary data to the browser and change the mime type so the browser handles it as pdf, or
2)  Stream the pdf bindara data to the broswer using the "attachment;file=" header which will cause the browser to give you the option of opening or saving the file.
The second option may solve your problem with the intermittent choking of the browser, although it is not as seamless as the first option and may not be the exact behaviour you want.


Question:
I have a image upload form that should take image types (PNG, JPEG, GIF), resize it and then save it to a path.

For some reason I can't get the PNG file types to work, it works fine with JPEG/GIF and the file is copied so it looks like it's something to do with how I'm creating the PNG.

Does PNG creation in PHP require different parameters or options?  Some sample code of lines that do image creation:

$src = imagecreatefrompng($uploadedfile);
imagecreatetruecolor($newWidth,$newHeight)
imagecopyresampled($tmp,$src,0,0,0,0,$newWidth,$newHeight,$width,$height);
imagepng($tmp,$destinationPath."/".$destinationFile,100);

The same commands work for JPG and GIF.

Answer:
You need to look how your PHP is built..   Eg:
```
```
GD Support  enabled
GD Version  bundled (2.0.28 compatible)
PNG Support     enabled
```
```
If you don't have PNG support compiled in, you'll need to have that updated.


Question:
What is meant by nvarchar?

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

Answer:
nchar and char pretty much operate in exactly the same way as each other, as do nvarchar and varchar. The only difference between them is that nchar/nvarchar store Unicode characters (essential if you require the use of extended character sets) whilst varchar does not.
Because Unicode characters require more storage, nchar/nvarchar fields take up twice as much space (so for example in earlier versions of SQL Server the maximum size of an nvarchar field is 4000).
This question is a duplicate of
this one
.


Question:
In the Google C++ Style Guide, there's a section on Operator Overloading that has a curious statement:

Overloading also has surprising
  ramifications. For instance, you can't
  forward declare classes that overload
  operator&.

This seems incorrect, and I haven't been able to find any code that causes GCC to have a problem with it. Does anyone know what that statement is referring to?

Answer:
Edited to account for comments:
This is a guess, but one of the main reasons to forward declare is to be able to declare pointers to that class.  The compiler has to make assumptions about the class before having the definition - for example, the size of pointers.
Is it possible to change the size of T* by overloading operator& for a T? (EDIT: Commentors -- and I think not) -- but
What assumption is violated by overloading operator& -- how does it change the class?
Here is one way.
I could write:
```
```
class A;

void f(A& x) {
    A* xPointer = &x;
}
```
```
That has a new meaning if operator&() is overloaded than if not, and the compiler may think it can generate code for it, but it would be wrong.


Question:
I'm writing an article about editing pages in order to hand pick what you really want to print. There are many tools (like "Print What you like") but I also found this script. Anyone knows anything about it? I haven't found any kind of documentation or references.

javascript:document.body.contentEditable='true'; document.designMode='on'; void 0

Thanks!

Answer:
document.designMode is supported in IE 4+ (which started it apparently) and FireFox 1.3+.
You turn it on and you can edit the content right in the browser, it's pretty trippy.
I've never used it before but it sounds like it would be pretty perfect for hand picking printable information.
Edited to say:  It also appears to work in Google Chrome.  I've only tested it in Chrome and Firefox, as those are the browsers in which I have a javascript console, so I can't guarantee it works in Internet Explorer as I've never personally used it.  My understanding is that this was an IE-only property that the other browsers picked up and isn't currently in any standards, so I'd be surprised if Firefox and Chrome support it but IE stopped.


Question:
I run into this quite often where a new page is supposedly "tested" and ready to go. But as soon as I change the page from http to https (secure) mode I get the "This page contains both secure and nonsecure items." error.

Usually I can find the problem and fix it pretty quick. Today is different. I've checked every image reference and every javascript reference and their source and haven't found anything that should be causing this error.

Are there any developer tools or techniques that can point out specifically what is causing this error?

Answer:
If you're in Firefox you can use Tools -> Page Info -> Media, then just scan down the list to find the non-https link. There might also be JavaScript building dynamic
```
<script>
```
tags, or CSS including non-secure elements.


Question:
VBA solutions can vary widely in size.

I would like to add user help documentation to all solutions but the level of effort to create and deploy the help needs to match the size of the solution.

Answer:
You should check the
VBA version of MZ-Tools
. It is an add-in for VBA that can automatically generate documentation from your code (function name, parameters, comments, subject, etc.). You can also use it to automatically generate line numbers, onError labels, etc. More on the automatic documenting feature can be found
here
.
It is free, easy, and very efficient. Once you notice how much you save time by using it, please do like me: donate.


Question: What's the best way to perform a deep copy in the constructor of an object that is part of multi-threaded C++ code?

Answer:
My first impulse (I'm not an expert):
Have a lock on that object that the code uses for writing to it. When you're deep copying, lock the object, perform your deep copy, and then unlock it.
Or, am I missing something here?


Question: What is the easiest way to do this? Is it possible with managed code?

Answer:
```
```
this.BackgroundImage = //Image
this.FormBorderStyle = FormBorderStyle.None;
this.Width = this.BackgroundImage.Width;
this.Height = this.BackgroundImage.Height;
this.TransparencyKey = Color.FromArgb(0, 255, 0); //Contrast Color
```
```
This allows you to create a form based on an image, and use transparency index to make it seem as though the form is not rectangular.


Question:
I'm writing a .NET forms control to edit HTML using MSHTML.  I am creating some custom elements and want to make them effectively read-only.  I thought I could go about this by focusing on the entire element any time focus entered anywhere in that element but the HtmlElement.Focus() doesn't select the entire element and I don't seem to be able to capture entry of the cursor.

Another option would be to raise an event whenever the text of the element is changed (on KeyDown I expect) but I can't get that event to fire, either.  Any ideas about why my expectations about event behavior is wrong or alternate suggestions for implementation?

Answer:
In case you are trying to apply readonly behavior to an User Input control, you can try using @readonly attribute of that control. Otherwise you could also add event listeners for appropriate UI events (keydown, mousedown) and prevent their default behavior (return false, or event.returnValue = false). As for custom events dispatch, you can indeed do that. Use event name that is known to IE. And another hint could be: register an onchange event handler and revert value of control to the value of defaultValue (property of any input controls).
Hope some of ideas will help.


Question:
I have a VB6 project in Visual Source Safe 6.0. When I open the project I want to Check Out (Get) all the files in the project so that I can edit them.

I have the VSS Options (within VB6) set to act on the Project recursively, but when I check out the project.vbp it only checks out the project file, not all the modules, etc.  Those files all remain write protected until I individually check out each one.

Answer:
SOLUTION
: Select the
Project.vbp
and, from the Tool>SourceSafe menu choose Check Out, you get a dialog which lets you choose ALL files (you get a checkbox for each and a button for Select All).
Why I had problems
For some reason, if you
right-click
on the Project in the Project tree and choose Check Out it doesn't give you that dialog. It just checks out the Project file. (However, if you do the same thing and Check In, it gives you the dialog with the checkboxes for each file. I guess that that point it
knows
that you have more than one file to check in.


Question:
I have an ASP.NET linkbutton control on my form. I would like to use it for javascript on the client side and prevent it from posting back to the server. (I'd like to use the linkbutton control so I can skin it and disable it in some cases, so a straight up  tag is not preferred).

How do I prevent it from posting back to the server?

Answer:
In C#, you'd do something like this:
```
```
MyButton.Attributes.Add("onclick", "put your javascript here including... return false;");
```
```


Question:
I have taken a copy of a database home with me so I can do some testing. However when I try to run a stored procedure I get Cannot open user default database. Login failed..

I have checked and checked and checked I can open tables in the databases login to sql management studio and access the default as well as other databases any ideas?

Possibly a corrupt user it was from sql 2000 at work to 2005 at home

Answer:
EDIT:
Mine was from 2005 to 2005. Not sure if this will work for your case...
I had a similar problem. For me, when I detach or create a back up and then re-create the database, it will loose connection to users. User I've been using is still there under Login but it would fail to log in.
In my case, I was able to log in by deleting the User under the database -> security -> users, not the user that's in the root sql server users list.
Then go to root users list and reassign database mapping or create user if not exists.
Hope this helps.