Friday 29 January 2016

Learning Java and C++

JAVA:
--------

Video tutorials:
https://javabrains.io/


Exercise for Java:
http://codingbat.com/
https://projecteuler.net/

Advanced Java video tutorials:
https://www.udemy.com/advanced-java-programming/




C++:
------
Complete C++ basics video tutorials:
https://www.youtube.com/playlist?list=PLAE85DE8440AA6B83

Only threads:
https://www.youtube.com/playlist?list=PL1835A90FC78FF8BE

Wednesday 27 January 2016

Where do we use extern keyword in C++ ?

We have two files, foo.c and bar.c.
Here is foo.c
#include <stdio.h>

volatile unsigned int stop_now = 0;
extern void bar_function(void);

int main(void)
{
  while (1) {
     bar_function();
     stop_now = 1;
  }
  return 0;
}
Now, here is bar.c
#include <stdio.h>

extern volatile unsigned int stop_now;

void bar_function(void)
{
   while (! stop_now) {
      printf("Hello, world!\n");
      sleep(30);
   }
}
As you can see, we have no shared header between foo.c and bar.c , however bar.c needs something declared in foo.c when it's linked, and foo.c needs a function from bar.c when it's linked.
By using 'extern', you are telling the compiler that whatever follows it will be found (non-static) at link time, don't reserve anything for it since it will be encountered later.
It's very useful if you need to share some global between modules and don't want to put / initialize it in a header.
Technically, every function in a library public header is 'extern', however labeling them as such has very little to no benefit, depending on the compiler. Most compilers can figure that out on their own. As you see, those functions are actually defined somewhere else.
In the above example, main() would print hello world only once, but continue to enter bar_function(). Also note, bar_function() is not going to return in this example (since it's just a simple example). Just imagine stop_now being modified when a signal is serviced if this doesn't seem practical enough.
Externs are very useful for things like signal handlers, a mutex that you don't want to put in a header or structure, etc. Most compilers will optimize to ensure that they don't reserve any memory for external objects, since they know they'll be reserving it in the module where the object is defined. However, again, there's little point in specifying it with modern compilers when prototyping public functions.

Tuesday 26 January 2016

Why do we use volatile keyword in C++

Consider this code,
int some_int = 100;

while(some_int == 100)
{
   //your code
}
When this program gets compiled, the compiler may optimize this code, if it finds that the programnever ever makes any attempt to change the value of some_int, so it may be tempted to optimize thewhile loop by changing it from while(some_int == 100) to simply while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int (if it's not loaded on a register) and compare it with 100, each time which obviously is a little bit slow.)
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
So, to ensure the desired result, you need to somehow stop the compiler from optimizing the whileloop. That is where the volatile keyword plays it's role. All you need to do is this,
volatile int some_int = 100; //note the 'volatile' qualifier now!

In others words I would explain this as follows:
volatile tells the compiler that,
"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lighting, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"
Well, that is how volatile prevents compiler from optimizing code. Now google it to see some sample examples.

Quoting from the C++ Standard ($7.1.5.1/8)
[..] volatile is a hint to the implementation to avoid aggressive optimization involving the objectbecause the value of the object might be changed by means undetectable by an implementation.[...]

vptr and vtable - runtime polymorphism

C++ compiler creates a hidden class member called virtual-pointer or in  short vptr when there are one or more virtual functions. This vptr is a  pointer that points to a table of function pointers. This table is also  created by compiler and called virtual function table or vtable. Each  row of the vtable is a function pointer pointing to a corresponding  virtual function.
To accomplish late binding, the compiler creates this vtable table for  each class that contains virtual functions and for the class derived  from it. The compiler places the addresses of the virtual functions for  that particular class in ‘vtable’.
When virtual function call is made through a base-class pointer, the  compiler quietly inserts code to fetch the VPTR and look up the function  address in the VTABLE, thus calling the right function and causing  late/dynamic binding to take place.


class base
 {   virtual void funct1(void);
 virtual void funct2(void);
}; base b;

b.vptr = address of b.vtable
b.vtable[0]= &base::funct1()
b.vtable[1]= &base::funct2()

#include <> vs #include ""

#include <stdio.h>
When the include file is in brackets the preprocessor,
  1. first searches in paths specified via the -I flag. 
  2. Then it searches the standard include paths (see the above link, and use the -v flag to test on your system).

#include "myFile.h"
When the include file is in quotes the preprocessor,
  1. first searches in the current directory, 
  2. then paths specified by -iquote
  3. then -I paths, 
  4. then the standard paths.

Monday 25 January 2016

Inter-process communication approaches

MethodShort DescriptionProvided by (operating systems or other environments)
FileA record stored on disk, or a record synthesized on demand by a file server, which can be accessed by multiple processes.Most operating systems
Signal; alsoAsynchronous System TrapA system message sent from one process to another, not usually used to transfer data but instead used to remotely command the partnered process.Most operating systems
SocketA data stream sent over a network interface, either to a different process on the same computer or to another computer on the network. Typically byte-oriented, sockets rarely preserve message boundaries. Data written through a socket requires formatting to preserve message boundaries.Most operating systems
Message queueA data stream similar to a socket, but which usually preserves message boundaries. Typically implemented by the operating system, they allow multiple processes to read and write to the message queue without being directly connected to each other.Most operating systems
PipeA two-way data stream between two processes interfaced through standard input and output and read in one character at a time.All POSIX systems, Windows
Named pipeA pipe implemented through a file on the file system instead of standard input and output. Multiple processes can read and write to the file as a buffer for IPC data.All POSIX systems, Windows, AmigaOS 2.0+
SemaphoreA simple structure that synchronizes multiple processes acting on shared resources.All POSIX systems, Windows, AmigaOS
Shared memoryMultiple processes are given access to the same block of memory which creates a shared buffer for the processes to communicate with each other.All POSIX systems, Windows
Message passingAllows multiple programs to communicate using message queues and/or non-OS managed channels, commonly used in concurrency models.Used in MPI paradigm, Java RMICORBADDSMSMQ,MailSlotsQNX, others
Memory-mapped fileA file mapped to RAM and can be modified by changing memory addresses directly instead of outputting to a stream. This shares the same benefits as a standard file.All POSIX systems, Windows

INSTALLING MYSQL ON CENTOS WITHOUT ROOT ACCOUNT:


1. Download MySQL Community Server 5.5.8 Linux - Generic Compressed TAR Archive

2. Unpack it. For example to: /home/martin/mysql

3. Create my.cnf file in your home directory. The file contents should be:
-----
[server]
user=martin
basedir=/home/martin/mysql
datadir=/home/martin/sql_data
socket=/home/martin/socket
port=3666
-----

4. Go to the /home/martin/mysql directory and execute:
-----
./scripts/mysql_install_db --defaults-file=~/my.cnf --user=martin --basedir=/home/martin/mysql --datadir=/home/martin/sql_data --socket=/home/martin/socket
-----
Note that --defaults-file MUST be the first parameter, otherwise it won't work! It's a MySQL bug.

5. Your MySQL server is ready. Start it with this command:
-----
./bin/mysqld_safe --defaults-file=~/my.cnf &
-----

6. Connecting to server:
-----
mysql -h 127.0.0.1 -P 3666 -u root -p (using tcp)
or
mysql --socket=/home/martin/socket -u root -p (using unix socket)
-----

7. Shutting down server:
-----
mysqladmin -h 127.0.0.1 -P 3666 -u root shutdown(using tcp)
or
mysqladmin --socket=/home/martin/socket -u root shutdown (using unix socket)
-----


Source: http://superuser.com/questions/209203/how-can-i-install-mysql-on-centos-without-being-root-su


Sunday 24 January 2016

C++ default member functions provided by compiler

If you declare an empty class like below, compiler will add all the below functions by default:
class T{}

====
class T {
        // default constructor
        T() {}

        // copy constructor
        T(T const& rhs) {}

        // destructor
        ~T() {}

        // assignment operator
        T& operator=(T const& rhs) { return *this; }

//Move constructor C++11
T(T&& other){}

//Move assignment operator C++11
T& operator=(T&& other){}
};
====

Thursday 21 January 2016

Type Casting in C++


dynamic_cast: Only upcast allowed

  Base * pb1 = new Derived;
  Base * pb2 = new Base;
  Derived * pd;

  pd = dynamic_cast<Derived*>(pb1); //Success. pd will be Non-Null value
  pd = dynamic_cast<Derived*>(pb2); //Failure. pd will be NULL


static_cast: Upcast and downcast both allowed

  Base * pb = new Base;
  Derived * pd = static_cast<Derived*>(pb); //Success. Programmer should ensure the safety.


reinterpret_cast: converts any pointer type to any other pointer type, even of unrelated classes.

  class A { /* ... */ };
  class B { /* ... */ };
  A * a = new A;
  B * b = reinterpret_cast<B*>(a); 

const_cast: manipulates the constness of the object pointed by a pointer, either to be set or to be removed.

  void display (char * str)
  {
    cout << str << '\n';
  }

  int main () {
    const char * c = "sample text";
    display ( const_cast<char *> (c) );
    return 0;
  }

C++11 new features

auto: Used for type inference

  //For variables
  auto i = 42;        // i is an int
  auto l = 42LL;      // l is an long long
  auto p = new foo(); // p is a foo*
  
  //For iterators
  std::map<std::string, std::vector<int>> map;
  for(auto it = begin(map); it != end(map); ++it) {}

  //For function return types
  template <typename T1, typename T2>
  auto compose(T1 t1, T2 t2) -> decltype(t1 + t2)
  {
     return t1+t2;
  }
  auto v = compose(2, 3.14); // v's type is double


nullptr:

  void display(int a){ cout<<"Integer version called"<<endl; }
  void display(int *p){ cout<<"Int pointer version called"<<endl; }
  void display(long a){ cout<<"long version called"<<endl; }
  int main()
  {
        display(nullptr); //Calls pointer version
        display(NULL); //Calls long version
        display(0); //Calls int version
  } 

range-based for loop:

  string str = "United Online";
  for(char c : str)
      cout<<c;

override:

  - For runtime polymorphism,
1. Signatures of functions must be same in both Base and Derived classes.
2. Base class pointer is used to achieve this.
base * pb = new Derived();
  - But there is a chance that by mistake the function signature is different in both Base and Derived     classes. Unnoticeably, we might be thinking that runtime polymorphism will work and Derived   version will be called. But ideally just compile time polymorphism will happen and Base version will be called.
  - To avoid such bugs, 'override' is introduced. It will error out if function signatures are different.

  class parent {
        public:
          virtual void handle_event(int something) {cout<<"Boring default code"<<endl;}
  };

  class child : public parent {
        public:
                // force handle_event to override a existing function in parent
                // error out if the function with the correct signature does not exist
                virtual void handle_event(int something) override {cout<<"New exciting code"<<endl;}
  };

  int main() {
      parent *p = new child();
      p->handle_event(1);
  }


final:

  - To stop Derived class overriding Base class virtual function.
  - To stop inheriting Base class it self.

enums:

  //Old style (Global scope)
   enum Animals{Cat, Dog, Chicken};
   enum Birds{Eagle, Duck, Chicken}; //Error, Chicken is already used

   //New style (Seperate scope)
   enum class Fruits{Apple, Mango, Orange};
   enum class Colors : char{Red, Green, Orange};//Allowed, Fruits::Orange != Colors::Orange

smart pointers: used for reference counting and auto releasing of owned memory.
  • unique_ptr: should be used when ownership of a memory resource does not have to be shared (it doesn't have a copy constructor), but it can be transferred to another unique_ptr (move constructor exists).
  • shared_ptr: should be used when ownership of a memory resource should be shared (hence the name).
  • weak_ptr: holds a reference to an object managed by a shared_ptr, but does not contribute to the reference count; it is used to break dependency cycles (think of a tree where the parent holds an owning reference (shared_ptr) to its children, but the children also must hold a reference to the parent; if this second reference was also an owning one, a cycle would be created and no object would ever be released).
  On the other hand the auto_ptr is obsolete and should no longer be used.

lambdas: Nothing but anonymous functions

Eg: [](int n){cout<<n<<" ";}

BOOST BOOST_FOREACH example

#include <iostream>
#include <string>
#include <boost/foreach.hpp>

using namespace std;
using namespace boost;

int main()
{
        string str = "United Online";

        char c;
        BOOST_FOREACH(c, str)
        {
                cout<<c;
        }
        cout<<endl;

        list l = {1,2,3,4,5};
        BOOST_FOREACH(int i, l)
        {
                cout<<i;
        }
        cout<<endl;
}

BOOST scoped_ptr example

#include <iostream>
#include <boost/scoped_ptr.hpp>

using namespace std;
using namespace boost;

class C
{
        public:
                int a;
                int b;

                C(){cout<<"Constructor called"<<endl;}
                ~C(){cout<<"Destructor called"<<endl;}
};

int main()
{
        C * pC = new C;
        scoped_ptr<C> scp(pC);
        scp->a = 10;
        scp->b = 20;

        cout<<"a: "<<scp->a<<endl;
        cout<<"b: "<<scp->b<<endl;

        scp.reset();

        cout<<"a: "<<pC->a<<endl;
        cout<<"b: "<<pC->b<<endl;
}

BOOST shared_ptr example

#include <iostream>
#include <memory>

using namespace std;

class C
{
        public:
                int a;
                int b;

                C(){cout<<"Constructor called"<<endl;}
                ~C(){cout<<"Destructor called"<<endl;}
                int add(int a, int b)
                {

                }
};

int main()
{
        C * pC = new C;
        shared_ptr<C> scp(pC);
        scp->a = 10;
        scp->b = 20;

        shared_ptr<C> scp1(scp);
        cout<<"a: "<<scp->a<<endl;
        cout<<"b: "<<scp->b<<endl;

        scp.reset();

        cout<<"a: "<<pC->a<<endl;
        cout<<"b: "<<pC->b<<endl;

        scp1.reset();

        cout<<"a: "<<pC->a<<endl;
        cout<<"b: "<<pC->b<<endl;
}

STL vector example

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
        //Initialize
        vector<int> v;
        for(int i = 0; i < 10; i++)
                v.push_back(i);

        int array[] = {100, 101, 102, 103};
        vector<int> v1;
        v1.assign(array, array + sizeof(array)/sizeof(array[0]));
        vector<int> v2(array, array + sizeof(array)/sizeof(array[0]));

        if(!v.empty())
                cout<<"Not empty"<<endl;

        //Insert
        v.resize(15);
        v[10] = 10;
        v[11] = 11;
        v.insert(v.begin()+12, 12);
        v1.insert(v1.begin()+4, 2, 30);
        v2.insert(v2.begin(), v1.begin(), v1.end());
        v.push_back(15);

        //Delete
        v.erase(v.begin());
        v.erase(v.begin(), v.begin()+2);

        //Search
        vector<int>::iterator it1 = find(v.begin(), v.end(), 7);
        cout<<"Found: "<<*it1<<" Index: "<<it1-v.begin()<<endl;

        if(v.empty())
                cout<<"Empty"<<endl;
        cout<<"Vector size: "<<v.size()<<endl;

        //Traverse
        cout<<"V: ";
        for(vector<int>::iterator it = v.begin(); it != v.end(); it++)
                cout<<*it<<" ";
        cout<<endl;
        cout<<"V1: ";
        for(vector<int>::iterator it = v1.begin(); it != v1.end(); it++)
                cout<<*it<<" ";
        cout<<endl;
        cout<<"V2: ";
        for(vector<int>::iterator it = v2.begin(); it != v2.end(); it++)
                cout<<*it<<" ";
        cout<<endl;


        //Clear
        v.clear();
}

STL sets example

#include <iostream>
#include <set>
#include <vector>
#include <algorithm>

using namespace std;
int main()
{
        int array[] = {9,8,7,9, 6, 5,1,2,3,4,1,2,5};
        //Initialize
        set<int> s(array, array + sizeof(array)/sizeof(array[0]));

        set<int>::iterator it1 = s.end();
        pair<set<int>::iterator, bool> pr;

        vector<int> v(3, 30);

        //Insert
        pr = s.insert(6);
        s.insert(s.end(), 10);
        s.insert(v.begin(), v.end());

        //Delete
        s.erase(s.begin());
        s.erase(s.begin(), ++s.begin());

        //Search
        set<int>::iterator it2 = s.find(7);
        set<int>::iterator it3 = find(s.begin(), s.end(), 7);
        cout<<"Found: "<<*it2<<endl;
        cout<<"Found: "<<*it3<<endl;

        //Traverse
        for(set<int>::iterator it = s.begin(); it != s.end(); it++)
                cout<<*it<<" ";
        cout<<endl;

        //Clear
        s.clear();
}

STL map example

#include <iostream>
#include <map>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
        //Initialize
        map<string, int> m;// = {{"Sundar", 1}, {"Priyanka", 2}};
        m["Sundar"] = 1;
        m["Priyanka"] = 2;
        map<string, int> m2(m);
        map<string, int> m3(m2.begin(), m2.end());

        map<string, int> m4;
        m4["Ambi"] = 10;
        m4["jay"] = 11;

        //Insert
        m.insert(pair<string, int>("Leela", 3));
        m.insert(m.begin(), pair<string, int>("Paramesh", 4));
        m.insert(m.begin(), pair<string, int>("Revanth", 5));
        m.insert(m4.begin(), m4.end());

        //Delete
        m.erase(m.begin());
        m.erase(m.begin(), ++m.begin());

        //Search
        map<string, int>::iterator it1 = m.find("Revanth");
        cout<<"Found: "<<it1->first<<" "<<it1->second<<endl;

        //Traverse
        for(map<string, int>::iterator it = m.begin(); it != m.end(); it++)
                cout<<it->first<<" : "<<it->second<<" ";
        cout<<endl;

        //Clear
        m.clear();
}

STL arrays example

// constructing arrays
#include <iostream>
#include <array>

// default initialization (non-local = static storage):
std::array<int,3> global;               // zero-initialized: {0,0,0}

int main ()
{
  // default initialization (local = automatic storage):
  std::array<int,3> first;              // uninitialized:    {?,?,?}

  // initializer-list initializations:
  std::array<int,3> second = {10,20};   // initialized as:   {10,20,0}
  std::array<int,3> third = {1,2,3};    // initialized as:   {1,2,3}

  // copy initialization:
  std::array<int,3> fourth = third;     // copy:             {1,2,3}

  std::cout << "The contents of fourth are:";
  for (auto x:fourth) std::cout << ' ' << x;
    std::cout << '\n';

  return 0;
}

STL list example

#include <iostream>
#include <list>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
        int array[] = {9,8,7,9, 6, 5,1,2,3,4,1,2,5};

        //Initialize
        list<int> l(array, array + sizeof(array)/sizeof(array[0]));
        list<int> l2;
        l2.assign(array, array + sizeof(array)/sizeof(array[0]));

        list<int>::iterator it = l.end();

        vector<int> v(3,30);

        //Insert
        l.insert(it, 10);
        l.insert(it, 2, 20);
        l.insert(it, v.begin(), v.end());
        l2.push_back(10);

        //Delete
        l.erase(l.begin());
        l2.erase(l2.begin(), l2.begin()++);

        //Search
        list<int>::iterator it1 = find(l.begin(), l.end(), 7);
        cout<<"Found: "<<*it1<<endl;

        //Traverse
        for(list<int>::iterator it = l.begin(); it != l.end(); it++)
                cout<<*it<<" ";
        cout<<endl;
        for(list<int>::iterator it = l2.begin(); it != l2.end(); it++)
                cout<<*it<<" ";
        cout<<endl;

        //Clear
        l.clear();
}