Hack an apt-get style installer into Cygwin

As you’ll probably know, you can install a bunch of plugins into Cygwin, but only during installation. Do the following to make life easier for yourself.

After installation, copy the setup executable into the cygwin folder.

Create install-pkg.bat with the following contents:

setup-x86_64.exe --no-desktop --no-shortcuts --no-startmenu --quiet-mode --root "%cd%" --packages %*

Now you can cd into /cygdrive/c/cygwin64 and install a package like so:

$ ./install-pkg.bat wget 

Ready to rock PHP 7.3 Docker LAMP Stack

I have built a full LAMP stack that comes with the following:

  • Apache
  • PHP 7.3.3
  • Mariadb
  • MailHog
  • XDebug
  • HTTPS Virtualhost with holding page

Here’s how you get a full LAMP stack up and running in no time at all, which will be identical on any platform.

Firstly, install Docker and Virtualbox if you don’t have them. Then create a default base VM.



docker-machine create --driver virtualbox default

OK. So, first thing you need to do is start your VM:

docker-machine start
docker-machine env
eval $(docker-machine env)

You should run eval $(docker-machine env) in any other terminal tabs you open too, this sets up environment vars for setting up docker. Take a note of that IP address, and edit your /etc/hosts file awesome.scot

Ok, lets clone the LAMP stack:

git clone https://github.com/delboy1978uk/lamp
cd lamp

This is another one off, build the image.

docker-compose build

That’s it! Now start your docker image like this

docker-compose up

and you can finally open your browser to


The McCrone Report in full

Mr Reid
New St Andrew’s House
St.James Centre, Edinburgh, EH13TA
Telephone 031-556 840. ext, 4017

J Garlick Esq
Cabinet Office
Great George Street
London SW1
23 April 1975

At the meeting which you held last week on various aspects of North Sea oil and devolution I suggested that I might send in the attached paper in the hope that it would serve as a starting point for any assessment the Unit may wish to carry out on the economics of Scottish Independence.

The Paper was written over a year ago in the weeks immediately before the February 1974 Election. This will be particularly apparent of page 5 where, of course, the Ministerial pronouncements referred to relate to the Conservative Government. I have not attempted to update any of the figures, since although there would be differences these do not seem to me to be such as to alter the argument.

As you will realise, the debate on Scottish nationalism has been founded to a surprising extent on economic arguments ad the purpose of this paper was to examine how far this was affected by North Sea Oil. The first part goes through most of the usual arguments which have been used against the Nationalists in the past with fairly convincing effect; the second part sets out the sort of economic strategy which an SNP Government might try to follow indicating both the dangers and the possibilities. As I said at the meeting, one can reach almost any conclusion depending upon the assumptions that are made about tariffs, a common currency, a Scottish Government’s spending priorities and its success in controlling inflation. My paper may give an SNP Government the benefit of too many doubts, but I was anxious to see whether a credible economic strategy could be put together which would appear to be more convincing in terms of solving Scotland’s traditional economic problems than the regional policies of the Unionist Governments have been up until now. I think the conclusion is that the most convincing way of taking the wind out of the SNP’s sails is by demonstrating that we now have policies which can make major in-roads into these problems.

When my paper was written it was classified “secret” and given only a most restricted circulation in the Scottish Office because of the extreme sensitivity of the subject. I am copying it now to Leo Pliatzky, Dick Ross, Jim Hamilton, John Liverman and Stuart Scott Whyte.

RGL McCrone



It is commonplace that the discovery of North Sea oil and entry to the EEC are factors of major economic significance for Scotland.

Already both issues, especially the former, feature widely in the SNP’s election material. The purpose of this paper is to reassess the economic arguments for an independent Scotland in the light of these developments, especially the discovery of oil. It will be shown that the whole framework within which the economic implications of nationalism were argued has indeed been altered. The importance of this is probably greater than is recognised at present by the majority of the public and it may well be, therefore, that the discovery of North Sea oil will come to be seen as something of a watershed in Scotland’s economic and political life.

The case for Scottish nationalism is, of course, very much more than an economic issue. This paper makes no attempt to examine the wider questions. Suffice it to say that Scottish nationalism has been much more concerned with economic prosperity than nationalist movements in other countries. Unlike Wales there is no great cultural movement attaching to the preservation of a language.

The main cause of discontent is the country’s unsatisfactory economic performance over the last half century, especially the persistent unemployment and net emigration above all in the West of Scotland.

Poor social and environmental conditions, especially in and around the city of Glasgow, accompany this outdated economic framework and are as much a source discontent.

Despite regional policy and the efforts of planners, these problems have not been overcome, nor do they look as if they will be in the foreseeable future. The SNP have therefore based their campaign on the assertion that Scotland would be economically better off independent; and it is for this reason that budgetary estimates have always featured so large in the controversy. Yet in spite of Scotland’s undoubtedly poor economic performance the SNP case until recently lack credibility. Most people regarded both their statistics and arguments suspect, and they continued to believe that Scotland derived more economic advantage than disadvantage from the Union.

The importance of North Sea oil is that it raises just this issue in a more acute form than at any other time since the Act of Union was passed.

The Case Against Nationalism

The traditional economic case against nationalism has always been that a politically independent Scotland would be unable to gain sufficient economic sovereignty to solve her problems successfully.

This is partly a question of the scale of the Scottish economy, but more of the extent to which it has become integrated with that of the rest of the UK over the last 270 years.

Scotland needs a faster rate of economic growth than either she or the UK has had in recent years if she is to absorb her excess labour resources and thereby cut down both unemployment and migration.

There are three principal ways in which an independent Government might seek to bring this about. First it could seek to foster and protect Scottish industry by means of tariffs and import controls. But such measures would risk retaliation from England which, given Scotland’s close trade ties with England, could cause damage far in excess of any benefit that may be hoped for. Such policies would also be incompatible with continued membership of the EEC and withdrawal, especially with England, Wales and Ireland remaining members, would clearly have very damaging consequences.

Secondly, fiscal policies might be used to give especially large benefits to new industrial investment or tax relief and subsidies to existing industry. This might involve the imposition of a tax frontier at the border, as still exists between most EEC countries, but this need not to make it impractical. Such policies have been used with considerable success by the Irish Republic since the mid-1950s. The main disadvantage is that England would probably feel obliged to match the Scottish measures with equivalent in grants or tax allowances for industry in English and Welsh Development Areas. Up to now England has always been in a position financially where, if she wished, she could have more than matched any measures which a Scottish Government would be able to afford.

It is here that the budgetary position of a Scottish Government becomes important. Various studies, notably the Treasury’s Scottish Budget of 1967/68 and the work of the Kilbrandon Commission have shown that public expenditure per head in Scotland is generally above the UK average, whereas public revenue is Scotland is slightly lower, largely because Scottish incomes are below the UK average. The result is that budgetary estimates for Scotland show a proportionately larger borrowing requirement than for the UK as a whole. His position is confirmed in the most recent estimate of Scotland’s budgetary position carried out by the Economic and Statistics Unit of SEPD for 1971/72. This shows a Scottish current account surplus of £24m. but a net borrowing requirement of £447m. overall.

There are, of course, various ways in which this could be tackled. In the first place it is not necessary to balance the budget. To finance loans and various items of capital investment, particularly those which yield a return by borrowing is quite reasonable; other items too may be covered by borrowing from time to time particularly if an expansionary budget is necessary to generate a higher level of economic activity in the economy. For these various reasons the United Kingdom budget normally involves a net borrowing requirement and whilst this will normally be fairly small this is not always so; in the present year, for example, the borrowing requirement reached the record figure of £4,000m.

