Question:
List of macOS text editors and code editors | I searched for this and found [Maudite's](https://stackoverflow.com/users/1632/maudite) question about [text editors](https://stackoverflow.com/questions/14155/text-editors#14203) but they were all for Windows.

As you have no doubt guessed, I am trying to find out if there are any text/code editors for the Mac besides what I know of. I'll edit my post to include editors listed.

### Free

1. [Textwrangler](http://www.barebones.com/products/textwrangler/)
2. [Xcode](https://developer.apple.com/xcode/)
3. [Mac Vim](https://github.com/macvim-dev/macvim)
4. [Aquamacs](http://aquamacs.org/) and closer to the original [EMacs](http://homepage.mac.com/zenitani/emacs-e.html)
5. [JEdit](http://www.jedit.org/)
6. [Editra](http://editra.org/)
7. [Eclipse](https://www.eclipse.org/)
8. [NetBeans](https://netbeans.org/kb/articles/mac.html)
9. [Kod](http://kodapp.com/)
10. [TextMate2](https://github.com/textmate/textmate#readme) - GPL
11. [Brackets](http://brackets.io/)
12. [Atom.io](https://atom.io/)

### Commercial

1. [Textmate](https://macromates.com/)
2. [BBEdit](http://www.barebones.com/products/bbedit/)
3. [SubEthaEdit](http://www.codingmonkeys.de/subethaedit/)
4. [Coda](http://www.panic.com/coda/)
5. [Sublime Text 2](http://www.sublimetext.com/2)
6. [Smultron](http://smultron.sourceforge.net/)
7. [WebStorm](http://www.jetbrains.com/webstorm/)
8. [Peppermint](http://osxpeppermint.com)

### Articles related to the subject

1. [Faceoff, which is the best text editor ever?](http://mac360.com/index.php/mac360/comments/faceoff_which_is_the_best_text_editor_ever/)
2. [Maceditors.com, mac editors features compared](http://maceditors.com)

Thank you everybody that has added suggestions.


Question: Why are there so few modal-editors that aren't vi*? | Pretty much every other editor that isn't a vi descendant (vim, cream, vi-emu) seems to use the emacs shortcuts (`ctrl`+`w` to delete back a word and so on)


Question:
How to make a tree in C++? | How do I make a tree data structure in C++ that uses iterators instead of pointers? I couldn't find anything in the STL that can do this. What I would like to do is to be able to create and manipulate trees like this:

```
#include <iostream>
#include <tree>
using namespace std;

int main()
{
    tree<int> myTree;

    tree<int>::iterator i = myTree.root();
    *i = 42;

    tree<int>::iterator j = i.add_child();
    *j = 777;
    j = j.parent();

    if (i == myTree.root() && i == j) cout << "i and j are both pointing to the root\n";

    return 0;
}

```

---

Thank you, tree.hh seems to be just what I was looking for.

>
> If this is for gaining the benefit of
>  a data-structure holding arbitrary
>  index types, optimized for searching
>  and good at insertion then consider
>  using a map.
>
>
> A map is an associative container that
>  has performance guarantees identical
>  to those of a tree: logarithmic
>  searching, logarithmic insertion,
>  logarithmic deletion, linear space.
>  Internally they are often implemented
>  as red-black trees, although that is
>  not a guarantee. Still, as an STL user
>  all you should care about is the
>  performance guarantees of the STL
>  algorithms and data-structures.
>  Whether they're implemented as trees
>  or little green men shouldn't matter
>  to you.
>
>
>

I'm not sure if a map is what I need, but thanks for the info. I will remember to use maps whenever possible instead of implementing trees.


Question: PHP4 to PHP5 Migration | What are some good steps to follow for a smooth migration from PHP4 to PHP5. What are some types of code that are likely to break?


Question:
Setting an ASP.NET Master Page at runtime | I'm working on a site which needs to be able to support two or more looks, changable at runtime. I'd hoped to be able to handle the change with a CSS switch, but it looks like I'll need to use a different masterpage for each design.

So, what's the best way to set the masterpage at runtime? Page.MasterPageFile can only be set in the Page.OnPreInit event. It looks like the solutions are to make all my pages inherit from a common base which handles the PreInit event, or to use an HttpModule which does that.

Any advice?


Question: Graph serialization | I'm looking for a simple algorithm to 'serialize' a directed graph. In particular I've got a set of files with interdependencies on their execution order, and I want to find the correct order at compile time. I know it must be a fairly common thing to do - compilers do it all the time - but my google-fu has been weak today. What's the 'go-to' algorithm for this?


Question:
How best to use File Version and Assembly Version? | In .NET there are two version numbers available when building a project, File Version and Assembly Version. How are you using these numbers? Keeping them the same? Auto-incrementing one, but manually changing the other?

Also what about the `AssemblyInformationalVersion` attribute?

I'd found this support Microsoft Knowledge Base (KB) article that provided some help: [How to use Assembly Version and Assembly File Version](http://support.microsoft.com/kb/556041).


Question:
Audio player on Windows Mobile | I'm trying to develop specialized audio player for windows mobile devices (Professional ones). And I've ran into the problem an once.

There no compressed audio APIs on WM or I was unable to found house in documentation. Yes there are WM6 Sound API but it cannot even pause playback or seek to specified position. There are allways Windows Media Player on WM device but I've not found it APIs documentation.

So the question is:

Is there simple way to play, pause, forward, rewind, getting playback position and getting audio file length on *compressed* audio of several popular formats? Any library? platform APIs? Anything?


Question:
C# Include Derived Control in Toolbox | This is in reference to my other question [Auto Clearing Textbox](https://stackoverflow.com/questions/16110/c-auto-clearing-winform-textbox).

If I choose to derive a new TextBox control from TextBox instead of implement a user control just containing my Textbox, how would I include that in the toolbox.


Question:
Being as DRY as possible in a Ruby on Rails App | I'm currently using the awesome attachment-fu plugin for a Rails app, but as a novice developer, I've never encountered a scenario like the one I've found myself in.

Essentially, I'm using the attachment-fu plugin on two levels.

1. Is for user avatars in the user class.
2. Is to allow file attachments (***PDFs***, etc) in a messaging system.

My question is what the best use practice would be in these situations to remain ***DRY***, clear, and consistent.

Clearly it would make no sense to define and execute the plugin in both classes, but there's something deeply strange to me (possibly unfounded) about just going ahead and setting it all up in the godly Application class.

Is there something in between, or is the parent class the way to go?

Thanks!


Question: How do I retrieve my MySQL username and password? | I lost my MySQL username and password. How do I retrieve it?


Question:
Calling Table-Valued SQL Functions From .NET | Scalar-valued functions can be called from .NET as follows:

```
SqlCommand cmd = new SqlCommand("testFunction", sqlConn); //testFunction is scalar
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("retVal", SqlDbType.Int);
cmd.Parameters["retVal"].Direction = ParameterDirection.ReturnValue;
cmd.ExecuteScalar();
int aFunctionResult = (int)cmd.Parameters["retVal"].Value;

```

I also know that table-valued functions can be called in a similar fashion, for example:

```
String query = "select * from testFunction(param1,...)"; //testFunction is table-valued
SqlCommand cmd = new SqlCommand(query, sqlConn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(tbl);

```

My question is, can table-valued functions be called as stored procedures, like scalar-valued functions can? (e.g., replicate my first code snippet with a table-valued function being called and getting the returned table through a ReturnValue parameter).


Question:
If you have a Java application that is consuming CPU when it isn't doing anything, how do you determine what it is doing? | I am calling a vendor's Java API, and on some servers it appears that the JVM goes into a low priority polling loop after logging into the API (CPU at 100% usage). The same app on other servers does not exhibit this behavior. This happens on WebSphere and Tomcat. The environment is tricky to set up so it is difficult to try to do something like profiling within Eclipse.

Is there a way to profile (or some other method of inspecting) an existing Java app running in Tomcat to find out what methods are being executed while it's in this spinwait kind of state? The app is only executing one method when it gets in this state (vendor's method). Vendor can't replicate the behavior (of course).

---

Update:

Using JConsole I was able to determine who was running and what they were doing. It took me a few hours to then figure out why it was doing it. The problem ended up being that the vendor's API jar that was being used did not match exactly to the the database configuration that it was using. It was defaulting to having tracing and performance monitoring enabled on the servers that had the slight mis-match in configuration. I used a different jar and all is well.

So thanks, Joshua, for your answer. JConsole was extremely easy to setup and use to monitor an existing application.

@Cringe - I did some experimenting with some of the options you suggested. I had some problems with getting JProfiler set up, it looks good (but pricey). Going forward I went ahead and added the Eclipse Profiler plugin and I'll be looking over the different open source profilers to compare functionality.


Question:
How to parse XML using vba | I work in VBA, and want to parse a string eg

```
<PointN xsi:type='typens:PointN'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
    <X>24.365</X>
    <Y>78.63</Y>
</PointN>

```

and get the X & Y values into two separate integer variables.

I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in.

How do I do this?


Question:
Detecting audio silence in WAV files using C# | I'm tasked with building a .NET client app to detect silence in a WAV files.

Is this possible with the built-in Windows APIs? Or alternately, any good libraries out there to help with this?


Question:
Mapping values from two array in Ruby | I'm wondering if there's a way to do what I can do below with Python, in Ruby:

```
sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))

```

I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.


Question:
Browse for a directory in C# | How can I present a control to the user that allows him/her to select a directory?

There doesn't seem to be any native .net controls which do this?


Question:
How to return a page of results from SQL? | Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results.

What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user?

Does LINQ simplify the solution?


Question:
How to load plugins in .NET? | I'd like to provide some way of creating dynamically loadable plugins in my software.
Typical way to do this is using the [LoadLibrary](http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx) WinAPI function to load a dll and calling [GetProcAddress](http://msdn.microsoft.com/en-us/library/ms683212(VS.85).aspx) to get an pointer to a function inside that dll.

My question is how do I dynamically load a plugin in C#/.Net application?


Question:
How do I split a delimited string so I can access individual items? | Using SQL Server, how do I split a string so I can access item x?

Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"?


Question: What's the best online payment processing solution? | Should be available to non-U.S. companies, easy to setup, reliable, cheap, customizable, etc. What are your experiences?


Question: How do you configure VS2008 to only open one webserver in a solution with multiple projects? | Starting with 2005, VS started this behavior of when starting debugging session it spawns up a webserver for every project in a solution. I have a solution with 15 projects so it takes a while and is a waste of resources. Is there a way to configure it differently besides just using IIS?


Question: How to host a WPF form in a MFC application | I'm looking for any resources on hosting a WPF form within an existing MFC application. Can anyone point me in the right direction on how to do this?


Question:
Fonts on the Web | The collection of fonts available to a web developer is depressingly limited. I remember reading long ago about TrueDoc, as a way of shipping fonts alongside a website - but it seems to have languished. Has anybody used this, or something similar? Is it supported by enough browsers? Am I missing a good solution?

Note that a responsible web developer does not use fonts that are only available on Windows (and *especially* ones that are only available on Vista), nor do they use a technology that isn't supported by at least the majority of browsers.

---

**Update:** As several people have pointed out, there's nothing wrong with providing a list of fallback fonts for people who don't have the specific font you use. I do in fact always do this, and didn't mean to suggest that this was wrong.

While my question was badly phrased, what I meant was that a designer should not make too many assumptions about what the client will have available. You should plan for how all users will see your site, not just for people using your own preferred setup.


Question:
Regex: To pull out a sub-string between two tags in a string | I have a file in the following format:

```

Data Data
Data
[Start]
Data I want
[End]
Data

```

I'd like to grab the `Data I want` from between the `[Start]` and `[End]` tags using a Regex. Can anyone show me how this might be done?


Question:
Privatizing a BlogEngine.Net Installation | I have a blogengine.net install that requires privatization.

I'm doing research work at the moment, but I have to keep my blog/journal private until certain conditions are met.

How can I privatize my blogEngine.net install so that readers must log in to read my posts?


Question:
HowTo Disable WebBrowser 'Click Sound' in your app only | The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus.

Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta.

```
using System;
using Microsoft.Win32;

namespace HowTo
{
    class WebClickSound
    {
        /// <summary>
        /// Enables or disables the web browser navigating click sound.
        /// </summary>
        public static bool Enabled
        {
            get
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
                string keyValue = (string)key.GetValue(null);
                return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\"";
            }
            set
            {
                string keyValue;

                if (value)
                {
                    keyValue = "%SystemRoot%\\Media\\";
                    if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0)
                    {
                        // XP
                        keyValue += "Windows XP Start.wav";
                    }
                    else if (Environment.OSVersion.Version.Major == 6)
                    {
                        // Vista
                        keyValue += "Windows Navigation Start.wav";
                    }
                    else
                    {
                        // Don't know the file name so I won't be able to re-enable it
                        return;
                    }
                }
                else
                {
                    keyValue = "\"\"";
                }

                // Open and set the key that points to the file
                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
                key.SetValue(null, keyValue,  RegistryValueKind.ExpandString);
                isEnabled = value;
            }
        }
    }
}

```

Then in the main form we use the above code in these 3 events:

* Activated
* Deactivated
* FormClosing

```
private void Form1_Activated(object sender, EventArgs e)
{
    // Disable the sound when the program has focus
    WebClickSound.Enabled = false;
}

private void Form1_Deactivate(object sender, EventArgs e)
{
    // Enable the sound when the program is out of focus
    WebClickSound.Enabled = true;
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // Enable the sound on app exit
    WebClickSound.Enabled = true;
}

```

The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that.

What do you guys think? Is this a good solution? What improvements can be made?


Question:
Using Visual Studio to develop for C++ for Unix | Does anyone have battle stories to share trying to use Visual Studio to develop applications for Unix? And I'm not talking using .NET with a Mono or Wine virtual platform running beneath.

Our company has about 20 developers all running Windows XP/Vista and developing primarily for Linux & Solaris. Until recently we all logged into a main Linux server and modified/built code the good old fashioned way: Emacs, Vi, dtpad - take your pick. Then someone said, "hey - we're living in the Dark Ages, we should be using an IDE".

So we tried out a few and decided that Visual Studio was the only one that would meet our performance needs (yes, I'm sure that IDE X is a very nice IDE, but we chose VS).

The problem is, how do you setup your environment to have the files available locally to VS, but also available to a build server? We settled with writing a Visual Studio plugin - it writes our files locally and to the build server whenever we hit "Save" and we have a bit fat "sync" button that we can push when our files change on the server side (for when we update to the latest files from our source control server).

The plugin also uses Visual Studio's external build system feature that ultimately just ssh's into the build server and calls our local "make" utility (which is Boost Build v2 - has great dependency checking, but is *really* slow to start as a result i.e. 30-60 seconds to begin). The results are piped back into Visual Studio so the developer can click on the error and be taken to the appropriate line of code (quite slick actually). The build server uses GCC and cross-compiles all of our Solaris builds.

But even after we've done all this, I can't help but sigh whenever I start to write code in Visual Studio. I click a file, start typing, and VS chugs to catch up with me.

Is there anything more annoying than having to stop and wait for your tools? Are the benefits worth the frustration?

Thoughts, stories, help?


Question: What is the best way to copy a database? | When I want to make a copy of a database, I always create a new empty database, and then restore a backup of the existing database into it. However, I'm wondering if this is really the least error-prone, least complicated, and most efficient way to do this?


Question:
Is there a way to make a constructor only visible to a parent class in C#? | I have a collection of classes that inherit from an abstract class I created. I'd like to use the abstract class as a factory for creating instances of concrete implementations of my abstract class.

Is there any way to hide a constructor from all code except a parent class.

I'd like to do this basically

```
public abstract class AbstractClass
{
    public static AbstractClass MakeAbstractClass(string args)
    {
        if (args == "a")
            return new ConcreteClassA();
        if (args == "b")
            return new ConcreteClassB();
    }
}

public class ConcreteClassA : AbstractClass
{
}

public class ConcreteClassB : AbstractClass
{
}

```

But I want to prevent anyone from directly instantiating the 2 concrete classes. I want to ensure that only the MakeAbstractClass() method can instantiate the base classes. Is there any way to do this?

**UPDATE**

I don't need to access any specific methods of ConcreteClassA or B from outside of the Abstract class. I only need the public methods my Abstract class provides. I don't really need to prevent the Concrete classes from being instantiated, I'm just trying to avoid it since they provide no new public interfaces, just different implementations of some very specific things internal to the abstract class.

To me, the simplest solution is to [make child classes as samjudson mentioned](https://stackoverflow.com/questions/20185/is-there-a-way-to-make-a-constructor-only-visible-to-a-parent-class-in-c#20200). I'd like to avoid this however since it would make my abstract class' file a lot bigger than I'd like it to be. I'd rather keep classes split out over a few files for organization.

I guess there's no easy solution to this...


Question:
Content Management system recommendations | Management is thinking of changing out Content Management Systems. What do you use/recommend?

1. What UCM solution is your company using?
2. How big is your company?
3. Are you happy with the implementation?

Current setup:

1. The company I work for uses `Oracle ECM` (formerly Stellent UCM).
2. We have somewhere over 10,000 employees across Australia, New
Zealand and Indonesia.
3. It works! Having worked with the system for a while now. I can see
where the initial implementation went wrong. Its 3 years later and
it is *Rewrite Time!* (Three year itch?)


Question:
What are good regular expressions? | I have worked for 5 years mainly in java desktop applications accessing Oracle databases and I have never used regular expressions. Now I enter Stack Overflow and I see a lot of questions about them; I feel like I missed something.

For what do you use regular expressions?

P.S. sorry for my bad english


Question:
How do you get sudo access for a file inside the vi text editor? | Often while editing config files, I'll open one with vi and then when I go to save it realize that I didn't type

```
sudo vi filename

```

Is there any way to give vi sudo privileges to save the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it.


Question:
LINQ to SQL strings to enums | LINQ to SQL allows table mappings to automatically convert back and forth to Enums by specifying the type for the column - this works for strings or integers.

Is there a way to make the conversion case insensitive or add a custom mapping class or extenstion method into the mix so that I can specify what the string should look like in more detail.

Reasons for doing so might be in order to supply a nicer naming convention inside some new funky C# code in a system where the data schema is already set (and is being relied upon by some legacy apps) so the actual text in the database can't be changed.


Question:
Faster way to find duplicates conditioned by time | In a machine with AIX without `PERL` I need to filter records that will be considered duplicated if they have the same id and if they were registered between a period of four hours.

I implemented this filter using `AWK` and work pretty well but I need a solution much faster:

```

# Generar lista de Duplicados
awk 'BEGIN {
FS=","
}
/OK/ {
    old[$8] = f[$8];
    f[$8] = mktime($4, $3, $2, $5, $6, $7);
    x[$8]++;
}
/OK/ && x[$8]>1 && f[$8]-old[$8]

Any suggestions? Are there ways to improve the environment (preloading the file or someting like that)?

The input file is already sorted.

With the corrections suggested by [jj33](https://stackoverflow.com/questions/6475/faster-way-to-find-duplicates-conditioned-by-time#6869) I made a new version with better treatment of dates, still maintaining a low profile for incorporating more operations:

awk 'BEGIN {
    FS=",";
    SECSPERMINUTE=60;
    SECSPERHOUR=3600;
    SECSPERDAY=86400;
    split("0 31 59 90 120 151 181 212 243 273 304 334", DAYSTOMONTH, " ");
    split("0 366 731 1096 1461 1827 2192 2557 2922 3288 3653 4018 4383 4749 5114 5479 5844 6210 6575 6940 7305", DAYSTOYEAR, " ");
}
/OK/ {
    old[$8] = f[$8];
    f[$8] = mktime($4, $3, $2, $5, $6, $7);
    x[$8]++;
}
/OK/ && x[$8]>1 && f[$8]-old[$8]  2 ) && ( ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0) ) ) {
        d2m = d2m + 1;
    }
    d2y = DAYSTOYEAR[ y - 1999 ];
    return ss + (mm*SECSPERMINUTE) + (hh*SECSPEROUR) + (d*SECSPERDAY) + (d2m*SECSPERDAY) + (d2y*SECSPERDAY);
}
'

```


Question:
ILMerge and Web Resources | We're attemtping to merge our DLL's into one for deployment, thus ILMerge. Almost everything seems to work great. We have a couple web controls that use `ClientScript.RegisterClientScriptResource` and these are 404-ing after the merge (These worked before the merge).

For example one of our controls would look like

```
namespace Company.WebControls
{
  public class ControlA: CompositeControl, INamingContainer
  {
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        this.Page.ClientScript.RegisterClientScriptResource(typeof(ControlA), "Company.WebControls.ControlA.js");
    }
  }
}

```

It would be located in Project WebControls, assembly Company.WebControls. Underneath would be ControlA.cs and ControlA.js. ControlA.js is marked as an embedded resource. In the AssemblyInfo.cs I include the following:

```
[assembly: System.Web.UI.WebResource("Company.WebControls.ControlA.js", "application/x-javascript")]

```

After this is merged into CompanyA.dll, what is the proper way to reference this web resource? The ILMerge command line is as follows (from the bin directory after the build): `"C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../CompanySK.snk /wildcards:True /copyattrs:True /out:Company.dll Company.*.dll`


Question:
Default Internet connection on Dual LAN Workstation | I know this is not programming directly, but it's regarding a development workstation I'm setting up.

I've got a Windows Server 2003 machine that needs to be on two LAN segments at the same time. One of them is a 10.17.x.x LAN and the other is 10.16.x.x

The problem is that I don't want to be using up the bandwidth on the 10.16.x.x network for internet traffic, etc (this network is basically only for internal stuff, though it does have internet access) so I would like the system to use the 10.17.x.x connection for anything that is external to the LAN (and for anything on 10.17.x.x of course, and to only use the 10.16.x.x connection for things that are on *that* specific LAN.

I've tried looking into the windows "route" command but it's fairly confusing and won't seem to let me delete routes tha tI believe are interfering with what I want it to do. Is there a better way of doing this? Any good software for segmenting your LAN access?


Question:
Capture MouseDown event for .NET TextBox | Is there any way to capture the MouseDown even from the .NET 2.0 TextBox control?
I know the inherited Control class has the event, but it's not exposed in TextBox.
Is there a way to override the event handler?

I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what I do, it doesn't fire the handler.

Any suggestions?

---

>
> What kind of crazy mobile device do
>  you have that has a mouse? :)
>
>
>

Yes, windows mobile does not have an actual mouse, but you are mistaken that Windows Mobile .NET do not support the Mouse events. A click or move on the screen is still considered a "Mouse" event. It was done this way so that code could port over from full Windows easily. And this is not a Windows Mobile specific issue. The TextBox control on Windows does not have native mouse events either. I just happened to be using Windows Mobile in this case.

Edit: And on a side note...as Windows Mobile is built of the WindowsCE core which is often used for embedded desktop systems and Slim Terminal Services clients or "WinTerms" it has support for a hardware mouse and has for a long time. Most devices just don't have the ports to plug one in.

---

>
> According to the .Net Framework, the
>  MouseDown Event Handler on a TextBox
>  is supported. What happens when you
>  try to run the code?
>
>
>

Actually, that's only there because it inherits it from "Control", as does *every* other Form control. It is, however, overridden (and changed to private I believe) in the TextBox class. So it will not show up in IntelliSense in Visual Studio.

However, you actually can write the code:

```
textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown);

```

and it will compile and run just fine, the only problem is that textBox1\_MouseDown() will not be fired when you tap the TextBox control. I assume this is because of the Event being overridden internally. I don't even want to change what's happening on the event internally, I just want to add my own event handler to that event so I can fire some custom code as you could with any other event.


Question:
How to filter and combine 2 datasets in C# | I am building a web page to show a customer what software they purchased and to give them a link to download said software. Unfortunately, the data on what was purchased and the download information are in separate databases so I can't just take care of it with joins in an SQL query.

The common item is SKU. I'll be pulling a list of SKUs from the customer purchases database and on the download table is a comma delineated list of SKUs associated with that download. My intention, at the moment, is to create from this one datatable to populate a `GridView`.

Any suggestions on how to do this efficiently would be appreciated. If it helps, I can pretty easily pull back the data as a `DataSet` or a `DataReader`, if either one would be better for this purpose.


Question:
Annotating YouTube videos programmatically | I want to be able to display a normal YouTube video with overlaid annotations, consisting of coloured rectangles for each frame. The only requirement is that this should be done programmatically.

YouTube has annotations now, but require you to use their front end to create them by hand. I want to be able to generate them. What's the best way of doing this?

Some ideas:

>
> 1. Build your own Flash player (ew?)
> 2. Somehow draw over the YouTube Flash player. Will this work?
> 3. Reverse engineer & hijack YouTube's annotation system. Either messing with the local files or redirecting its attempt to download
>  the annotations. (using Greasemonkey? Firefox plugin?)
>
>
>

Idea that doesn't count:

>
> download the video
>
>
>


Question:
Unit test execution speed (how many tests per second?) | What kind of execution rate do you aim for with your unit tests (# test per second)? How long is too long for an individual unit test?

I'd be interested in knowing if people have any specific thresholds for determining whether their tests are too slow, or is it just when the friction of a long running test suite gets the better of you?

Finally, when you do decide the tests need to run faster, what techniques do you use to speed up your tests?

*Note: integration tests are obviously a different matter again. We are strictly talking unit tests that need to be run as frequently as possible.*

---

**Response roundup:** Thanks for the great responses so far. Most advice seems to be don't worry about the speed -- concentrate on quality and just selectively run them if they are too slow. Answers with specific numbers have included aiming for <10ms up to 0.5 and 1 second per test, or just keeping the entire suite of commonly run tests under 10 seconds.

Not sure whether it's right to mark one as an "accepted answer" when they're all helpful :)


Question:
Developing addins for World of Warcraft - Getting started? | As a long time World of Warcraft player, and a passionate developer I have decided that I would like to combine the two and set about developing some addins. Not only to improve my gameplay experience but as a great opportunity to learn something new.

Does anyone have any advice on how to go about starting out?

Is there an IDE one can use? How does one go about testing? Are there any ready made libraries available? Or would I get a better learning experience by ignoring the libraries and building from scratch? How do I oneshot Hogger?

Would love to hear your advice, experiences and views.


Question:
How is the HTML on this site so clean? | I work with C# at work but dislike how with webforms it spews out a lot of JavaScript not including the many lines for viewstate that it creates.

That's why I like coding with PHP as I have full control.

But I was just wondering how this sites HTML is so clean and elegant?

Does using MVC have something to do with it? I see that JQuery is used but surely you still use asp:required validators? If you do, where is all the hideous code that it normally produces?

And if they arent using required field validators, why not? Surely it's quicker to develop in than using JQuery?

One of the main reasons I code my personal sites in PHP was due to the more elegant HTML that it produces but if I can produce code like this site then I will go full time .net!


Question:
Why did the width collapse in the percentage width child element in an absolutely positioned parent on Internet Explorer 7? | I have an absolutely positioned `div` containing several children, one of which is a relatively positioned `div`. When I use a `percentage-based width` on the child `div`, it collapses to `0 width` on IE7, but not on Firefox or Safari.

If I use `pixel width`, it works. If the parent is relatively positioned, the percentage width on the child works.

1. Is there something I'm missing here?
2. Is there an easy fix for this besides the `pixel-based width` on the child?
3. Is there an area of the CSS specification that covers this?


Question:
XPATHS and Default Namespaces | What is the story behind XPath and support for namespaces? Did XPath as a specification precede namespaces? If I have a document where elements have been given a default namespace:

```
<foo xmlns="uri" />

```

It appears as though some of the XPath processor libraries won't recognize `//foo` because of the namespace whereas others will. The option my team has thought about is to add a namespace prefix using regular expressions to the XPath (you can add a namespace prefix via XmlNameTable) but this seems brittle since XPath is such a flexible language when it comes to node tests.

Is there a standard that applies to this?

My approach is a bit hackish but it seems to work fine; I remove the `xmlns` declaration with a search/replace and then apply XPath.

```
string readyForXpath = Regex.Replace(xmldocument, "xmlns=\".+\"", String.Empty );

```

Is that a fair approach or has anyone solved this differently?


Question:
Validation Patterns for Custom XML Documents | I have a web application that generates a medium sized XML dataset to be consumed by a third party.

I thought it would be a good idea to provide some form of schema document for the XML that I generate so I pasted the XML into Visual Studio and got it to generate an XSD.

The annoying thing is that my XML doesn't validate to the XSD that was generated!

Is it better to roll your own XSD?

What about different schema docs like DTDs, Relax NG, or Schematron?

The key is that I would like to be able to validate my document using C#.

What are your XML validation strategies?


Question:
Clearing Page Cache in ASP.NET | For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine...

```
<%@OutputCache Duration="600" VaryByParam="*" %>

```

However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen.

How do I do this in ASP.Net C#?


Question:
Convert integers to written numbers | Is there an efficient method of converting an integer into the written numbers, for example:

```
string Written = IntegerToWritten(21);

```

would return "Twenty One".

Is there any way of doing this that doesn't involve a massive look-up table?


Question: How to get only directory name from SaveFileDialog.FileName | What would be the easiest way to separate the directory name from the file name when dealing with `SaveFileDialog.FileName` in C#?


Question:
Center text output from Graphics.DrawString() | I'm using the .NETCF (Windows Mobile) `Graphics` class and the `DrawString()` method to render a single character to the screen.

The problem is that I can't seem to get it centred properly. No matter what I set for the Y coordinate of the location of the string render, it always comes out lower than that and the larger the text size the greater the Y offset.

For example, at text size 12, the offset is about 4, but at 32 the offset is about 10.

I want the character to vertically take up most of the rectangle it's being drawn in and be centred horizontally. Here's my basic code. `this` is referencing the user control it's being drawn in.

```
Graphics g = this.CreateGraphics();

float padx = ((float)this.Size.Width) * (0.05F);
float pady = ((float)this.Size.Height) * (0.05F);

float width = ((float)this.Size.Width) - 2 * padx;
float height = ((float)this.Size.Height) - 2 * pady;

float emSize = height;

g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular),
            new SolidBrush(Color.Black), padx, pady);

```

Yes, I know there is the label control that I could use instead and set the centring with that, but I actually do need to do this manually with the `Graphics` class.


Question:
How do I do an Upsert Into Table? | I have a view that has a list of jobs in it, with data like who they're assigned to and the stage they are in. I need to write a stored procedure that returns how many jobs each person has at each stage.

So far I have this (simplified):

```
DECLARE @ResultTable table
(
  StaffName nvarchar(100),
  Stage1Count int,
  Stage2Count int
)

INSERT INTO @ResultTable (StaffName, Stage1Count)
  SELECT StaffName, COUNT(*) FROM ViewJob
  WHERE InStage1 = 1
  GROUP BY StaffName

INSERT INTO @ResultTable (StaffName, Stage2Count)
  SELECT StaffName, COUNT(*) FROM ViewJob
  WHERE InStage2 = 1
  GROUP BY StaffName

```

The problem with that is that the rows don't combine. So if a staff member has jobs in stage1 and stage2 there's two rows in @ResultTable. What I would really like to do is to update the row if one exists for the staff member and insert a new row if one doesn't exist.

Does anyone know how to do this, or can suggest a different approach?
I would really like to avoid using cursors to iterate on the list of users (but that's my fall back option).

I'm using SQL Server 2005.

**Edit: @Lee:** Unfortunately the InStage1 = 1 was a simplification. It's really more like WHERE DateStarted IS NOT NULL and DateFinished IS NULL.

**Edit: @BCS:** I like the idea of doing an insert of all the staff first so I just have to do an update every time. But I'm struggling to get those UPDATE statements correct.


Question:
Image UriSource and Data Binding | I'm trying to bind a list of custom objects to a WPF Image like this:

```
<Image>
    <Image.Source>
        <BitmapImage UriSource="{Binding Path=ImagePath}" />
    </Image.Source>
</Image>

```

But it doesn't work. This is the error I'm getting:

*"Property 'UriSource' or property 'StreamSource' must be set."*

What am I missing?


Question:
Huge Web App With Memory Leak in IE 6 | I have a huge web app that is having issues with memory leak in IE 6.

Fixing a memory leak in a 5 line code sample that demonstrates the problem is easy.

But if I have a very huge application, where should a start from?


Question:
Why do we need entity objects? | I really need to see some honest, thoughtful debate on the merits of the currently accepted ***enterprise application*** design paradigm.

I am not convinced that entity objects should exist.

By entity objects I mean the typical things we tend to build for our applications, like "Person", "Account", "Order", etc.

My current design philosophy is this:

* All database access must be accomplished via stored procedures.
* Whenever you need data, call a stored procedure and iterate over a SqlDataReader or the rows in a DataTable

(Note: I have also built enterprise applications with Java EE, java folks please substitute the equvalent for my .NET examples)

I am not anti-OO. I write lots of classes for different purposes, just not entities. I will admit that a large portion of the classes I write are static helper classes.

I am not building toys. I'm talking about large, high volume transactional applications deployed across multiple machines. Web applications, windows services, web services, b2b interaction, you name it.

I have used OR Mappers. I have written a few. I have used the Java EE stack, CSLA, and a few other equivalents. I have not only used them but actively developed and maintained these applications in production environments.

I have come to the battle-tested conclusion that entity objects are getting in our way, and our lives would be *so* much easier without them.

Consider this simple example: you get a support call about a certain page in your application that is not working correctly, maybe one of the fields is not being persisted like it should be. With my model, the developer assigned to find the problem opens *exactly 3 files*. An ASPX, an ASPX.CS and a SQL file with the stored procedure. The problem, which might be a missing parameter to the stored procedure call, takes minutes to solve. But with any entity model, you will invariably fire up the debugger, start stepping through code, and you may end up with 15-20 files open in Visual Studio. By the time you step down to the bottom of the stack, you forgot where you started. We can only keep so many things in our heads at one time. Software is incredibly complex without adding any unnecessary layers.

Development complexity and troubleshooting are just one side of my gripe.

Now let's talk about scalability.

Do developers realize that each and every time they write or modify any code that interacts with the database, they need to do a throrough analysis of the exact impact on the database? And not just the development copy, I mean a mimic of production, so you can see that the additional column you now require for your object just invalidated the current query plan and a report that was running in 1 second will now take 2 minutes, just because you added a single column to the select list? And it turns out that the index you now require is so big that the DBA is going to have to modify the physical layout of your files?

If you let people get too far away from the physical data store with an abstraction, they will create havoc with an application that needs to scale.

I am not a zealot. I can be convinced if I am wrong, and maybe I am, since there is such a strong push towards Linq to Sql, ADO.NET EF, Hibernate, Java EE, etc. Please think through your responses, if I am missing something I really want to know what it is, and why I should change my thinking.

***[Edit]***

It looks like this question is suddenly active again, so now that we have the new comment feature I have commented directly on several answers. Thanks for the replies, I think this is a healthy discussion.

I probably should have been more clear that I am talking about enterprise applications. I really can't comment on, say, a game that's running on someone's desktop, or a mobile app.

One thing I have to put up here at the top in response to several similar answers: orthogonality and separation of concerns often get cited as reasons to go entity/ORM. Stored procedures, to me, are the best example of separation of concerns that I can think of. If you disallow all other access to the database, other than via stored procedures, you could in theory redesign your entire data model and not break any code, so long as you maintained the inputs and outputs of the stored procedures. They are a perfect example of programming by contract (just so long as you avoid "select \*" and document the result sets).

Ask someone who's been in the industry for a long time and has worked with long-lived applications: how many application and UI layers have come and gone while a database has lived on? How hard is it to tune and refactor a database when there are 4 or 5 different persistence layers generating SQL to get at the data? You can't change anything! ORMs or any code that generates SQL ***lock your database in stone***.


Question:
Resources on wordpress theme-development | What are the best resources for Wordpress theme-development? I am currently in the phase of starting my own blog, and don't want to use one of the many free themes. I already have a theme for my website, so I want to read about best-practices.

Any advice on how to get started would be very welcome :)

---

I have now created my theme (wohoo!), and thought I should summarize the best resources I found. Lets see..

**Resources:**

* [ThemeTation's three-part guide to create a wordpress-theme from scratch](http://themetation.com/2008/07/14/how-to-create-wordpress-themes-from-scratch-part-1/)
* [Nettuts.com's guide: How to Create a Wordpress Theme from Scratch](https://code.tutsplus.com/articles/how-to-create-a-wordpress-theme-from-scratch--net-706)

Didn't actually use this, it's a quite new article, but anyway - it's great. It will get a follow-up in the next few days too..
* [Wordpress.org's own guide on templates](http://codex.wordpress.org/Theme_Development)

Definatly a must-read for everyone new to wordpress-designing..
* ["The loop"](http://codex.wordpress.org/The_Loop)

Essential knowledge, also a must-read
* [Directory of all the template tags](http://codex.wordpress.org/Template_Tags)

Used by wordpress to actually output blog-content..

**Inspiration:**

* Smashing Magazine's lists: [first](http://www.smashingmagazine.com/2008/01/08/100-excellent-free-high-quality-wordpress-themes/), [one more](http://www.smashingmagazine.com/2007/02/09/83-beautiful-wordpress-themes-you-probably-havent-seen/), [yet another one](http://www.smashingmagazine.com/2008/08/25/30-free-high-quality-wordpress-themes/)
* [Wordpress.org's theme-directory](http://wordpress.org/extend/themes/)


Question:
Automating WSDL.exe in a Custom Build | I have a web application written in C# that consumes several internal web services. We have a development tier, a testing tier, and a production tier. Also, we use the `WSDL.exe` command to generate a `Proxies.cs` file for a given tier's web services.

When we are ready to deploy our code up the stack from development to test or test to production, we need to run the `WSDL.exe` command to point to the appropriate version of the web services.

Is there a generally accepted way to automate this?


Question:
E-mail Notifications | In a .net system I'm building, there is a need for automated e-mail notifications. These should be editable by an admin. What's the easiest way to do this? SQL table and WYSIWIG for editing?

---

The queue is a great idea. I've been throwing around that type of process for awhile with my old company.


Question:
Python version of PHP's stripslashes | I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:

```
cleaned = stringwithslashes
cleaned = cleaned.replace('\\n', '\n')
cleaned = cleaned.replace('\\r', '\n')
cleaned = cleaned.replace('\\', '')

```

How can I condense it?


Question:
Best practice for integrating TDD with web application development? | Unit testing and ASP.NET web applications are an ambiguous point in my group. More often than not, good testing practices fall through the cracks and web applications end up going live for several years with no tests.

The cause of this pain point generally revolves around the hassle of writing UI automation mid-development.

How do you or your organization integrate best TDD practices with web application development?


Question:
LINQ on the .NET 2.0 Runtime | Can a LINQ enabled app run on a machine that only has the .NET 2.0 runtime installed?

In theory, LINQ is nothing more than syntactic sugar, and the resulting IL code should look the same as it would have in .NET 2.0.

How can I write LINQ without using the .NET 3.5 libraries? Will it run on .NET 2.0?


Question:
How to encourage someone to learn programming? | I have a friend that has a little bit of a holiday coming up and they want ideas on what they should do during the holiday, I plan to suggest programming to them, what are the pros and cons that I need to mention?

I'll add to the list below as people reply, I apologise if I duplicate any entries.

**Pros I have so far**

1. Minimal money requirement (they already have a computer)
2. Will help them to think in new ways
3. (Rob Cooper) Great challenge, every day really is a fresh challenge in some way, shape or form. Not many jobs can truly offer that.
4. (Rob Cooper) I like the way it makes me think.. I look at EVERYTHING more logically as my skills improve.. This helps with general living as well as programming.
5. (Rob Cooper) Money is/can be pretty good.
6. (Rob Cooper) Its a pretty portable trade.. With collaboration tech as it is, you can pretty much work anywhere in the world so long as you have an Internet connection.
7. (Rob Cooper) It's an exciting industry to work in, theres massive amounts of tech to work and play with!
8. (Quarrelsome) Jetpacks. Programming is Technology and the more time we spend with technology the closer we get to having Jetpacks. (*Teifion: This is a really cool analogy!*)
9. (Saj) Profitable way of Exercising Brain Muscles.
10. (Saj) It makes you look brilliant to some audience.
11. (Saj) Makes you tech-smart.
12. (Saj) Makes you eligible to the future world.
13. (Saj) It's easy, fun, not in a math way..
14. (kiwiBastard) If the person likes problem solving then programming is no better example.
15. (kiwiBastard) Brilliant sense of achivement when you can interact with something you have designed and coded
16. (kiwiBastard) Great way to meet chicks/chaps - erm, maybe not that one (*Teifion: I dunno where you do programming but I want to come visit some time*)
17. (epatel) Learning how to program is like learning spell casting at Hogwarts . The computer will be your servant forever...

**Cons I have so far**

1. Can be frustrating when it's not working
2. Not physical exercise
3. (Rob Cooper) There are a lot of people doing it just for the money. They have no love for the craft and just appear lazy, annoying and sometimes it can really grind my gears seeing an industry and workforce I enjoy so much being diluted with crap. Which can often reflect badly on all of us.
4. (Rob Cooper) Not so sure about the initial cost.. Yeah you can get started with Java or something at low cost, but for me, locally, the vast demand is for .NET developers, which can be costly getting up and running with. However, this is rapidly/has not becoming the case with the amount of work put in by MS with releasing pretty damn good Express editions of their main development product line.
5. (Rob Cooper) Its a lifelong career.. I truly feel you never really become a "master" by nature of the industry, you stop for 1-2 years. You're behind the times.. Some people do not like the pace.
6. (Rob Cooper) Some geeks can be hard to work with.. While I think the general geek movement is really changing for the better, you will always have the classic "I am more intelligent than you" geeks that can really just be a pain in the ass for all!
7. (Saj) Can cause virtual damage.
8. (Saj) Can make one throw their computer away.
9. (Saj) Can make one only virtually available to the world.


Question:
Can you access the windows registry from Adobe Air? | (y/N)

Edit: Read-only access is fine.


Question:
How to redirect siteA to siteB with A or CNAME records | I have 2 hosts and I would like to point a subdomain on host one to a subdomain on host two:

```
subdomain.hostone.com --> subdomain.hosttwo.com

```

I added a CNAME record to host one that points to subdomain.hosttwo.com but all I get is a '**400 Bad Request**' Error.

Can anyone see what I'm doing wrong?


Question:
Best way to store a database password in a startup script / config file? | So our web server apps need to connect to the database, and some other apps have startup scripts that execute at boot time.

What's the best way to store the name/password for these applications, in terms of

* security, e.g. perhaps we don't want sysadmins to know the database password
* maintainability, e.g. making the configuration easy to change when the password changes, etc.

both windows and linux solutions appreciated!


Question:
Telligent's Community Server | The company I work for is wanting to add blog functionality to our website and they were looking to spend an awful amount of money to have some crap being built on top of a CMS they purchased (sitecore). I pointed them to Telligent's Community Server and we had a sales like meeting today to get the Marketing folks on board.
My question is if anyone has had issues working with Community Server, skinning it and extending it?

I wanted to explain a bit why I am thinking Community Server, the company is wanting multiple blogs with multiple authors. I want to be out of the admin part of this as much as possible and didn't think there were too many engines that having multiple blogs didn't mean db work. I also like the other functionality that Community Server provides and think the company will find it useful, particularly the media section as right now we have some really shotty way of dealing with whitepapers and stuff.

edit: We are actually using the Sitecore blog module for a single blog on our intranet (which is actually what the CMS is serving). Some reasoning for why I don't like it for our public site are they are on different servers, it doesn't support multiple authors, there is no built in syndication, it is a little flimsy feeling to me from looking at the source and I personally think the other features of Community Server make its price tag worth it.

another edit: Need to stick to .net software that run on sql server in my company's case, but I don't mind seeing recommendations for others. ExpressionEngine looks promising, will try it out on my personal box.


Question:
Which scripting language to support in an existing codebase? | I'm looking at adding scripting functionality to an existing codebase and am weighing up the pros/cons of various packages. Lua is probably the most obvious choice, but I was wondering if people have any other suggestions based on their experience.

Scripts will be triggered upon certain events and may stay resident for a period of time. For example upon startup a script may define several options which the program presents to the user as a number of buttons. Upon selecting one of these buttons the program will notify the script where further events may occur.

These are the only real requirements;

1. Must be a cross-platform library that is compilable from source
2. Scripts must be able to call registered code-side functions
3. Code must be able to call script-side functions
4. Be used within a C/C++ codebase.


Question: How to display "12 minutes ago" etc in a PHP webpage? | Can anyone tell me how I can display a status message like "12 seconds ago" or "5 minutes ago" etc in a web page?


Question:
SQL Server 2008 vs 2005 Linq integration | Linq To SQL or Entity framework both integrate nicely with SQL Server 2005.

The SQL Server 2008 spec sheet promises even better integration - but I can't see it.

What are some examples of what you can do Linq-wise when talking to a 2008 server that you can't when talking to SQL Server 2005?


Question:
Filling a DataSet or a DataTable from a LINQ query result set | How do you expose a LINQ query as an ASMX web service?

Usually, from the business tier, I can return a typed `DataSet` or a `DataTable` which can be serialized for transport over ASMX.

How can I do the same for a LINQ query?

Is there a way to populate a typed `DataSet` or a `DataTable` via a LINQ query?

```
public static MyDataTable CallMySproc()
{
    string conn = "...";

    MyDatabaseDataContext db = new MyDatabaseDataContext(conn);
    MyDataTable dt = new MyDataTable();

    // execute a sproc via LINQ
    var query = from dr
                in db.MySproc().AsEnumerable
                select dr;

    // copy LINQ query resultset into a DataTable -this does not work !
    dt = query.CopyToDataTable();

    return dt;
}

```

How could I put the result set of a LINQ query into a `DataSet` or a `DataTable`?

Alternatively, can the LINQ query be serializable so that I can expose it as an ASMX web service?


Question:
WPF: How to style or disable the default ContextMenu of a TextBox | Apparantly when users right-click in our WPF application, and they use the Windows Classic theme, the default ContextMenu of the TextBox (which contains Copy, Cut and Paste) has a black background.

I know this works well:

```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

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

  <TextBox ContextMenu="{x:Null}"/>

</Page>

```

But this doesn't work:

```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Page.Resources>

 <Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
   <Setter Property="ContextMenu" Value="{x:Null}"/>
</Style>
</Page.Resources>

  <TextBox/>
</Page>

```

Does anyone know how to style or disable the default ContextMenu for all TextBoxes in WPF?


Question:
What are the best practices for using Extension Methods in .Net? | I have seen these being used every which way, and have been accused of using them the wrong way (though in that case, I was using them that way to demonstrate a [point](http://blog.gadodia.net/extension-methods-in-vbnet-and-c/)).

So, what do you think are the best practices for employing Extension Methods?

Should development teams create a library of extension methods and deploy them across various projects?

Should there be a collection of common extension methods in the form of an open source project?

*Update: have decided to create an organization wide extension methods library*


Question:
How print Flex components in FireFox3? | Thanks to FireFox's buggy implementation of ActiveX components (it really should take an image of them when printing) Flex components (in our case charts) don't print in FX.

They print fine in IE7, even IE6.

We need these charts to print, but they also have dynamic content. I don't really want to draw them again as images when the user prints - the Flex component should do it.

We've found a [potential workaround](http://www.anychart.com/blog/2007/09/23/solving-problem-with-printing-flash-content-in-firefox-browser/), but unfortunately it doesn't work in FireFox3 (in FireFox2 it sort-of works, but not well enough).

Anyone know a workaround?


Question:
How do you handle huge if-conditions? | It's something that's bugged me in every language I've used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, use a nested if statement or just accept that it's ugly and move on with my life.

Are there any other methods that you've found that might be of use to me and anybody else that's hit the same problem?

Example, all on one line:

```
if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true)
{

```

Example, multi-line:

```
if (var1 = true && var2 = true && var2 = true
 && var3 = true && var4 = true && var5 = true
 && var6 = true)
{

```

Example-nested:

```
if (var1 = true && var2 = true && var2 = true && var3 = true)
{
     if (var4 = true && var5 = true && var6 = true)
     {

```


Question: Find broken symlinks with Python | If I call `os.stat()` on a broken `symlink`, python throws an `OSError` exception. This makes it useful for finding them. However, there are a few other reasons that `os.stat()` might throw a similar exception. Is there a more precise way of detecting broken `symlinks` with Python under Linux?


Question:
JavaScript Profiler in IE | Does anyone know a tool for Profiling JavaScript in IE?

List available:

* [IE8](http://blogs.msdn.com/ie/archive/2008/09/11/introducing-the-ie8-developer-tools-jscript-profiler.aspx) (Internet Explorer 8 only)
* [JavaScript Profiler](http://www.whitefrost.com/documents/html/technical/dhtml/jsprof.html)
* [YUI!](http://developer.yahoo.com/yui/profiler/)


Question: How can I permanently enable line numbers in IntelliJ? | How can I permanently enable line numbers in IntelliJ IDEA?


Question:
String output: format or concat in C#? | Let's say that you want to output or concat strings. Which of the following styles do you prefer?

* `var p = new { FirstName = "Bill", LastName = "Gates" };`
* `Console.WriteLine("{0} {1}", p.FirstName, p.LastName);`
* `Console.WriteLine(p.FirstName + " " + p.LastName);`

Do you rather use format or do you simply concat strings? What is your favorite? Is one of these hurting your eyes?

Do you have any rational arguments to use one and not the other?

I'd go for the second one.


Question:
PHP with SQL Server 2005+ | Currently we have a hybrid ASP/PHP setup connecting to a SQL Server 2005 database. But all the query work is done on the client side, I'd like to move some of this to PHP.

What driver and/or connection string is needed to connect to Sql Svr and what is the syntax to use in PHP?

---

Update: OK so I was definitely trying to avoid using anything to do with copying DLLs etc. I'll look into the [SQL2K5PHP](http://www.codeplex.com/SQL2K5PHP) driver (thanks Vincent). @jcarrascal for the sake of clarity, by "client side" I mean our application is an internal web app that runs as an [HTA](http://msdn.microsoft.com/en-us/library/ms536471.aspx), with all queries done via javascript calls to an ASP which actually submits the DB request.


Question:
How do I convert a file path to a URL in ASP.NET | Basically I have some code to check a specific directory to see if an image is there and if so I want to assign a URL to the image to an ImageControl.

```
if (System.IO.Directory.Exists(photosLocation))
{
    string[] files = System.IO.Directory.GetFiles(photosLocation, "*.jpg");
    if (files.Length > 0)
    {
        // TODO: return the url of the first file found;
    }
}

```


Question: What are the list of Resharper like plugins for VS I should consider? | My license for Whole Tomatoes Visual AssistX is about to expire and I'm not really planning on renewing it. I use it for spell checking but that's about it. The refactoring abilities have been a little disappointing. Before I just jump into Resharper though what are your thoughts on other possible plugins?


Question:
Editing User Profile w/ Forms Authentication | We're using Forms Authentication in SharePoint. When the account is created, the administrator can add some information, like name and address. But the required fields are username and email address.

When a user goes to their profile page, all the fields are blank and they are unable to edit them. I have read a number of articles discussing how to import profiles from another data store, or to sync profiles. This doesn't work for us, because we don't have another data store where these profiles are stored.

Will I just have to recreate the edit profile page and build a custom profile editor? Is this information exposed via SharePoint API? I don't think directly editing the database is a good solution.


Question:
Tracking state using ASP.NET AJAX / ICallbackEventHandler | I have a problem with maintaining state in an ASP.NET AJAX page. Short version: I need some way to update the page ViewState after an async callback has been made, to reflect any state changes the server made during the async call.

This seems to be a common problem, but I will describe my scenario to help explain:

I have a grid-like control which has some JavaScript enhancements - namely, the ability to drag and drop columns and rows. When a column or row is dropped into a new position, an AJAX method is invoked to notify the control server-side and fire a corresponding server-side event ("OnColumnMoved" or "OnRowMoved").

ASP.NET AJAX calls, by default, send the entire page as the request. That way the page goes through a complete lifecycle, viewstate is persisted and the state of the control is restored before the RaiseCallbackEvent method is invoked.

However, since the AJAX call does not update the page, the ViewState reflects the *original* state of the control, even after the column or row has been moved. So the second time a client-side action occurs, the AJAX request goes to the server and the page & control are built back up again to reflect the *first* state of the control, not the state after the first column or row was moved.

This problem extends to many implications. For example if we have a client-side/AJAX action to add a new item to the grid, and then a row is dragged, the grid is built server-side with one less item than on the client-side.

And finally & most seriously for my specific example, the actual data source object we are acting upon is stored in the page ViewState. That was a design decision to allow keeping a stateful copy of the manipulated data which can either be committed to DB after many manipulations or discarded if the user backs out. That is very difficult to change.

So, again, I need a way for the page ViewState to be updated on callback after the AJAX method is fired.


Question: What's the best UML diagramming tool? | I'm trying to choose a tool for creating UML diagrams of all flavours. Usability is a major criteria for me, but I'd still take more power with a steeper learning curve and be happy. Free (as in beer) would be nice, but I'd be willing to pay if the tool's worth it. What should I be using?


Question:
How to check set of files conform to a naming scheme | I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme..

Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths.

Then, I loop though each valid-filename regex, if it matches, append it to a "valid" dict, if not, do the same with the missing-ep-name regexs, if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name'), if it matches neither, it gets added to invalid with the 'malformed name' error code.

The current code can be found [here](http://github.com/dbr/checktveps/tree/8a6dc68ad61e684c8d8f0ca1dc37a22d1c51aa82/2checkTvEps.py)

I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state..

How could I write this system in a more expandable way?

The rules it needs to check would be..

* File is in the format `Show Name - [01x23] - Episode Name.avi` or `Show Name - [01xSpecial02] - Special Name.avi` or `Show Name - [01xExtra01] - Extra Name.avi`
* If filename is in the format `Show Name - [01x23].avi` display it a 'missing episode name' section of the output
* The path should be in the format `Show Name/season 2/the_file.avi` (where season 2 should be the correct season number in the filename)
* each `Show Name/season 1/` folder should contain "folder.jpg"

.any ideas? While I'm trying to check TV episodes, this concept/code should be able to apply to many things..

The only thought I had was a list of dicts in the format:

```
checker = [
{
    'name':'valid files',
    'type':'file',
    'function':check_valid(), # runs check_valid() on all files
    'status':0 # if it returns True, this is the status the file gets
}

```


Question:
Is gettimeofday() guaranteed to be of microsecond resolution? | I am porting a game, that was originally written for the Win32 API, to Linux (well, porting the OS X port of the Win32 port to Linux).

I have implemented `QueryPerformanceCounter` by giving the uSeconds since the process start up:

```
BOOL QueryPerformanceCounter(LARGE_INTEGER* performanceCount)
{
    gettimeofday(&currentTimeVal, NULL);
    performanceCount->QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec);
    performanceCount->QuadPart *= (1000 * 1000);
    performanceCount->QuadPart += (currentTimeVal.tv_usec - startTimeVal.tv_usec);

    return true;
}

```

This, coupled with `QueryPerformanceFrequency()` giving a constant 1000000 as the frequency, works well **on my machine**, giving me a 64-bit variable that contains `uSeconds` since the program's start-up.

So *is this portable?* I don't want to discover it works differently if the kernel was compiled in a certain way or anything like that. I am fine with it being non-portable to something other than Linux, however.


Question:
TCL development: debug environment | I like a bit of TiVo hacking in spare time - TiVo uses a Linux variant and [TCL](http://wiki.tcl.tk/299). I'd like to write TCL scripts on my Windows laptop, test them and then FTP them over to my TiVo.

Can I have a recommendation for a TCL debugging environment for Windows, please?


Question:
Singletons: good design or a crutch? | Singletons are a hotly debated design pattern, so I am interested in what the Stack Overflow community thought about them.

Please provide reasons for your opinions, not just "Singletons are for lazy programmers!"

Here is a fairly good article on the issue, although it is against the use of Singletons:
[scientificninja.com: performant-singletons](http://web.archive.org/web/20090303174418/http://scientificninja.com/advice/performant-singletons).

Does anyone have any other good articles on them? Maybe in support of Singletons?


Question:
SQL Server Management Studio alternatives to browse/edit tables and run queries | I was wondering if there are any alternatives to Microsoft's SQL Server Management Studio?

Not there's anything wrong with SSMS, but sometimes it just seem too big an application where all I want todo is browse/edit tables and run queries.


Question:
Passing more parameters in C function pointers | Let's say I'm creating a chess program. I have a function

```
void foreachMove( void (*action)(chess_move*), chess_game* game);

```

which will call the function pointer action on each valid move. This is all well and good, but what if I need to pass more parameters to the action function? For example:

```
chess_move getNextMove(chess_game* game, int depth){
  //for each valid move, determine how good the move is
  foreachMove(moveHandler, game);
}

void moveHandler(chess_move* move){
  //uh oh, now I need the variables "game" and "depth" from the above function
}

```

Redefining the function pointer is not the optimal solution. The foreachMove function is versatile and many different places in the code reference it. It doesn't make sense for each one of those references to have to update their function to include parameters that they don't need.

How can I pass extra parameters to a function that I'm calling through a pointer?


Question:
What do you look for from a User Group? | I'm in the process of starting a User Group in my area related to .NET development. The format of the community will be the average free food, presentation, and then maybe free swag giveaway.

What would you, as a member of a user community, look for in order to keep you coming back month to month?


Question:
Best way to custom edit records in ASP.NET? | I'm coming from a Rails background and doing some work on a ASP.NET project (not ASP MVC). Newbie question: what's the easiest way to make a custom editor for a table of records?

For example: I have a bunch of data rows and want to change the "category" field on each -- maybe a dropdown, maybe a link, maybe the user types it in.

In Rails, I'd iterate over the rows to build a table, and would have a form for each row. The form would have an input box or dropdown, and submit the data to a controller like "/item/edit/15?category=foo" where 15 was the itemID and the new category was "foo".

I'm new to the ASP.NET model and am not sure of the "right" way to do this -- just the simplest way to get back the new data & save it off. Would I make a custom control and append it to each row? Any help appreciated.


Question:
Test Distribution | At my work we are running a group of tests that consist of about 3,000 separate test cases. Previously we were running this entire test suite on one machine, which took about 24-72 hours to complete the entire test run. We now have created our own system for grouping and distributing the tests among about three separate machines and the tests are prioritized so that the core tests get run first for more immediate results and the extra tests run when there is an available machine.

I am curious if anyone has found a good way to distribute their tests among several machines to reduce total test time for a complete run and what tools were used to achieve that. I've done some research and it looks like TestNG is [moving in this direction](http://beust.com/weblog/archives/000362.html), but it looks like it is still under quite a bit of development.

We don't plan on rewriting any of our tests, but as we add new tests and test new products or add-ons I'd like to be able to deal with the fact that we are working with very large numbers of tests. On the other hand, if we can find a tool that would help distribute our Junit `3.x` tests even in a very basic fashion, that *would* be helpful since we wouldn't have to maintain our own tooling to do that.


Question:
Creating Redundancy for a Subversion Repository? | What is the best way to create redundant subversion repositories?

I have a subversion repository (linked through apache2 and WebDAV) and would like to create a mirror repository on a different server in the event of outages, but I am not certain of the best way to proceed.

I am thinking that post-commit scripts could be used to propagate changes, but I am not sure if this is the best way to go, anyone have any input


Question: Object Oriented Bayesian Spam Filtering? | I was wondering if there is any good and clean object-oriented programming (OOP) implementation of Bayesian filtering for spam and text classification? This is just for learning purposes.


Question:
Load an XmlNodeList into an XmlDocument without looping? | I originally asked this question on [RefactorMyCode](http://refactormycode.com/codes/36-load-xmlnodelist-into-an-xmldocument), but got no responses there...

Basically I'm just try to load an `XmlNodeList` into an `XmlDocument` and I was wondering if there's a more efficient method than looping.

```
Private Function GetPreviousMonthsXml(ByVal months As Integer, ByVal startDate As Date, ByVal xDoc As XmlDocument, ByVal path As String, ByVal nodeName As String) As XmlDocument
    '' build xpath string with list of months to return
    Dim xp As New StringBuilder("//")
    xp.Append(nodeName)
    xp.Append("[")
    For i As Integer = 0 To (months - 1)
      '' get year and month portion of date for datestring
      xp.Append("starts-with(@Id, '")
      xp.Append(startDate.AddMonths(-i).ToString("yyyy-MM"))
      If i < (months - 1) Then
        xp.Append("') or ")
      Else
        xp.Append("')]")
      End If
    Next

    '' *** This is the block that needs to be refactored ***
    '' import nodelist into an xmldocument
    Dim xnl As XmlNodeList = xDoc.SelectNodes(xp.ToString())
    Dim returnXDoc As New XmlDocument(xDoc.NameTable)
    returnXDoc = xDoc.Clone()
    Dim nodeParents As XmlNodeList = returnXDoc.SelectNodes(path)
    For Each nodeParent As XmlNode In nodeParents
      For Each nodeToDelete As XmlNode In nodeParent.SelectNodes(nodeName)
        nodeParent.RemoveChild(nodeToDelete)
      Next
    Next

    For Each node As XmlNode In xnl
      Dim newNode As XmlNode = returnXDoc.ImportNode(node, True)
      returnXDoc.DocumentElement.SelectSingleNode("//" & node.ParentNode.Name & "[@Id='" & newNode.Attributes("Id").Value.Split("-")(0) & "']").AppendChild(newNode)
    Next

    '' *** end ***
    Return returnXDoc
End Function

```


Question:
Linq to SQL - Underlying Column Length | I've been using Linq to SQL for some time now and I find it to be really helpful and easy to use. With other ORM tools I've used in the past, the entity object filled from the database normally has a property indicating the length of the underlying data column in the database. This is helpful in databinding situations where you can set the MaxLength property on a textbox, for example, to limit the length of input entered by the user.

I cannot find a way using Linq to SQL to obtain the length of an underlying data column. Does anyone know of a way to do this? Help please.


Question:
How do I avoid using cursors in Sybase (T-SQL)? | Imagine the scene, you're updating some legacy Sybase code and come across a cursor. The stored procedure builds up a result set in a #temporary table which is all ready to be returned except that one of columns isn't terribly human readable, it's an alphanumeric code.

What we need to do, is figure out the possible distinct values of this code, call another stored procedure to cross reference these discrete values and then update the result set with the newly deciphered values:

```
declare c_lookup_codes for
select distinct lookup_code
from #workinprogress

while(1=1)
begin
    fetch c_lookup_codes into @lookup_code

    if @@sqlstatus<>0
    begin
        break
    end

    exec proc_code_xref @lookup_code @xref_code OUTPUT

    update #workinprogress
    set xref = @xref_code
    where lookup_code = @lookup_code
end

```

Now then, whilst this may give some folks palpitations, it does work. My question is, how best would one avoid this kind of thing?

\_NB: for the purposes of this example you can also imagine that the result set is in the region of 500k rows and that there are 100 distinct values of look\_up\_code and finally, that it is not possible to have a table with the xref values in as the logic in proc\_code\_xref is too arcane.\_


Question:
VS 2008 - ctrl-tab behavior | As you may know, in `VS 2008` `ctrl`+`tab` brings up a nifty navigator window with a thumbnail of each file. I love it, but there is one tiny thing that is annoying to me about this feature: *the window stays around after releasing the `ctrl` key*. When doing an `alt`+`tab` in windows, you can hit tab to get to the item you want (while still holding down the `alt` key), and then when you find what you want, *lifting up* on the `alt` key selects that item.

I wish `VS 2008` would do the same. For me, when I lift off of `ctrl`, the window is still there. I have to hit `enter` to actually select the item. I find this annoying.

Does anyone know how to make `VS 2008` dismiss the window on the *release* of the `ctrl` key?


Question: Absolute path back to web-relative path | If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the **fastest** way to convert that absolute path back into a relative web path?


Question:
How do you keep two related, but separate, systems in sync with each other? | My current development project has two aspects to it. First, there is a public website where external users can submit and update information for various purposes. This information is then saved to a local SQL Server at the colo facility.

The second aspect is an internal application which employees use to manage those same records (conceptually) and provide status updates, approvals, etc. This application is hosted within the corporate firewall with its own local SQL Server database.

The two networks are connected by a hardware VPN solution, which is decent, but obviously not the speediest thing in the world.

The two databases are similar, and share many of the same tables, but they are not 100% the same. Many of the tables on both sides are very specific to either the internal or external application.

So the question is: when a user updates their information or submits a record on the public website, how do you transfer that data to the internal application's database so it can be managed by the internal staff? And vice versa... how do you push updates made by the staff back out to the website?

It is worth mentioning that the more "real time" these updates occur, the better. Not that it has to be instant, just reasonably quick.

So far, I have thought about using the following types of approaches:

1. Bi-directional replication
2. Web service interfaces on both sides with code to sync the changes as they are made (in real time).
3. Web service interfaces on both sides with code to asynchronously sync the changes (using a queueing mechanism).

Any advice? Has anyone run into this problem before? Did you come up with a solution that worked well for you?


Question:
What is Inversion of Control? | Inversion of Control (IoC) can be quite confusing when it is first encountered.

1. What is it?
2. Which problem does it solve?
3. When is it appropriate to use and when not?


Question:
How can I unit test Flex applications from within the IDE or a build script? | I'm currently working on an application with a frontend written in Adobe Flex 3. I'm aware of [FlexUnit](http://code.google.com/p/as3flexunitlib/) but what I'd really like is a unit test runner for Ant/NAnt and a runner that integrates with the Flex Builder IDE (AKA Eclipse). Does one exist?

Also, are there any other resources on how to do Flex development "the right way" besides the [Cairngorm microarchitecture](http://labs.adobe.com/wiki/index.php/Cairngorm) example?


Question:
I would like some tips for debugging WCF Web Service exceptions | I've created a WCF service and when I browse to the endpoint I get the following fault:

```
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <s:Fault>
      <faultcode
            xmlns:a="http://schemas.microsoft.com/ws/2005/05/addressing/none">
            a:ActionNotSupported
      </faultcode>
      <faultstring xml:lang="en-GB">
            The message with Action '' cannot be processed at the receiver,
            due to a ContractFilter mismatch at the EndpointDispatcher.
            This may be because of either a contract mismatch (mismatched
            Actions between sender and receiver) or a binding/security
            mismatch between the sender and the receiver. Check that sender
            and receiver have the same contract and the same binding
            (including security requirements, e.g. Message, Transport, None).
      </faultstring>
    </s:Fault>
  </s:Body>
</s:Envelope>

```

I've fixed the problem but didn't enjoy the experience! Does anyone have any tips or tools for debugging problems like this?


Question:
Python and MySQL | I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.

I found [bpgsql](http://barryp.org/software/bpgsql/) really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?


Question:
What's the best way to get started with OSGI? | What makes a module/service/bit of application functionality a particularly good candidate for an OSGi module?

I'm interested in using [OSGi](http://en.wikipedia.org/wiki/OSGi) in my applications. We're a Java shop and we use Spring pretty extensively, so I'm leaning toward using [Spring Dynamic Modules for OSGi(tm) Service Platforms](http://www.springframework.org/osgi). I'm looking for a good way to incorporate a little bit of OSGi into an application as a trial. Has anyone here used this or a similar OSGi technology? Are there any pitfalls?

@Nicolas - Thanks, I've seen that one. It's a good tutorial, but I'm looking more for ideas on how to do my first "real" OSGi bundle, as opposed to a Hello World example.

@david - Thanks for the link! Ideally, with a greenfield app, I'd design the whole thing to be dynamic. What I'm looking for right now, though, is to introduce it in a small piece of an existing application. Assuming I can pick any piece of the app, what are some factors to consider that would make that piece better or worse as an OSGi guinea pig?


Question:
What is the single most influential book every programmer should read? | If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be?

I expect this list to be varied and to cover a wide range of things.

**To search:** Use the search box in the upper-right corner. To search the answers of the current question, use `inquestion:this`. For example:

```
inquestion:this "Code Complete"

```


Question:
Small modification to an XML document using StAX | I'm currently trying to read in an XML file, make some minor changes (alter the value of some attributes), and write it back out again.

I have intended to use a StAX parser (`javax.xml.stream.XMLStreamReader`) to read in each event, see if it was one I wanted to change, and then pass it straight on to the StAX writer (`javax.xml.stream.XMLStreamReader`) if no changes were required.

Unfortunately, that doesn't look to be so simple - The writer has no way to take an event type and a parser object, only methods like `writeAttribute` and `writeStartElement`. Obviously I could write a big switch statement with a case for every possible type of element which can occur in an XML document, and just write it back out again, but it seems like a lot of trouble for something which seems like it should be simple.

Is there something I'm missing that makes it easy to write out a very similar XML document to the one you read in with StAX?


Question:
How to set up a DB2 linked server on a 64-bit SQL Server 2005? | I need to create a linked server to a DB2 database on a mainframe. Has anyone done this successfully on a 64-bit version of SQL Server 2005? If so, which provider and settings were used?

It's important that the linked server work whether we are using a Windows authenticated account to login to SQL Server or a SQL Server login. It's also important that both the 4-part name and `OPENQUERY` query methods are functional. We have one set up on a SQL Server 2000 machine that works well, but it uses a provider that's not available for 64-bit SS 2005.


Question:
How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox? | I have an application that displays an image inside of a Windows Forms `PictureBox` control. The `SizeMode` of the control is set to `Zoom` so that the image contained in the `PictureBox` will be displayed in an aspect-correct way regardless of the dimensions of the `PictureBox`.

This is great for the visual appearance of the application because you can size the window however you want and the image will always be displayed using its best fit. Unfortunately, I also need to handle mouse click events on the picture box and need to be able to translate from screen-space coordinates to image-space coordinates.

It looks like it's easy to translate from screen space to control space, but I don't see any obvious way to translate from control space to image space (i.e. the pixel coordinate in the source image that has been scaled in the picture box).

Is there an easy way to do this, or should I just duplicate the scaling math that they're using internally to position the image and do the translation myself?


Question:
How to patch on Windows? | Given a (source) patch file, what's the easiest way to apply this patch on the source files under Windows?

A GUI tool where I can visually compare the unchanged-changed source lines would be great.


Question:
How do I enable MSDTC on SQL Server? | Is this even a valid question? I have a .NET Windows app that is using MSTDC and it is throwing an exception:

>
> System.Transactions.TransactionManagerCommunicationException: Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for
>  network access in the security configuration for MSDTC using the Component Services Administrative tool ---> System.Runtime.InteropServices.COMException (0x8004D024): The transaction manager has disabled its support for remote/network
>  transactions. (Exception from HRESULT: 0x8004D024) at System.Transactions.Oletx.IDtcProxyShimFactory.ReceiveTransaction(UInt32
>  propgationTokenSize, Byte[] propgationToken, IntPtr managedIdentifier,
>  Guid& transactionIdentifier, OletxTransactionIsolationLevel&
>  isolationLevel, ITransactionShim& transactionShim)....
>
>
>

I followed [the Kbalertz guide to enable MSDTC](https://support.microsoft.com/en-us/kb/883960) on the PC on which the app is installed, but the error still occurs.

I was wondering if this was a database issue? If so, how can I resolve it?


Question: Watch for change in ip address status | Is there a way to watch for changes in the ip-address much the same as it is possible to watch for changes to files using the FileSystemWatcher? I'm connecting to a machine via tcp/ip but it takes a while until it gives me an ip-address. I would like to dim out the connect button until I have a valid ip-address.


Question:
How do you convert the number you get from datepart to the name of the day? | Is there a quick one-liner to call datepart in Sql Server and get back the name of the day instead of just the number?

```
select datepart(dw, getdate());

```

This will return 1-7, with Sunday being 1. I would like 'Sunday' instead of 1.


Question:
Is there a way to check to see if the user is currently idle? | There is some documentation on the internet that shows that Windows changes the behavior of the NotifyIcon.BalloonTipShown command if the user is currently idle and this is [detected by checking for keyboard and mouse events](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=343411&SiteID=1). I am currently working on an application that spends most of its time in the system tray, but pop-ups up multiple balloon tips from time to time and I would like to prevent the user from missing any of them if they are currently away from the system. Since any currently displayed balloon tips are destroyed if a new one is displayed, I want to hold off on displaying them if the user is away.

As such, is there any way to check to see if the user is currently idle if the application is minimized to the system tray?


Question: grep: show lines surrounding each match | How do I `grep` and show the preceding and following 5 lines surrounding each matched line?


Question:
What do the different brackets in Ruby mean? | In Ruby, what's the difference between `{}` and `[]`?

`{}` seems to be used for both code blocks and hashes.

Are `[]` only for arrays?

The documention isn't very clear.


Question:
How to insert/replace XML tag in XmlDocument? | I have a `XmlDocument` in java, created with the `Weblogic XmlDocument` parser.

I want to replace the content of a tag in this `XMLDocument` with my own data, or insert the tag if it isn't there.

```
<customdata>
   <tag1 />
   <tag2>mfkdslmlfkm</tag2>
   <location />
   <tag3 />
</customdata>

```

For example I want to insert a URL in the location tag:

```
<location>http://something</location>

```

but otherwise leave the XML as is.

Currently I use a `XMLCursor`:

```
    XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options);
    XmlCursor xmlcur = xmlobj.newCursor();

    while (xmlcur.hasNextToken()) {
      boolean found = false;
      if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) {
        xmlcur.setTextValue("http://replaced");
        System.out.println("replaced");
        found = true;
      } else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) {
        xmlcur.push();
      } else if (xmlcur.isEnddoc()) {
        if (!found) {
          xmlcur.pop();
          xmlcur.toEndToken();
          xmlcur.insertElementWithText("schema-location", "http://inserted");
          System.out.println("inserted");
        }

      }
      xmlcur.toNextToken();
    }

```

I tried to find a "quick" `xquery` way to do this since the `XmlDocument` has an `execQuery` method, but didn't find it very easy.

Do anyone have a better way than this? It seems a bit elaborate.


Question:
Accessing a CONST attribute of series of Classes | This is how I wanted to do it which would work in PHP 5.3.0+

```
<?php
    class MyClass
    {
        const CONSTANT = 'Const var';
    }

    $classname = 'MyClass';
    echo $classname::CONSTANT; // As of PHP 5.3.0
?>

```

But I'm restricted to using PHP 5.2.6. Can anyone think of a simple way to simulate this behavior without instantiating the class?


Question:
How can I improve performance when adding InDesign XMLElements via AppleScript? | I have an AppleScript program which creates XML tags and elements within an Adobe InDesign document. The data is in tables, and tagging each cell takes .5 seconds. The entire script takes several hours to complete.

I can post the inner loop code, but I'm not sure if SO is supposed to be generic or specific. I'll let the mob decide.

[edit]
The code builds a list (prior to this loop) which contains one item per row in the table. There is also a list containing one string for each column in the table. For each cell, the program creates an XML element and an XML tag by concatenating the items in the [row]/[column] positions of the two lists. It also associates the text in that cell to the newly-created element.

I'm completely new to AppleScript so some of this code is crudely modified from Adobe's samples. If the code is atrocious I won't be offended.

Here's the code:

```
repeat with columnNumber from COL_START to COL_END

    select text of cell ((columnNumber as string) & ":" & (rowNumber as string)) of ThisTable

    tell activeDocument

        set thisXmlTag to make XML tag with properties {name:item rowNumber of symbolList & "_" & item columnNumber of my histLabelList}

        tell rootXmlElement

            set thisXmlElement to make XML element with properties {markup tag:thisXmlTag}

        end tell

        set contents of thisXmlElement to (selection as string)

    end tell

end repeat

```

EDIT: I've rephrased the question to better reflect the correct answer.


Question:
How to write stored procedure output directly to a file on an FTP without using local or temp files? | I want to get the results of a stored procedure and place them into a CSV file onto an FTP location.

The catch though is that I cannot create a local/temporary file that I can then FTP over.

The approach I was taking was to use an SSIS package to create a temporary file and then have a FTP Task within the pack to FTP the file over, but our DBA's do not allow temporary files to be created on any servers.

[in reply to Yaakov Ellis](https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20596)
-----------------------------------------------------------------------------------------------------------------------------------------------------------

I think we will need to convince the DBA's to let me use at least a share on a server that they do not operate, or ask them how they would do it.

[in reply to Kev](https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20689)
--------------------------------------------------------------------------------------------------------------------------------------------------

I like the idea of the CLR integration, but I don't think our DBA's even know what that is *lol* and they would probably not allow it either. But I will probably be able to do this within a Script Task in an SSIS package that can be scheduled.


Question:
Refactoring away labeled loops | After I was convinced that labeled breaks/continues are a total "nono" over [here](https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501), I need help to remove the label out of my code.

I have a square matrix and a vector that has the same length. The vector has already some values in it an depending on the values in the matrix the vector is changed in the loop.

I hope, the code-fragment is basically understandable…

```
vectorLoop:
for( int idx = 0; idx < vectorLength; idx++) {
    if( conditionAtVectorPosition( v, idx ) ) continue vectorLoop;

    matrixLoop:
    for( rowIdx = 0; rowIdx < n; rowIdx++ ) {
        if( anotherConditionAtVector( v, rowIdx ) ) continue matrixLoop;
        if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) continue vectorLoop;
    }
    setValueInVector( v, idx );
}

```

Please convince me, that there is a more readable/better version without the labels.


Question:
Bigger than a char but smaller than a blob | Char's are great because they are fixed size and thus make for a faster table. They are however limited to 255 characters. I want to hold 500 characters but a blob is variable length and that's not what I want.

Is there some way to have a fixed length field of 500 characters in MySQL or am I going to have to use 2 char fields?


Question:
XRef Relationships in dbml | So I have a database schema like this:

**Users**

 UserId

**RoleUserXRef**

 RoleUserId

 RoleId

 UserId

**Roles**

With foreign keys defined between User & RoleUserXRef and RoleUserXRef & Role. Basically, I have a one to many relationship between users and roles.

How would I model this in dbml, such that the generated User class has a list of Roles that the user has assigned to them?