Saturday, July 30, 2016

Inheritance in Lua

Consider this code:

#!/usr/bin/lua
Account = { balance = 0 }
function Account:new (o)
print("Calling constructor for "..tostring(self))
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
-- self.__index = self
self.__index = function(table, key)
print("Accessing key = "..key.." for "..tostring(table).."; self = "..tostring(self))
return self[key]
end
return o
end
function Account:deposit (v)
print("Account:deposit(): self = "..tostring(self))
self.balance = self.balance + v
end
function Account:withdraw (v)
print("Account:withdraw(): self = "..tostring(self))
if v > self.balance then error"insufficient funds" end
self.balance = self.balance - v
end
function Account:get_balance()
print("Account:get_balance(): self = "..tostring(self))
return self.balance
end
SpecialAccount = Account:new()
function SpecialAccount:withdraw (v)
print("SpecialAccount:withdraw(): self = "..tostring(self))
if v - self.balance >= self:getLimit() then
error"insufficient funds"
end
self.balance = self.balance - v
end
function SpecialAccount:getLimit ()
print("SpecialAccount:getLimit(): self = "..tostring(self))
return self.limit or 0
end
s = SpecialAccount:new{limit=1000.00}
s:deposit(100.00)
s:withdraw(200)
print(s:get_balance())
view raw inheritance.lua hosted with ❤ by GitHub
This is the output when run:

kuyu@castor-ub:~/dkuyu/Dropbox/practice/lua/oop$ ./inheritance.lua
Calling constructor for table: 0x2414180
Accessing key = new for table: 0x2412f40; self = table: 0x2414180
Calling constructor for table: 0x2412f40
Accessing key = deposit for table: 0x2411eb0; self = table: 0x2412f40
Accessing key = deposit for table: 0x2412f40; self = table: 0x2414180
Account:deposit(): self = table: 0x2411eb0
Accessing key = balance for table: 0x2411eb0; self = table: 0x2412f40
Accessing key = balance for table: 0x2412f40; self = table: 0x2414180
Accessing key = withdraw for table: 0x2411eb0; self = table: 0x2412f40
SpecialAccount:withdraw(): self = table: 0x2411eb0
Accessing key = getLimit for table: 0x2411eb0; self = table: 0x2412f40
SpecialAccount:getLimit(): self = table: 0x2411eb0
Accessing key = get_balance for table: 0x2411eb0; self = table: 0x2412f40
Accessing key = get_balance for table: 0x2412f40; self = table: 0x2414180
Account:get_balance(): self = table: 0x2411eb0
-100
kuyu@castor-ub:~/dkuyu/Dropbox/practice/lua/oop$

Notice how searching for a key is recursive. When a key is not found in s, it is searched in SpecialAccount. When the key is not found in SpecialAccount, it is searched in Account.

Classes in Lua

This is an adaptation of the code found here:

#!/usr/bin/lua
Account = { balance = 0 }
function Account:new (o)
print("Calling constructor for "..tostring(self))
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
-- self.__index = self
self.__index = function(table, key)
print("Accessing key = "..key.." for "..tostring(table).."; self = "..tostring(self))
return self[key]
end
return o
end
function Account:deposit (v)
print("Account:deposit(): self = "..tostring(self))
self.balance = self.balance + v
end
function Account:withdraw (v)
print("Account:withdraw(): self = "..tostring(self))
self.balance = self.balance - v
end
function Account:get_balance()
print("Account:get_balance(): self = "..tostring(self))
return self.balance
end
a = Account:new{balance = 0}
a:deposit(100.00)
print("a's balance: " .. a:get_balance())
b = Account:new{}
b:deposit(100.00)
print("Account:balance = "..Account.balance)
b:withdraw(40.00)
print("b's balance: " .. b:get_balance())
view raw l.lua hosted with ❤ by GitHub
When run, the output looks like this:

kuyu@castor-ub:~/dkuyu/Dropbox/practice/lua/oop$ ./l.lua 
Calling constructor for table: 0x8a2160
Accessing key = deposit for table: 0x8a1df0; self = table: 0x8a2160
Account:deposit(): self = table: 0x8a1df0
Accessing key = get_balance for table: 0x8a1df0; self = table: 0x8a2160
Account:get_balance(): self = table: 0x8a1df0
a's balance: 100
Calling constructor for table: 0x8a2160
Accessing key = deposit for table: 0x89a4a0; self = table: 0x8a2160
Account:deposit(): self = table: 0x89a4a0
Accessing key = balance for table: 0x89a4a0; self = table: 0x8a2160
Account:balance = 0
Accessing key = withdraw for table: 0x89a4a0; self = table: 0x8a2160
Account:withdraw(): self = table: 0x89a4a0
Accessing key = get_balance for table: 0x89a4a0; self = table: 0x8a2160
Account:get_balance(): self = table: 0x89a4a0
b's balance: 60
kuyu@castor-ub:~/dkuyu/Dropbox/practice/lua/oop$ 