If allowance is made for the capital items that it would normally be reasonable to finance by loan, this would still lave a Scottish deficit of over £200m., a very similar figure in 1971/72 to what it was in 1967/68. Whilst such a figure could be covered if it arose only exceptionally, it could not be tolerated as a regular feature of the budget. It would involve a steadily increasing Scottish debt and it would have serious implications both for interest rates and monetary policy, unless a substantial part of it could be financed from abroad. A Scottish Government would therefore have to take steps to reduce the deficit either by raising taxes or cutting expenditure. Such measures are perfectly possible, and on the scale necessary, need not provoke a intolerable situation, especially if defence was one of the items cut; but they would create a background of acute budgetary stringency against which it is hard to see it being possible to provide a major fiscal stimulus to encourage economic expansion.

The third possible course of action would be to devalue the Scottish currency. This would stimulate economic activity by increasing the demand for exports and making Scottish goods more competitive against imports in their home market. In many respects devaluation would be the obvious measure for an economy in Scotland’s condition with persistent unemployment, a budgetary deficit and probably a serious adverse balance on the balance of payments.

Indeed, if the later was persistent, it might be that devaluation would be inescapable.

Exchange rate adjustment is, of course, the ultimate and most effective weapon by which an economically sovereign state maintains approximately full employment while at the same time avoiding balance of payments disequilibrium. Indeed, if Scotland could have devalued by a good thumping 2 percent and made the adjustment effective in terms of costs, this would be by far the best way of solving Scotland’s economic problems of the last two decades. It has been argued that the ‘regional problem’ only arises because exchange rate adjustment, the normal way of dealing with disequilibria between countries, is not possible between regions.

However, the economic case against Scottish nationalism has always at bottom come down to the proposition that an independent Scotland would not find it possible to carry out an effective devaluation.

To be effective, devaluation involves a country in making a cut in its real living standards at least until such time as production is able to catch up. But the Scottish labour market is so closely linked with that of the rest of the UK that it is hard to see how real earnings could be adjusted downwards without giving rise to the most serious difficulties.

For such a small country heavily dependent of international trade, devaluation would, of course, have serious inflationary consequences, since all imports would rise in price. Trade Unions are to a large extent on a Great Britain basis and it is hard to see them accepting a deliberate attempt to cut real wages in Scotland compared with England whatever the reason for it may be. Furthermore, even with independence, freedom of labour movement between England and Scotland would be likely to continue, a common language and two and a half centuries of free movement make this easy. Changes in real wage levels would therefore be likely to be reflected in migration figures and could lead to a shortage of certain types of skilled labour in Scotland even while a surplus among the less mobile unskilled persisted.

It is for these reasons that many economists have in the past concluded that Scotland, if she were independent, would probably be unable to devalue effectively against the rest of the United Kingdom.

Lacking this ultimate weapon of economic sovereignty and limited by the budgetary situation in the use she could make of fiscal policy, it did not seem that political independence would give Scotland sufficient economic sovereignty to enable her to tackle her economic problems successfully, At the same time, whatever the constitutional set-up, the Scottish economy would remain closely integrated with that of the rest of the UK and would be greatly affected by policy decisions taken in London, though as an independent state her ability to influence those decisions would be greatly reduced.

The Implications of North Sea Oil

The analysis in the last section is based on the situation as it appeared before the discovery of North Sea oil. Even after its discovery the full significance of North Sea oil was not immediately apparent and it still remains in large measure disguised from the Scottish public by the DTI’s failure to make provision for a proper Government return when the fourth round of licences was issued.

So far all that Ministers have said is that they expect North Sea oil to be yielding 70-100m. tons of oil per annum by 1980 and that on that basis the Government revenue from rent and royalties from the whole of the Continental Shelf including the gas fields in the southern sector may be of the order of £100m. per annum at that time. It has been explained that this estimate does not include the yield from ordinary taxation on the oil companies and it has been stated that licensing policy is currently under review but the significance of this has probably not been fully appreciated by the public.

The SNP countered these figures by claiming that North Sea oil should by 1980 be yielding a Government revenue of approximately £800m. and have charged the Government with giving Scottish oil away to the international companies ridiculously cheap. Up to now much of the Scottish public may have regarded the SNP figures as pretty wild and they have been publicly condemned as such by Ministers.

But authoritative support for the charge that the Government has failed to do a satisfactory bargain with the companies is provided in the criticisms of the Public Accounts Committee which so far remain unanswered. The example of Norwegian policy on Government revenue from oil likewise shows up the failure of British.

The Government’s reveiw of licensing policy has been in progress since the early summer of 1973. This has confirmed the total inadequacy of arrangements to secure Government revenue and shows that some of the most attractive measures to put this right would involve breaking the terms on which the licences were given. It is partly for this reason that the Government has so far failed to take a decision, the choice lying between carried interest (ie state participation), which would provide the biggest revenue and also give some power of control but would go back on the terms of the licences, and excess revenue tax, from which the return in 1980 would be some £200m. less but would be defensible in international law.

The DTI estimates of last summer showed that total Government revenue following adoption of these measures would have been between £800m. and £1,200m. a year in 1980 depending on the system used and the prices prevailing in 1980; today, following the huge increase in international oil prices of recent months the corresponding figures are in the range of £1,500m. to over £3,000m. Thus, all that is wrong now with the SNP estimate is that it is far too low; there is a prospect of Government oil revenues in 1980 which could greatly exceed the present Government revenue in Scotland from all sources and could even be comparable in size to the whole of the Scottish national income in 1970.

As well as the gain to the Government Revenue, North Sea oil will of course make a massive contribution to the balance of payments; indeed these two aspects are closely linked. At present world prices the expected output of 100m. tons of oil in 1980 is worth approximately £3,000m.; assuming price rises from the present £33 a ton to £51 a ton as in the Government revenue calculations the value could be as high as $5,000m. Part of this will, of course, be repatriated by the international companies in the form of profits distributed to their shareholders or reinvested in projects in other areas. The balance of payments gain to Scotland would therefore depend critically on the amount of Government revenue secured from the profits. Indeed, since none of the major companies operating in the North Sea are predominantly Scottish owned, the Government revenue would be the major element, apart from the expenditure of the companies on goods and services produced in Scotland, which would accrue from the value of oil produced as a balance of payments gain. Thus assuming measures which would yield Government revenue of the scale referred to in previous paragraphs, plus some additional revenue to shareholders in Scotland and to suppliers of equipment, then the net balance of payments gain might be expected to lie very approximately in the range of £2,000m. to £3,500m. a year, depending on prices and the share of the Government ‘take’.

It is not possible to compare these figures with an accurate estimate of Scotland’s present balance of payments position. From the state of Scotland’s economy one would expect a balance of payments deficit on current account and a rough comparison of income and expenditure estimates for GDP suggest that this could be of the order of £300m. a year in 1970/71.

Plainly this is a most unreliable figure and it will vary from year to year, but it is probably sufficient to suggest the orders of magnitude.

What is quite clear is that the balance of payments gain from North Sea oil would easily swamp the existing deficit whatever its size and transform Scotland into a country with a substantial and chronic surplus.

All the above figures are, of course, based on the estimated output of 100m. tons of oil in 1980. This was the DTI’s revised estimate in the early summer of 1973.

