Question:
I've been using Winforms since .NET 1.1 and I want to start learning WPF.

I'm looking for some good resources for a beginner in WPF. What should I read, what tools do I need, and what are the best practices I should follow?

Answer:
I'd recommend the book
Windows Presentation Foundation Unleashed
by Adam Nathan
Then I'd recommend you write an application.  Like every other dev environment, there are no perfect guidelines.  You have to find the ones that make the most sense for your circumstance.  The only way to do that is to just start coding.
As for tools, Visual Studio 2008 [Express] is your best bet.  Or you might be able to limp along with XamlPad.


Question:
Hi I'd like to schedule an existing job in the Sql Server 2005 agent via C# code... i.e. when someone clicks a button on an asp.net web page.

How can I do this?

Thanks!

Answer:
Have a look here:
SMO Job Class
The
SQL Server Management Objects (SMO) Class Library
lets you do practically anything programmatically in SQL Server.


Question: I am working on a geometry problem that requires finding the intersection of two parabolic arcs in any rotation.  I was able to intesect a line and a parabolic arc by rotating the plane to align the arc with an axis, but two parabolas cannot both align with an axis.  I am working on deriving the formulas, but I would like to know if there is a resource already available for this.

Answer:
I'd first define the equation for the parabolic arc in 2D without rotations:
```
```
x(t) = ax² + bx + c
  y(t) = t;
```
```
You can now apply the rotation by building a rotation matrix:
```
```
s = sin(angle)
  c = cos(angle)

  matrix = | c -s |
           | s  c |
```
```
Apply that matrix and you'll get the rotated parametric equation:
```
```
x' (t) = x(t) * c - s*t;
y' (t) = x(t) * s + c*t;
```
```
This will give you two equations (for x and y) of your parabolic arcs.
Do that for both of your rotated arcs and subtract them. This gives you an equation like this:
```
```
xa'(t) = rotated equation of arc1 in x
  ya'(t) = rotated equation of arc1 in y.
  xb'(t) = rotated equation of arc2 in x
  yb'(t) = rotated equation of arc2 in y.
  t1 = parametric value of arc1
  t2 = parametric value of arc2

  0 = xa'(t1) - xb'(t2)
  0 = ya'(t1) - yb'(t2)
```
```
Each of these equation is just a order 2 polynomial. These are easy to solve.
To find the intersection points you solve the above equation (e.g. find the roots).
You'll get up to two roots for each axis. Any root that is equal on x and y is an intersection point between the curves.
Getting the position is easy now: Just plug the root into your parametric equation and you can directly get x and y.


Question:
If I want to put a form up on SharePoint, is it easier to use InfoPath or build a custom web part in C#?  Are there other options that I should consider?

What are the requirements and hurdles for each option?

Answer:
Can you be more specific about the form and sharepoint version ?
It depends on your version of Sharepoint : if you got 2003, if you want to use InfoPath, it has to be installed on the clients as well. On SharePoint 2007, i
think
it is not required.
If it is a large form with few business rule, InfoPath can be the way to go -> wysiwyg, and easy deployment.
If your form involves more business rules, a web part or a page in _layouts can be "simpler" and more maintainable.


Question:
It is a bit of a "chicken or egg" kind of query, but can someone dreamup a query that can return the name of the current database instance in which the query executes? Believe me when I say I understand the paradox: why do you need to know the name of the database instance if you're already connected to execute the query? Auditing in a multi-database environment.

I've looked at all the @@ globals in Books Online. "SELECT @@servername" comes close, but I want the name of the database instance rather than the server.

Answer:
```
```
SELECT DB_NAME()
```
```
Returns the database name.


Question:
I'm writing a function to find triangle numbers and the natural way to write it is recursively:

function triangle (x)
   if x == 0 then return 0 end
   return x+triangle(x-1)
end

But attempting to calculate the first 100,000 triangle numbers fails with a stack overflow after a while.  This is an ideal function to memoize, but I want a solution that will memoize any function I pass to it.

Answer:
```
```
function memoize (f)
   local cache = {}
   return function (x)
             if cache[x] then
                return cache[x]
             else
                local y = f(x)
                cache[x] = y
                return y
             end
          end
end

triangle = memoize(triangle);
```
```
Note that to avoid a stack overflow, triangle would still need to be seeded.


Question:
What property in Netbeans to I need to change to set the name of my java swing app in the OS X menubar and dock? I found info.plist, but changing @PROJECTNAMEASIDENTIFIEER@ in multiple keys here had no effect.

Thanks,
hating netbeans.

Answer:
Check:
```
```
nbproject/project.properties

nbproject/project.xml
```
```
in project.xml look for the name element...
But... Why not just select the main project and right click and do rename?


Question: I've heard the term MVC (Model View Controller) tossed about with a ton of Buzz lately, but what really is it?

Answer:
Wikipedia seems to describe it best so far:
http://en.wikipedia.org/wiki/Model-view-controller
Model-view-controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements


Question:
I have a page in my vb.net web application that needs to toss a bunch of data into a text file and then present it to the user for download.  What's the best / most efficient way to build such a text file on a .net web server?

Edit: to answer a question down below, this is going to be a download once and then throw-away kind of file.

Update: I glued together the suggestions by John Rudy and DavidK, and it worked perfectly.  Thanks, all!

Answer:
Use a StringBuilder to create the text of the file, and then send it to the user using Content-Disposition.
Example found here:
http://www.eggheadcafe.com/community/aspnet/17/76432/use-the-contentdispositi.aspx
```
```
private void Button1_Click(object sender, System.EventArgs e)
{
        StringBuilder output = new StringBuilder;
        //populate output with the string content
        String fileName = "textfile.txt";

        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.WriteFile(output.ToString());

}
```
```


Question: Can someone explain what exactly the string "0 but true" means in Perl? As far as I understand, it equals zero in an integer comparison, but evaluates to true when used as a boolean. Is this correct? Is this a normal behavior of the language or is this a special string treated as a special case in the interpreter?

Answer:
In an integer context, it evaluates to 0 (the numeric part at the beginning of the string) and is zero.  In a scalar context, it's a non-empty value, so it is true.
```
if (int("0 but true")) { print "zero"; }
```
(no output)
```
if ("0 but true") { print "true"; }
```
(prints true)


Question: Is it possible to convert a com.vividsolutions.jts.geom.Geometry (or a subclass of it) into a class that implements java.awt.Shape? Which library or method can I use to achieve that goal?

Answer:
According to:
http://lists.jump-project.org/pipermail/jts-devel/2007-May/001954.html
There's a class:
```
```
com.vividsolutions.jump.workbench.ui.renderer.java2D.Java2DConverter
```
```
which can do it?


Question:
We've developed a Java application and would like to use this application from a C# client. The application has dependencies on Spring, Log4j, ...

What would be the most efficient mechanism - make DLL(s) from Java code, ... - to achieve this ?

Answer:
IKVM!
It is really awesome.  The only problem is that it DOES add ~30MB to the project.
log4net and Spring .NET are available as well, but if living with existing code, go the ikvm route.


Question:
I have a Rails 2.0.2 application running with a postgresql db. The machine will receive data on a TCP port. I already have coded a working ruby multithreaded tcp server to receive the requests, but I need this code to run alongside my Rails app.

So I guess I need to know how to span a new process inside Rails, or how to create a worker thread that will run my threaded tcp server loop. My ruby tcp server could have access to ActiveRecord, but it's not necessary (I can always create an http request, posting the received data to the original Rails server)

Answer:
Why complicate things?  Just run the applications -- your TCP server and the Rails application -- side by side.
Either pull the model tier (and ActiveRecord) into your TCP server (svn::externals or Piston might work well for that) and let the communication between the two applications happen through the database, or let the Rails application be the "master" and communicate with it via HTTP as you suggest.
To turn a Ruby application into a Windows service, see the
```
win32-service
```
gem available from the
```
win32utils
```
project:
http://rubyforge.org/projects/win32utils/


Question: Can anyone recommend a dropdownlist control for asp.net (3.5) that can render option groups? Thanks

Answer:
I've used the standard control in the past, and just added a simple
ControlAdapter
for it that would override the default behavior so it could render <optgroup>s in certain places. This works great even if you have controls that don't need the special behavior, because the additional feature doesn't get in the way.
Note that this was for a specific purpose and written in .Net 2.0, so it may not suit you as well, but it should at least give you a starting point. Also, you have to hook it up using a .browserfile in your project (see the end of the post for an example).
```
```
'This codes makes the dropdownlist control recognize items with "--"
'for the label or items with an OptionGroup attribute and render them
'as <optgroup> instead of <option>.
Public Class DropDownListAdapter
    Inherits System.Web.UI.WebControls.Adapters.WebControlAdapter

    Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)
        Dim list As DropDownList = Me.Control
        Dim currentOptionGroup As String
        Dim renderedOptionGroups As New Generic.List(Of String)

        For Each item As ListItem In list.Items
            Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value)
            If item.Attributes("OptionGroup") IsNot Nothing Then
                'The item is part of an option group
                currentOptionGroup = item.Attributes("OptionGroup")
                If Not renderedOptionGroups.Contains(currentOptionGroup) Then
                    'the header was not written- do that first
                    'TODO: make this stack-based, so the same option group can be used more than once in longer select element (check the most-recent stack item instead of anything in the list)
                    If (renderedOptionGroups.Count > 0) Then
                        RenderOptionGroupEndTag(writer) 'need to close previous group
                    End If
                    RenderOptionGroupBeginTag(currentOptionGroup, writer)
                    renderedOptionGroups.Add(currentOptionGroup)
                End If
                RenderListItem(item, writer)
            ElseIf item.Text = "--" Then 'simple separator
                RenderOptionGroupBeginTag("--", writer)
                RenderOptionGroupEndTag(writer)
            Else
                'default behavior: render the list item as normal
                RenderListItem(item, writer)
            End If
        Next item

        If renderedOptionGroups.Count > 0 Then
            RenderOptionGroupEndTag(writer)
        End If
    End Sub

    Private Sub RenderOptionGroupBeginTag(ByVal name As String, ByVal writer As HtmlTextWriter)
        writer.WriteBeginTag("optgroup")
        writer.WriteAttribute("label", name)
        writer.Write(HtmlTextWriter.TagRightChar)
        writer.WriteLine()
    End Sub

    Private Sub RenderOptionGroupEndTag(ByVal writer As HtmlTextWriter)
        writer.WriteEndTag("optgroup")
        writer.WriteLine()
    End Sub

    Private Sub RenderListItem(ByVal item As ListItem, ByVal writer As HtmlTextWriter)
        writer.WriteBeginTag("option")
        writer.WriteAttribute("value", item.Value, True)
        If item.Selected Then
            writer.WriteAttribute("selected", "selected", False)
        End If

        For Each key As String In item.Attributes.Keys
            writer.WriteAttribute(key, item.Attributes(key))
        Next key

        writer.Write(HtmlTextWriter.TagRightChar)
        HttpUtility.HtmlEncode(item.Text, writer)
        writer.WriteEndTag("option")
        writer.WriteLine()
    End Sub
