Wednesday 22 October 2014

Prove it - factorial is bigger than 2^n

I've been doing the scala coursera and wanted to write down the proof that

factorial(n) ≥ 2n when n ≥ 4

since it uses induction and I am out of practise.

Base case

For n = 4

factorial(4) = 4*3*2*1 = 24
and 24 = 2*2*2*2 = 16
and 24 ≥ 16

so factorial(n) ≥ 2n when n = 4

Induction step

For n >= 4 assume we have

factorial(n) >= 2n

and consider

factorial(n+1) = factorial(n) × (n+1)
 ≥ 2n × (n+1)
 ≥ 2n × 2 since (n+1) ≥ 2 when n ≥ 4
 = 2n+1

QED
(I also wanted to learn about writing maths in html)

Wednesday 9 July 2014

Remote debugging python in Visual Studio

Suppose you have a script you want to run on linux and you only know how to drive the Visual Studio debugger. By installing an add-in for Visual Studio locally, installing the python tools for Visual Studio debugging on the remote machine, e.g. with pip install ptvsd==2.0.0pr1 and adding a (minimum of) a couple of lines to your script you can debug in Visual Studio even if the remote machine is running linux.
The additional lines are highlighted in the following script:

#!/usr/bin/python

"""
You will need to insert both these in your script
The remote box requires the ptvsd package (otherwise the import fails)
"""
import ptvsd
ptvsd.enable_attach(secret = 'joshua')
#use None instead of joshua but that is not secure
#The secret can be any string - but this is not properly secure


def say_it(it):
  """
  This inserts a breakpoint
  but you can add new breakpoints in Visual Studio
  if required too/instead
  """
  ptvsd.break_into_debugger()
  print(it)

if __name__ == "__main__":
  #pause this script til we attach to it
  ptvsd.wait_for_attach()
  say_it("Hello world")


See https://pytools.codeplex.com/wikipage?title=Remote%20Debugging%20for%20Windows%2C%20Linux%20and%20OS%20X for more details and be wary of line ending in VS which may be inappropriate for linux.

Install the ptvs from the relevant msi for your version of Visual Studio.

Start the script on the linux box:
$python VSPyNoodle.py

It will hang, since it has a wait_for_attach call in main. 
ctrl-Z will stop it on the remote box if something goes wrong.

Select "Attach to process" in the Debug menu on Visual Studio
Change the "Transport" to "Python remote debugging (unsecured)"

Add the secret (joshua in this script) @ hostname to Qualifier
e.g. joshua@hostname

Hit "Refresh"

It should find the process running on the linux box and add the port it uses to the Qualifier
Select your process in the list box and hit "Attach"
  then debug as you are used to in VS.

If it complains about stack frames and not being able to see the code you may need to make a VS project from a local version of the code. having made sure it exactly matches the remote code.



Wednesday 5 February 2014

Mutable structs in C#

We know what this does, right?

    struct Pricer
    {
        public double Price;
        public long Size;

        public void AddExecution(long lastSize, double lastPrice)
        {
            Price = (Price * Size + lastSize * lastPrice) / (Size + lastSize);
            Size += lastSize;
        }
    }

    class PriceData
    {
        public Pricer pricer;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Pricer price = new Pricer{Price = 0.0, Size = 0};
            for (int i = 0; i < 5; ++i)
            {
                Console.WriteLine("{0} {1}", price.Price, price.Size);
                price.AddExecution(1, 2.5 * (i + 1));
            }

            for (int i = 0; i < 5; ++i)
            {
                Console.WriteLine("{0} {1}", price.Price, price.Size);
                price.Price= 2.5 * (i + 1);
            }

            PriceData priceData = new PriceData();
            priceData.pricer = price;
            for (int i = 0; i < 5; ++i)
            {
                Console.WriteLine("{0} {1}", price.Price, price.Size);
                priceData.pricer.AddExecution(1, 2.5 * (i + 1));
            }
       }
    }

Eric Lippert tells us about mutating *readonly* structs: http://blogs.msdn.com/b/ericlippert/archive/2008/05/14/mutating-readonly-structs.aspx but even non-readonly structs can get us in a mess.

Wednesday 29 January 2014

Pdb ftw

pdb - python debugger

If a script throws an exception, try running it in the debugger
python -m pdb myscript.py
For example given the following (rubbish) python program
C:\Dev\src>cat bad.py
def naughty():
 raise Exception()
naughty()

if we just run it the exception tries to escape ...
C:\Dev\src>python bad.py
Traceback (most recent call last):
 File "bad.py", line 4, in <module>
 naughty()
 File "bad.py", line 2, in naughty
 raise Exception()
Exception

So, we know what line the problem's on. We could change the script to see what's going on using
import pdb; pdb.set_trace()
or we could run it under a debugger.

Run script through debugger

Invoke the pdb module in python and send it your script, e.g.
python -m pdb bad.py
This gives a (Pdb) prompt to type instructions in to:
> c:\dev\src\bad.py(1)<module>()
-> def naughty():
(Pdb)
Type 'c' for continue - it will halt when it gets an exception, as follows
(Pdb) c
Traceback (most recent call last):
 File "C:\Python27\lib\pdb.py", line 1314, in main
 pdb._runscript(mainpyfile)
 File "C:\Python27\lib\pdb.py", line 1233, in _runscript
 self.run(statement)
 File "C:\Python27\lib\bdb.py", line 387, in run
 exec cmd in globals, locals
 File "<string>", line 1, in <module>
 File "bad.py", line 1, in <module>
 def naughty():
 File "bad.py", line 2, in naughty
 raise Exception()
Exception
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> c:\dev\src\bad.py(2)naughty()
-> raise Exception()
(Pdb)
At this point
 (Pdb) p <variable_name>
can be used to inspect variables, and
 (Pdb) a
shows any arguments to a function.

Main Pdb commands

Type 'q' for quit, 's' to step (maybe into another function) or 'n' to move on to the next line.
'w' shows where you are in the stack, 'u' moves up and 'd' moves down.
b(reak) [[filename:]lineno  sets a breakpoint.
There are more details in the manual: http://docs.python.org/2/library/pdb.html

Tuesday 21 January 2014

Virtual functions in constructors and destructors

Interview question.

What does this do?

class Base
{
public:
Base()
{
log();
}
virtual ~Base()
{
log();
}

//virtual void log() = 0;//note this compiles but doesn't link
virtual void log()
{
std::cout << "Base\n";
}
};

class Derived : public Base
{
public:
Derived()
{
log();
}
~Derived()
{
log();
}
virtual void log()
{
std::cout << "Derived\n";
}
};

int main()
{
Derived d;
}

I half remembered this http://www.artima.com/cppsource/nevercall.html so wasn't sure.