Already it is beginning to look as if these estimates may be too conservative. Recent finds and the plans of companies appear to indicate that the Shetland basin may prove very productive indeed. Zetland County Council’s consultants worked on the assumption that 70m. tons a year might actually be piped ashore in the county. It is now known that Shell expect to land 50m. tons a year through their own pipe alone and pipelines may also be expected from Total’s Alwyn field, Conoco’s Hutton and the recent BP and Burmah finds. In addition to this there are, of course, substantial finds further south, particularly BP’s Forties field and Occidental’s Piner. Whether or not this, plus any new finds that are made, result in the 1980 estimate of 100m. tons being exceeded largely depends on how quickly newly discovered fields are brought into production, but it does now seem extremely likely that production during the 1980s will use well above 100m. tons a year with consequent increases in revenue and gain to the balance of payments.

Can one be certain that the oil is without doubt a Scottish asset or, even if it is, that these substantial revenues and balance of payments advantages would indeed accrue to an independent Scotland? Clearly these questions raise complicated issues in international law which could, if allowed, occupy the legal profession for many years. Two possible lines of argument may be expected: either that Scotland should pay England some compensation for appropriating the most productive part of the Continental Shelf, or that the whole shelf should be regarded as the common property of the nations of the former United Kingdom with revenue distributed in accordance with some population based formula irrespective of where oil is discovered. As regards the first of the arguments, the prospective return from oil revenue would at the very least be one of the factors taken into account in determining the financial settlement between the two countries when they become independent. To argue the second would be directly counter to the line that the UK Government has taken with the EEC, that the resources of the Continental Shelf are as much a national asset as are those on land, like coal mines, and that there is therefore no question of the Europeanisation of North Sea oil.

Disputes on these matters might well occasion much bitterness between the two countries, but it is hard to see any conclusion other than to allow Scotland to have that part of the Continental Shelf which would have been hers if she had been independent all along.

There might be some argument about where the boundary between English and Scottish waters would lie. At present this is considered to be along the line of latitude which lies just north of Berwick on Tweed, and it might perhaps be held that it should run NE/SW as an extension of the Border. This could have the effect of transferring the small oilfields in the south, Auk and Argyll, to the English sector, but would not affect the main finds.

It must be concluded therefore that large revenues and balance of payments gains would indeed accrue to a Scottish Government in the event of independence provided that steps were taken either by carried interest or by taxation to secure the Government ‘take’. Undoubtedly this would banish any anxieties the Government might have had about its budgetary position or its balance of payments. The country would tend to be in chronic surplus to a quite embarrassing degree and its currency would become the hardest in Europe, with the exception perhaps of the Norwegian kroner. Just as deposed monarchs and African leaders have in the past used the Swiss franc as a haven of security, so now would the Scottish pound be seen as a good hedge against inflation and devaluation and the Scottish banks could expect to find themselves inundated with a speculative inflow of foreign funds.

II A Policy for Development

The situation described in the first part of this paper is indeed an astounding reversal of the problems which are usually considered in a Scottish or British context. But it could nonetheless give rise to some serious difficulties and would require careful handling if Scotland was really to derive maximum benefit from it. It is, of course, perfectly possible that these difficulties would not be overcome and that an independent Scotland despite its wealth would continue to have an unsatisfactory economic performance. It takes more than money to eliminate the traditional problems of the Scottish economy and nationalist movements, dependent as they are on strong emotional pressures, have not always been notable for their economic realism. In this respect the example of Ireland’s poor economic performance between 1922 and 1956 comes immediately to mind and the SNP is already showing signs of making promises which could be an embarrassment to its economic management.

Nevertheless it is obvious that the surpluses from North Sea oil would open up new opportunities for a nationalist Government. The purpose of this second part of the paper is therefore to consider in very brief outline some of the policies a nationalist Government could follow to try to bring about the development and prosperity of the country as a whole.

Scotland’s central economic problem is to secure a faster rate of economic growth so that she can raise income levels and absorb the excess labour which presently appears as high unemployment and emigration. As has been explained, this is a situation which would normally point to devaluation as a possible remedy. North Sea oil, however, by giving the country a chronic balance of payments surplus, would rule out any possibility of devaluation. Indeed, it is hard to see how an upward valuation of the currency could be avoided. Obviously this pressure should be resisted as far as possible; but unless there was a remarkable change in the strength of sterling, it must be expected that the Scots pound would rise in relation to it fairly soon after independence, especially if the latter continues its downward slide. A revaluation would give rise to none of the difficulties which were argued earlier to apply to a Scottish devaluation.

Since the effect would be to reduce prices and raise incomes there would not be the same resistance to making it effective in Scotland. An exchange rate of £1 Scots to 120p sterling within two years of independence therefore seems quite probable.

This exchange rate movement would improve Scottish real incomes; imports would all become cheaper, and GDP per head in Scotland, which would include the value of the oil produced, would rise smartly. The gap between Scottish income per head and English would probably soon be eliminated and might well be reversed. The danger is that with a rising currency Scotland’s traditional economy would find it more and more difficult to compete; manufactured exports would be priced out of foreign markets and imports would become highly competitive at home; tourists would find that the rate of exchange made Scotland a very expensive country for holidays; and Scottish farmers would find that the EEC’s Common Agricultural Policy gave them a much less satisfactory level of support than expected. Thus there would be grave risk that the economy would be driven more and more to depend on the oil industry and other activities would tend to wither.

But while oil would give Scotland a good income, it could never be an adequate source of employment with the rest of the economy in decline.

Scotland, therefore, could face the danger of prosperity coupled with continuing or even worsening unemployment and emigration.

To counteract this situation it would be essential to try to keep the surpluses on the balance of payments down and thereby reduce the upward pressure on the exchange rate. This could involve extensive lending abroad, whether to England, the EEC or under-developed countries. Such lending could well be in Scotland’s interest rather than face the prospect of an intolerably high exchange rate; it might also do much to help cement relations with other EEC countries and, coupled with the supplies of oil for export, would make Scotland a highly desirable member of EEC with a strong bargaining position.

The first priority, however, would be to spend the surpluses as far as possible in developing Scotland’s domestic economy and providing a modern infrastructure. The following paragraphs suggest how this might be done.

a. Manufacturing Industry

Output per head in most sectors of Scottish industry is well below European levels. This is largely because the British economy has invested much less than other European countries over the last 25 years. A substantial increase in manufacturing investment is therefore necessary if this is to be put right. Only then will Scottish industry be able to compete effectively with other members of EEC at anything other than low exchange rates.

Part of the reason for the low investment in Scotland in the past has been the persistence of ‘stop-go’ in the UK economy. Every time investment has begun to rise satisfactorily, as it was doing in 1973, the emergence of a balance of payments deficit has forced the Government to take strong deflationary measures with the result that the investment boom has petered out again. Scotland made good progress in 1973, but ideally from her point of view the 5 per cent growth rate needed to go on for another couple of years. As an independent state, Scotland’s balance of payments position would enable her to break out of the ‘stop-go’ cycle and a sustained rate of growth could be planned on the basis that it could be carried on for at least a decade.

The strength of the currency coupled with the budgetary surplus would help to keep interest rates down and there would be no need for sudden increases in taxation or massive cuts in public expenditure.

Admittedly, since Scotland is so closely tied to the English market, her economy would continue to be affected by measures taken in London, but this effect would diminish the more Scotland expands trade with other EEC countries. Furthermore, it would be quite proper for a Scottish Government to take countervailing measures to stimulate the Scottish economy at times when England was going through a recession.

Such measures would help to keep Scottish output up and would help the English economy by reducing the Scottish balance of payments surplus. It can be expected therefore that the prospect of sustained expansion and an end to ‘stop-go’ would do more than anything else could both to raise investment in domestic industry and to encourage foreign investment to come to Scotland.