End Class
```
```
Here's a C# implementation of the same Class:
```
```
/* This codes makes the dropdownlist control recognize items with "--"
 * for the label or items with an OptionGroup attribute and render them
 * as <optgroup> instead of <option>.
 */
public class DropDownListAdapter : WebControlAdapter
{
    protected override void RenderContents(HtmlTextWriter writer)
    {
        //System.Web.HttpContext.Current.Response.Write("here");
        var list = (DropDownList)this.Control;
        string currentOptionGroup;
        var renderedOptionGroups = new List<string>();

        foreach (ListItem item in list.Items)
        {
            Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value);
            //Is the item part of an option group?
            if (item.Attributes["OptionGroup"] != null)
            {
                currentOptionGroup = item.Attributes["OptionGroup"];
                //Was the option header already written, then just render the list item
                if (renderedOptionGroups.Contains(currentOptionGroup))
                    RenderListItem(item, writer);
                //The header was not written,do that first
                else
                {
                    //Close previous group
                    if (renderedOptionGroups.Count > 0)
                        RenderOptionGroupEndTag(writer);

                    RenderOptionGroupBeginTag(currentOptionGroup, writer);
                    renderedOptionGroups.Add(currentOptionGroup);
                    RenderListItem(item, writer);
                }
            }
            //Simple separator
            else if (item.Text == "--")
            {
                RenderOptionGroupBeginTag("--", writer);
                RenderOptionGroupEndTag(writer);
            }
            //Default behavior, render the list item as normal
            else
                RenderListItem(item, writer);
        }

        if (renderedOptionGroups.Count > 0)
            RenderOptionGroupEndTag(writer);
    }

    private void RenderOptionGroupBeginTag(string name, HtmlTextWriter writer)
    {
        writer.WriteBeginTag("optgroup");
        writer.WriteAttribute("label", name);
        writer.Write(HtmlTextWriter.TagRightChar);
        writer.WriteLine();
    }
    private void RenderOptionGroupEndTag(HtmlTextWriter writer)
    {
        writer.WriteEndTag("optgroup");
        writer.WriteLine();
    }
    private void RenderListItem(ListItem item, HtmlTextWriter writer)
    {
        writer.WriteBeginTag("option");
        writer.WriteAttribute("value", item.Value, true);
        if (item.Selected)
            writer.WriteAttribute("selected", "selected", false);

        foreach (string key in item.Attributes.Keys)
            writer.WriteAttribute(key, item.Attributes[key]);

        writer.Write(HtmlTextWriter.TagRightChar);
        HttpUtility.HtmlEncode(item.Text, writer);
        writer.WriteEndTag("option");
        writer.WriteLine();
    }
}
```
```
My browser file was named "App_Browsers\BrowserFile.browser" and looked like this:
```
```
<!--
    You can find existing browser definitions at
    <windir>\Microsoft.NET\Framework\<ver>\CONFIG\Browsers
-->
<browsers>
   <browser refID="Default">
      <controlAdapters>
        <adapter controlType="System.Web.UI.WebControls.DropDownList"
               adapterType="DropDownListAdapter" />
      </controlAdapters>
   </browser>
</browsers>
```
```


Question: Is there a built-in editor for a multi-line string in a PropertyGrid.

Answer:
No, you will need to create what's called a modal UI type editor. You'll need to create a class that inherits from UITypeEditor. This is basically a form that gets shown when you click on the ellipsis button on the right side of the property you are editing.
The only drawback I found, was that I needed to decorate the specific string property with a specific attribute. It's been a while since I had to do that. I got this information from a book by Chris Sells called "Windows Forms Programming in C#"
There's a commercial propertygrid called
Smart PropertyGrid.NET
by VisualHint.


Question:
I mean, I always was wondered about how the hell somebody can develop algorithms to break/cheat the constraints of legal use in many shareware programs out there.

Just for curiosity.

Answer:
The bad guys search for the key-check code using a disassembler. This is relative easy if you know how to do this.
Afterwards you translate the key-checking code to C or another language (this step is optional). Reversing the process of key-checking gives you a key-generator.
If you know assembler it takes roughly a weekend to learn how to do this. I've done it just some years ago (never released anything though. It was just research for my game-development job. To write a hard to crack key you have to understand how people approach cracking).


Question:
python's time module seems a little haphazard.  For example, here is a list of methods in there, from the docstring:

time() -- return current time in seconds since the Epoch as a float
clock() -- return CPU time since process start as a float
sleep() -- delay for a number of seconds given as a float
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone

Looking at localtime() and its inverse mktime(), why is there no inverse for gmtime() ?

Bonus questions: what would you name the method ? How would you implement it ?

Answer:
I always thought the time and datetime modules were a little incoherent.  Anyways, here's the inverse of mktime
```
```
import time
def mkgmtime(t):
    """Convert UTC tuple to seconds since Epoch"""
    return time.mktime(t)-time.timezone
```
```


Question: How can you get the directory of the script that was run and use it within the .cmd file?

Answer:
Raymond Chen has a few ideas:
https://devblogs.microsoft.com/oldnewthing/20050128-00/?p=36573
Quoted here in full because MSDN archives tend to be somewhat unreliable:
The easy way is to use the
```
%CD%
```
pseudo-variable. It expands to the
  current working directory.
