I came across an article at Luminous logic a couple of years ago. Lumilog provides excellent sample code to download historical and current stock data from Yahoo! Finance, for free.

Since then, MATLAB has released their Datafeed toolbox. The Datafeed toolbox makes it very easy to import stock data from a number of providers, such as Reuters, Bloomberg, and Yahoo! It’s also incredibly simple to use, and does not require that you download anything, if you have the full version of MATLAB installed.

Getting the data

Enter the following command in MATLAB to open up a simple GUI.

dftool

screen-matlab

A GUI should pop up, simply select Yahoo under Data Source, click connect and select the Data tab.

The GUI is quite self explanatory, but enter the ticker of the security for which you would like to download data. Select whether you want current or historical data. Name a MATLAB variable into which the data should be stored and select which fields to retrieve. Click Get Data and you’re done.

This is a very quick approach to retrieve data, however, there’s also a direct interface that you can access from your code.

This little snippet, will retrieve the historical closing prices for GOOG between 1 Jan 2011, and 1 Jan 2012.

C = yahoo;
d = fetch(C, ['GOOG'], {'close'}, datenum('2011-01-01'), datenum('2012-01-01'));
plot(d(:,1),d(:,2));

goog
To access the complete documentation simply type:

help datafeed

Ever run into an immediate ArgumentNullException in a debug session, with no source available. This problem occurs when your ClickOnce Security settings are incorrect. You can disable them under Project properties -> Security.

Ever run into problems with different tables having different collations? Here’s a short script to change all columns with Finnish-Swedish collation into Latin1. Modify as needed. Enjoy!

DECLARE @msg nvarchar(2048)

declare mycursor CURSOR
	FOR
		select 'alter table ' + a.table_name + ' alter column ' + b.column_name + ' (' + b.data_type  + ' (' +
		 cast(character_maximum_length as varchar) + ') collate ' + 'SQL_Latin1_General_CP1_CI_AS'--collation_name
		from
		 information_schema.tables as a
		inner join information_schema.columns as b
		 on a.table_name = b.table_name
		where b.collation_name = 'Finnish_Swedish_CI_AS'
		and a.table_type = 'BASE TABLE'
		order by 1
OPEN mycursor

FETCH NEXT FROM mycursor
INTO @msg
WHILE @@FETCH_STATUS = 0
BEGIN
	PRINT @msg

	EXEC(@msg)
	PRINT 'executed successfully'
	PRINT ''
	FETCH NEXT FROM mycursor
	INTO @msg
END
CLOSE mycursor
DEALLOCATE mycursor

Yesterday when I attempted to launch SQL Server Configuration Manager I came across this error:

Cannot connect to WMI provider.You do not have permission or the server is unreachable. Note that you can only manage SQL Server 2005 servers with SQL Server Configuration Manager.

It turns out that my WMI-files had been corrupted AND that the permissions where wrong on the Microsoft SQL Server/90/Shared folder.

The only thing I had done since the previous night was enable the Guest account.

Since I was running Windows XP I had to boot into safe mode to edit the fine-grained permissions on the folders. You do not need to do this in Professional or Windows Server. Network operators need full control of the folder.

Attempting to fix mof for SQL Server still failed though

C:\Program Files\Microsoft SQL Server\90\Shared>mofcomp "C:\Program Files\Microsoft SQL Server\90\Shared\sqlmgmproviderxpsp2up.mof"

If it fails for you as well then your WMI has probably been corrupted.
Katy has an extensive tutorial on her homepage on how to resolve this. Though the easiest approach is probably to just recompile everything. I found a batch script that will do just that:

net stop winmgmt
c:
cd %systemroot%\system32\wbem
rd /S /Q repository
regsvr32 /s %systemroot%\system32\scecli.dll
regsvr32 /s %systemroot%\system32\userenv.dll
mofcomp cimwin32.mof
mofcomp cimwin32.mfl
mofcomp rsop.mof
mofcomp rsop.mfl
for /f %%s in ('dir /b /s *.dll') do regsvr32 /s %%s
for /f %%s in ('dir /b *.mof') do mofcomp %%s
for /f %%s in ('dir /b *.mfl') do mofcomp %%s
echo Repair has completed, please reboot the system now. pause

The following command shouldn’t fail this time:

C:\Program Files\Microsoft SQL Server\90\Shared>mofcomp "C:\Program Files\Microsoft SQL Server\90\Shared\sqlmgmproviderxpsp2up.mof"

You ought to be able to launch the configuration manager now.

