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


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

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

s: huggingface

c: devops

d: intermediate


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

[A]
```
```
SELECT TOP (@count) * FROM SomeTable
```
```
This will only work with SQL 2005+


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


q:
What is meant by nvarchar?

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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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

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

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

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

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

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


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

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


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

[A]
Running a jar is as simple as
```
```
java -jar filename.jar
```
```


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

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

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


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

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


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

Property Group

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

Task

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

Output

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

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

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

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

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


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

So I tried following inline function:

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

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

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


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

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


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

I have installed to C:\PHP

set PHPRC = C:\PHP\php.ini

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

in php.ini, uncommented the line

extension=php_curl.dll

extension_dir="C:\PHP\ext"

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

C:\PHP is in PATH

still getting

Fatal error: Call to undefined function curl_init()

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


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

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

For example:

Łódź  =>  Lodz

Assunção  =>  Assuncao

Schloß  =>  Schloss

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

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

thanks.

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


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

Thanks!

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


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

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

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

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


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

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

Looking for the programmatic equivalent of what process explorer does.

Most likely this will require interop.

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

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


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

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

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

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

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


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

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

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

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


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


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

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

Apply Themes Programattically

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

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

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


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

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

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

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


q:
Possible Duplicate:

  Unit Testing C Code

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

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

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

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

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

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


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

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

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

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

Any suggestions would be most welcome!

Many thanks,
Mike

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


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

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


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

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

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

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

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


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

For example, I started off with this:

Dim nodes As List(Of String)

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

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

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


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

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

Update:

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

[A]
what about this:
```
```
import win32api

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


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

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

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


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

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

Update: Moved the distracting parts to another question.

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


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

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


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

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

Edit:
I tried this:

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

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

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


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

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

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


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

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


q:
const static int foo = 42;

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

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


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

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

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


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

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

How can I avoid this?

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


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

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


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

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

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

N.times do
    ...
end

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

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

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

...

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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

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

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

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


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

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

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


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

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

throw a SecurityException 'Request failed'.

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

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


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

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

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


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

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


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

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


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

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

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

Is it right ?

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

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


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

To this end, I have the following line:

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

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

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


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

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

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

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

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


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

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


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

Normally it would be like this:

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

The /i flag would be for case-insensitive.

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

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

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

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

How can I achieve this?

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

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

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


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

my $name = getpwuid($uid);

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

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

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


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

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

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

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