```
set OLDDIR=%CD%
```
```
.. do stuff ..
```
```
chdir /d %OLDDIR% &rem restore current directory
```
(Of course, directory save/restore could more easily have
  been done with
```
pushd
```
/
```
popd
```
, but that's not the point here.)
The
```
%CD%
```
trick is handy even from the command line. For example, I
  often find myself in a directory where there's a file that I want to
  operate on but... oh, I need to chdir to some other directory in order
  to perform that operation.
```
set _=%CD%\curfile.txt
```
```
cd ... some other directory ...
```
```
somecommand args %_% args
```
(I like to use
```
%_%
```
as my scratch environment variable.)
Type
```
SET /?
```
to see the other pseudo-variables provided by the command
  processor.
Also the comments in the article are well worth scanning for example this one (via the WayBack Machine, since comments are gone from older articles):
http://blogs.msdn.com/oldnewthing/archive/2005/01/28/362565.aspx#362741
This covers the use of %~dp0:
If you want to know where the batch file lives:
```
%~dp0
```
```
%0
```
is the name of the batch file.
```
~dp
```
gives you the drive and path of
  the specified argument.


Question: How can I read the first line from a text file using a Windows batch file? Since the file is large I only want to deal with the first line.

Answer:
You might give this a try:
```
```
@echo off

for /f %%a in (sample.txt) do (
  echo %%a
  exit /b
)
```
```
edit
Or, say you have four columns of data and want from the 5th row down to the bottom, try this:
```
```
@echo off

for /f "skip=4 tokens=1-4" %%a in (junkl.txt) do (
  echo %%a %%b %%c %%d
)
```
```


Question:
Has anyone worked with the StarTeam COM API (Specifically, intergrating with C#).

I need to write a helper function that returns a directory structure out of Starteam, but all I've been able to retrieve using this API has been a list of views.

Has anyone else tried this?

Answer:
the Starteam object model is heirachical, projects contain views, views contain folders, folders contain items (child folders, files, cr's etc)
So once you have your view list you can get the folders that belong to the view, then you have a few properties that determine how they map to the local file system, both the view object and the folder objects have a readonly path property. There are 4 other properties of interest though, on the view object read up on the DefaultPath and AlternatePath properties and on the folder object the DefaultPathFragment and AlternatePathFragment.


Question: I am trying to write a macro that would "click" a command button that is in another workbook. Is that possible? Without changing any of the code within that other workbook?

Answer:
You can use
```
Application.Run
```
for that:
```
```
Run "OtherWorkbook.xls!MyOtherMacro"
```
```


Question:
Assuming I have only the class name of a generic as a string in the form of "MyCustomGenericCollection(of MyCustomObjectClass)" and don't know the assembly it comes from, what is the easiest way to create an instance of that object?

If it helps, I know that the class implements IMyCustomInterface and is from an assembly loaded into the current AppDomain.

Markus Olsson gave an excellent example here, but I don't see how to apply it to generics.

Answer:
Once you parse it up, use
Type.GetType(string)
to get a reference to the types involved, then use
Type.MakeGenericType(Type[])
to construct the specific generic type you need.  Then, use
Type.GetConstructor(Type[])
to get a reference to a constructor for the specific generic type, and finally call
ConstructorInfo.Invoke
to get an instance of the object.
```
```
Type t1 = Type.GetType("MyCustomGenericCollection");
Type t2 = Type.GetType("MyCustomObjectClass");
Type t3 = t1.MakeGenericType(new Type[] { t2 });
ConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes);
object obj = ci.Invoke(null);
```
```


Question:
I started using subversion for one of my projects and it would be absolutely amazing if I could just export the latest version from the repository on my production server by for example running a php or perl script.

The production site is hosted with a shared hosting provider who doesn't allow shell access or for example the php exec() function. (I don't know much about perl; I only know that my hoster allows perl and custom cgi scripts).

Is it possible to perform a SVN export in this environment?

Answer:
SVN supports access over WebDAV (i.e. HTTPS). This means for simple read access you don't actually need an SVN client to access an SVN repository. You can even use a web browser, or in your case any PHP function that accepts a URL as its argument. SVN has to be set up on the server side to work with apache, for more info check out the
svn red book


Question:
The Python list comprehension syntax makes it easy to filter values within a comprehension.  For example:

result = [x**2 for x in mylist if type(x) is int]

Will return a list of the squares of integers in mylist.  However, what if the test involves some (costly) computation and you want to filter on the result?  One option is:

result = [expensive(x) for x in mylist if expensive(x)]

This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x.  Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?

Answer:
Came up with my own answer after a minute of thought.  It can be done with nested comprehensions:
```
```
result = [y for y in (expensive(x) for x in mylist) if y]
```
```
I guess that works, though I find nested comprehensions are only marginally readable


Question:
Background

Normal rails eager-loading of collections works like this:

Person.find(:all, :include=>:companies)

This generates some sql which does

LEFT OUTER JOIN companies ON people.company_id = companies.id

Question

However, I need a custom join (this could also arise if I was using find_by_sql) so I can't use the vanilla :include => :companies

The custom join/sql will get me all the data I need, but how can I tell activerecord that it belongs to the associated Company objects rather than just being a pile of extra rows?

Update

I need to put additional conditions in the join. Something like this:

SELECT blah blah blah
LEFT OUTER JOIN companies ON people.company_id = companies.id AND people.magical_flag IS NULL
<Several other joins>
WHERE blahblahblah

Answer:
Can you not add the join conditions using ActiveRecord?
For example, I have a quite complex query using several dependent records and it works fine by combining conditions and include directives
```
```
Contractors.find(
  :all,
  :include => {:council_areas => :suburbs},
  :conditions => ["suburbs.postcode = ?", customer.postcode]
)
```
```
Assuming that:
Contractors have_many CouncilAreas
CouncilAreas have_many Suburbs
This join returns the Contractors in the suburb identified by
customer.postcode
.
The generated query looks like:
```
```
SELECT contractors.*, council_areas.*, suburbs.*
FROM `contractors`
LEFT OUTER JOIN `contractors_council_areas` ON `contractors_council_areas`.contractor_id = `contractors`.id
LEFT OUTER JOIN `council_areas` ON `council_areas`.id = `contractors_council_areas`.council_area_id
LEFT OUTER JOIN `council_areas_suburbs` ON `council_areas_suburbs`.council_area_id = `council_areas`.id
LEFT OUTER JOIN `suburbs` ON `suburbs`.id = `council_areas_suburbs`.suburb_id WHERE (suburbs.postcode = '5000')
```
```
(Note: I edited the column list for brevity).


Question:
I have a server that sends data via a socket, the data is a wav 'file'. I can easily write the data to disk and then play it in WMP, but I have no idea how I can play it as I read it from the socket. Is it possible?

Bonus question: how would I do it if the stream was in mp3 or other format?

This is for windows in native C++.

Answer:
Because you've said WMP, I'm assuming the question applies to trying to play a wav file on a windows machine.  If not, this answer isn't relevant.
What you want to do isn't trivial.  There is a good article
here
on code project that describes the windows audio model.  It describes how to set up the audio device and how to stream data into the device for playback.  You "simply" need to supply data coming in from your socket as data for the playback buffers.  But that's where all of the tricky work is.  You have to be sure that
You have enough data to begin a playback
Handle the case when your socket is starved for data and you have nothing to send to the playback buffer
You are able to read data off of the socket with enough speed to keep the playback buffers full
It's an interesting exercise.  But tricky.


Question:
What is the proper way to inject a data access dependency when I do lazy loading?

For example I have the following class structure

class CustomerDao : ICustomerDao
  public Customer GetById(int id) {...}

class Transaction {
  int customer_id; //Transaction always knows this value
  Customer _customer = null;
  ICustomerDao _customer_dao;
  Customer GetCustomer() {
    if(_customer == null)
      _customer = _customer_dao.GetById(_customer_id);
    return _customer
  }

How do I get the reference to _customer_dao into the transaction object?  Requiring it for the constructor seems like it wouldn't really make sense if I want the Transaction to at least look like a POCO.  Is it ok to have the Transaction object reference the Inversion of Control Container directly?  That also seems awkward too.

How do frameworks like NHibernate handle this?

Answer:
I typically do the dependency injection in the constructor like you have above, but take the lazy loading a step further by acting only when the "get" is called like I have below.  Not sure if this is the pure approach you are looking for, but it does eliminate the "dirty" constructor DI/Lazy Loading in 1 step ;)
```
```
public class Product
{
    private int mProductID;
    private Supplier mSupplier;
    private ISupplierService mSupplierService;

    public Product()
    {
      //if you want your object to remain POCO you can use dual constr
      //this constr will be for app use, the next will be for testing
    }

    public Product(ISupplierService SupplierService)
    {
        mSupplierService = SupplierService;
    }

    public Supplier Supplier {
        get {
            if (mSupplier == null) {
                if (mSupplierService == null) {
                    mSupplierService = new SupplierService();
                }
                mSupplier = mSupplierService.GetSupplierByProductID(mProductID);
            }
            return mSupplier;
        }
        set { mSupplier = value; }
    }
}
```
```


Question: I cant seem to find much info on haskells layout features, as I understand it is something like pythons formatting requirements except that is optional. How can I choose not to use this option correctly? Would it be a good idea to start without it so that I get a solid feel for the language itself?

Answer:
See
http://en.wikibooks.org/wiki/Programming:Haskell_indentation
and
http://www.haskell.org/onlinereport/lexemes.html#sect2.7
(both contain examples).
Pros:
less typing
less to read, nicer-looking (if you're comfortable with it)
Cons:
you might get it wrong, especially if you're not familiar with it. Braces make things crystal clear if you're not sure.


Question:
Is there a way to use constants in JavaScript?

If not, what's the common practice for specifying variables that are used as constants?

Answer:
No, not in general. Firefox implements
```
const
```
but I know IE doesn't.
@John
points to a common naming practice for consts that has been used for years in other languages, I see no reason why you couldn't use that. Of course that doesn't mean someone will not write over the variable's value anyway. :)


Question:
I'm trying to find a way to "pretty print" a JavaScript data structure in a human-readable form for debugging.

I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI.

All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I'd usually use Firebug's excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn't seem to be possible in Firebug.

Answer:
In
```
Firebug
```
, if you just
```
console.debug ("%o", my_object)
```
you can click on it in the console and enter an interactive object explorer. It shows the entire object, and lets you expand nested objects.


Question:
How does AOP (Aspect Oriented Programming) work in Drupal?

I have learned about AOP in terms of using it for logging and security, but how does it apply to Drupal?

Answer:
Drupal mimics AOP paradigms through hooks, which basically allow developers to weave in bits of code during the flow of execution. You can take a look at the hooks a developer can implement on the
list of Drupal hooks
shown in the Drupal documentation site, which just lists the hooks invoked from Drupal core and its modules.
As a quick example, if I were developing a new node based module (nodes being the basic data form in Drupal), I have instant access to comments and taxonomy with no additional work on my part. the comment and taxonomy modules have the ability to hook into nodes, and provide that added functionality. So in that sense, I don't have to account for such features in my program but I am able to take advantage of that flexibility.


Question:
Does a hash shrink in Perl as you delete elements.

More specifically I had a perl program that I inherited that would parse a huge file ( 1 GB ) and load up a hash of hashes. it would do that same for another file and then do a comparison of different elements. The memory consumption was huge during this process and even though I added deleting hash elements has they were used the memory consumption seemed to be unaffected.

The script was extremely slow and such a memory hog. I know it was not well designed but any ideas about the hash memory usage?

Answer:
In general, Perl cannot return memory to the operating system. It may be able to reuse memory internally, though, which could reduce the amount of memory needed by a program.
See perlfaq3:
How can I free an array or hash so my program shrinks?
If the memory used by the hashes is excessive (i.e. > physical memory) you could
```
tie
```
them to a file on disk. This would greatly reduce your memory usage but be warned that accessing a structure on disk is much slower than accessing one in memory. (So is disk thrashing.)


Question: I use the commercial version of Jalopy for my Java projects but it doesn't work on Groovy files.  IntelliJ has a serviceable formatter but I don't like requiring a particular IDE.

Answer:
Try "BUSL"
2022-10-26 NOTE:
HISTORIC. "BUSL" seems to be dead.
Last archived webpage is from 2020
.
I've found that
BUSL
works really well on Groovy files. It's standalone too, so you can use it from your text editor or whatever.


Question: I'd really like to get into some D3D coding, but I don't have the time lately to learn C++ for what will amount to a hobby project.

Answer:
The number that your application needs; no more, and no less.
Obviously, if you're writing an application which contains some parallelisable algorithm, then you can probably start benchmarking to find a good balance in the number of threads, but bear in mind that hundreds of threads won't speed up any operation.
If your algorithm can't be parallelised, then no number of additional threads is going to help.


Question:
I am building an application where a page will load user controls (x.ascx) dynamically based on query string.

I have a validation summary on the page and want to update it from the User Controls. This will allow me to have multiple controls using one Validation Summary. How can I pass data between controls and pages.

I know I can define the control at design time and use events to do that but these controls are loaded dynamically using Page.LoadControl.

Also, I want to avoid using sessions or querystring.

Answer:
Assuming you're talking about asp's validator controls, making them work with the validation summary should be easy: use the same Validation Group. Normally, I derive all usercontrols from a base class that adds a ValidationGroup property whose setter calls a overriden method that changes all internal validators to the same validation group.
The tricky part is making them behave when added dynamically. There are some gotchas you should be aware of, mainly concerning the page cycle and when you add them to your Page object. If you know all the possible user controls you'll use during design time, I'd try to add them statically using EnableViewState and Visible to minimize overhead, even if there are too many of them.


Question: I am writing a page where I need an HTML table to maintain a set size. I need the headers at the top of the table to stay there at all times but I also need the body of the table to scroll no matter how many rows are added to the table. Think a mini version of excel. This seems like a simple task but almost every solution I have found on the web has some drawback. How can I solve this?

Answer:
Have you tried using thead and tbody, and setting a fixed height on tbody with overflow:scroll?
What are your target browsers?
EDIT: It worked well (almost) in firefox - the addition of the vertical scrollbar caused the need for a horizontal scrollbar as well - yuck.  IE just set the height of each td to what I had specifed the height of tbody to be.  Here's the best I could come up with:
```
```

    <title>Blah</title>

              One	Two

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

Data	Data

```
```


Question:
We have recently moved back to InstallShield 2008 from rolling our own install. So, I am still trying to get up the learning curve on it.

We are using Firebird and a usb driver, that we couldn't find good msi install solutions. So, we have a cmd line to install firebird silently and the usb driver mostly silently.

We have put this code into the event handler DefaultFeatureInstalled. This works really well on the first time install. But, when I do an uninstall it trys to launch the firebird installer again, so it must be sending the DefaultFeatureInstalled event again.

Is their another event to use, or is there a way to detect whether its an install or uninstall in the DefaultFeatureInstalled event?

Answer:
There are MSI properties you can look at that will tell you if a product is already installed or if an uninstall is taking place. The Installed property will be true if the product is already there, so you can use it in a Boolean expression (Ex: Not Installed). The REMOVE property will be set to "ALL" if an uninstall is taking place. You might be able to condition your Firebird installation logic on these properties, which you can retrieve using the
MsiGetProperty
function.
Note: Property names mean different things based on case, so make sure you use the cases above.
I couldn't find any reference in the IS online help or Google to the DefaultFeatureInstalled event. Is your InstallShield project Basic MSI or InstallScript?


Question:
How do they compare to the DevXpress ones or the original MSOffice ones.

Are they worth investing time in them (for practical usage now, not academic curiosity which I'll do anyway)?

Answer:
From my experience, the new ribbon control implements the entire specification as laid out by Microsoft.  The only issue I noticed was a slight flicker when the form was resized which caused one of the sections to collapse or expand.
Worth spending time in?  Definitely, as they are lighter weight and its a matter of time before someone gets rid of the flicker (could be as simple as a lockwindowupdate inserted in the source?).  It doesn't hurt to use the Delphi action manager, from which all is based.


Question:
I've never used CI tools before, but from what I've read, I'm not sure it would provide any benefit to a solo developer that isn't writing code every day.

First - what benefits does CI provide to any project?

Second - who should use CI? Does it benefit all developers?

Answer:
The benefit of CI lies in the ability to discover early when a check in has broken the build. You can also run your suite of automated tests against the build, as well as run any kind of tools to give you metrics and such.
Obviously, this is very valuable when you have a team of commiters, not all of whom are diligent to check for breaking changes. As a solo developer, it is not quite as valuable. Presumably, you run your unit tests, and even maybe integration tests.  However, I have seen a number of occasions where the developer forgets to checkin a file out of a set.
The CI build can also be thought of as your "release" build.  The environment should be stable, and unaffected by whatever development gizmo you just add to your machine.  It should allow you to always reproduce a build.
This can be valuable if you add a new dependency to your project, and forget to setup the release build environment to take that into account.


Question:
I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that.

ie.

50 + 100 = 150

int.Max + 50 = int.Max and not int.Min + 50

Answer:
```
```
int penaltySum(int a, int b)
{
    return (int.MaxValue - a < b) ? int.MaxValue : a + b;
}
```
```
Update: If your penalties can be negative, this would be more appropriate:
```
```
int penaltySum(int a, int b)
{
    if (a > 0 && b > 0)
    {
        return (int.MaxValue - a < b) ? int.MaxValue : a + b;
    }

    if (a < 0 && b < 0)
    {
        return (int.MinValue - a > b) ? int.MinValue : a + b;
    }

    return a + b;
}
```
```


Question:
I have a table of Users that includes a bitmask of roles that the user belongs to. I'd like to select users that belong to one or more of the roles in a bitmask value. For example:

select *
from   [User]
where  UserRolesBitmask | 22 = 22

This selects all users that have the roles '2', '4' or '16' in their bitmask. Is this possible to express this in a LINQ query? Thanks.

Answer:
I think this will work, but I haven't tested it.Substitute the name of your DataContext object. YMMV.
```
```
from u in DataContext.Users
where UserRolesBitmask | 22 == 22
select u
```
```


Question:
I've got a dictionary, something like

Dictionary<Foo,String> fooDict

I step through everything in the dictionary, e.g.

foreach (Foo foo in fooDict.Keys)
    MessageBox.show(fooDict[foo]);

It does that in the order the foos were added to the dictionary, so the first item added is the first foo returned.

How can I change the cardinality so that, for example, the third foo added will be the second foo returned? In other words, I want to change its "index."

Answer:
I am
not fully educated in the domain
to properly answer the question, but I have
a feeling
that the dictionary sorts the values according to the key, in order to perform quick key search. This would suggest that the dictionary is sorted by key values according to key comparison. However, looking at
object
methods, I assume they are using hash codes to compare different objects considering there is no requirement on the type used for keys. This is only a guess. Someone more knowledgey should fill in with more detail.
Why are you interested in manipulating the "index" of a dictionary when its purpose is to index with arbitrary types?


Question:
I'm trying to start a service as a user and things work fine, until I try a user that doesn't have a password. Then, it fails to start (due to log-on error).

Am I doing something wrong or is this "by design"?

The code to register this service:

    SC_HANDLE schService = CreateService(
        schSCManager,
        strNameNoSpaces,
        strServiceName,
        SERVICE_ALL_ACCESS,
        SERVICE_WIN32_OWN_PROCESS,
        SERVICE_AUTO_START,
        SERVICE_ERROR_NORMAL,
        szPath,
        NULL,
        NULL,
        NULL,
        strUser,
        (strPassword.IsEmpty())?NULL:strPassword);

Answer:
You need to specify an empty string, not NULL if there is no password. NULL is not a valid empty string, "" is. Probably you should just pass
```
strPassword
```
for the last parameter.
```
```
SC_HANDLE schService = CreateService(
            schSCManager,
            strNameNoSpaces,
            strServiceName,
            SERVICE_ALL_ACCESS,
            SERVICE_WIN32_OWN_PROCESS,
            SERVICE_AUTO_START,
            SERVICE_ERROR_NORMAL,
            szPath,
            NULL,
            NULL,
            NULL,
            strUser,

// change this line to:
            strPassword.IsEmpty() ? L"" : strPassword);
// or maybe
            strPassword);
```
```


Question:
I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to:

if (datetime.now() - self.timestamp) > 100
# Where 100 is either seconds or minutes

This generates a type error.

What is the proper way to do date time comparison in python? I already looked at WorkingWithTime which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison.

Please post lists of datetime best practices.

Answer:
You can subtract two
datetime
objects to find the difference between them.
You can use
```
datetime.fromtimestamp
```
to parse a POSIX time stamp.


Question:
I want to wrap a Perl one-liner in a batch file. For a (trivial) example, in a Unix shell, I could quote up a command like this:

perl -e 'print localtime() . "\n"'

But DOS chokes on that with this helpful error message:

Can't find string terminator "'" anywhere before EOF at -e line 1.

What's the best way to do this within a .bat file?

Answer:
For Perl stuff on Windows, I try to use the generalized quoting as much as possible so I don't get leaning toothpick syndrome. I save the quotes for the stuff that DOS needs:
```
```
perl -e "print scalar localtime() . qq(\n)"
```
```
If you just need a newline at the end of the print, you can let the
```
-l
```
switch do that for you:
```
```
perl -le "print scalar localtime()"
```
```
For other cool things you can do with switches, see the
perlrun
documentation.


Question:
I wonder how long it would usually take for:

Professional

Average

Beginner

to setup and configure CI for a new project?

Answer:
CI Factory
TeamCity
CC.NET sample configs
Try.


Question:
It's been a while since I've had to do any HTML-like code in Vim, but recently I came across this again. Say I'm writing some simple HTML:

<html><head><title>This is a title</title></head></html>

How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one.

Of course I can use CtrlP to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.

Answer:
Check this out..
closetag.vim
```
```
Functions and mappings to close open HTML/XML tags
```
```
https://www.vim.org/scripts/script.php?script_id=13
I use something similar.


Question:
I've got a form where I have two radio buttons and two interchangeable controls (made up of a ListView and a handful of buttons). Based on which radio button is selected I want to display the proper control to the user.

The way I'm doing this now is just loading both controls and setting up an OnRadioButtonSelectionChanged() method which gets called at form load (to set the initial state) and at any time the selection is changed. This method just sets the visible property on each control to the proper value.

This seems to work well enough, but I was curious as to if there was a better or more common way of doing it?

Answer:
Yep, that's pretty much how I do it.  I would set the CheckedChanged event of both radio buttons to point at a single event handler and would place the following code to swap out the visible control.
```
```
private void OnRadioButtonCheckedChanged(object sender, EventArgs e)
{
    Control1.Visible = RadioButton1.Checked;
    Control2.Visible = RadioButton2.Checked;
}
```
```


Question:
I want my Python script to copy files on Vista. When I run it from a normal cmd.exe window, no errors are generated, yet the files are NOT copied. If I run cmd.exe "as administator" and then run my script, it works fine.

This makes sense since User Account Control (UAC) normally prevents many file system actions.

Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")

If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?

Answer:
It seems there's no way to elevate the application privileges for a while for you to perform a particular task. Windows needs to know at the start of the program whether the application requires certain privileges, and will ask the user to confirm when the application performs any tasks that
need
those privileges. There are two ways to do this:
Write a manifest file that tells Windows the application might require some privileges
Run the application with elevated privileges from inside another program
This
two
articles
explain in much more detail how this works.
What I'd do, if you don't want to write a nasty ctypes wrapper for the CreateElevatedProcess API, is use the ShellExecuteEx trick explained in the Code Project article (Pywin32 comes with a wrapper for ShellExecute). How? Something like this:
When your program starts, it checks if it has Administrator privileges, if it doesn't it runs itself using the ShellExecute trick and exits immediately, if it does, it performs the task at hand.
As you describe your program as a "script", I suppose that's enough for your needs.
Cheers.


Question:
I have some C# code in an ASP.Net application that does this:

Bitmap bmp = new Bitmap(1184, 1900);

And occasionally it throws an exception "Parameter is not valid". Now i've been googling around and apparently GDI+ is infamous for throwing random exceptions, and lots of people have had this problem, but nobody has a solution to it! I've checked the system and it has plenty of both RAM and swap space.
Now in the past if i do an 'iisreset' then the problem goes away, but it comes back in a few days. But i'm not convinced i've caused a memory leak, because as i say above there is plenty of ram+swap free.

Anyone have any solutions?

Answer:
You not only need enough memory, it needs to be contiguous.  Over time memory becomes fragmented and it becomes harder to find big blocks.  There aren't a lot of good solutions to this, aside from building up images from smaller bitmaps.
new Bitmap(x, y) pretty much just needs to allocate memory -- assuming that your program isn't corrupted in some way (is there any unsafe code that could corrupt the heap), then I would start with this allocation failing.  Needing a contiguous block is how a seemingly small allocation could fail.  Fragmentation of the heap is something that is usually solved with a custom allocator -- I don't think this is a good idea in IIS (or possible).
To see what error you get on out of memory, try just allocation a gigantic Bitmap as a test -- see what error it throws.
One strategy I've seen is to pre-allocate some large blocks of memory (in your case Bitmaps) and treat them as a pool (get and return them to the pool).  If you only need them for a short period of time, you might be able to get away with just keeping a few in memory and sharing them.


Question:
There have been several questions already posted with specific questions about dependency injection, such as when to use it and what frameworks are there for it. However,

What is dependency injection and when/why should or shouldn't it be used?

Answer:
Dependency Injection
is passing dependency to other
objects
or
framework
( dependency injector).
Dependency injection makes testing easier. The injection can be done through
constructor
.
```
SomeClass()
```
has its constructor as following:
```
```
public SomeClass() {
    myObject = Factory.getObject();
}
```
```
Problem
:
If
```
myObject
```
involves complex tasks such as disk access or network access, it is
hard
to do unit test on
```
SomeClass()
```
. Programmers have to mock
```
myObject
```
and might
intercept
the factory call.
Alternative solution
:
Passing
```
myObject
```
in as an argument to the constructor
```
```
public SomeClass (MyClass myObject) {
    this.myObject = myObject;
}
```
```
```
myObject
```
can be passed directly which makes testing easier.
One common alternative is defining a
do-nothing constructor
. Dependency injection can be done through setters. (h/t @MikeVella).
Martin Fowler
documents a third alternative (h/t @MarcDix), where
classes explicitly implement an interface
for the dependencies programmers wish injected.
It is harder to isolate components in unit testing without dependency injection.
In 2013, when I wrote this answer, this was a major theme on the
Google Testing Blog
. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.


Question:
I'm using GNU autotools for the build system on a particular project. I want to start writing automated tests for verifcation. I would like to just type "make check" to have it automatically run these. My project is in C++, although I am still curious about writing automated tests for other languages as well.

Is this compatible with pretty much every unit testing framework out there (I was thinking of using cppunit)? How do I hook these unit testing frameworks into make check? Can I make sure that I don't require the unit test software to be installed to be able to configure and build the rest of the project?

Answer:
You seem to be asking 2 questions in the first paragraph.
The first is about adding tests to the GNU autotools toolchain - but those tests, if I'm understanding you correctly, are for both validating that the environment necessary to build your application exists (dependent libraries and tools) as well as adapt the build to the environment (platform specific differences).
The second is about unit testing your C++ application and where to invoke those tests, you've proposed doing so from the autotools tool chain, presumably from the configure script.  Doing that isn't conventional though - putting a 'test' target in your Makefile is a more conventional way of executing your test suite.  The typical steps for building and installing an application with autotools (at least from a user's perspective, not from your, the developer, perspective) is to run the configure script, then run make, then optionally run make test and finally make install.
For the second issue, not wanting cppunit to be a dependency, why not just distribute it with your c++ application?  Can you just put it right in what ever archive format you're using (be it tar.gz, tar.bz2 or .zip) along with your source code.  I've used cppunit in the past and was happy with it, having used JUnit and other xUnit style frameworks.


Question:
I'm not that up on VB.NET, the application I'm working on was not written by myself.

It works fine through the IDE but once I run it from the exe it gives me the above error.

Any clues?

This is really hacking me off!

Answer:
The only user defined break point that I can think of is
```
```
Debugger.Break()
```
```
So, I would suspect that the .exe is compiled in debug mode.  I would recommend
Reflector
to look at the code and find out for sure whether or not there is a Debugger.Break() somewhere in there.


Question:
I have 3 points in a 3D space of which I know the exact locations. Suppose they are: (x0,y0,z0), (x1,y1,z1) and (x2,y2,z2).

Also I have a camera that is looking at these 3 points and I know the 2D locations of those three points on camera view plane. So for example (x0,y0,z0) will be (x0',y0'), and (x1,y1,z1) will be (x1',y1') and (x2,y2,z2) will be (x2',y2') from the camera's point of view.

What is the easiest way to find the projection matrix that will project those 3D points into 2D points on camera view plane. We don't know anything about the camera location.

Answer:
This gives you two sets, each of three equations in 3 variables:
```
```
a*x0+b*y0+c*z0 = x0'
a*x1+b*y1+c*z1 = x1'
a*x2+b*y2+c*z2 = x2'

d*x0+e*y0+f*z0 = y0'
d*x1+e*y1+f*z1 = y1'
d*x2+e*y2+f*z2 = y2'
```
```
Just use whatever method of solving simultaneous equations is easiest in your situation (it isn't even hard to solve these "by hand").  Then your transformation matrix is just ((a,b,c)(d,e,f)).
...
Actually, that is over-simplified and assumes a camera pointed at the origin of your 3D coordinate system and no perspective.
For perspective, the transformation matrix works more like:
```
```
( a, b, c, d )   ( xt )
( x, y, z, 1 ) ( e, f, g, h ) = ( yt )
               ( i, j, k, l )   ( zt )

( xv, yv ) = ( xc+s*xt/zt, yc+s*yt/zt ) if md < zt;
```
```
but the 4x3 matrix is more constrained than 12 degrees of freedom since we should have
```
```
a*a+b*b+c*c = e*e+f*f+g*g = i*i+j*j+k*k = 1
a*a+e*e+i*i = b*b+f*f+j*j = c*c+g*g+k*k = 1
```
```
So you should probably have 4 points to get 8 equations to cover the 6 variables for camera position and angle and 1 more for scaling of the 2-D view points since we'll be able to eliminate the "center" coordinates (xc,yc).
So if you have 4 points and transform your 2-D view points to be relative to the center of your display, then you can get 14 simultaneous equations in 13 variables and solve.
Unfortunately, six of the equations are not linear equations.  Fortunately, all of the variables in those equations are restricted to the values between -1 and 1 so it is still probably feasible to solve the equations.


Question:
I'm still learning RegEx at the moment, but for the time being could someone help me out with this?  I have a few special requirements for formatting the string:

No directories.  JUST the file name.

File name needs to be all lowercase.

Whitespaces need to be replaced with underscores.

Shouldn't be hard, but I'm pressed for time and I'm not sure on the 'correct' way to ensure a valid file name (namely I forget which characters were supposed to be invalid for file names).

Answer:
If you're in a super-quick hurry, you can usually find acceptable regular expressions in the library at
http://regexlib.com/
.
Edit to say:
Here's one that might work for you
:
```
```
([0-9a-z_-]+[\.][0-9a-z_-]{1,3})$
```
```


Question: What function will let us know whether a date in VBA is in DST or not?

Answer:
For non-current dates (DST 2007+):
First, you need a function to find the number of specific weekdays in a month:
```
```
Public Function NDow(Y As Integer, M As Integer, _
                N As Integer, DOW As Integer) As Date

' Returns Date of Nth Day of the Week in Month

NDow = DateSerial(Y, M, (8 - Weekday(DateSerial(Y, M, 1), _
              (DOW + 1) Mod 8)) + ((N - 1) * 7))

End Function
```
```
Then, you can check for the DST day versus the following function calls:
Fall:     NDow(Year(newdate), 11, 1, 1)
Spring:   NDow(Year(newdate), 3, 2, 1)
For the current date:
Call the Windows API function GetTimeZoneInformation,
and it will return an enum (integer) with the status.
I got the code for this from Chip Pearson's great Excel site.
Pearson's site


Question: How can I perform list comprehensions in C#?

Answer:
While this isn't a tutorial, here's some code that illustrates the concept:
```
```
public List<string> ValidUsers(List<User> users) {
  List<string> names = new List<string>();
  foreach(User user in users) {
    if(user.Valid) {
      names.Add(user.Name);
    }
  }
  return names;
}
```
```


Question: Is it at the state where it is actually useful and can do more than rename classes?

Answer:
CDT (C/C++ Development Tools - eclipse project) 5.0 has a bunch of new refactorings
```
```
* Declare Method
* Extract Baseclass
* Extract Constant
* Extract Method
* Extract Subclass
* Hide Method
* Implement Method
* Move Field / Method
* Replace Number
* Separate Class
* Generate Getters and Setters
```
```
There is a CDT refactoring
wiki


Question:
I need an easy way to take a tar file and convert it into a string (and vice versa). Is there a way to do this in Ruby? My best attempt was this:

file = File.open("path-to-file.tar.gz")
contents = ""
file.each {|line|
  contents << line
}

I thought that would be enough to convert it to a string, but then when I try to write it back out like this...

newFile = File.open("test.tar.gz", "w")
newFile.write(contents)

It isn't the same file. Doing ls -l shows the files are of different sizes, although they are pretty close (and opening the file reveals most of the contents intact). Is there a small mistake I'm making or an entirely different (but workable) way to accomplish this?

Answer:
You can probably encode the tar file in Base64. Base 64 will give you a pure ASCII representation of the file that you can store in a plain text file. Then you can retrieve the tar file by decoding the text back.
You do something like:
```
```
require 'base64'

file_contents = Base64.encode64(tar_file_data)
```
```
Have look at the Base64
Rubydocs
to get a better idea.


Question:
I have a table that has redundant data and I'm trying to identify all rows that have duplicate sub-rows (for lack of a better word). By sub-rows I mean considering COL1 and COL2 only.

So let's say I have something like this:

 COL1   COL2   COL3
 ---------------------
 aa     111    blah_x
 aa     111    blah_j
 aa     112    blah_m
 ab     111    blah_s
 bb     112    blah_d
 bb     112    blah_d
 cc     112    blah_w
 cc     113    blah_p

I need a SQL query that returns this:

 COL1   COL2   COL3
 ---------------------
 aa     111    blah_x
 aa     111    blah_j
 bb     112    blah_d
 bb     112    blah_d

Answer:
Join on yourself like this:
```
```
SELECT a.col3, b.col3, a.col1, a.col2
FROM tablename a, tablename b
WHERE a.col1 = b.col1 AND a.col2 = b.col2 AND a.col3 != b.col3
```
```
If you're using postgresql, you can use the oid to make it return less duplicated results, like this:
```
```
SELECT a.col3, b.col3, a.col1, a.col2
FROM tablename a, tablename b
WHERE a.col1 = b.col1 AND a.col2 = b.col2 AND a.col3 != b.col3
  AND a.oid < b.oid
```
```


Question:
I have a backroundrb scheduled task that takes quite a long time to run. However it seems that the process is ending after only 2.5 minutes.

My background.yml file:

:schedules:
  :named_worker:
    :task_name:
      :trigger_args: 0 0 12 * * * *
      :data: input_data

I have zero activity on the server when the process is running. (Meaning I am the only one on the server watching the log files do their thing until the process suddenly stops.)

Any ideas?

Answer:
There's not much information here that allows us to get to the bottom of the problem.
Because backgroundrb operates in the background, it can be quite hard to monitor/debug.
Here are some ideas I use:
Write a unit test to test the worker code itself and make sure there are no problems there
Put "puts" statements at multiple points in the code so you can at least see some responses while the worker is running.
Wrap the entire worker in a begin..rescue..end block so that you can catch any errors that might be occurring and cutting the process short.


Question:
I know there is a list-comprehension library for common lisp (incf-cl), I know they're supported natively in various other functional (and some non-functional) languages (F#, Erlang, Haskell and C#) - is there a list comprehension library for Scheme?

incf-cl is implemented in CL as a library using macros - shouldn't it be possible to use the same techniques to create one for Scheme?

Answer:
Swindle
is primarily a CLOS emulator library, but it has list comprehensions too. I've used them, they're convenient, but the version I used was buggy and incomplete. (I just needed generic functions.)
However, you probably want
SRFI-42
. I haven't used it, but it HAS to have fewer bugs than the Swindle list comprehensions.
I don't know which Scheme you use.
PLT Scheme
bundles Swindle and SRFI-42. Both are supposed to be cross-Scheme compatible, though.
If you use PLT Scheme, here is SRFI-42's
man page
. You say
```
(require srfi/42)
```
to get it.


Question:
Is it possible to do at least one of the following:

1) Detect a setting of a Local Security Policy (Accounts: Limit local account use of blank passwords to console logon only)

2) Modify that setting

Using Win32/MFC?

Answer:
Swindle
is primarily a CLOS emulator library, but it has list comprehensions too. I've used them, they're convenient, but the version I used was buggy and incomplete. (I just needed generic functions.)
However, you probably want
SRFI-42
. I haven't used it, but it HAS to have fewer bugs than the Swindle list comprehensions.
I don't know which Scheme you use.
PLT Scheme
bundles Swindle and SRFI-42. Both are supposed to be cross-Scheme compatible, though.
If you use PLT Scheme, here is SRFI-42's
man page
. You say
```
(require srfi/42)
```
to get it.


Question:
I installed mediawiki on my server as my personal knowledge base. Sometimes I copy some stuff from Web and paste to my wiki - such as tips & tricks from somebody's blog. How do I make the copied content appear in a box with border?

For example, the box at the end of this blog post looks pretty nice:

http://blog.dreamhost.com/2008/03/21/good-reminiscing-friday/

I could use the pre tag, but paragraphs in a pre tag won't wrap automatically.. Any ideas?

Answer:
Mediawiki supports the div tag.  Combine the div tag with some styles:
```
```
<div style="background-color: cyan; border-style: dashed;">
A bunch of text that will wrap.
</div>
```
```
You can play around with whatever css attributes you want, but that should get you started.


Question:
Since AS3 does not allow private constructors, it seems the only way to construct a singleton and guarantee the constructor isn't explicitly created via "new" is to pass a single parameter and check it.

I've heard two recommendations, one is to check the caller and ensure it's the static getInstance(), and the other is to have a private/internal class in the same package namespace.

The private object passed on the constructor seems preferable but it does not look like you can have a private class in the same package.  Is this true?  And more importantly is it the best way to implement a singleton?

Answer:
The pattern which is used by Cairngorm (which may not be the best) is to throw a runtime exception in the constructor if the constructor is being called a second time. For Example:
```
```
public class Foo {
  private static var instance : Foo;

  public Foo() {
    if( instance != null ) {
      throw new Exception ("Singleton constructor called");
    }
    instance = this;
  }

  public static getInstance() : Foo {
    if( instance == null ) {
      instance = new Foo();
    }
    return instance;
  }

}
```
```


Question:
I have been getting an error in VB .Net

object reference not set to an instance of object.

Can you tell me what are the causes of this error ?

Answer:
The object has not been initialized before use.
At the top of your code file type:
```
```
Option Strict On
Option Explicit On
```
```


Question:
Not sure how to ask a followup on SO, but this is in reference to an earlier question:
Fetch one row per account id from list

The query I'm working with is:

SELECT *
FROM scores s1
WHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score < s2.score)
ORDER BY score DESC

This selects the top scores, and limits results to one row per accountid; their top score.

The last hurdle is that this query is returning multiple rows for accountids that have multiple occurrences of their top score. So if accountid 17 has scores of 40, 75, 30, 75 the query returns both rows with scores of 75.

Can anyone modify this query (or provide a better one) to fix this case, and truly limit it to one row per account id?

Thanks again!

Answer:
If you are selecting a subset of columns then you can use the DISTINCT keyword to filter results.
```
```
SELECT DISTINCT UserID, score
FROM scores s1
WHERE accountid NOT IN (SELECT accountid FROM scores s2 WHERE s1.score < s2.score)
ORDER BY score DESC
```
```


Question:
I would like to create a copy of a database with approximately 40 InnoDB tables and around 1.5GB of data with mysqldump and MySQL 5.1.

What are the best parameters (ie: --single-transaction) that will result in the quickest dump and load of the data?

As well, when loading the data into the second DB, is it quicker to:

1) pipe the results directly to the second MySQL server instance and use the --compress option