I’m often surprised of the poor quality of classes and methods that I come across. Often it seems, programmers have hurried through their class and method design, leaving the clients (other programmers) with ambiguous undocumented code. Maybe this article is a bit on the basic side of things, but sadly I come across these kind of mistakes on a daily basis.

So how do you go about writing your methods and classes in c++? This is a good way to write a member method right?

int foo(long param)
{
 //Do something.
 return something;
}

Wrong.

Just going ahead and writing your method is bound to lead to bugs and poor code. I keep a mental check-list whenever I design my methods.

  1. What will this method do?
  2. What would be a good name for this method?
  3. How will I implement it?

What will the method do?

This is possibly the most important part of designing your method. You need to decide what input the method will accept, and what the output should be. Will the method modify the parameters, the class instance? Will I be returning a reference or a new object?

It’s a good thing to write down what you want the method to do early in the development process, you’re going to have to write the documentation later anyhow.

  1. If clients will be calling this method it needs to be public, otherwise make it private or protected.
  2. Should the method modify the instance? If not, declare it const
  3. Will I be modifying my input parameters? If not, declare them const too. Generally your clients will not expect your methods to modify the parameters they supply.
  4. Should I be passing my parameters as value-types, references or perhaps pointers? It’s often best to use references, with the exception of the built in types where you probably want to accept value types for your method to accept constants. I avoid using pointers for parameters altogether because I believe it breaks more than it helps. If you really need them, consider using auto_ptr or shared_ptr instead.
  5. It’s always a good thing to name the parameters in the method declaration, even if you do not have to. Some people even typedef the built in types to provide the client with even more information, but I consider this overkill.

If you find that you are unable to declare your method const because of legacy code, consider using the mutable keyword.  This is dangerous though, and you should be very careful when using it.

What is a good name for this method?

This is as well a very important aspect. Once you’ve shipped your software, library or whatever it is you are writing and clients have begun utilizing your code, you will find it very hard to change either the name, return type or parameters of your methods. There are so many vastly different philosophies on method naming that I will omit discussing it in any detail here, but the name should clearly communicate what the method does.

How will I implement it?

Surprisingly, how you implement your method is probably the least important step in the design. As long as you’ve specified how you want the method to behave, you can always modify the actual implementation at any time without notifying your clients. You seldom need to consider optimisation on your first pass. The Pareto principle states that 80% of your programs execution time will be spent in 20% of the source, so you really only need to optimise that part. It doesn’t matter if your sorting algorithm runs in O(n^2) when you’re only sorting 15 elements. There are though, a few considerations that could save you from some nasty bugs.

I like to check my input parameters for any errors at the very beginning of the method. You could be using conditionals and throw exceptions, or just have your error checking while debugging with asserts.

void myclass::a_good_method_name(const some_type & param1, const some_type & param2)
{
	if(param1 == bad)
		throw exception("Some error message");
	if(param2 == bad)
		throw exception("Some other error message");
}

it’s also important that if the method breaks for some reason you’ll leave the program in the same state as when the method was called when you return.
The easiest way to ensure this is by using the Copy and swap-idiom.
Just make a copy of your instance (if it can be copied). Do any modifications on the copy and then swap the this pointer with a pointer to your copy just before returning from the method.

void myclass::a_good_method_name(const some_type & param1, const some_type & param2)
{
	if(param1 == bad)
		throw exception("Some error message");
	if(param2 == bad)
		throw exception("Some other error message");

	myclass inst(*this);

	//Do stuff to inst.
	//If we throw, then this will remain unchanged.
	//Do some more stuff to instance.

	//All is well, apply changes to this
	this->swap(inst);
	return;
}

I’d consider this a good start for a method. The next step would be to design some good unit tests and write the documentation for this method. Some people prefer to design their methods and classes around the unit tests.

There are surely many other things to consider when writing your methods. The important thing is to think everything through before writing it. Remember, if a client can break something, they probably will.

If your name, like mine, isn’t Scott Meyers, or perhaps it is, but you’re not the one Scott Meyers, you will undoubtedly have made a mistake or two when programming. And by the way, while we’re on Scott Meyers, if you haven’t read his books you most certainly should do that right now. In fact, you’re not allowed to continue reading until you have.

So you’ve made a mistake or two while programming. If you’re unlucky like me, you’ve also been writing templatized code with errors in them. Compilers generally do not output pretty error messages when you do.