Thursday, July 21, 2016

Compiling and running Google test and Google mock in Ubuntu

To compile and run Google Test and Google Mock in Ubuntu, you can follow these steps.

First download Google Test from here. Extract the downloaded zip file to a directory of your choice.

After extraction, you will see a folder named googletest-master. Enter this folder.

Inside the googletest-master folder, you will see these two folders: googletest and googlemock.

To compile and test run google test, go to the googletest directory. There you will see a make directory. Go inside the make directory and type 'make'.

Executing the make command will create the executable file, sample1_unittest. You can then run this executable file:

kuyu@castor-ub:~/dkuyu/bin/googletest-master/googletest/make$ pwd; ls
/home/kuyu/dkuyu/bin/googletest-master/googletest/make
Makefile
kuyu@castor-ub:~/dkuyu/bin/googletest-master/googletest/make$ make && ./sample1_unittest
g++ -isystem ../include -g -Wall -Wextra -pthread -c ../samples/sample1.cc
g++ -isystem ../include -g -Wall -Wextra -pthread -c ../samples/sample1_unittest.cc
g++ -isystem ../include -I.. -g -Wall -Wextra -pthread -c \
            ../src/gtest-all.cc
g++ -isystem ../include -I.. -g -Wall -Wextra -pthread -c \
            ../src/gtest_main.cc
ar rv gtest_main.a gtest-all.o gtest_main.o
ar: creating gtest_main.a
a - gtest-all.o
a - gtest_main.o
g++ -isystem ../include -g -Wall -Wextra -pthread -lpthread sample1.o sample1_unittest.o gtest_main.a -o sample1_unittest
Running main() from gtest_main.cc
[==========] Running 6 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 3 tests from FactorialTest
[ RUN      ] FactorialTest.Negative
[       OK ] FactorialTest.Negative (0 ms)
[ RUN      ] FactorialTest.Zero
[       OK ] FactorialTest.Zero (0 ms)
[ RUN      ] FactorialTest.Positive
[       OK ] FactorialTest.Positive (0 ms)
[----------] 3 tests from FactorialTest (0 ms total)

[----------] 3 tests from IsPrimeTest
[ RUN      ] IsPrimeTest.Negative
[       OK ] IsPrimeTest.Negative (0 ms)
[ RUN      ] IsPrimeTest.Trivial
[       OK ] IsPrimeTest.Trivial (0 ms)
[ RUN      ] IsPrimeTest.Positive
[       OK ] IsPrimeTest.Positive (0 ms)
[----------] 3 tests from IsPrimeTest (0 ms total)

[----------] Global test environment tear-down
[==========] 6 tests from 2 test cases ran. (0 ms total)
[  PASSED  ] 6 tests.
kuyu@castor-ub:~/dkuyu/bin/googletest-master/googletest/make$ 

You can follow similar steps to compile and test run Google Mock in Ubuntu. From the googletest-master directory, go to the googlemock/make directory. Then type make. The executable created by the make command is named gmock_test.

You can actually study the Makefile file in the googletest/make and googlemock/make directories. There you can edit the GTEST_DIR, USER_DIR, and GMOCK_DIR (for googlemock).

Wednesday, July 20, 2016

Google test

Getting started in Google test is also difficult.

To setup Google test to run in Ubuntu, I followed this site.

CppUMock example

This is an example CppUMock test. It consists of 3 files: test_main.cpp, test.cpp and makefile.

test_main.cpp:

#include "CppUTest/CommandLineTestRunner.h"
int main(int argc, char** argv)
{
return CommandLineTestRunner::RunAllTests(argc, argv);
}
view raw test_main.cpp hosted with ❤ by GitHub
test.cpp:

#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include <cstdio>
class ProtocolFsm
{
public:
virtual int GetObjectId()
{
return 10;
}
};
class ProtocolFsmMock : public ProtocolFsm
{
public:
virtual int GetObjectId()
{
mock().actualCall("GetObjectId").onObject(this);
return mock().intReturnValue();
}
};
void ProtocolProcedure(ProtocolFsm* pProtocolFsm)
{
printf("%s: Got %d\n", __FUNCTION__, pProtocolFsm->GetObjectId());
}
TEST_GROUP(MockDocumentation)
{
void teardown()
{
mock().clear();
}
};
void productionCode()
{
mock().actualCall("productionCode");
}
TEST(MockDocumentation, SimpleScenario)
{
mock().expectOneCall("productionCode");
productionCode();
ProtocolFsm* pProtocolFsm = new ProtocolFsmMock;
printf("%s: pProtocolFsm=%p\n", __FUNCTION__, pProtocolFsm);
mock().expectOneCall("GetObjectId").onObject(pProtocolFsm).andReturnValue(3);
ProtocolProcedure(pProtocolFsm);
mock().expectOneCall("GetObjectId").onObject(pProtocolFsm).andReturnValue(5);
ProtocolProcedure(pProtocolFsm);
mock().expectOneCall("GetObjectId").onObject(pProtocolFsm).andReturnValue(7);
ProtocolProcedure(pProtocolFsm);
mock().checkExpectations();
delete pProtocolFsm;
}
view raw test.cpp hosted with ❤ by GitHub
makefile:

all: a.out
export CPPUTEST_HOME=/usr/local
CPPFLAGS += -I$(CPPUTEST_HOME)/include
LD_LIBRARIES = -L$(CPPUTEST_HOME)/lib -lCppUTest -lCppUTestExt
a.out: test_main.o test.o
g++ -g -o a.out test.o test_main.o $(LD_LIBRARIES)
test_main.o: test_main.cpp
g++ -g $(CPPFLAGS) -c test_main.cpp
test.o: test.cpp
g++ -g $(CPPFLAGS) -c test.cpp
clean:
rm -f *.o a.out
view raw makefile hosted with ❤ by GitHub
Output:

kuyu@castor-ub:~/dkuyu/Dropbox/practice/cpp/cpputest/ho$ make && ./a.out
g++ -g -I/usr/local/include  -c test_main.cpp
g++ -g -I/usr/local/include  -c test.cpp
g++ -g -o a.out test.o test_main.o -L/usr/local/lib -lCppUTest -lCppUTestExt
testBody: pProtocolFsm=0x189d4c0
ProtocolProcedure: Got 3
ProtocolProcedure: Got 5
ProtocolProcedure: Got 7
.
OK (1 tests, 1 ran, 3 checks, 0 ignored, 0 filtered out, 1 ms)

kuyu@castor-ub:~/dkuyu/Dropbox/practice/cpp/cpputest/ho$ 

Wednesday, July 13, 2016

cpputest

I spent several hours figuring out how to run cpputest in Ubuntu. I searched several websites, but they were not helpful. You can imagine the agony that I went through.

Finally, I came across this stackoverflow question. Thank you, pradeep (the author of the question (and also the answer)).

Well, first you need to install CppUTest in Ubuntu:

% sudo apt-get install cpputest

After that, create the files: test.cpp, test_main.cpp, and makefile

For the makefile file, be sure to use tab indentations and not spaces.

After creating the files:

kuyu@castor-ub:~/dkuyu/practice/cpp/cpputest/hello$ make 
g++ -g -I/usr/local/include  -c test_main.cpp
g++ -g -I/usr/local/include  -c test.cpp
g++ -g -o mytest test.o test_main.o -L/usr/local/lib -lCppUTest -lCppUTestExt
kuyu@castor-ub:~/dkuyu/practice/cpp/cpputest/hello$ ./mytest 

test.cpp:15: error: Failure in TEST(FirstTestGroup, SecondTest)
expected <hello>
but was  <world>
difference starts at position 0 at: <          world     >
                                              ^

.
test.cpp:10: error: Failure in TEST(FirstTestGroup, FirstTest)
Fail me!

.
Errors (2 failures, 2 tests, 2 ran, 1 checks, 0 ignored, 0 filtered out, 1 ms)

kuyu@castor-ub:~/dkuyu/practice/cpp/cpputest/hello$ 

It finally ran.

Saturday, July 9, 2016

Iterator swap for vector proxy class

Here is an example of iterator swapping for the vector<bool> proxy class:

#include <iterator>
#include <cstdio>
template <class ForwardIterator1, class ForwardIterator2>
void iter_swap(ForwardIterator1 i1, ForwardIterator2 i2)
{
typename std::iterator_traits<ForwardIterator1>::value_type
tmp = *i1;
*i1 = *i2;
*i2 = tmp;
}
struct proxy
{
proxy& operator=(bool x)
{
if (x)
bytes[pos/8] |= (1u << (pos%8));
else
bytes[pos/8] &= ~(1u << (pos%8));
return *this;
}
proxy& operator=(proxy const& other)
{
bool x = bool(other);
if (x)
bytes[pos/8] |= (1u << (pos%8));
else
bytes[pos/8] &= ~(1u << (pos%8));
return *this;
}
operator bool() const
{
return bytes[pos/8] & (1u << (pos%8));
}
unsigned char* bytes;
size_t pos;
};
struct bit_iterator
{
typedef bool value_type;
typedef proxy reference;
typedef std::forward_iterator_tag iterator_category;
typedef int difference_type;
typedef int pointer;
proxy operator*() const { return prx; };
bit_iterator(proxy& other) : prx(other) { }
proxy& prx;
};
int main()
{
unsigned char vec[2];
proxy a;
proxy b;
a.bytes = vec;
b.bytes = vec;
a.pos = 3;
b.pos = 12;
bit_iterator i_a(a);
bit_iterator i_b(b);
a = true;
b = false;
printf("Before swap\n");
printf("\ta.bytes=%p a.pos=%u a.bool=%u\n", a.bytes, a.pos, bool(a));
printf("\tb.bytes=%p b.pos=%u b.bool=%u\n", b.bytes, b.pos, bool(b));
iter_swap(i_a, i_b);
printf("After 1st swap\n");
printf("\ta.bytes=%p a.pos=%u a.bool=%u\n", a.bytes, a.pos, bool(a));
printf("\tb.bytes=%p b.pos=%u b.bool=%u\n", b.bytes, b.pos, bool(b));
iter_swap(i_a, i_b);
printf("After 2nd swap\n");
printf("\ta.bytes=%p a.pos=%u a.bool=%u\n", a.bytes, a.pos, bool(a));
printf("\tb.bytes=%p b.pos=%u b.bool=%u\n", b.bytes, b.pos, bool(b));
return 0;
}
Here is the output:

kuyu@castor-ub:~/dkuyu/practice/cpp/iter_swap_bool$ g++ -Wformat=0 iter_swap_bool.cpp && ./a.out
Before swap
a.bytes=0x7ffdd8f29760 a.pos=3 a.bool=1
b.bytes=0x7ffdd8f29760 b.pos=12 b.bool=0
After 1st swap
a.bytes=0x7ffdd8f29760 a.pos=3 a.bool=0
b.bytes=0x7ffdd8f29760 b.pos=12 b.bool=1
After 2nd swap
a.bytes=0x7ffdd8f29760 a.pos=3 a.bool=1
b.bytes=0x7ffdd8f29760 b.pos=12 b.bool=0
kuyu@castor-ub:~/dkuyu/practice/cpp/iter_swap_bool$

Some questions to consider:
  1. What happens if the function starting at line 25 is deleted?
  2. What happens if the function at line 54 returned proxy& instead of only proxy?

iterator_traits

Been trying to read this book:

Abraham, David; Gurtovoy, Aleksey. 2004. C++ template metaprogramming: Concepts, tools, and techniques from Boost and beyond. Addison Wesley.

Tried to code a little on iterator_traits:

#include <iostream>
#include <string>
class myclass
{
public:
typedef std::string value_type;
myclass(value_type const& arg) : priv(arg) { }
myclass& operator=(myclass const& rhs)
{
priv = rhs.priv;
return *this;
}
value_type const& get_priv()
{
return priv;
}
value_type& operator*()
{
return priv;
}
private:
value_type priv;
};
namespace std
{
template<>
struct iterator_traits<myclass>
{
typedef typename myclass::value_type value_type;
};
}
template <class ForwardIterator1, class ForwardIterator2>
void swap(ForwardIterator1& i1, ForwardIterator2& i2)
{
typename std::iterator_traits<ForwardIterator1>::value_type tmp = *i1;
*i1 = *i2;
*i2 = tmp;
}
int main()
{
myclass a("a");
myclass b("b");
std::cout << "Before:" << std::endl;
std::cout << "a = " << a.get_priv() << std::endl;
std::cout << "b = " << b.get_priv() << std::endl;
swap(a, b);
std::cout << "After:" << std::endl;
std::cout << "a = " << a.get_priv() << std::endl;
std::cout << "b = " << b.get_priv() << std::endl;
return 0;
}
When I run it:

kuyu@castor-ub:~/dkuyu/practice/cpp/iterator_traits$ g++ iterator_traits.cpp && ./a.out 
Before:
a = a
b = b
After:
a = b
b = a
kuyu@castor-ub:~/dkuyu/practice/cpp/iterator_traits$ 

Example boost:fusion

Example of boost::fusion vector. It is like a C++ tuple.

#include <boost/fusion/include/sequence.hpp>
#include <boost/fusion/include/vector.hpp>
#include <iostream>
int main()
{
boost::fusion::vector<int, char, std::string> stuff(1, 'x', "howdy");
int i = boost::fusion::at_c<0>(stuff);
char ch = boost::fusion::at_c<1>(stuff);
std::string s = boost::fusion::at_c<2>(stuff);
std::cout << s << std::endl;
return 0;
}
view raw vec.cpp hosted with ❤ by GitHub
I guess you can guess what the output is:

kuyu@castor-ub:~/dkuyu/practice/cpp/boost/fusion$ g++ -I/home/kuyu/dkuyu/bin/boost_1_60_0 vec.cpp && ./a.out 
howdy
kuyu@castor-ub:~/dkuyu/practice/cpp/boost/fusion$

Tuesday, July 5, 2016

make

I've always been confused about make and makefiles.

One of the simplest tutorials on make I found is this.