or

2) load it from a text file (ie: mysql < my_sql_dump.sql)

Answer:
Pipe it directly to another instance, to avoid disk overhead. Don't bother with
```
--compress
```
unless you're running over a slow network, since on a fast LAN or loopback the network overhead doesn't matter.


Question: I'm wondering if updating statistics has helped you before and how did you know to update them?

Answer:
```
```
exec sp_updatestats
```
```
Yes, updating statistics can be very helpful if you find that your queries are not performing as well as they should.  This is evidenced by inspecting the query plan and noticing when, for example, table scans or index scans are being performed instead of index seeks.  All of this assumes that you have set up your indexes correctly.
There is also the
UPDATE STATISTICS
command, but I've personally never used that.


Question:
If I have a Range object--for example, let's say it refers to cell A1 on a worksheet called Book1.  So I know that calling Address()  will get me a simple local reference: $A$1.  I know it can also be called as Address(External:=True) to get a reference including the workbook name and worksheet name: [Book1]Sheet1!$A$1.

What I want is to get an address including the sheet name, but not the book name.  I really don't want to call Address(External:=True) and try to strip out the workbook name myself with string functions.  Is there any call I can make on the range to get Sheet1!$A$1?

Answer:
Only way I can think of is to concatenate the worksheet name with the cell reference, as follows:
```
```
Dim cell As Range
Dim cellAddress As String
Set cell = ThisWorkbook.Worksheets(1).Cells(1, 1)
cellAddress = cell.Parent.Name & "!" & cell.Address(External:=False)
```
```
EDIT:
Modify last line to :
```
```
cellAddress = "'" & cell.Parent.Name & "'!" & cell.Address(External:=False)
```
```
if you want it to work even if there are spaces or other funny characters in the sheet name.