Such an error is fairly often not neither a syntax error, nor error in your templte code, but because the type you’re passing to your function or class simply does not support the ‘implied’ requirements of that templatized method. What is an implied requirement then? Glad you asked.
Consider the following code.

template<typename T>
T divide (T & numerator, T & denominator)
{
	return numerator/denominator;
}

Looks good enough. Let’s try to use our templatized method.

double dn = 1
double dd = 2

int in = -5;
int id = 7;

string sn = "Hello";
string sd = "World";

divide(dn,dd); //Fine
divide(in,id); //Fine
divide(sn,sd); //Fails with a horrible horrible error message.

Now you’re thinking. You silly man! You can’t divide strings. Well, how am I supposed to know that? And why is that error message so long, tedious and hard to decipher? (Try compiling it yourself). It’d be nice if I could get a nice error message.

Enter Concepts.

Concepts are a bit like interfaces in the Java or C# sense, but for templates.
To call our templatized divide method, our type needs to support operator/. So let’s define a concept, and have our method require it.

auto concept Dividable<typename T>
{
	T operator/ (const T &, const T &);
}

template<typename T> requires Dividable<T>
T divide (T & numerator, T & denominator)
{
	return numerator/denominator;
}

I know dividable is not the right word, but it should be. Divisible sounds like you can observe an object in the locations simultaneously which is, needless to say, absolutely preposterous. I’m sticking to dividable.

Concepts are not completely unlike classes in many cases. You can use inheritance with them, require support for multiple methods, and even require support for axioms! The axioms however, are not enforced by the compiler (as it would be impossible in many cases to verify its validity) but merely serve as optimisation hints for your compiler.

As an example of using an axiom let’s define the mathematical concept of a group the c++0x way. If you don’t remember your definitions, (who does?) here’s a handy link.

concept Group<typename Operator, typename T>
{
	T operator() (Operator, T, T);

	axiom Associativity(Operator oper, T a, T b, T c)
	{
		oper(oper(a,b),c) == oper(a,oper(b,c));
	}

	axiom Identity(Operator oper, T a)
	{
		oper(a::identity,a) == oper(a,a::identity);
	}
	//The (reverse element) axiom is impossible to test!
}

A group is called abelian if it is commutative as well. So while we’re at it, let’s define a concept for that too.

concept AbelianGroup<typename Operator, typename T> : Group<Operator,T>
{
	axiom Commutativity(Operator oper, T a, T b)
	{
		oper(a,b) == oper(b,a);
	}
}

You might have noticed I used the auto keyword for my Dividable concept, but not the Group concepts. Specifying the auto keyword just means that any type that implicitly supports the concept is considered to have implemented it. If we omit the keyword then types have to explicitly declare that they support a concept if you want them to be used with a method that requires a concept.

If you want a good read on the subject, here’s the proposed standard as of March 2009

I came across an article on stream fusion in c++. If you don’t know what it is, the aforementioned article provides an excellent introduction. I was not very familiar with the subject either, so I googled about a bit. I came across a forum thread where people weren’t too enthusiastic. I am obliged to agree that the C++-soup approach was overly tedious. Why not just use for_each with variadic arguments to achieve the same result?

I decided to create a new method, mult_for_each, for the sake of clarity in the following example, but you could do the same thing with a functor and just use the regular for_each in the standard library. The exact same functionality, but in a simpler reusable packaging.

Here’s the header file.

#include &lt;iostream&gt;

#include <iostream>

using namespace std;
namespace
{
	template<typename T>
	void call(T && val)
	{
	}

	template<typename T, typename FirstArg, typename... Args>
	void call(T && val, FirstArg& firstarg, Args&... args)
	{
		firstarg(val);
		call(move(val), args...);
	}
}

template<class InputIterator, typename... Functions>
void mult_for_each(InputIterator first, InputIterator last, Functions&... f)
{
	while ( first!=last )
	{
		call(*first, f...);
		first++;
	}
}

… and an example implementation

#include
#include ”mult_for_each.h”
#include
#include
#include

template
struct max_functor
{
max_functor()
{
value = numeric_limits::min();
}

void operator() (const T & v)
{
if(v > value)
value = v;
}

T value;
};

template
struct min_functor
{
min_functor()
{
value = numeric_limits::max();
}

void operator() (const T & v)
{
if(v < value) value = v; } T value; }; template
struct avg_functor
{
avg_functor()
{
count = 0;
total = 0;
}

void operator() (const T & v)
{
total += v;
count++;
}

size_t count;
T total;

T value() const
{
if(count == 0)
return 0;
else
return total/static_cast(count);
}
};