However, this expansionary macroeconomic policy would need to be backed up by firm regional policy measures. The position in West Central Scotland has deteriorated vis-a-vis the rest of Scotland over the last decade and this is likely to be even more accentuated by North Sea oil developments.

Furthermore, as an independent state, it would seem to be quite inappropriate for Scotland to regard the whole of the territory as subject for regional policy. Something along the lines of the following package of measures therefore seems to be most appropriate:

i. For Scotland as a whole the Regional Development Grant would be abolished, but to stimulate investment Corporation Tax would either be abolished or reduced to a purely nominal rate. This would have the effect of more or less removing the tax from industry’s retained profits while leaving distributed profits taxed roughly as they are at present. As a national fiscal policy measure it would not come within the control of the EEC’s ceilings on regional aids. The cost of abolishing Corporation Tax would be £120m.

ii. West Central Scotland would be scheduled as Scotland’s Development Area and the definition could be extended to certain smaller areas in the Highlands and Islands if necessary. Within this area there would be a 20 per cent Regional Development Grant paid as at present in addition to (i) above.

iii. There would be a Scottish Development Authority covering the whole of Scotland but with instructions to give particular priority to West Central Scotland.

Its budget would at least be on a scale equivalent to the funds which previously went into REP and SIDO. It would be empowered to give discretionary grants and loans and would be equipped to provide advice to companies. It would be responsible for working out a strategy for developing Scotland’s domestic industry as well as promoting foreign investment. The HIDB would continue to operate with its own much wider remit in the Highlands.

iv. Steps would be taken to strengthen the shipbuilding industry by adopting a scheme for insurance against inflationary risk as operated in France and approved by EEC. The new SDA would be especially charged with the preparation of proposals for the modernisation of the industry.

b. Construction

The construction industry employs a substantial part of the labour force and its fluctuations have been a major factor in unemployment. In 1971 no less than 25,000 of the 100,000 unemployed were registered as construction workers.

In times of boom the shortage of skilled labour in the industry becomes a serious bottleneck in the economy although coupled with continuing large numbers of unskilled unemployment.

The industry does not play as large a part in the British economy as in most other European countries and this coupled with the manifest need for urban rebuilding and house replacement suggest that, with the proper policy, the industry could play a much larger part in providing steady employment for the Scottish labour force. Indeed, if the Scottish construction industry employed 10 per cent of the labour force, the EEC average, this would mean employment for an additional 40 thousand.

With North Sea oil revenues, public expenditure on construction projects could be greatly stepped up and a major operation should be mounted to carry on the rebuilding of Glasgow and do much more than has been done in the past for environmental recovery. This would probably require a special Environmental Recovery Agency to assist the local authorities rather in the way that SSHA operates.

Housing policy has been bedevilled in the past by the subsidisation of certain types of housing. This has led to the colossal public housing sector in Scotland with the emphasis on quantity rather than quality. It seems desirable to subsidise housing for many years to come both to improve the living conditions of the Scottish people and to keep up the demand on the construction industry. Instead of subsidising rents at one extreme and at the other giving tax relief on mortgages which is greater the larger the mortgage, it would seem much more appropriate to give the assistance to individuals regardless of the type of house they occupy or whether they are tenants or owners.

This could probably be done under the new tax credit system and it would have the effect of providing a housing subsidy or negative tax to those with low incomes and a housing tax allowance to others. In this way demand for housing as a whole could be encouraged while avoiding the distortion between different types of housing which has been such a feature of the past. It would be likely that local authority housing would then gradually decline in importance and housing associations would assume greater prominence. As competition between different forms of housing increased, so the quality of housing would improve.

c. Service Industry

In the past service industry has received much less assistance from regional policy than manufacturing.

In part this is right because many service activities, such as medical services, education, accountants, distribution, are governed simply by local demand. But there are service activities, notably major offices, which have a choice of location and every effort should be made to attract them to areas where labour is available.

Following independence the increased Government activity would largely wipe out any spare labour resources in Edinburgh, but major efforts would be needed to promote commercial and office development in Glasgow. The Scottish Development Authority should be empowered to offer assistance, comparable in scale to that available to manufacturing industry, to encourage such development in the Glasgow conurbation and the system of property rating should be revised, if not abolished, to prevent high rates being a brake on commercial development as they have been in the past.

Tourist development would obviously assume major importance for any independent Scotland and the financial resources available to the Tourist Board could be increased.

d. The Pace of North Sea Oil Development

On the face of it the pace of development of North Sea oil appropriate for Scotland would be very different from that now being demanded by the UK.

Apart from the need to avoid piling up excessive surpluses, Scotland would wish to extend her North Sea oil revenue over a much longer period than the 30 or so years which seems likely at presently planned rates of extraction. It is also desirable to avoid the frenzied peaks of activity which seem likely in Shetland, the Moray Firth and Loch Carron on present plans.

These will impose immense infrastructure demands, lead to a substantial inflow of population and leave in their wake problems of readjustment and unemployment which it may take years of regional policy to overcome. In addition the contribution of Scottish Industry to oil developments, which is so far disappointing, might be increased substantially if the whole programme is not required to go at the maximum possible speed.

From a purely Scottish point of view this suggests that a production flow of, say, 50m. tons a year might be ideal.

Even this would be five times Scotland’s present consumption and yield and annual revenue of between £700m and £1,500m.

However one cannot look at the Scottish position in isolation.

If, because of action in the Middle East, there is a serious energy shortage in Europe, Scotland would undoubtedly suffer severely from the resulting slump. It would therefore be in Scotland’s interests to increase her oil production well beyond what would otherwise seem desirable. If however there is no serious shortage in physical terms, merely a crisis of price, then action by Scotland is not going to affect the international price of oil, nor will it matter to the other countries what the source of their oil is.

e. Inflation, Income Policy and Training

The strength of the Scottish exchange rate and the low interest rates which would result from the budgetary and balance of payments position would do much to reduce inflationary pressure. A major part of the British inflation has resulted from the downward drift of the currency and the consequent rise in import prices. The absence of this, relaxations in taxation and subsidies for housing would no doubt help to reduce the pressure of wage increases.

Nevertheless as Scotland moved nearer full employment serious shortages of certain types of skilled labour would occur and this would tend to produce acute inflationary pressure.

Some form of incomes policy is clearly going to be a continuing feature of advanced economies and would be essential in Scotland if the economy was not to price itself out of international markets. It is important to recognise, however, that the labour shortages which give rise to the pressure could be avoided to a considerable degree if training schemes were more flexible and if a substantial increased effort was put into retraining. A full-scale examination of training is clearly an early priority.

The European Community Membership of the EEC affects the economics of Scottish independence in several important respects. It guarantees access to English and Continental markets in a way which would not be possible otherwise. Without EEC Scotland would always run the risk that England might find it expedient to impose an import surcharge, a quantitative control or even a tariff on goods coming from Scotland. It was largely to eliminate this that Scotland accepted the Union of 1707. New EEC rules would have the same effect and for all nine member states. In the unlikely event of England leaving the EEC, Scottish access to the other countries could in time largely compensate for any restrictions that might arise on English trade.

Access to EEC should also help to provide a major stimulus to Scottish industrial investment. The EEC is not only a bigger market than the UK but its economy has been much more buoyant than that of Britain. There is no doubt that the exclusion of the United Kingdom had a damaging effect on investment and that foreign firms in particular preferred development within EEC. To gain the full advantage of this stimulus from membership it will, of course, be necessary to have a stable domestic economy.

High rates of inflation and a declining currency such as the UK has had recently would do much to discourage foreign companies from coming to Scotland.