Question:
Short version: I'm wondering if it's possible, and how best, to utilise CPU specific
instructions within a DLL?

Slightly longer version:
When downloading (32bit) DLLs from, say, Microsoft it seems that one size fits all processors.

Does this mean that they are strictly built for the lowest common denominator (ie. the
minimum platform supported by the OS)?
Or is there some technique that is used to export a single interface within the DLL but utilise
CPU specific code behind the scenes to get optimal performance? And if so, how is it done?

Answer:
The DLL is expected to work on every computer WIN32 runs on, so you are stuck to the i386 instruction set in general. There is no official method of exposing functionality/code for specific instruction sets. You have to do it by hand and transparently.
The technique used basically is as follows:
 - determine CPU features like MMX, SSE in runtime
 - if they are present, use them, if not, have fallback code ready
Because you cannot let your compiler optimise for anything else than i386, you will have to write the code using the specific instruction sets in inline assembler. I don't know if there are higher-language toolkits for this. Determining the CPU features is straight forward, but could also need to be done in assembler.


Question:
As much as I generally don't like the discussion/subjective posts on SO, I have really come to appreciate the "Hidden Secrets" set of posts that people have put together.  They provide a great overview of some commonly missed tools that you might now otherwise discover.

For this question I would like to explore the Visual Studio .NET debugger.  What are some of the "hidden secrets" in the VS.NET debugger that you use often or recently discovered and wish you would have known long ago?