int main()
{
max_functor m1;
min_functor m2;
avg_functor m3;

vector v;

v.push_back(5);
v.push_back(-1);
v.push_back(2);
v.push_back(11);
v.push_back(19);

mult_for_each(v.begin(),v.end(),m1,m2,m3);

cout << endl << "Output!" << endl; cout << m1.value << endl << m2.value << endl; cout << m3.value() << endl; } [/sourcecode] Oh yeah, and to compile you need to add the option -std=c++0x if you’re using gcc.

This post is still a draft. There may be errors in the examples.

One exciting new feature in the draft of the new C++0x standard is the inclusion of support for variadic constructs. Although, not in the current standard, you have surely come across the variadic function printf or one of its relatives

int printf (const char *, ...);

In C we would use va_list and various other macros to access the variadic arguments. It’s possible to design functions that accept 1, 5 and 10 arguments in the same declaration. Very convenient indeed.

In the proposed C++0x-standard the concept has been extended to include templates as well. The mighty standards gods have chosen the ellipses as the operator, probably for C compatibility.

template <typename... Args>
int printf(const char *, Args);

So, how would you access the parameters? Well there are several ways. You can if you want, create an array

template <typename... Args>
void foo(Args)
{
boost::any myArray[sizeof...(Args)] = { Args... };
}

The ellipses on the right of Args expands the argument list.

There’s no need for any work on the parameters to be done in run-time, and it’d be neater if we could do it in compile time. Fortunately we can. We need to unpack the variadic parameters. We can do it with some simple template metaprogramming. For example:

//We define the base case, where there are no 0 arguments
template <>
struct sumitup
{
static const double value = 0;
}

/*Note how the first parameter is extracted into T, and the others follow in Args*/
template <typename T, typename... Args>
struct sumitup
{
static const double value = T + sumitup::value;
}

template <typename... Args>
double sum(Args)
{
return sumitup(Args);
}

There are many other aspects of variadic templates that I have not even touched upon in this article. A good place to start digging if you want more information is the proposed standard

There’s an annoying bug in Visual Studio. It’s perfectly legal to inherit your own cool user control from another (perhaps even sweeter) abstract user control. But you shouldn’t. If you do you’ll break the Windows-Forms designer view for anyone who tries to use your control in their Form. Visual Studio needs to initialise the base classes for some reason or another, and it can’t if the class is virtual. A simple workaround is to just replace any abstract methods with empty virtual ones, but it’s ugly.

Please let me know if you know of a better way around the problem.

As any software developer knows, deprecating features is always a problem. Any changes are bound to break code. Some changes are worse than others.

In the next version of SQL Server, Microsoft has decided the alter the behaviour of the widely used ‘SET ROWCOUNT’ to no longer affect UPDATE and DELETE statements.

Imagine what would happen if a database was upgraded and a stored procedure contained:

SET ROWCOUNT 1
DELETE FROM bigImportantTable

Microsoft suggest that:

… for DELETE, INSERT, and UPDATE statements that currently use SET ROWCOUNT, we recommend that you rewrite them to use the TOP syntax.

So we are free to write something like this:

USE Northwind
DELETE TOP (10) FROM dbo.[Order Details]

Microsoft has kindly provided us with a few examples on how we could achieve identical functionality:

USE AdventureWorks
DELETE authors 
FROM (SELECT TOP 10 * FROM authors) AS t1
WHERE authors.au_id = t1.au_id

There is an inherent problem with both of these approaches though. Which are the specific TOP 10 rows to be deleted from the table? In fact, using SET ROWCOUNT in the first place also suffers from this problem.

TOP is not a deterministic keyword, that is, we are not guaranteed that we will be getting the same rows if we repeat the same query (on the same table with the same data). To make TOP deterministic we would need to use it in combination with ORDER BY, and WITH TIES. These clauses add a little bit of overhead to our statement.

Unfortunately we are unable to use the ORDER BY-clause in the first example. If you are running recent version of SQL Server (later than 2000) a good solution would be to avoid using TOP altogether and rely on a Common Table Expression or CTE instead like the one below:

USE Northwind

;WITH OrderDetailsWithRows AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY OrderID, ProductID) AS Row
FROM dbo.[Order Details]
)
DELETE FROM OrderDetailsWithRows WHERE Row <= 1;[/sourcecode] Why is there a semicolon preceeding the WITH clause? Some statements queries can be suffixed by a WITH clause, so I tend to include a semicolon to remove any ambiguities. More on CTE's soon