Tuesday, November 20, 2018

STL Containers

container.at(2) is same as container[2], but at(2) can throw range_error if it is out of range.
empty(), size(), clear(), swap(), copy constr - are some common methods for all containers.


Sequential Containers - dynamic array
[] -> subscript operator

Vector - dynamic array, one sided (push_back only)
Fast remove and insert only at the end of the array (append).
Search, delete, insert at non terminal location is linear time.

Deque - dynamic array, two sided (push_front and push_back)
Fast remove and insert only at the end or start of the array (append).
Search, delete, insert at non terminal location is linear time.

list - linked list (bi-directional)
Fast insert and remove at any place.
Search is linear. But because of non contiguous memory location, it is slower than vector.
special function - splice - cut a range of data from mylist2 and insert into mylist1 very easily with constant time complexity.
mylist1.splice(itr, mylist2.begin(), mylist.end());

container array - array
array a = {3,4,5};


Associative Containers - Binary tree - always sorted, insert at proper location all the time (that's why its not editable(key non editable in case of maps)).
Find is very fast - log(n)
Traversing is slow (compared to vector and deque)
No random access, no [] operator like vector or array

set - unique (a map of key = value) - has '<' operator default overloaded.
multiset - dupes allowed.

map - unique - (mostly implemented as a red black tree)
multimap - dupes allowed


C++11 introduced Unordered Container - hashmaps - most of the operations are O(1).
unordered_set
unordered_map

Internally implemented as hashtable, array of linked list
Arrays is also called array of buckets and link list is called entries
Each element has a hashvalue, and based on that value its inserted in its own place in entries.

Hash collision - performance degrade
Hash collision occurs when most elements are in the same linked list (entry).
If it degrades, it goes to linear time; so if your business logic has chances of degrading the hash, better go for map, which guarantees log(n) at all times.




Tuesday, November 6, 2018

JSON and Protobuf

JSON : Java Script Object Notation (but not a strict subset of javascript, can be used by python, java, javascript etc)

Messages sent as object, instead of plain text string, so it's easier to read by the consumer (without the need for parsing).

Convert object from java to JSON on the producer side, and convert from JSON to java object on the consumer side.

For using JSON with C++, you can use Boost's property tree. Boost Property tree can be used to represent XML, JSON, INI files, file paths etc.

read_json, write_json are the two basic methods.
For more info - http://zenol.fr/blog/boost-property-tree/en.html


Protobuf : Protocol buffer (by google)
Messages and services are defined in file.proto, compiled using 'protoc'
Supports - mandatory(required) and optional fields, tagging (to provide bandwidth/storage savings), composition, repeated (container).

Financial terms

Derivatives

Derivatives - the value is derived from the underlying asset (stock, fx, commodity)
Uses - 1. to hedge risk; 2. Speculation - just for profit

Types
Forwards -
A customised contract between 2 parties to buy/sell an asset at a specified price at a future date.
particularly used for hedging, but not on standard exchanges.

Futures
Same as forwards, but standardised and regulated on exchanges.
Has lot size. Monthly lots. Expiry dates.

Options
A contract with rights, but not the obligation to buy (call) or sell(put) a security stock.
Call : You make profit, if your underlying asset goes up.
Put : You make profit, if your underlying asset goes down.
Has lot size. Monthly lots. Expiry dates.

Swaps
It's an exchange of one security for another.

Object Oriented Database - in simple words

OODMS
Complex data like images, objects etc.
Its has OO concepts like encapsulation, inheritance, polymorphism, overloading
Access things at object level instead of rows and columns.
Can be relatively slow, if objects are not optimally defined; but can be very fast if defined well.
Nodal architecture.

These youtube videos looks good -
https://www.youtube.com/watch?v=C10T9M83Gj8
https://www.youtube.com/watch?v=7v_5vfTKDVs

Sunday, November 4, 2018

A brief intro to C++11 features

17. delete function
if you do
void func(int)
void func(double) = delete

then when you do func(1.1) it will not be typecasted to int and call func(int), but will throw an error.

16. default function
A way to provide default implementation of the function, like a constructor.

15. foreach
for (auto iter: myContainer)    //myContainer is any type that has begin() and end(). Read only.
for (auto &iter:myContainer) //Read/Write access


14.delegating constructor
Replacement for the typical 'init()' function.
Disadvantage is - it can only be invoked at the beginning of constructor call, not laters.

myClass() //delegating constr
myClass(type a) : myClass() { do_something_on_a();}

Also, data members of the class can be initialized in the class declaration itself. All the objects will have this initial value, which may later be changed.

13.constexpr
Compile time evaluation of a const expression, which will eventually save cycles during the run time.


12.enums : Strong typed enum class
enum class car{german, japanese, korean}
enum class bike{german, american, Indian}

a = car::german; b = bike::german
In C++03, a==b will return true, but in C++11, it will not; but it will give a compile error because == is not overloaded for car and bike.

11. nullptr
In C++03, NULL is 0; so we have a new definition, especially for removing this ambiguity.

9. final (earlier solution was to have private constructor)
class - no class can be derived from the final class.
virtual function - no class can override the function.

8.  override
To fix the name hiding problem.

Base class
virtual void f (int);
Derived class
virtual void f(float);

If we add override keyword to the derived::f, compile will throw an error to highlight the fact that overriding will not be possible. Either remove override keyword (not the desired outcome) or correct the signature.

7. lambda expressions
A very powerful feature of functional programming - anonymous function
std::cout << [](std::string a, std::string b){return (a+b);} ("abc", "def");
Having this line in main will print 'abcdef';

It can access local variables too.

6. auto
Typically useful while iterating.
A drawback is 'readability is lost'; but in a good IDE it can be overcome.

Automatically infers the type from the rvalue (but it also means, it needs a rvalue, otherwise how can it infer?)

5. Static assertion
Compile time assert (in addition to the C++03 run time assert)
C++03 : assert (ptr != NULL);
C++11 : static_assert(sizeof(char) == 1);


4. Initialiser list
Similar to array initialisation is vector(any other container) initialisation now.

You can also define your own initialiser list constructor for the class like this -
#include
class MyClass
{
    vector vec;
    public:
    MyClass(const std::initializer_list &v)
    {
        for (initializer_list::iterator iter = v.begin(); iter!=v.end(); ++iter)
            vec.push_back(*iter);
    }
};

MyClass obj = {1,3,5,9};
MyClass obj{1,3,5,9};


3. Variadic templates
... is called parameter pack.

template
void log(T first, Args... args);

the function log can take any number/type of arguments equal to or more than 1.

A good example given here - https://thispointer.com/c11-variadic-template-function-tutorial-examples/

2. rvalue references
lvalue = any object that occupies some identifiable location in memory
rvalue = anything that is not a lvalue

Simple examples -
int x = 0;                                        //x is lvalue, 0 is rvalue
int &x1 = x;                                   //x1 is lvalue
int *p = &x;                                   //p is lvalue
int y = x+2;                                    //(x+2) is rvalue, y is lvalue
int *p1 = & (x+2);                         //error - (x+2) doesnt have a memory, its a rvalue
int result = add (3,4);                     //add(3,4) is rvalue, result is lvalue
int add(int a, int b)
{
    return (a+b);                              //(a+b) is rvalue
}

Usage:
void abraCaDabra(int &a){}
void abraCaDabra(int && a) {}

You can call using abraCaDabra(i) (will call lvalue) or abraCaDabra(5) (will call rvalue)
With c++03, it will give compile error.


1. Move Semantics
Unlike Copy constructor, move constructor moves the object to the new one, thereby the old object becomes unusable (mostly).

Move constructor : Inexpensive shallow copy
MyClass (Myclass && rhs)
{
    member = rhs.member;
    ptr = rhs.ptr // In a copy constructor, ptr would be newly allocated, and then contents copied.
}

Wednesday, October 31, 2018

Python

Having already worked on C++, my Python self learning crash course was as below -

1.
The 43 min youtube by Derek Banas : over 2 days, doing simple basic programs

Python Programming by Derek Banas

2.
To understand some advanced concepts like OO, we have this playlist by Coray Schafer
Python OOP Tutorial
There are 6 short videos of all less than 20 mins.

2 days, with some practice programs on pycharm, and revisiting each video multiple times to grasp all the concepts.

3.
Next comes this entire text based tutorial to revisit and to practice some simple examples/exercises by w3schools - here

2 days

4.
A day spent on various random videos about python programs. My videos are -
Socrates Python Videos Playlist
List Comprehension
Python Playlists by Corey Schafer

Exercises and Programs - stay tuned.