Answer:
```
$exception
```
in the watch window will show the exception that is currently being processed even if you don't have a catch that assign the
```
Exception
```
instance to a named variable.


Question: I'm looking for resources that can help me determine which approach to use in creating a 2d data structure with C#.

Answer:
Do you mean multidimensional array? It's simple:
```
```
<type>[,] <name> = new <type>[<first dimenison>,<second dimension>];
```
```
Here is MSDN reference:
Multidimensional Arrays (C#)


Question: I am going to install SVN for my personal projects. Is it better to install it on a spare machine(Win XP) or will I save myself grief if I install it on the machine I use for development(Vista).

Answer:
Installing your repository on a separate machine is probably a better idea, since at a minimum, it will allow your source code to survive a hard drive crash on your development machine.
If you're new to SVN, you can't beat the free e-book from Red-Bean and O'Reilly ... Check out "Version Control with Subversion" here:
http://svnbook.red-bean.com/
.


Question: I'm stuck on a PHP 4 server, and I would like to start moving an old legacy project to modern Design Patterns, including Dependency Injection.  Are there any dependency injection frameworks that will work with PHP 4?

Answer:
I don't think a dependency injection framework will really work on PHP because of the way object-oriented programs are structured in it. First of all, it's not like C# or Java wherein the binaries are already there and you just have to find a way to instantiate this object and inject it into another. PHP has to load the class files and interpret them before it can use them. So if you have deep inheritance hierarchies with PHP I don't think that's a good idea.
Given that PHP is a scripting language, it's best to leverage it as that -- a scripting language. Which means, I would just make use of simple factory or builder methods to do something similar to dependency injection. I wouldn't burden it with a DI framework that will only add to the stuff the PHP runtime has to process for every web request (unless you do opcode caching, but there will still be overhead that's not incurred by web platforms for Java and .NET). If I have to change the objects that will be injected into objects or how they are created, it would be a simple task to just edit the script that contains the factory/builder methods. No need to recompile there anyway. So I have flexibility and I have a lightweight architecture that's suitable for the PHP way of doing things.


Question:
There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice?

Here are a few methods that I know of:

var a = 2.5;
window.parseInt(a); // 2
Math.floor(a);      // 2
a | 0;              // 2

I'm sure there are others out there. Suggestions?

Answer:
parseInt() is probably the best one.
```
a | 0
```
doesn't do what you really want (it just assigns 0 if a is an undefined or null value, which means an empty object or array passes the test), and Math.floor works by some type trickery (it basically calls parseInt() in the background).


Question:
I've read JRM's Syntax-rules Primer for the Merely Eccentric and it has helped me understand syntax-rules and how it's different from common-lisp's define-macro.  syntax-rules is only one way of implementing a syntax transformer within define-syntax.

I'm looking for two things, the first is more examples and explanations of syntax-rules and the second is good sources for learning the other ways of using define-syntax.  What resources do you recommend?

Answer:
To answer your second question:
```
syntax-case
```
is the other form that goes inside
```
define-syntax
```
. Kent Dybvig is the primary proponent of
```
syntax-case
```
, and
he has a tutorial on using it [PDF].
I also
read the PLT Scheme documentation
on
```
syntax-case
```
for a few more examples, and to learn about the variation in implementation.


Question:
What does it take to get C++ tr1 members (shared_ptr especially, but we'd like function and bind and ALL the others) working with GCC 3.4.4 (for the Nokia N810 tablet computer).

Has anyone done this?  Attempted this?

It may not be feasible for us to upgrade to GCC 4.x to cross-compile for this device (but if you've done that, we'd love to know).

There may be many approaches, and I'd like to avoid dead ends others have hit.

We're trying to avoid bringing in boost, since it can be pretty interdependent (you bring in one boost header and you end up with 20 more), and keeping code size down is important to us.

Thank you!

Answer:
Are you able to use
Boost
(
Smart Pointers
,
Bind
,
Function
) directly? From the
GCC changelogs
, the actual
```
std::tr1
```
stuff is only available from 4.0 onwards. :-(
I know there are differences between the Boost and
```
std::tr1
```
, but hopefully these can be worked around satisfactorily. Let me know how it works for you. :-)


Question:
I have this code:

chars = #some list

try:
    indx = chars.index(chars)
except ValueError:
    #doSomething
else:
   #doSomethingElse

I want to be able to do this because I don't like knowfully causing Exceptions:

chars = #some list

indx = chars.index(chars)

if indx == -1:
    #doSomething
else:
   #doSomethingElse

Is there a way I can do this?

Answer:
```
```
if element in mylist:
    index = mylist.index(element)
    # ... do something
else:
    # ... do something else
```
```


Question:
How do I apply the MarshalAsAttribute to the return type of the code below?

public ISomething Foo()
{
    return new MyFoo();
}

Answer:
According to
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx
:
```
```
[return: MarshalAs(<your marshal type>)]
public ISomething Foo()
{
    return new MyFoo();
}
```
```


Question: I am just curious to know how long, in minutes, does the reporting service take to generate report when it returns 1MB of data. Maybe using views and table is properly index. SSRS reporting  and server side generation.

Answer: How long is acceptable? Depends on what it's doing, how much it's run, things like that. Anything below 30 seconds would be fine if it's run once every day or two. If it's run once a week or once a month that number could be a lot higher.


Question:
I have a web application using ASP.NET 2.0 and I want to know if I should be moving it to ASP.NET 3.5, particularly... what am I missing by not moving to ASP.NET 3.5?

I understand the disadvantages, but I don't understand the advantages.

What are the biggest benefits of migrating/rewriting?

Will I get a speed improvement?

Is MVC that much easier than my old-fashioned WebForm application?

Will it look cooler?

Answer:
You will only miss access to the newer .NET 3.5 libraries, and cool syntax such as LINQ and lambda expressions. Performance wise they will run the same.
By the way, ASP.NET MVC is NOT included with .NET 3.5...yet.


Question:
I've got a BPG file that I've modified to use as a make file for our company's automated build server. In order to get it to work I had to change

Uses                       *  Uses
  unit1 in 'unit1.pas'     *   unit1
  unit2 in 'unit2.pas'     *   unit2
   ...                     *    ...

in the DPR file to get it to work without the compiler giving me some guff about unit1.pas not found.
This is annoying because I want to use a BPG file to actually see the stuff in my project and every time I add a new unit, it auto-jacks that in 'unitx.pas' into my DPR file.

I'm running make -f [then some options], the DPR's that I'm compiling are not in the same directory as the make file, but I'm not certain that this matters. Everything compiles fine as long as the in 'unit1.pas is removed.

Answer:
Well this work-around worked for me.
```
//{$define PACKAGE}
{$ifdef PACKAGE}
 uses
  unit1 in 'unit1.pas'
  unit2 in 'unit2.pas'
   ...
{$else}
 uses
  unit1
  unit2
   ...
{$endif}
```
The only problem is whenever you add a new unit, delphi erases your
```
ifdef package
```
at the top.


Question:
In my ASP.Net 1.1 application, i've added the following to my Web.Config (within the System.Web tag section):

<httpHandlers>
  <add verb="*" path="*.bcn" type="Internet2008.Beacon.BeaconHandler, Internet2008" />
</httpHandlers>

This works fine, and the HTTPHandler kicks in for files of type .bcn, and does its thing.. however for some reason all ASMX files stop working.  Any idea why this would be the case?

Cheers
Greg

Answer:
It sounds like it as an inherant <clear /> in it although I don't know if I've seen this behaviour before, you could just add the general handler back, let me find you the code.
```
```
<add verb="*" path="*.asmx" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services" validate="false">
```
```
I think thats the right element, give it a shot.
EDIT: That is odd, I don't have a copy of 2003 on this machine so I can't open a 1.1 but I thought that was the right declaration.  You could try adding
```
validate="false"
```
into each element and see if that makes a difference.


Question:
I am using VS 2008 with a very simple UpdatePanel scenario.
But i cannot get UpdatePanel to work and cant seem to find out why

I have in fact reverted to a very simple example to validate it is not my code:
http://ajax.net-tutorials.com/controls/updatepanel-control/

In this example I click on either button and both text links update.

I dont get any errors, the page just behaves like a normal ASPX page.
What things do i need to check. I've been googling this for an hour and not found what I need.

Edit: Works in Visual Studio web server but not in IIS

Answer:
If it's working locally, but not when deployed to a remote server, that usually indicates that you're using ASP.NET 2.0 and the ASP.NET AJAX extensions aren't installed on the remote server.
If it's a server you have administrative control over, you can download the installer here:
http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en
If it's a web host, tell them to get their act together.


Question:
Is there a way to search for multiple strings simultaneously in Vim? I recall reading somewhere that it was possible but somehow forgot the technique.

So for example, I have a text file and I want to search for "foo" and "bar" simultaneously (not necessarily as a single string, can be in different lines altogether).

How do I achieve that?

Answer:
```
```
/(foo|bar)
```
```


Question:
I know that embedding CSS styles directly into the HTML tags they affect defeats much of the purpose of CSS, but sometimes it's useful for debugging purposes, as in:

<p style="font-size: 24px">asdf</p>

What's the syntax for embedding a rule like:

a:hover {text-decoration: underline;}

into the style attribute of an A tag? It's obviously not this...

<a href="foo" style="text-decoration: underline">bar</a>

...since that would apply all the time, as opposed to just during hover.

Answer:
I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet.
I should mention that
technically
you
should
be able to do it
according to the CSS spec
, but most browsers don't support it
Edit:
I just did a quick test with this:
```
```
Test
```
```
And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome.  Can anyone else test in any other browsers?


Question: What is the right place to store program data files which are the same for every user but have to be writeable for the program? What would be the equivalent location on MS Windows XP? I have read that C:\ProgramData is not writeable after installation by normal users. Is that true? How can I retrieve that directory programmatically using the Platform SDK?

Answer:
```
SHGetFolderPath()
```
with CSIDL of
```
CSIDL_COMMON_APPDATA
```
.
Read more at
http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx
If you need the path in a batch file, you can also use the
```
%ALLUSERSPROFILE%
```
environment variable.


Question:
Several years back, I innocently tried to write a little app to save my tactically placed desktop icons because I was sick of dragging them back to their locations when some event reset them.  I gave up after buring WAY too much time having failed to find a way to query, much less save and reset, my icons' desktop position.

Anyone know where Windows persists this info and if there's an API to set them?

Thanks,
Richard

Answer:
I have no idea about the API, but I know Ultramon (
http://www.realtimesoft.com/ultramon/
) has a feature included for preserving icon placement (although I've never used it for preserving icon location, it is indispensable for multiple monitor usage). The latest beta release works flawlessly with Vista (except for sometimes having a minor glitch or two when initially logging into my machine via RDP), and of course, haven't had any issues with XP. I've used it for over four years now.
And did I mention that it's the best utility for multiple monitor usage?


Question:
How do I read the Response Headers that are being sent down in a page ? I want to be able to read the header values and modify some of them. This is for an ASP.NET 1.1 application but I would be curious to know if it can done in any version of ASP.NET.
The reason for doing this is someone may have added custom headers of their own before the point I am examining the response - so I cannot blindly clear all the headers and append my own - I need to read the all the headers so I can modify the appropriate ones only.

Answer:
AFAIK it cannot be done in ASP.NET 1.1. There is no way for you to get at the response headers - request headers are available but not response headers.
I am not sure if you can do this in other stacks like Java, LAMP though and I am curious to find out...


Question:
I'm using the Telerik RAD Controls RADEditor/WYSIWYG control as part of a Dynamic Data solution.

I would like to be able to upload files using the Document Manager of this control.

However, these files are larger than whatever the default setting is for maximum upload file size.

Can anyone point me in the right direction to fix this?

Thanks Yaakov Ellis, see your answer + the answer I linked through a comment for the solution.

Answer:
The Telerik website has instructions
here
.
Short version: in Web.config set the maxRequestLength
```
```
<system.web>
  <httpRuntime maxRequestLength="102400" executionTimeout= "3600" />
</system.web>
```
```


Question: I have an old Delphi codebase I have to maintain, lots of DLLs, some older than others. In some of these DLLs there is no version information in the Project Options dialog. The controls for adding a version are greyed out and I can't even add a version number by manually editing the .DOF file. How can I include a version number in these projects?

Answer:
Check if the default .RES file exists in the project source location. Delphi includes the version number of the project in a .res file with the same name as the .dpr file. If the .RES file does not exist, the simplest way to recreate it is to add the {$R *.RES} compiler directive to the .DPR file, immediately after the uses clause.
```
```
library foolib;

uses
    foo in 'foo.pas',
    baz in 'baz.pas';

{$R *.RES}

exports
    foofunc name 'foofunc';

end;
```
```
As soon as you add the {$R *.RES} compiler directive Delphi will tell you it has recreated the foolib.res resource file.


Question: I notice that modern C and C++ code seems to use size_t instead of int/unsigned int pretty much everywhere - from parameters for C string functions to the STL.  I am curious as to the reason for this and the benefits it brings.

Answer:
The
```
size_t
```
type is the unsigned integer type that is the result of the
```
sizeof
```
operator (and the
```
offsetof
```
operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).
The
```
size_t
```
type may be bigger than, equal to, or smaller than an
```
unsigned int
```
, and your compiler might make assumptions about it for optimization.
You may find more precise information in the C99 standard, section 7.17, a draft of which is available on the Internet in
pdf
format, or in the C11 standard, section 7.19, also available as a
pdf draft
.


Question:
What is the SQL command to copy a table from one database to another database?
I am using MySQL and I have two databases x and y. Suppose I have a table in x called a and I need to copy that table to y database.
Sorry if the question is too novice.

Thanks.

Answer:
If you just want to copy the contents, you might be looking for
```
select into
```
:
http://www.w3schools.com/Sql/sql_select_into.asp
. This will not create an identical copy though, it will just copy every row from one table to another.


Question:
Can someone explain why how the result for the following unpack is computed?

"aaa".unpack('h2H2')               #=> ["16", "61"]

In binary, 'a' = 0110 0001.  I'm not sure how the 'h2' can become 16 (0001 0000) or 'H2' can become 61 (0011 1101).

Answer:
Check out the Programming Ruby
reference
on unpack. Here's a snippet:
Decodes str (which may contain binary
data) according to the format string,
returning an array of each value
extracted. The format string consists
of a sequence of single-character
directives, summarized in Table 22.8
on page 379. Each directive may be
followed by a number, indicating the
number of times to repeat with this
directive. An asterisk ("*") will
use up all remaining elements. The
directives sSiIlL may each be followed
by an underscore ("_") to use the
underlying platform's native size for
the specified type; otherwise, it uses
a platform-independent consistent
size. Spaces are ignored in the format
string. See also  Array#pack   on page
286.
And the relevant characters from your example:
H     Extract hex nibbles from each character (most significant first).
h     Extract hex nibbles from each character (least significant first).


Question:
I want to calculate the time span between 2 times which I saved in a database.
So literally I want to know the length of time between the 2 values.

14:10:20 - 10:05:15 = 02:05:05

So the result would be 02:05:05.

How would I be able to achieve this using C#?

14:10:20 is the format I saved it in in my database.

Answer:
Read the two time values into TimeSpan variables, then perform a
```
.Subtract()
```
on the bigger TimeSpan variable to get the TimeSpan result.
E.g.
```
TimeSpan difference = t1.Subtract(t2);
```
.


Question:
I have an ellipse centered at (0,0) and the bounding rectangle is x = [-5,5], y = [-6,6]. The ellipse intersects the rectangle at (-5,3),(-2.5,6),(2.5,-6),and (5,-3)

I know nothing else about the ellipse, but the only thing I need to know is what angle the major axis is rotated at.

seems like the answer must be really simple but I'm just not seeing it... thanks for the help!

Answer:
The gradient of the ellipse is identical to the gradient of the intersects with the bounding rectangle along one side of the ellipse.  In your case, that's the line from (-2.5,6) to (5,-3), the top side of your ellipse.  That line has a vertical drop of 9 and a horizontal run of 7.5.
So we end up with the following right-angled triangle.
```
```
(-2.5,6)
  *-----
  |\x
  | \
  |  \
9 |   \
  |    \
  |    x\
  +------* (5,-3)
    7.5
```
```
The angle we're looking for is x which is the same in both locations.
We can calculate it as:
```
```
-1
tan   (9/7.5)
```
```
which gives us an angle of -50.19 degrees


Question: How do I read a time value and then insert it into a TimeSpan variables?

Answer:
```
```
TimeSpan span = new TimeSpan(days,hours,minutes,seconds,milliseonds);
```
```
Or, if you mean DateTime:
```
```
DateTime time = new DateTime(year,month,day,minutes,seconds,milliseconds);
```
```
Where all of the parameters are ints.


Question: See the question. I want to see the methods and classes offered by a DLLs library.

Answer:
This is exactly what the Object Browser is for.
Add a reference to the DLL.
Right click it in the list.
Click
View in Object Browser
.


Question:
Right now I have a visual studio project which contains a custom content type that I made. It also contains all the necessary files for making a sharepoint solution (wsp) file and a script to generate this.

Now, I would like to do 2 things.

First, I'd like to create a custom display form for the content type and include it in my solution so that it is automatically deployed when I deploy my solution. How do I include this in my solution and make my content type use it?

Secondly, you can query this type with the CQWP. I've thought about exporting it, adding more common view fields, and then modifying the XSL that is used to render it. How do I include this into my solution so that it is also deployed. I know i can export the CQWP webpart once it's all setup and include it in my project as a feature. But what abuot the XSL?

Looking forward to see your suggestions, cheers.

Did as described in the first answer. Worked like a charm.

Answer:
Use
STSDev
to create the solution package.
That should help with creating the WSP. The custom form, CQWP webpart and the .xls file should also be deployable within the project.
To deploy the xslt, your feature will have an
```
<ElementManifest Location="mywebpartManifest.xml">
```
This then points to a files such as
```
```
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="Yourfile.xslt" Url="Style Library" Path="" RootWebOnly="TRUE">
    <File Url="yourfile.xslt" Type="GhostableInLibrary" />
  </Module>
</Elements>
```
```
for the webpart:
```
```
<Module Name="myWebpart" List="113" Url="_catalogs/wp" RootWebOnly="FALSE">
   <File Url="myWebpart.webpart" Type="GhostableInLibrary" />
</Module>
```
```
Now that file will need to be contained in the solution manifest.xml. This is done automatically from the STSDev project.
e.g.
```
```
<Resources>
    <Resource Location="SimpleFeature\Feature.xml"/>
```
```
The actual schemas are:
Site
Solution
Feature
and a link to someone else with the issue


Question:
I am trying to implement in windows scripting host the same function as windows Send To/Mail Recipient does. Did not find anything usefull on google except steps to instantiate Outlook.Application and directly calling its methods.

I need to go the same path as windows do, as there is a mix of Outlook and Lotus Notes installed, I don't see it good to perform some sort of testing and deciding which object to talk to...

What I have found is that the actual work is done by sendmail.dll, there is a handler defined in registry under HKEY_CLASSES_ROOT\CLSID\{9E56BE60-C50F-11CF-9A2C-00A0C90A90CE}. I would like either to use this dll somehow or to simulate the same steps it does.

Thanks for your input.

Answer:
Use
STSDev
to create the solution package.
That should help with creating the WSP. The custom form, CQWP webpart and the .xls file should also be deployable within the project.
To deploy the xslt, your feature will have an
```
<ElementManifest Location="mywebpartManifest.xml">
```
This then points to a files such as
```
```
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="Yourfile.xslt" Url="Style Library" Path="" RootWebOnly="TRUE">
    <File Url="yourfile.xslt" Type="GhostableInLibrary" />
  </Module>
</Elements>
```
```
for the webpart:
```
```
<Module Name="myWebpart" List="113" Url="_catalogs/wp" RootWebOnly="FALSE">
   <File Url="myWebpart.webpart" Type="GhostableInLibrary" />
</Module>
```
```
Now that file will need to be contained in the solution manifest.xml. This is done automatically from the STSDev project.
e.g.
```
```
<Resources>
    <Resource Location="SimpleFeature\Feature.xml"/>
```
```
The actual schemas are:
Site
Solution
Feature
and a link to someone else with the issue


Question:
I have a really big database (running on PostgreSQL) containing a lot of tables with sophisticated relations between them (foreign keys, on delete cascade and so on).
I need remove some data from a number of tables, but I'm not sure what amount of data will be really deleted from database due to cascade removals.

How can I check that I'll not delete data that should not be deleted?

I have a test database - just a copy of real one where I can do what I want :)

The only idea I have is dump database before and after and check it. But it not looks comfortable.
Another idea - dump part of database, that, as I think, should not be affected by my DELETE statements and check this part before and after data removal. But I see no simple ways to do it (there are hundreds of tables and removal should work with ~10 of them). Is there some way to do it?

Any other ideas how to solve the problem?

Answer:
If the worry is keys left dangling (i.e.: pointing to a deleted record) then run the deletion on your test database, then use queries to find any keys that now point to invalid targets.  (while you're doing this you can also make sure the part that should be unaffected did not change)
A better solution would be to spend time mapping out the delete cascades so you know what to expect - knowing how your database works is pretty valuable so the effort spent on this will be useful beyond this particular deletion.
And no matter how sure you are back the DB up before doing big changes!


Question:
I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done.

What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.

Answer:
Here's a quick example:
I find the comma separated list syntax quite useful for building function calls:
```
```
% Build a list of args, like so:
args = {'a', 1, 'b', 2};
% Then expand this into arguments:
output = func(args{:})
```
```