North Sea oil could have far-reaching consequences for Scottish membership of EEC because of the tremendously increased political power it would confer. Without oil other members might pay little enough regard to Scotland; her voting power would not be large and it might indeed be argued that she could exert more leverage on the Community as part of the United Kingdom. As the major producer of oil in Western Europe, however, Scotland would be in a key position and other countries would be extremely foolish if they did not seek to do all they could to accommodate Scottish interests. For Scotland the net cost of Common Agricultural Policy, which features so large in British discussions would be at most some £40m. a year, a small sum compared with the balance of payments gain from North Sea oil. The more common policies come to be decided in Brussels in the years ahead, the more Scotland would benefit from having her own Commissioner in the EEC as of right and her own voice in the Council of Ministers instead of relying on the indirect, and so far hardly satisfactory, form of vicarious representation through UK departments.

Conclusion This paper has shown that the advent of North Sea oil has completely overturned the traditional economic arguments used against Scottish nationalism. An independent Scotland could now expect to have massive surpluses both on its budget and on its balance of payments and with the proper husbanding of resources this situation could last for a very long time into the future.

Wealth does not automatically mean full employment and the end of net emigration. But provided sensible policies are pursued, it is possible to see how this situation could be used to re-equip Scottish industry and renew outworn social capital thereby providing the expansion necessary to absorb Scotland’s excess labour and the increase in productivity required to raise incomes. Thus, for the first time since the Act of Union was passed, it can now be credibly argued that Scotland’s economic advantage lies in its repeal. When this situation comes to be fully appreciated in the years ahead, it is likely to have a major impact on Scottish politics, since it is on social and political grounds alone that the case for retention of the union will in future have to be based.

Nationalist policy as outlined in this paper can, of course, be regarded as extremely selfish.

Undoubtedly it is, but it can be argued in reply that so long as Scottish GDP per head is only 70 per cent of the European average, the unemployment and emigration rates among the highest and the country regarded by the EEC as one of its worst problem regions, then Scotland is justified in using her own resources to rectify these problems rather than relying on the generosity of others at least until she has managed to catch up.

Yet undoubtedly the greatest weakness in the nationalist economic case is that Scotland, even with its oil, cannot expect to prosper in isolation.

Economic conditions in Europe and above all in England, with whom Scotland will remain closely tied in trade, are of particular importance. Even with greater diversification of Scottish trade to Europe and to North America, an impoverished England or one perpetually suffering the rigours of demand restraint would have most serious consequences for the Scottish economy. Britain is now counting so heavily on North Sea oil to redress its balance of payments that it is easy to imagine England in dire straits without it. The oil prices since the Yom Kippur war make this a much more serious matter than could have been imagined before; and it is now likely that transfer of North Sea oil to Scottish ownership would occasion much bitterness in England if not an attempt to forcibly prevent it. England would, of course, be no worse off than most of the Continental EEC countries in this respect; indeed, probably there are better chances of finding oil in the Celtic Sea or the English Channel than are open to most of them. If therefore the other countries can adjust to the new energy situation, England should be able as well.

Nevertheless it is now clear, as perhaps never before, that Europe could bring about its economic ruin by disunity. If supplies of oil become seriously restricted or the burden on the balance of payments of importing countries proves more than the international monetary system can cope with, a serious breakdown in the economic system of Western Europe could well result.

This danger imposes serious international responsibilities on those European countries which are likely to be exporters of energy, Norway, Scotland if independent, and Ireland where oil is likely to be discovered. A spirit of European co-operation is not very evident yet either in discussions or plans for the development of energy and the rather nationalistic attitude so far followed by Britain would hardly be a good example to an independent Scotland. Yet the situation offers the energy producers a real opportunity to contribute to the economic strength of Europe and in so doing to ensure their own prosperity; if instead they retreat into narrow nationalism, developing their energy resources with regard to their own interests alone, they could undermine the whole European economy and seal their own fate in the process.

Perhaps the most important conclusion is that time is now extremely limited. British regional policy has been in operation for forty years and the annual cost of the measures applied to Scotland is now about £100m. a year. But, although there have been undoubtedly been notable achievements and the Scottish economy would have been in a much worse state without such a policy, there is still little prospect that it will solve the problems of West Central Scotland in the foreseeable future. High hopes have been held out for European regional policy but any impact from this is likely to be very small for a long time to come. In much the same way agitation for a workable form of political devolution has persisted amongst a substantial part of the Scottish electorate for a considerable time but without any practical result so far and it is still far from clear whether anything will stem from the consideration of the Kilbrandon Report.

If, in five years’ time North Sea oil is contributing massively to the UK budget, while the economic and social condition of West Central Scotland continues in the poor state that it is today, it would be hard to imagine conditions more favourable to the growth of support for the nationalist movement.

Very determined steps to urgently transform economic conditions in Scotland will therefore be necessary and the Scottish people will have to be persuaded that their problems really have received the attention and expenditure they deserve if this outcome is to be avoided.

Install your composer package somewhere outside vendor

And I don’t mean change the vendor folder name, that’s easy. I mean getting one package in a custom location, whereas the rest still go into vendor.

This will only work with packages that require composer/installers, so if it isn’t your own package and they don’t require that in, then you can stop reading.

Still here? Awesome. In your vendor package, you need to add the installer

composer require composer/installers

Now in your composer.json, change (or add) the type. The package we just required in is actually to help various CMS’es and frameworks, so you must supply a valid type. Thankfully, it doesn’t matter which we choose, as we override the install path anyway.

"type": "ppi-module",

Commit that, and then go to your main project. In the composer.json, add the following:

"extra": {
"installer-paths": {
"/some/custom/path": ["your/package"]

Now when you run composer install, you’ll see everything but your package in the vendor folder, and your custom package in its custom location! 😀

Setting up a multi user XDebug proxy

I absolutely love XDebug, it’s a tool that no PHP developer should go without! I constantly find myself in contracts where the workplace aren’t using it, and I end up installing and configuring it for them. However, using XDebug alone will only allow one connection at a time. This is fine when we are are developing in an isolated environment, but in many offices an entire team of developers could be working on a server at once! The solution to this is to add an XDebug proxy!

I will assume for this tutorial that you already have XDebug working and can connect with one user.

The first step is to download the debugger proxy itself to the machine running PHP. This can be found here http://code.activestate.com/komodo/remotedebugging/

Now, before you click on the PHP download, DON’T. You actually want the Python one. Download the package for your OS. If you use Linux or Mac, you’ll need python installed too. Windows comes with a binary .exe so Python isn’t required.

Depending whether you are using PHP-FPM or not will determine which port XDebug is currently listening on. PHP-FPM itself runs on port 9000, so if you are using that, your XDebug port will probably be 9001. If you are using PHP as an apache module or whatever, XDebug will probably be listening on port 9000. For the purposes of this article I will assume XDebug is listening on port 9000.

To start the proxy on Windows:

.\pydbgpproxy.exe -d -i

To start the proxy on Linux:

export PYTHONPATH=<_Komodo install directory_>/lib/support/dbgp/pythonlib;$PYTHONPATH
cd <_Komodo install directory_>/lib/support/dbgp/bin
python pydbgpproxy -d -i

To start the proxy on OS X:

export PYTHONPATH=<_Komodo install directory_>/Contents/SharedSupport/dbgp/pythonlib;$PYTHONPATH
cd <_Komodo install directory_>/Contents/SharedSupport/dbgp/bin
python pydbgpproxy -d -i

The options;

-d is the debugger itself, listening on port 9000 on the same machine

-i is the IDE listener port. The IP itself is actually the external IP of this same machine.

If it’s running, you should see something like this:

proxy> .\pydbgpproxy.exe -d -i
INFO: dbgp.proxy: starting proxy listeners. appid: 8080
INFO: dbgp.proxy: dbgp listener on
INFO: dbgp.proxy: IDE listener on

Now back in PHPStorm (or some inferior product) Goto the DBGp Proxy settings in the tools menu, and select configure. Put your name in the IDE key box, the IP of the PHP server, and port 9001.

Again in the tool DBGp proxy, and click Register IDE. If successful, you should be able to see lines like this:

INFO: dbgp.proxy: Server:onConnect ('', 60748) [proxyinit -p 9000 -k DEREK -m 1 ]
INFO: dbgp.proxy: Server:onConnect ('', 60996) [proxyinit -p 9000 -k KPATIL -m 1 ]

And that’s it! Now two or more developers can simultaneously use XDebug at the same time. Have fun!

Fixing detatched Doctrine entity problems

I’m not sure WHY it happens, but sometimes Doctrine entities can become detatched from the entity manager (If anyone does, please comment below!).

If you’ve ever added an existing object to a new one and tried to persist, you may see this error:

A new entity was found through the relationship ‘OAuth\Client#user’ that was not configured to cascade persist operations for entity: OAuth\OAuthUser@000
000007e2d73fd0000000054f34ea6. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist t
his association in the mapping for example @ManyToOne(..,cascade={“persist”}). If you cannot find out which entity causes the problem implement ‘OAuth\OA
uthUser#__toString()’ to get a clue.

In the case of my code above, the user entity had become detached somehow. Previously, I had managed to solve this problem by calling merge($entity) instead of persist($entity), but this is itself causes problems. If you have join column collections, these will no longer persist!

Therefore the answer is to re-attach the entity first!

public function create(Client $client)
$em = $this->getEntityManager();
$user = $client->getUser();
if ($em->getUnitOfWork()->getEntityState($user) !== UnitOfWork::STATE_MANAGED) {
$user = $em->merge($user);
return $client;

Debugging a Memcached server

Is your Memcached instance working correctly? Who the hell knows? Well, we will in a minute.

Open your terminal, and use the ancient telnet to connect to your server on the correct port (usually 11211):

$ telnet my.memcache.server.net 11211
Trying my.memcache.server.net...
Connected to my.memcache.server.net.
Escape character is '^]'.

Next we reset existing stats then turn on stats collection:

stats reset
stats detail on

Now, make a request on your website that will call memcache.

Finally, turn stats collection off, then dump the stats collected. If you have output, your memcached server is successfully caching your keys!

stats detail off
stats detail dump
PREFIX User get 3 hit 2 set 1 del 0
PREFIX Trade get 1 hit 0 set 1 del 0
PREFIX Currency get 1 hit 0 set 0 del 0
PREFIX Orders get 2 hit 0 set 2 del 0
PREFIX Prices get 2 hit 0 set 0 del 0

To get out of telnet, you type quit.

Bypass HSTS on local dev sites

HTTP Strict Transport Security will BLOCK your dev site if it is using a self signed certificate. And once the browser has given you that, it remembers it, so fixing it doesn’t help until you fix Firefox/Chrome.


  • Close any tabs
  • Ctrl + Shift + H (Cmd + Shift + H on Mac)
  • Find the site in question
  • Right click, forget about this site
  • Close and reopen browser
  • Add certificate exception this time 😎


  • chrome://net-internals/#hsts
  • type the hostname into the Query Domain
  • If found, enter the domain in the Delete domain section 😎


Binary Search Trees in PHP

Full credit to googleguy, who can be found on Freenode IRC channel ##php (sometimes).

Imagine you’re a phone company and you want to implement an automated system on your website for assigning phone numbers for your customers. There are two use cases. One, is that the customer can ask if a specific number is available. The other, is that the customer can ask for any random number that’s available. What data structure would you use to efficiently store and search these phone numbers? Keep in mind that you could potentially have billions of these phone numbers (1011 if we include international numbers).

If you use an Array, access is O(1) so it seems like a good idea at first, but that’s only in cases where you know the index of the value you want to access. Finding that index means searching the entire array, which is really O(n). If you use a Hash Table, the cost of search is O(1) so it seems like a better idea, but the cost of deletion and insertion can be O(n) in the worst case scenario (where you have 100% collision).

The best answer is to use a BST or Binary Search Tree, because they have average O(log n) for search, insertion, and deletion. That is assuming it’s a self-balancing tree implementation.

If you’re not at all familiar with Binary Search Trees or Binary Trees in general, let me give you a simple analogy to try and grasp this particular concept of search in computer science.

Let’s say a friend of yours is stuck on the road due to car trouble. Like a good friend you go to pick them up. You know they are stuck at a fork on this road and you arrive at a fork. At the fork there is a sign with a number on it. The number is 5 and your friend sees a sign with the number 16. You know that if you go left, you will only find numbers less than 5 and if you go right you will find numbers greater than 5. So you go right and arrive at another fork. This time you see a sign with the number 11. What do you do?

Knowing how to get to your friend, on this road, is no different than knowing how to search a (BST). You must always know two things, and always be able to make one of two simple choices. Is this number more than or less than the number I’m searching for? Do I go left, or do I go right at the fork?

Learning Opportunity

A BST is a data structure made up of nodes (the forks in our road analogy) which have left and right branches that, may or may not, each have an attached node (i.e there could be a dead end). A node attached to the left branch is less than the current node. A node attached to the right branch is greater than the current node. This always holds true no matter which node you’re currently looking at. The entirety of the structure makes up what looks like a tree, given all these nodes connected by branches. The fact that there can only be two branches on each node is what makes it binary. In the context of search these distinct properties are what make a BST very efficient.

The idea here is that you can always discard one-half of the tree with every iteration. This makes it possible to search for any value in the tree logarithmically, i.e. O(log n). Consequently, the cost of insertion or deletion to and from the tree are the same.

So say we have 9 random integers in a BST and we want to find out if the integer 16 is one of them. You always start at the root node of the tree and compare the given value to the search value. If the node’s value is greater than the search value we move to the node in the left branch. If the node’s value is less than the search value we move to the node in the right branch. Repeat this step until you find the value or reach the end (a null branch).

In PHP, we know that arrays are really just ordered hashmaps, and the cost of search in a hashmap is O(1), which makes it much faster than O(log n). However, BSTs have other properties that make them more desirable than a hashmap in many use cases. For example, finding the min or max value in a hashmap is O(n) whereas in a BST it is O(log n). In a real vector, or contiguous block, the values would need to be sorted before search can be O(1), but Quicksort requires O(n log n) making it very inefficient for insertion and deletion, because you have to resort each time you insert or delete.

Implementation in PHP

The best way to learn is to just roll up your sleeves and do it, right? So let’s implement a BST in PHP and learn something!

We already know that a binary search tree is made up of nodes. The properties that best describe these nodes is that they have a value, a left branch, and a right branch. Each branch can also contain a node. So let’s write up the node class first since it’s simply described by a set of properties and doesn’t have any real behavior (i.e. methods).

class Node
    public $value, $left, $right;

    public function __construct($value)
        $this->value = $value;

Simple enough. Now that we have a way to create a node, we’ll need the actual binary search tree implementation to be able to create the tree. So far we understand that a BST has a root node, so that will be one of the properties that describe this object.

The BST also has a couple of behaviors, that will make up the methods of this class. We’ll start by implementing the simplest of these behaviors, which is search.

class BST
    public $root;

    public function __construct($value = null)
        if ($value !== null) {
            $this->root = new Node($value);

    public function search($value)
        $node = $this->root;

        while($node) {
            if ($value > $node->value) {
                $node = $node->right;
            } elseif ($value < $node->value) {
                $node = $node->left;
            } else {

        return $node;

As you can see search is quite simple. We merely compare the search value to the current node (starting at the root node). If it’s greater than the value of the current node, we go to the node in the right branch. If it’s less than the value of the current node we go to the node in the left branch. If they’re equal we return the current node. This repeats in the loop until we reach a branch that is null. This tells us that the value does not exist in the tree.


Now let’s implement the insert functionality of the tree in order to make it really useful. This is very similar to our search behavior, with one difference. We’re looking for a null branch to insert the value. So ideally, our insert function should look fairly similar to our search function with the minor difference being that we will attach a new node to the null branch reached at the end of our loop.

public function insert($value)
    $node = $this->root;
    if (!$node) {
        return $this->root = new Node($value);

    while($node) {
        if ($value > $node->value) {
            if ($node->right) {
                $node = $node->right;
            } else {
                $node = $node->right = new Node($value);
        } elseif ($value < $node->value) {
            if ($node->left) {
                $node = $node->left;
            } else {
                $node = $node->left = new Node($value);
        } else {
    return $node;

OK, so what’s going on here? Every time we go right or left we check to see if the branch is null before proceeding and based on that information we make a decision to either attach a new node to the branch and break from the loop, or move to the next node. So insertion happens just before the point where we would normally end up with null and break from the loop, but since we can’t attach a node to null, we attach just before the $node is assigned null, and then break.


Before we can learn about deleting nodes from the tree we must first grasp an important concept of binary search trees, which is how to find their minimum and maximum values. Remember that every time you go left in a BST you are guaranteed to get a value smaller than its parent. So if we start at the root node, and keep going left until we arrive at a node with a null left branch, we should have reached the smallest value in the tree.

So our implementation of min in the BST class should look something like this.

public function min()
    if (!$this->root) {
        throw new Exception('Tree root is empty!');

    $node = $this->root;
    return $node->min();

Notice that BST::min() will only call on root->min() so we must implement the actual functionality in our Node class. This makes sense since we will likely find it useful to find the minimum value from a specific branch in the tree and not just from the root.

So our implementation of min in the Node class should look something like this.

public function min()
    $node = $this;
    while ($node->left) {
        if (!$node->left) {
        $node = $node->left;
    return $node;

Notice that if you start at the root and keep going left in our example tree illustrated earlier, you will ultimately reach the smallest value in the tree, but consequently, if you were to start at any other node in the tree and keep going left until you arrive at a null left branch, you will have the smallest value in that branch.


You can probably guess how the implementation for max will work in our BST class…

public function max()
    if (!$this->root) {
        throw new Exception('Tree root is empty!');

    $node = $this->root;
    return $node->max();

In our Node class the same concept applies, but we’re going right instead of left.

public function max()
    $node = $this;
    while ($node->right) {
        if (!$node->right) {
        $node = $node->right;
    return $node;


Great, now we have a way to insert nodes into the tree and a way to search the tree. Next, we need to have a way to delete nodes from the tree. Deletion is slightly trickier than search and insertion, but that’s OK, because we’re super ninja programmers that can code our way out of any problem, right?


There are three kinds of deletion in a binary search tree we should be aware of, because they’re each handled just a little differently.

  1. Deleting a node that has no children
  2. Deleting a node that has one child node
  3. Deleting a node that has two child nodes

The easiest is the first one with no nodes, obviously. You simply just delete the node by assigning null to its parent branch, which means you must keep track of the parent branch. So in our earlier BST, if we decided to delete the node with the value of 1, its parent node 2, would then have a left branch of null and the node would be removed from the tree.

Now, let’s say we want to delete the node with the value 2, which at this point only has one branch (containing the node with the value 4). It doesn’t actually matter if the child’s branch is right or left. As long as it only has one branch we simply take the node in that branch and attach it to the parent branch of the node we’re about to delete.

Finally, the last case is when we wish to delete a node that has both branches occupied. To do this we must first find the smallest node of its right branch. We can do this using the node’s min method that we implemented earlier.

Now we assign that min value to value of the node we’re trying to delete, which will give us duplicate nodes.

Next we apply a delete operation to the duplicate node.

Now, to make this concept a little easier to implement we can make one small modification to our Node class. By allowing each node to keep track of its parent node, we never need to pass along the parent by keeping track of it from the calling context. This will simplify the last and most complex case of deletion for us quite a bit. It will also make it easier to walk the tree later.

class Node
    public $parent, $value, $left, $right;

    public function __construct($value, Node $parent = null)
        $this->value = $value;
        $this->parent = $parent;

Now we just need to modify the insert method of our BST class to pass the parent into the Node’s constructor when doing insertion.

What this gives us is a doubly-linked list of nodes. Making it possible for a child node, in the tree, to know about its parent node. This is also a recursive relationship, because the child stores the parent property as the parent node object itself. So, be careful of (recursion there) recursion there.

public function insert($value)
    $node = $this->root;
    if (!$node) {
        return $this->root = new Node($value);

    while($node) {
        if ($value > $node->value) {
            if ($node->right) {
                $node = $node->right;
            } else {
                $node = $node->right = new Node($value, $node);
        } elseif ($value < $node->value) {
            if ($node->left) {
                $node = $node->left;
            } else {
                $node = $node->left = new Node($value, $node);
        } else {
    return $node;

The root will have a null parent, and that’s fine. So nothing else should change in our implementation. We’re now ready to implement delete in our BST class.

public function delete($value)
    $node = $this->search($value);
    if ($node) {

The delete method in our BST class is rather simple. It just searches for the node we’re trying to delete, and calls the delete method on that Node. The Node should be able to take care of the rest from here.

public function delete()
    if ($this->left && $this->right) {
        $min = $this->right->min();
        $this->value = $min->value;
    } elseif ($this->right) {
        if ($this->parent->left === $this) {
            $this->parent->left = $this->right;
            $this->right->parent = $this->parent->left;
        } elseif ($this->parent->right === $this) {
            $this->parent->right = $this->right;
            $this->right->parent = $this->parent->right;
        $this->parent = null;
        $this->right   = null;
    } elseif ($this->left) {
        if ($this->parent->left === $this) {
            $this->parent->left = $this->left;
            $this->left->parent = $this->parent->left;
        } elseif ($this->parent->right === $this) {
            $this->parent->right = $this->left;
            $this->left->parent = $this->parent->right;
        $this->parent = null;
        $this->left   = null;
    } else {
        if ($this->parent->right === $this) {
            $this->parent->right = null;
        } elseif ($this->parent->left === $this) {
            $this->parent->left = null;
        $this->parent = null;

Our Node::delete(), on the other hand, is not so simple.

The first if condition, in this method, is the number 3 scenario on our list, mentioned earlier. When the node we’re trying to delete has both a left and right branch, we must first find the min of its right branch and set its value to the value of that node. Then we call delete on that node. Notice, once we do that the min node cannot meet the first condition again. It will only fall into one of the other two scenarios—it either has one child or no children at all (because it will never have a left branch).

The animation here, highlights the most complex of deletion cases, where we need to perform a delete on a node that has both left and right branches occupied.

Let’s Take a Walk

Now, we’ll look at how you can walk through the binary search tree and some of the different ways you can do it.

One thing you should note about tree structures like the binary search tree is that they are not linear structures, like vectors, or linked lists. They can not be viewed sequentially. They are actually traversed as graphs, which means there is more than one way to traverse them. However, there must be a systematic way in which you can visit every node in the tree exactly once. Otherwise, the implementation is considered inefficient and potentially defective. Imagine you wanted to print all of the node values in the tree and your method allowed some nodes to be visited more than once. This wouldn’t be very helpful.

There are two conceptual ways in which you can traverse a binary tree. One way is iterative, meaning it works sequentially (one after the other), but requires a little more memory. The other way is to do it recursively, and since a binary tree is by definition is a corecursive structure, that would make sense. Doing it iteratively requires storing or deferring some nodes to memory before traversing them. This is usually accomplished by using a stack or queue data structure. I actually find it easier to implement a walk method on a tree recursively, but that’s just me. Then again, I’m the one writing this so, what do I care how you like to do it?!

Now whether the method of implementation is recursive or iterative, you still have to choose the order of traversal on the tree, which can be either Depth First or Breadth First. Breadth First order is also sometimes referred to as level order, because you visit every node on a particular level of the tree before moving down to the next level.

In Depth First order there are three different algorithms commonly used for traversal.

  1. Pre-order
  2. In-order
  3. Post-order

We’re not going to go through all of these approaches here. In this article, we’re just going to use Depth First In-order traversal, since I find it to make the most sense for demonstration purposes.

Depth First In-order Traversal

First, let’s plot out our chartered course so that I have some high-level view of where we want to go, before we try to get there.

The sequence looks kind of like a roller coaster ride, but this particular aproach will give us the nodes in order.

So the result is all values in ascending order as [1, 2, 4, 5, 7, 11, 16, 23, 34], which is what you’d expect if this was a sorted array, for example.

public function walk(Node $node = null)
    if (!$node) {
        $node = $this->root;
    if (!$node) {
        return false;
    if ($node->left) {
        yield from $this->walk($node->left);
    yield $node;
    if ($node->right) {
        yield from $this->walk($node->right);

I’ve used a generator implementation, which will only work in PHP 7, but that’s just because it makes the implementation so much simpler. You can accomplish the same thing in PHP 5 by replacing the yield calls with an array assignment, for example, and then using array_reduce to return the actual results back to the caller. You might need a wrapper function for this, but the concept is the same. It’s just so much less code using a generator!

If we ran this code…

// Instantiate a new tree with root node of 5
$bst = new BST(5);

// Insert left branch nodes

// Insert right branch nodes

// Walk the tree
$tree = $bst->walk();
foreach($tree as $node) {
    echo "{$node->value}\n";

We should get output like this…


Other Real World Applications

So, you’re probably thinking, what on earth would I need a binary tree for, and especially in a language like PHP? And you’re probably very right for thinking that, but don’t confuse what you’ll need it for with why you almost never need to implement a binary tree in practice. In PHP, particularly, the performance gains of binary search are dwarfed by the context-switching overhead of having to implement them as objects (it takes a lot longer to carry out a function call in PHP than it would to do simple pointer dereferencing in a language like C, for example).

It’s very important to know about and understand this data structure in concert with other data structures so that you’re aware of the performance (time and memory) characteristics of each in a given problem. In many cases, you’ll be using tools that implement a btree quite frequently, but will rarely be required to implement one yourself. For example, your Database Management System (DBMS) implements a type of btree commonly referred to as B+ tree. In 3D computer graphics, many games will often implement a kind of btree usually called a Binary Space Parition (BSP), which allows for recursively subdividing a space into convex sets by hyperplanes.

There are many areas where trees or graphs (nodes and edges) are generally useful in a wide array of programming problems. So having a good grasp of BST, is not a bad start!

Final Thoughts

As mentioned in the beginning of this article, only a self-balancing implementation of a BST, such as AVL-tree will accomplish average O(log n) in search, insertion, and deletion, because as you can see by our implementation if I were to simply insert the numbers [1,2,3,4,5] or [5,4,3,2,1] you would have O(n) since the tree would be entirely right or left heavy.

So, as always, I like to leave something up to the imagination. So I’ll leave it to you to play around with the implementation and see if you can figure out how to implement a balance method that will automatically balance the tree.

Delboy’s Bitcoin Blog

Late 2017. I now find myself inundated with messages from people that want to know about Bitcoin. So instead of repeating myself over and again, I decided to write this blog post.

What is Bitcoin

It’s like emailing money. Transactions are sent from one address to another.  The difference being that there is no central authority verifying the transactions. To be able to securely send coins to each other without the need of a trusted third party like the banks (who incidentally, aren’t to be trusted!*) has been a problem that has been solved by the “Blockchain”, the underlying technology behind Bitcoin.

What is the Blockchain?

The Blockchain is nothing more than a trusted ledger of transactions. It’s a public online bank statement, recording money in and money out from all the different bitcoin addresses (bank accounts).

The computers with the Bitcoin server installed that process all the transactions, do insanely difficult mathematics in order to solve a puzzle, and are racing against each other to be the first to find the answer. The computer that finds the answer has ‘struck gold’ and mints 12.5 BTC into the system, and another block of transactions are recorded on the blockchain.

There will only ever be 21 million Bitcoin, and I believe around 15 million have already been ‘mined’. Many miners combine their computing power in a ‘mining pool’, which shares their part of the 12.5BTC mining reward for doing the calculations and verifying the transactions.

Each block in the chain gets mined every ten minutes, on average. If blocks start being mined too quickly (or too slowly), the difficulty of the math problem the computers need to solve is adjusted accordingly.  So adding faster hardware is pointless, as the software adjusts to make it a waste of time. This is the reason Bitcoin now uses more electricity than several countries!

Never mind that, I want some, what now?

There are various ways of holding bitcoin. The first thing you need to worry about is downloading a wallet.

Pick whatever suits your computer here: https://bitcoin.org/en/choose-your-wallet

The SAFEST way of keeping your Bitcoin safe is by opening the freshly installed wallet, taking a note of the public address, and the private key. There will be an export private key function. Open the exported text file and write the private key down on paper! Then delete everything from your computer! You can still send money to your wallet by giving people your public address, but you cant spend it again until you re-import the private key back into a wallet! So it’s the best way to keep savings.

If you want to spend and use your bitcoin you should leave it installed obviously. It’s better having a wallet on your computer than it is on your phone, or through a website, for the simple reason that the website is someone else’s computer, and that the phone app gets info from someone else’s website too. You will have accounts on websites however that come with a bitcoin address, but be sure to get the one on your computer set up, being your ‘withdrawal address’, and the one you hold the keys for.

Right I have a wallet, what now?

Other than dealing face to face with someone, you buy your Bitcoin from a trading exchange, like any other stock market. Good exchanges for the UK and Europe include Coinbase and Kraken. There’s a pain in the ass verification process to hook your bank account up, but when you do, you can deposit and then buy!

It’s a trading exchange, so you can also sell! Anyway, the website will show your balance, wether in euros, pounds, dollars, or BTC. But you want to withdraw from the website and send it to the wallet you set up earlier.

The Quick way

You can still get your hands on Bitcoin, and indeed trade with Bitcoin, without the annoying verification process. However, you can’t get it back out in GBP or EUR if you haven’t.

I have used Bittylicious several times to buy Bitcoin. You send a bank transfer yourself via digital banking, and the website sees it and sends your coins immediately.

I also use Wex for trading, they allow you to deposit and trade BTC for USD without verification. So long as you withdraw in BTC they don’t care. Like I said though Coinbase or Kraken is the one to use if you intend to cash in one day!

If you have any questions, fire them across and I’ll update this blog post!

Feel free to donate 1De1boyXJzdk4TYmHkR3st6dJmHuEaneHB