Saturday, September 6, 2025

How to check even or odd number without divide by 2

 How to check even or odd number without divide by 2. :-
-------------------------------------------------------

here is a program that checks even/odd number without divide by two. Here is theory

let start with number, consider number table as :-

decimal numbers     it's binary  last digit ( LSB )
------------------   ---------------    ------

1  -> odd                0001                1

2  -> even               0010               0

3  -> odd                0011                1

4  -> even               0100               0

5  -> odd                0101                1

6  -> even              0110                0

7  -> odd                0111                1

8  -> even              1000                 0

9  -> odd                1001                1

10 -> even              1010               0
.
.
.
.

Now it is clear that in number table after every odd ( started from 1) there is an even number, and after every even there is odd number. And in ther binary form, LSB of odd is " 1 ", and LSB of even is " 0 ".

So by using bitwise "and" operation ( & ) with a char having LSB " 1 ", i.e. 

0x01 ( 0000 0001 ) we can chack number's LSB is " 1 "  or " 0 ". and from that we can determine even or odd. Here is a program :-

#include <iostream>

using namespace std;

bool evenodd(int num)
{
    char *pch;

    pch = (char*)(&num);

    int i = (*pch) & (0x01);

    if(i == 0)
    {
        return true;
    }
    else if(i == 1)
    {
        return false;
    }
}

int main()
{
    int i;

    cout << "Enter integer to check even/odd : ";
    cin  >> i;

    bool tf = evenodd(i);

    if(tf == true)
    {
        cout << "even number" << endl;
    }
    else
    {
        cout << "odd number" << endl;
    }

    return 0;
}

OUTPUT of program :-
--------------------

[rahul@kaljayi Debug]$ ./prime-num
Enter integer to check even/odd : 1
odd number
[rahul@kaljayi Debug]$ ./prime-num
Enter integer to check even/odd : 3
odd number
[rahul@kaljayi Debug]$ ./prime-num
Enter integer to check even/odd : 5
odd number
[rahul@kaljayi Debug]$ ./prime-num
Enter integer to check even/odd : 4
even number
[rahul@kaljayi Debug]$ ./prime-num
Enter integer to check even/odd : 121212
even number
[rahul@kaljayi Debug]$ ./prime-num
Enter integer to check even/odd : 1212121
odd number
[rahul@kaljayi Debug]$ ./prime-num
Enter integer to check even/odd : 12121223
odd number
[rahul@kaljayi Debug]$

Sunday, May 18, 2025

About Segmentation fault in Linux

 in linux segmentation fault is :-

-------------------------------------------------

 

accessing unauthorized memory for "reading" or "writing" is segmentation fault.

For example :-

let you have created a class 

class ABCD

{

    // here you have created a pointer variable as :-

    MYSQL *mysql;

}; 

Now in somewhere your project you used this pointer without initialized it, somethig like this :-

 void ABCD::myfunction-abcd()

{

....................

....................

mysql->...................... // or something like that 

/*

 then in above line you will get "segmentation fault" error in console and your program will be terminated immediately. Because when we, create object, program will give you a memory allocated for your object. And above pointer will be allocated a memory. But here program or compiler will not initialize it by default, it's your responsibility to initialize it. Now because of that allocated memory for above pointer will have garbage value. And in this stage pointer is called "dangling pointer". And because of that pointer will point to any location in memory, so "reading" or "writing" by this pointer is "segmentation fault", because this pointer is pointing to unauthorized memory. and that's all.................

*/

}

Sunday, June 9, 2024

trim a string in C++

 bool trim(string *str)
{

    int atstart = 0, atend = -1;


    string str2;
    if(str->length() != 0)
    {
        str2 = *str;
    }
    else
    {
        return false;
    }   

    for(int i = 0; i < str2.size(); i++)
    {
        if(str2[i] != ' ')
        {
            atstart = i;
            break;
        }
    }

    for(int i = str2.size()-1; i >= 0; i--)
    {
        if(str2[i] != ' ')
        {
            atend = i;
            break;
        }
    }

    str->clear();

    for(int i = atstart; i <= atend; i++)
    {
        *str += str2[i];
    }

    if(str->length() == 0)
    {
        return false;
    }

    return true;
}

Sunday, April 21, 2024

building QMYSQL sqldriver plugin for Qt-5.12, get rid of error '-Wdate-time', make it loaded & to connect mysql with Qt

how to connect mysql and Qt 5.12 and building QMYSQL driver & make them loaded, get rid of error '-Wdate-time'

 I have centos 7 in one client as VM with MySQL client and mysql server in second VM. In client I've installed Qt 5.12. To install MySQL sqldriver fire this command

[root@C-Client mysql]# /opt/Qt5.12.12/5.12.12/gcc_64/bin/qmake  -- MYSQL_INCDIR=/usr/include/mysql -- MYSQL_LIBDIR=/usr/lib64/mysql/  -lrt -ldl -lmysqlclient_r -lz -lcrypt -lnsl -lm -lssl -lcrypto mysql.pro

but unfortunetly it showed me following error :-
"g++: error: unrecognized command line option ‘-Wdate-time’"

as here :-

[root@C-Client mysql]# make
g++ -c -pipe -O2 -g -std=c++1y -fvisibility=hidden -fvisibility-inlines-hidden -fno-exceptions -Wall -W -Wvla -Wdate-time -D_REENTRANT -fPIC -DQT_DEPRECATED_WARNINGS -DQT_NO_NARROWING_CONVERSIONS_IN_CONNECT -DQT_NO_CAST_TO_ASCII -DQT_NO_CAST_FROM_ASCII -DQT_NO_EXCEPTIONS -D_LARGEFILE64_SOURCE -D_LARGEFILE_SOURCE -DQT_NO_DEBUG -DQT_PLUGIN -DQT_SQL_LIB -DQT_CORE_LIB -I. -I/opt/Qt5.12.12/5.12.12/gcc_64/include/QtSql/5.12.12 -I/opt/Qt5.12.12/5.12.12/gcc_64/include/QtSql/5.12.12/QtSql -I/opt/Qt5.12.12/5.12.12/gcc_64/include/QtCore/5.12.12 -I/opt/Qt5.12.12/5.12.12/gcc_64/include/QtCore/5.12.12/QtCore -I/opt/Qt5.12.12/5.12.12/gcc_64/include -I/opt/Qt5.12.12/5.12.12/gcc_64/include/QtSql -I/opt/Qt5.12.12/5.12.12/gcc_64/include/QtCore -I.moc -isystem /usr/include/mysql -I/home/qt/openssl-1.1.1k/include -I/opt/Qt5.12.12/5.12.12/gcc_64/mkspecs/linux-g++ -o .obj/qsql_mysql.o qsql_mysql.cpp
g++: error: unrecognized command line option ‘-Wdate-time’
make: *** [.obj/qsql_mysql.o] Error 1

Now to recover this, do this :-
go to installation dir as mine is : "/opt/Qt5.12.12/5.12.12/Src/qtbase/src/plugins/sqldrivers/mysql". fire following command :

# chmod 777 Makefile

# gedit Makefile

search for "-Wdate-time" by Pressing Ctrl + f. There will be two places by this search. delete "-Wdate-time" on both places, save & close file Makefile. Re-run make command as :-

# make

Now this will give you no error. Then install plugin as :-

# make install 

this copies binary sql-driver in to appropriate dir in Qt folder automatically.

# make clean

last line to clean binaries generated during process.
now your plugin is installed. Test it as you want.


Friday, April 12, 2024

Menus, Menus, Menus & Menus one inside another upto any level in terminal Centos 7 and its shared library.

 
You can implement many more menus. Just Define a class of your need declare a function getFunctionOfChoice() ( or as you want you can give name). Also to call menu inside CMenu class you need to define your own menu object.
 To build a menu use std::vector<std::string> mineMenu. use function push_back(/*arguments as string only*/).

 pass this menu to CMenu::getChoice( your-menu-pointer->menu-Vector, "Header Of Your Choice to display", lastLine);

 this will return index number, you entered to select from menu item. Get it in a int variable choice. Then pass it to
 switch statements. Which will handle so-on. As given here.

You can also build its shared library as "libmenus.so", as I explored in old blogs. And then add its header file and library file in your project and use it as defined here.

I've added two shared libraries named : "libvalidator.so" & "libclrscr-getch.so". I already posted those, how to build libraires
and how to attach these in our project. Please refer previous posts. 

you can also build this project as shared library and call this lib to another project without including source code. As we did with "libvalidator.so" and "libclrscr-getch.so". its may be "libmenus.so" or as you wish.

To run this program do all these : 

1. Set "so library files" i.e. shared libraries to path "/opt/so-files/sos/.". Then set library path to LD_LIBRARY_PATH for this dir. Then run MENUs.
as follows :-

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/so-files/sos/clrscr-getch-so:/opt/so-files/sos/validators

or

you can put header files in "/usr/include/clrscr-getch" "/usr/include/menus/" "/usr/include/validator"

this will call headers without adding header file path in our project

and lib files in "/usr/lib64/clrscr-getch" "/usr/lib64/menus" "/usr/lib64/validtor"

here you must give full path for each library file containing directory. 

then run this executable from any where on your  system. Mine executable file name is : Menus , run this as follows :-

$ ./Menus <-| ( i.e. press Enter )

main.cpp :-
-----------

#include <iostream>
#include <bits/stdc++.h>
#include <string>

#include "CMenu.h"
#include "CLinkedList.h"
#include "CQueue.h"
#include "CSorting.h"
#include "CVecMenu.h"

using std::cout;
using std::cin;
using std::endl;
using std::string;

int main()
{
//    CLinkedlist  *llist = new CLinkedlist;

    CValidator *validator = new CValidator;
    CClrscrGetch *get = new CClrscrGetch;

    CMenu       *menu       = new CMenu;
    CVecMenu    *vecmenu    = new CVecMenu;
    CLinkedList *llist      = new CLinkedList;
    CQueue      *qu         = new CQueue;
    CSorting    *sor        = new CSorting;

    int choice = 0;

    do
    {
        get->clrscr();
        int lastLine = 0;
        choice = menu->getChoice(vecmenu->mainMenu, "MAIN MENU", lastLine);

        switch(choice)
        {
        case 1:

            get->clrscr();
            llist->getFunctionOfChoice();

            break;

        case 2:
            get->clrscr();
            qu->getFunctionOfChoice();
//            menu->get->getch();

            break;

        case 3:
            cout << " Stack ";
            menu->get->getch();
            break;

        case 4:
//            cout << " Sorting ";
            sor->getFunctionOfChoice();

//            menu->get->getch();
            break;

        case 5:
            cout << " Searching ";
            menu->get->getch();
            break;

        case 6:
            cout << " Trees ";
            menu->get->getch();
            break;

        case 7:
            cout << " Graphs ";
            menu->get->getch();
            break;

        case 8:
            cout << " Sparse Metrices ";
            menu->get->getch();
            break;

        case 9:
            get->clrscr();
            exit(0);
        }

    }while(choice != 9 );

    return 0;
}

/*
You can implement many more menus. Just Define a class of your need declare a function getFunctionOfChoice()
( or as you want you can give name). Also to call menu inside CMenu class you need to define your own menu object.
 To build a menu use std::vector<std::string> mineMenu. use function push_cack(/*arguments as string only*//*).

 pass this menu to CMenu::getChoice( your-menu-pointer->menu-Vector, "Header Of Your Choice toi display", lastLine);

 this will return index number, you entered to select from menu item. Get it in a int variable choice. Then pass it to
 switch statements. Which will handle so-on. As given above.

*/
--------------------------------------------------------------------------

File : CVecMenu.h :-
--------------------

#ifndef CVECMENU_H
#define CVECMENU_H

#include <vector>
#include <string>

class CVecMenu
{
    public:
        CVecMenu();
        virtual ~CVecMenu();
        CVecMenu(const CVecMenu& other);
        CVecMenu& operator=(const CVecMenu& other);

    std::vector<std::string> menu;
    std::vector<std::string>::const_iterator iter;

    std::vector<std::string> mainMenu;
    std::vector<std::string>::const_iterator iterMainMenu;

    std::vector<std::string> stackMenu;
    std::vector<std::string>::const_iterator iterStackMenu;

    std::vector<std::string> queueMenu;
    std::vector<std::string>::const_iterator iterQueueMenu;

    std::vector<std::string> listMenu;
    std::vector<std::string>::const_iterator iterListMenu;

    std::vector<std::string> listSubMenu1;
    std::vector<std::string>::const_iterator iterListSubMenu1;

    std::vector<std::string> listOperationalMenu;
    std::vector<std::string>::const_iterator  iterListOperationalMenu;

    std::vector<std::string> treeMenu;
    std::vector<std::string>::const_iterator iterTreeMenu;

    std::vector<std::string> sortingMenu;
    std::vector<std::string>::const_iterator iterSortingMenu;

    std::vector<std::string> searchMenu;
    std::vector<std::string>::const_iterator iterSearchMenu;

    std::vector<std::string> graphMenu;
    std::vector<std::string>::const_iterator iterGraphMenu;

    std::vector<std::string> sparseMetricesMenu;
    std::vector<std::string>::const_iterator iterSparseMtrices;

};

#endif // CVECMENU_H

--------------------------------------------------------------------------
File : CVecMenu.cpp :-
----------------------

#include "CVecMenu.h"

CVecMenu::CVecMenu()
{
    //ctor

    mainMenu.push_back("1. Linked List ");
    mainMenu.push_back("2. Queue ");
    mainMenu.push_back("3. Stack ");
    mainMenu.push_back("4. Sorting ");
    mainMenu.push_back("5. Searching ");
    mainMenu.push_back("6. Trees ");
    mainMenu.push_back("7. Graphs ");
    mainMenu.push_back("8. Sparse Metrices ");
    mainMenu.push_back("9. Exit ");

    listMenu.push_back("1. Singlly Linked List");
    listMenu.push_back("2. Doubly Linked List ");
    listMenu.push_back("3. Circular linked List ");
    listMenu.push_back("4. Doubly Circular Linked List ");
    listMenu.push_back("5. Back ");
    listMenu.push_back("6. Exit ");

    listOperationalMenu.push_back("1. Create ");
    listOperationalMenu.push_back("2. Add at beginning ");
    listOperationalMenu.push_back("3. Add after node ");
    listOperationalMenu.push_back("4. Add Before node ");
    listOperationalMenu.push_back("5. Add last ");
    listOperationalMenu.push_back("6. Delete first node ");
    listOperationalMenu.push_back("7. Delete node before a node ");
    listOperationalMenu.push_back("8. Delete node after a node ");
    listOperationalMenu.push_back("9. Delete a last node ");
    listOperationalMenu.push_back("10. Delete Specified node ");

    queueMenu.push_back("1. Sequential Queue as Linked List ");
    queueMenu.push_back("2. Priority Queue ");
    queueMenu.push_back("3. Circular Queue ");
    queueMenu.push_back("4. Dequeue ");
    queueMenu.push_back("5. Back");
    queueMenu.push_back("6. End");

    treeMenu.push_back("1. Binary Tree ");
    treeMenu.push_back("2. Binary Search Tree ");
    treeMenu.push_back("3. Expressionsin Binary Search Tree ");
    treeMenu.push_back("4. Extened Binary Tree ");
    treeMenu.push_back("5. Threaded Binary Tree ");
    treeMenu.push_back("6. General Trees ");
    treeMenu.push_back("7. AVL Trees ");
    treeMenu.push_back("8. 2-3 Trees ");
    treeMenu.push_back("9. B Tree ");
    treeMenu.push_back("10. Heap ");

    searchMenu.push_back("1. Linear Search ");
    searchMenu.push_back("2. Binary Search ");

    sortingMenu.push_back("1. Bubble Sort ");
    sortingMenu.push_back("2. Selection Sort ");
    sortingMenu.push_back("3. Quick Sort ");
    sortingMenu.push_back("4. Insertion Sort ");
    sortingMenu.push_back("5. Binary Tree Sort ");
    sortingMenu.push_back("6. Heap Sort ");
    sortingMenu.push_back("7. Merge Sort ");
    sortingMenu.push_back("8. External Sort ");
    sortingMenu.push_back("9. Back");
    sortingMenu.push_back("10. Exit");

    graphMenu.push_back("1. Depth First Search ");
    graphMenu.push_back("2. Breadth First Search ");
    graphMenu.push_back("3. Spanning Tree ");
    graphMenu.push_back("4. Kruskal Algorithms ");

    sparseMetricesMenu.push_back("1. Transpose of Sparse Metrices ");
    sparseMetricesMenu.push_back("2. Addition of Two Sparse Metrices ");
    sparseMetricesMenu.push_back("3. Multiplication of Two Sparse Metrices ");
    sparseMetricesMenu.push_back("4. Linked Representation of Sparse Metrices ");


}

CVecMenu::~CVecMenu()
{
    //dtor
}

CVecMenu::CVecMenu(const CVecMenu& other)
{
    //copy ctor
}

CVecMenu& CVecMenu::operator=(const CVecMenu& rhs)
{
    if (this == &rhs) return *this; // handle self assignment
    //assignment operator
    return *this;
}

--------------------------------------------------------------------------
file : CLinkedList.h :-
-----------------------

#ifndef CLINKEDLIST_H
#define CLINKEDLIST_H

#include "CMenu.h"
#include "CVecMenu.h"
#include <validator/validator.h>
#include <clrscr-getch/clrscr-getch.h>

class CLinkedList
{
public:
    CLinkedList();
    virtual ~CLinkedList();
    CLinkedList(const CLinkedList& other);
    CLinkedList& operator=(const CLinkedList& other);

//    bool getFuncitonOfChoice(int choice);

    int  getFunctionOfChoice();

    CMenu *menu;
    CVecMenu *vecmenu;
    CClrscrGetch *get;
    CValidator   *validator;

protected:

private:

    int lastLine;
};

#endif // CLINKEDLIST_H
--------------------------------------------------------------------------

File : ClinkedList.cpp :-
-------------------------

#include "CLinkedList.h"
#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::string;

CLinkedList::CLinkedList()
{
    //ctor

    menu        = new CMenu;
    vecmenu     = new CVecMenu;
    get         = new CClrscrGetch;
    validator   = new CValidator;
}

CLinkedList::~CLinkedList()
{
    //dtor

    delete menu;
    delete get;
    delete validator;
    delete vecmenu;
}

CLinkedList::CLinkedList(const CLinkedList& other)
{
    //copy ctor
}

CLinkedList& CLinkedList::operator=(const CLinkedList& rhs)
{
    if (this == &rhs) return *this; // handle self assignment
    //assignment operator
    return *this;
}

int CLinkedList::getFunctionOfChoice()
{
    int choice;

    do
    {
        get->clrscr();

        choice = menu->getChoice(vecmenu->listMenu, "Linked List Menu", lastLine);

        int downline;

        switch(choice)
        {
        case 1:
            cout << " Singlly Linked list ";
            get->getch();

            break;

        case 2:
            cout << " doubly linked list ";
            get->getch();

            break;

        case 3:
            cout << " Circular linked list ";
            get->getch();

            break;

        case 4:
            cout << " doubly circular linked list ";
            get->getch();

            break;

        case 5:
            break;
        case 6:
            get->clrscr();
            exit(0);
        }
    }while(choice != 6 && choice != 5);

    return 0;
}
--------------------------------------------------------------------------
File : CMenu.h :-
-----------------

#ifndef CMENU_H
#define CMENU_H

#include <vector>
#include <string>

#include <clrscr-getch/clrscr-getch.h>
#include <validator/validator.h>

#include "CString.h"

class CMenu
{

protected:

private:


    int i;
    int spacer;
    int l;

    std::string strchoice;
    std::string header;

    struct winsize w;
    bool tf;

//    CString *strtrim;

public:
    CMenu();
    virtual ~CMenu();

    CValidator *validator;
    CClrscrGetch * get;

    int printMenu(std::vector<std::string> menu, std::string header);
    int getChoice(std::vector<std::string> choices, std::string header, int &lastLine);
};

#endif // CMENU_H

--------------------------------------------------------------------------
File : CMenu.cpp :-
-------------------
#include "CMenu.h"

#include <ctype.h>

//#include <bits/stdc++.h>
#include <cstdlib>
#include <iostream>
#include <vector>

using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;
using std::boolalpha;

CMenu::CMenu()
{
    //ctor

    validator = new CValidator;
    get = new CClrscrGetch;

//    strtrim = new CString;
}

CMenu::~CMenu()
{
    //dtor
    delete validator;
    delete get;
}

int CMenu::printMenu(vector<string> menuDisplay, string header)
{
    vector<string>::const_iterator iterMenu;

    menu->get->gotoxy(15, 2);
    cout << header;

    menu->get->gotoxy(13, 3);
    int len = header.length();

    spacer = 13 + 3 + len;

    for( i = 13; i <= spacer; i++)
    {
        cout << "-";
    }

    l = 5;

    iterMenu = menuDisplay.begin();

    while(iterMenu != menuDisplay.end())
    {
        menu->get->gotoxy(2, l);
        cout << *iterMenu++;
        l++;
    }

    return l;
}

int CMenu::getChoice(vector<string> choice, string header, int &lastLine)
{
    int l = 0;
    int optionChoice = 0;
    int i = 0;
    int j = 0;
    int downline;
    int display = 30;
    int limit = 0;
    int d = 0;

    char c = ' ';
    char ch;

    bool tf = false;

    string strtrimmed;


    string strcheck;
    strcheck.clear();

    string strch;

    l = printMenu(choice, header);

    get->gotoxy(15, ++l);

    int lastOptIndex = choice.size();
    string sloi = std::to_string(lastOptIndex);

    int lensloi = sloi.length();

    strch.clear();
    get->gotoxy(15, l);
    ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
    for(int i = 0; i < w.ws_col; i++)
    {
        cout << " ";
    }

    get->gotoxy(15, l);
    cout << "Enter Choice : ";

    downline = l;

    do
    {
        get->gotoxy(display + i, l);
        ch = get->getche();

        strcheck += ch;
        i++;

        tf = CString::trimfunc(&strcheck);

        if(tf == false)
        {
            --i;
            get->gotoxy(display + i, l);

            continue;
        }

        if(tf == true && ch == ' ')
        {
            int len = strcheck.length();
            get->gotoxy(display + len, l);
            --i;

            continue;
        }

        if( (int(ch) == 127) || (strcheck.length() > lensloi) || (int(ch) == 10) )
        {
            j = strcheck.length();

            int m = j;

            if(int(strcheck.at(--m)) == 10 )
            {
                strcheck.pop_back();
            }

            if( int(ch) == 127 )
            {
                strcheck.pop_back();

                if(strcheck.length() > 0)
                {
                    strcheck.pop_back();
                    i -= 2;

                    get->gotoxy(display + i, l);
                    cout << " ";
                    get->gotoxy(display + i, l);
                }
                else
                {
                    i = 0;
                }

                continue;
            }

            if( strcheck.length() > lensloi )
            {
                strcheck.pop_back();
                int sz = strcheck.length();

                get->gotoxy(display + sz, l);
                cout << " ";
                get->gotoxy(display + sz, l);

                --i;

                continue;
            }

            tf = CValidator::intvalidator(strcheck);

            if(tf == false)
            {
                strcheck.clear();

                strch.clear();
                i = 0;

                get->gotoxy(display + 2, l);
                cout << " -> invalid input, please correct it";
                get->getch();

                get->gotoxy(display, l);
                ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

                for(int k = display; k < w.ws_col; k++)
                {
                    cout << " ";
                }

                get->gotoxy(display, l);

                continue;
            }
            else if (tf == true)
            {
                limit = CString::intChange(strcheck);

                if( limit < 1 || limit > lastOptIndex )
                {
                    strcheck.clear();

                    get->gotoxy(display + lensloi + 1, l);
                    cout << " -> outside of range, only between 1 to " << lastOptIndex;
                    get->getch();

                    ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);

                    get->gotoxy(display, l);
                    for(d = display; d < w.ws_col; d++)
                    {
                        get->gotoxy(d, l);
                        cout << " ";
                    }
                    get->gotoxy(display, l);

                    i = 0;

                    continue;
                }
                else if( int(ch) == 10)
                {
                    optionChoice = std::atoi(strcheck.c_str());
                }
            }
        }

    }while(optionChoice < 1 || optionChoice > lastOptIndex  );

    lastLine = l + 1;

    return optionChoice;
}
--------------------------------------------------------------------------
File : CQueue.h :-
------------------

#ifndef CQUEUE_H
#define CQUEUE_H

#include <clrscr-getch/clrscr-getch.h>
#include <validator/validator.h>

#include "CMenu.h"
#include "CVecMenu.h"

class CQueue
{
public:
    CQueue();
    virtual ~CQueue();
    CQueue(const CQueue& other);
    CQueue& operator=(const CQueue& other);

    int getFunctionOfChoice();

protected:

private:

    CMenu        * menu;
    CClrscrGetch *get;
    CValidator   *validator;
    CVecMenu     *vecmenu;
};

#endif // CQUEUE_H

--------------------------------------------------------------------------
File : CQueue.cpp :-
--------------------

#include "CQueue.h"

#include <iostream>

using std::cout;
using std::cin;
using std::endl;
using std::string;

CQueue::CQueue()
{
    //ctor

    menu        = new CMenu;
    get         = new CClrscrGetch;
    validator   = new CValidator;
    vecmenu     = new CVecMenu;
}

CQueue::~CQueue()
{
    //dtor
    delete menu;
    delete get;
    delete validator;
    delete vecmenu;
}

CQueue::CQueue(const CQueue& other)
{
    //copy ctor
}

CQueue& CQueue::operator=(const CQueue& rhs)
{
    if (this == &rhs) return *this; // handle self assignment
    //assignment operator
    return *this;
}

 int CQueue::getFunctionOfChoice()
 {
     int choice;
    do
    {
        get->clrscr();

        int lastLine = 0;
        int downline;


        choice = menu->getChoice(vecmenu->queueMenu, "Queue Menu", lastLine);
        downline = lastLine;

        switch(choice)
        {
        case 1:
            cout << " Sequential Queue as Linked List ";
            get->getch();

            break;

        case 2:
            cout << " Priority Queue ";
            get->getch();

            break;

        case 3:
            cout << " Circular Queue  ";
            get->getch();

            break;

        case 4:
            cout << " Dequeue ";
            get->getch();

            break;

        case 5:
            break;
        case 6:
            get->clrscr();
            exit(0);
        }
    }while(choice != 6 && choice != 5);

    return 0;

 }

--------------------------------------------------------------------------
File : CSorting.h :-
--------------------

#ifndef CSORTING_H
#define CSORTING_H

#include "CMenu.h"
#include "CVecMenu.h"

#include <iostream>
#include <clrscr-getch/clrscr-getch.h>
#include <validator/validator.h>

class CSorting
{
public:
    CSorting();
    virtual ~CSorting();
    CSorting(const CSorting& other);
    CSorting& operator=(const CSorting& other);

    int getFunctionOfChoice();

protected:

private:

    CMenu * menu;
    CValidator * validator;
    CClrscrGetch *get;
    CVecMenu *vecmenu;
};

#endif // CSORTING_H

--------------------------------------------------------------------------
File : CSorting.cpp :-
----------------------

#include "CSorting.h"

#include <iostream>

using std::cout;

CSorting::CSorting()
{
    //ctor
    menu        = new CMenu;
    get         = new CClrscrGetch;
    validator   = new CValidator;
    vecmenu     = new CVecMenu;
}

CSorting::~CSorting()
{
    //dtor
    delete menu;
    delete get;
    delete validator;
    delete vecmenu;
}

CSorting::CSorting(const CSorting& other)
{
    //copy ctor
}

CSorting& CSorting::operator=(const CSorting& rhs)
{
    if (this == &rhs) return *this; // handle self assignment
    //assignment operator
    return *this;
}

int CSorting::getFunctionOfChoice()
{
    int choice;
    int lastLine;

    do
    {
        get->clrscr();

        choice = menu->getChoice(vecmenu->sortingMenu, "Sorting Menu", lastLine);

        switch(choice)
        {
        case 1:
                cout << "Bubble Sort";
                get->getch();


                break;

        case 2:
                cout << "Selection Sort";
                get->getch();

                break;

        case 3:
                cout << "Quick Sort";
                get->getch();

                break;

        case 4:
                cout << "Insertion Sort";
                get->getch();

                break;

        case 5:
                cout << "Binary Tree Sort";
                get->getch();

                break;

        case 6:
                cout << "Heap Sort";
                get->getch();

                break;

        case 7:
                cout << "Merge Sort";
                get->getch();

                break;

        case 8 :
                cout << "External Sort";
                get->getch();

                break;

        case 9:
            break;

        case 10:
                get->clrscr();
                exit(0);
        }
    }while (choice != 9 && choice != 10);

    return 0;
}
--------------------------------------------------------------------------
File : CStack.h :-
------------------

#ifndef CSTACK_H
#define CSTACK_H

#include "CMenu.h"

#include <iostream>
#include <clrscr-getch/clrscr-getch.h>
#include <validator/validator.h>

class CStack
{
public:
    CStack();
    virtual ~CStack();
    CStack(const CStack& other);
    CStack& operator=(const CStack& other);

    int getFucitonOfChoice();

protected:

private:

    CMenu *menu;
    CValidator * validator;
    CClrscrGetch *get;

};

#endif // CSTACK_H

--------------------------------------------------------------------------
File : CStack.cpp :-
--------------------

#include "CStack.h"

CStack::CStack()
{
    //ctor
    menu        = new CMenu;
    get         = new CClrscrGetch;
    validator   = new CValidator;
}

CStack::~CStack()
{
    //dtor

    delete menu;
    delete get;
    delete validator;
}

CStack::CStack(const CStack& other)
{
    //copy ctor
}

CStack& CStack::operator=(const CStack& rhs)
{
    if (this == &rhs) return *this; // handle self assignment
    //assignment operator
    return *this;
}

int CStack::getFucitonOfChoice()
{
    int choice;

 

//    do
//    {

//           chioce = menu->getChoice(menu->)

//            switch(choice)

//            {

//            }
//
//    }while()

    return 0;

}

--------------------------------------------------------------------------
File : CString.h :-
-------------------

#ifndef CSTRING_H
#define CSTRING_H

#include <string>
#include <iostream>

class CString
{
public:
    CString();
    virtual ~CString();
    CString(const CString& other);
    CString& operator=(const CString& other);

    static bool trimfunc(std::string *str);
    static int intChange(std::string str);

protected:

private:


};

#endif // CSTRING_H

--------------------------------------------------------------------------
File : CString.cpp :-
---------------------

#include "CString.h"

using std::cin;
using std::cout;
using std::endl;
using std::string;

CString::CString()
{
    //ctor
}

CString::~CString()
{
    //dtor
}

CString::CString(const CString& other)
{
    //copy ctor
}

CString& CString::operator=(const CString& rhs)
{
    if (this == &rhs) return *this; // handle self assignment
    //assignment operator
    return *this;
}

bool CString::trimfunc(string *str2)
{

    int atstart = 0, atend = -1;


    string str;
    if(str2->length() != 0)
    {
        str = *str2;
    }
    else
    {
        return false;
    }   

    for(int i = 0; i < str.size(); i++)
    {
        if(str[i] != ' ')
        {
            atstart = i;
            break;
        }
    }

    for(int i = str.size()-1; i >= 0; i--)
    {
        if(str[i] != ' ')
        {
            atend = i;
            break;
        }
    }

    str2->clear();

    for(int i = atstart; i <= atend; i++)
    {
        *str2 += str[i];
    }

    if(str2->length() == 0)
    {
        return false;
    }

    return true;
}

int CString::intChange(string str)
{
    int i = std::atoi(str.c_str());

    return i;
}

--------------------------------------------------------------------------


--------------------------------------------------------------------------
















Thursday, February 15, 2024

C++ and MySQL 5.6 program in client server model in CLI ( command line interface )

 CPP and MySQL 5.6 program :-
----------------------------

I presume you have already installed and configured centos 7 DNS server in one VM, centos 6 as MySQL server in second VM DNS Client and centos 7 as MySQL client as third DNS client VM having Code Blocks IDE for C++ command line interface. Also installed cpp and mysql connector rpm. Also you must have installed boost asio c++ library at least version 1.58 or above.

Also you have to install following rpm for mysql connection with CPP.

mysql-connector-c++-1.1.4-linux-glibc2.5-x86-64bit.rpm 

for "MySQL-5.6.23-1.linux_glibc2.5.x86_64.rpm-bundle.tar"

search "index of MySQL" in google and find web for rpms downloads.

To install boost asio library download it from "https://www.boost.org/users/download/". Now install like this :

Easy Build and Install of boost library :-
-----------------------------------------------------------

Issue the following commands in the shell (don't type #; that represents the shell's root prompt):
# cd path/to/boost_1_61_0

# ./bootstrap.sh --help

Select your configuration options and invoke ./bootstrap.sh again without the --help option. Unless you have write permission in your system's /usr/local/ directory, you'll probably want to at least use


# ./bootstrap.sh --prefix=path/to/installation/prefix

or just :-

# ./bootstrap.sh

to install somewhere else. Also, consider using the --show-libraries and --with-libraries=library-name-list options to limit the long wait you'll experience if you build everything. Finally,


# ./b2 install

will leave Boost binaries in the lib/ subdirectory of your installation prefix. You will also find a copy of the Boost headers in the include/ subdirectory of the installation prefix, so you can henceforth use that directory as an #include path in place of the Boost root directory.


Now set as follows in Codeblocks IDE :-
---------------------------------------

Create a new project -> console application -> next -> C++ ->
project title : CppMySQLConn
path : give as you want : "/opt/projects/cpp/cppmysqlconn"
next -> next

On IDE : proect-> build options :-


1. Compiler flags     : c++14 : right tick on it
                                : -m 64 : right tick on it

2. linker settings    : mysqlcppconn, pthread, dl

3. search directories     :
compiler     : /usr/local/boost/include/boost
            : /usr/include/mysql

    linker         : /usr/lib64/mysql
            : /usr/local/boost/lib


Now open project "CppConnMysql" in CodeBlocks C++ IDE and do as follows :-

/*
    here :     mysql server      : centos6mss.db.net

                    ip address    : 192.168.2.3
                   user name     : rahul
                    password     : rahul
                    port         : 3306
                    database schema    : cbs

Database cbs is :- ( you have to populate this table first )
------------------

As : 'tablename'.'column' :-
----------------------------

`tableBilling`.`id`,
`tableBilling`.`ProductID`,
`tableBilling`.`Quantity`,
`tableBilling`.`Dateofsale`,
`tableBilling`.`Total`,
`tableBilling`.`Billno`,
`tableBilling`.`CustomerID`,
`tableCustomers`.`id`,
`tableCustomers`.`CustomerName`,
`tableCustomers`.`ContactAddress`,
`tableCustomers`.`MobileNo`,
`tableCustomers`.`BillNo`,
`tableProductRecords`.`ProductName`,
`tableProductRecords`.`Stock`,
`tableProductRecords`.`Rate`,
`tableProductRecords`.`ProductID`

*/
// program is :-

--------------------------

*/
#include <cstdlib>
#include <iostream>

#include <mysql_connection.h>
#include <mysql_driver.h>

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>

using namespace std;
//using namespace sql;
int main()
{
    cout << endl;

    cout << "Let's have a MySQL count from last to first .... " << endl;

    try
    {
        sql::Driver *driver;
        sql::Connection *conn;
        sql::Statement *stmt;
        sql::ResultSet *res;
        sql::PreparedStatement *pstmt;

        driver = get_driver_instance();
        conn = driver->connect("centos6mss.db.net:3306", "username", "password");
//        conn = driver->connect("192.168.2.3:3306", "username", "password");
        conn->setSchema("cbs");

        pstmt = conn->prepareStatement("select id from tableCustomers;");
        res = pstmt->executeQuery();
        res->afterLast();

        while(res->previous())
        {
            cout << "customers id : " << res->getInt("id") << endl;
        }
        delete res;
        delete pstmt;
        delete conn;
    }
    catch(sql::SQLException &e)
    {
        cout << "#ERR : sql excep : in " << __FILE__ << endl;
        cout << "#Func : in " << __FUNCTION__<< " on line : " << __LINE__ << endl;
        cout << "#ERR what : " << e.what() << endl;
    }

    cout << endl;

    return EXIT_SUCCESS;
}

/*
output  :-
----------

[rahul@client1 Debug]$ ./first

Let's have a MySQL count from last to first ....
customers id : 25
customers id : 24
customers id : 23
customers id : 22
customers id : 21
customers id : 20
customers id : 19
customers id : 18
customers id : 17
customers id : 16
customers id : 15
customers id : 14
customers id : 13
customers id : 12
customers id : 11
customers id : 10
customers id : 9
customers id : 8
customers id : 6
customers id : 5
customers id : 4
customers id : 3
customers id : 2

[rahul@client1 Debug]$
*/



Sunday, January 14, 2024

windows ntfs and Extrnal HDDs partitions mount in Centos 7 Linux

first download ntfs-3g driver for Linux source code from 

"https://www.tuxera.com/company/open-source/".

 now get root prompt, extract file get inside it and run following commands :-

# cd ntfs-3g-progs

# chmod +x configure

# ./configure

# make

# make install

# mkdir /mnt/wind

# mkdir /mnt/wine

 now open /etc/fstab as 

# gedit /etc/fstab & ( ampersand for background mode )

inside fstab file :-

# device name - mount directory - file system type - read/write mode 0 0 

/dev/sdb1         /mnt/wind               ntfs-3g                 defaults 0 0
/dev/sdb2         /mnt/wine               ntfs-3g                 defaults 0 0 


to get /dev/sdx name goto other locations in left pane of nautilus. You can see /dev/sdx numbers of drives. Those are set in above lines in fstab. you may set mode to "defaults" or "rw" for read and write both. Same thing you can do with other file systems of any OS.  Now run following comands :-

# mount -a

this command will mount all filesystems as mentioned. to un mount all file systems except systems defined do this :-

# umount -a

to mount external HDD drives :-

# mount -t ntfs-3g /dev/sdx /mnt/directory 

where x in sdx is filesystem number. You may get it by clicking into name of external HDD in left pane of nautilus. This will show a message box having text that "dev/sdx" can not be mounted or something like that. But there is name of  device name something like this  : /dev/sdd1. Here /dev/sdd1 is name of filesystem. replace it with /dev/sdx in above command. You can write down thes commands in a shell script and run it as root user as :-

mount -t ntfs-3g /dev/sdd1 /mnt/ext4tb-1
mount -t ntfs-3g /dev/sdd2 /mnt/ext4tb-2
mount -t ntfs-3g /dev/sdd3 /mnt/ext4tb-3
mount -t ntfs-3g /dev/sdd4 /mnt/ext4tb-4

save this as mountntfs.sh. set its permission to executable as (requires only when this file is created ):-

# chmod +x mountntfs.sh

and run as :-

# ./mountntfs.sh

this will mount all filesystems "/dev/sdx" to /mnt/ext4tb-x"

if you "umount -a" all filesystems except of "UUIDs" will be un-mouned. to remount you need to fire all commands for filesystems written in /etc/fstab and mountntfs.sh as mentioned above. Or you can use command "mount -a" to mount all filesystems in /etc/fstab file.

dual boot CentOS 7 & Kali linux 2023

 Let we have two HDDs 1st for Centos 7 and 2nd of Kali linux.

Boot in Centos and go to root prompt.

# cd /opt

# grub2-mkconfig -o grub.cfg

# cp grub.cfg /boot/grub2/grub.cfg.new

# cd /boot/grub2/

# mv grub.cfg grub.cfg.original.backup 

# mv grub.cfg.new grub.cfg

# gedit grub.cfg

search for timeout=5 and change it to your timeout at boot menu of centos.

As I changed it to timeout=60 ( for 60 seconds ).

Again you can change title ( menuentry ) for kali linux, because it is set as Debian...  

you may change it to  'Kali Linux 2023'.

# reboot 

and you will have dual boot  of CentOS 7 and Kali.

If you want to change default boot OS high lighting in boot menu, open file as :-

# gedit /boot/grub2/grubenv & ( in background mode of gedit )

change to for CentoOS as here :

saved_entry=CentOS Linux (3.10.0-862.el7.x86_64) 7 (Core)

or  for kali linux :-

saved_entry=Kali Linux 2023 (on /dev/sda3)

These are obtained from line in "grub.cfg" as here :-

menuentry 'Kali Linux 2023 (on /dev/sda3)'

copy text between both single quotes, of course without quotes and paste in file "grubenv" without single quotes. And that will be the default boot option in boot menu. There is entry like :-

# GRUB Environment Block
saved_entry=CentOS Linux (3.10.0-862.el7.x86_64) 7 (Core)

or 

 saved_entry=Kali Linux 2023 (on /dev/sda3)

Change it as your wish.

If there is any mismatch between menyentry text and saved_entry text and even you add double quots or space in last or before then default boot option will be high lighted.

Thursday, October 19, 2023

get rid of 169.254.x.x ip address resolution in windows server 2016-2019 and win 10

169.254.x.x ip address resolution in windows server 2016-2019 :-

---------------------------------------------------------------------------------------------------

 let mine ip address is : 169.254.31.112

step 1 :

cmd : as admin : fire this command :

promt > netsh interface ipv4 show inter

this will show all network adapters.

step 2 :
prompt >  netsh interface ipv4 set interface * dadtransmits=0 stor=persistent


Here " * " is number of interface as mine is 3 that i want to change. so command will be :

prompt >  netsh interface ipv4 set interface 3 dadtransmits=0 stor=persistent
step 3 :

run -> ncpa.cpl <-|( press enter )
set static ip address :

192.168.6.1 ( this is mine server's static ip address )

mask : 255.255.255.0
gateway :
preferred DNS : 192.168.6.1 ( mine server's ip address, do not enter 127.0.0.1 )

step 4 :

go to services.msc
go to DHCP Client and stop it permanently.
if it does not stops, set start up type to "disabled".
and stop it.

step 5 :
Reboot System.

check details of network adapter. It's got fixed.

 For windows 10 :-

----------------------

cmd : as admin : fire this command :

promt > netsh interface ipv4 show inter

this will show all network adapters.

step 2 :
prompt >  netsh interface ipv4 set interface * dadtransmits=0 stor=persistent
Here "*" is number of interface as mine is 3 that i want to change. so command will be :

prompt >  netsh interface ipv4 set interface 3 dadtransmits=0 stor=persistent
step 3 :

run -> ncpa.cpl <-|( press enter )
set static ip address :
as mine

192.168.2.8

192.168.6.1 ( this is mine server's static ip address )

mask : 255.255.255.0
gateway :
preferred DNS : 192.168.6.1 ( mine server's ip address, do not enter 127.0.0.1 )

for example :-
--------------
Microsoft Windows [Version 10.0.10240]
(c) 2015 Microsoft Corporation. All rights reserved.

C:\Windows\system32>netsh interface ipv4 show inter

Idx     Met         MTU          State                Name
---  ----------  ----------  ------------  ---------------------------
  1          50  4294967295  connected     Loopback Pseudo-Interface 1
  3          10        1500  connected     Ethernet0

Here mine " * " is 3 i.e. Idx 3 display output of above command.

Then fire this command :-


C:\Windows\system32>netsh interface ipv4 set interface 3 dadtransmits=0 stor=persistent


Ok.

Now change ip address of your host as given above. Or you may use DHCP server to get IP Address.

Its now Solved.

Wednesday, September 27, 2023

How to install Oracle11gR2 Database Server in Centos 6 server with auto-restart

 

Download oracle11rgr2 database from website :- oracle database for linux
I assume that you have installed oracle or Centos 6 linux and on that you are installing oracle database. ( Be noted oracle 11g R2 doesn't install on Centos 7 and above version )

Create following groups and users for oracle :-
# groupadd dba
# groupadd oinstall
# groupadd oper
# groupadd asmadmin

# useradd  -g ointall -G dba,oper,asmadmin oracle

# passwd oracle
now you have to add following entries in files : (edit these files as root user)

file 1 :   /etc/security/limits.conf

Entry will be :-
#added for oracle 11gR2
oracle   soft   nproc    131072
oracle   hard   nproc    131072
oracle   soft   nofile   131072
oracle   hard   nofile   131072
oracle   soft   core     unlimited
oracle   hard   core     unlimited
oracle   soft   memlock  50000000
oracle   hard   memlock  50000000

file 2 : /etc/sysctl.conf

Entry will be :-
#added for Oracle 11gR2
kernel.shmmin = 4096
kernel.shmmax = 4398046511104
kernel.shmall = 1073741824
kernel.sem = 250 32000 100 128
fs.aio-max-nr = 1048576
fs.file-max = 6815744
net.ipv4.ip_local_port_range = 9000 65500
net.core.rmem_default = 262144
net.core.rmem_max = 4194304
net.core.wmem_default = 262144
net.core.wmem_max = 1048586


Apply  kernel parameters : -
 

# /sbin/sysctl -p
 

file 3 : /etc/pam.d/login

Entry will be :-

# added for oracle 11gR2
session     required     pam_limits.so


 file 4 :  .bash_profile ( profile of user oracle )

 Entry will be :-


TMPDIR=/tmp; export TMPDIR
ORACLE_HOSTNAME=`hostname`; export ORACLE_HOSTNAME
ORACLE_SID=ora11gr2; export ORACLE_SID
ORACLE_UNQNAME=ora11gr2; export ORACLE_UNQNAME
ORACLE_BASE=/opt/oracle/app/oracle; export ORACLE_BASE
ORACLE_TERM=xterm; export ORACLE_TERM
ORACLE_HOME= $ORACLE_BASE /product/11.2.0/dbhome_1; export ORACLE_HOME

PATH=/usr/bin:$PATH:$ORACLE_HOME/bin; export PATH

LD_LIBRARY_PATH=$ORACLE_HOME/lib:lib:/usr/lib; export LD_LIBRARY_PATH
CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib; export CLASSPATH

if after restarting of server machine i.e. Centos 6 linux server PC , and does not starts or crashes at booting OS, then go to emergency mode and open file "/home/oracle/.bash_profile" in vim and remove special character "^M" from all lines and save and exit and restart PC.

Now it will be started.


file 5 :  /etc/hosts

Entry will be :-  


<ip-address> <hostname>  <fully qualified domain name of host>


e.g mine is : 


192.168.10.254   oel11gr2   oel11gr2.oraclehomenet.com


Verify your network settings :-


[root@centos7 ~]# ping -c 1 centos7
PING centos7 (127.0.0.1) 56(84) bytes of data.
64 bytes from centos7 (127.0.0.1): icmp_seq=1 ttl=64 time=0.040 ms

--- centos7 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.040/0.040/0.040/0.000 ms


Now install or update following packages : (from your oracle linux ISO, all packages will be there)
binutils
elfutils-libelf
elfutils-libelf-devel
gcc
gcc-c++
glibc
glibc-common
glibc-devel
glibc-headers
ksh
libaio
libaio-devel
libgcc
libstdc++
libstdc++-devel
make
sysstat
unixODBC
unixODBC-devel


Create following paths :-


# mkdir -p /opt/oracle/app/oracle/product/11.2.0/dbhome_1
# chown oracle:oinstall -R /opt/oracle/
# chmod -R 755 /opt/oracle/


 Disable secure linux by editing the

 /etc/selinux/config 

SELINUX=permissive

file making sure the SELINUX flag is set as follows. It requires REBOOT to be effective !!!

Now begin  installation of oracle 11g R2( login as user  : oracle then start installation ) :-
In path of oracle uncompressed directory ( mine is : /opt/software/database and be sure that there should not be any space in path of oracle setup directory database  )
$ ./runInstaller ( press enter )

 

01 configure security updates :-

02 installation options :-



03 system class :-



04 grid options :-
05 install type :-
06 product language :-
07 database edition :-
08 installation location :-

09 create inventory :- 

   



10 general purpose :-



11 database identifier :-
12 configuration option_1 :-
13 char set _2 :-



14 security_3 :-
15 sample schema :-


16 leave as it is :-

17 database storage :-
18 no automated backup :-

19 sys passwords :-


20 OS group :-


then click on next, this will check prerequisites and then installation will begin finally :-

21 installation :-

22 dbca :-



23 script execution :-



24 completion :-



Now Oracle 11g R2 is installed in your oracle linux 6 or centos 6 linux.

To set "gedit " or "vim" as default editor, which comes out via command "ed path_to_sqlfile"

set in a file of location "$ORACLE_HOME/sqlplus/admin/glogin.sql" :-

"define _editor=gedit" or  "define _editor=/usr/bin/vim" ,of course without quotes.

Now fire command in sqlplus :-

SQL> ed /opt/a <-|  ( i.e. press enter )

type in file, save and exit. Then run a.sql ( by default extension changes by oracle)

SQL> @/opt/a <-|

result......

Thats it.

 e.g. :-

SQL> ed /opt/as


SQL> SQL>
SQL> @as
SP2-0310: unable to open file "as.sql"
SQL> @/opt/as
select * from  emp
               *
ERROR at line 1:
ORA-00942: table or view does not exist


SQL>             

Now for installation of oracle instant client, see mine older post. "how to install oracle instant client in centos 7 VM"

--------------------------------------------------------------------------------------------------

Now its time to set auto start of Oracle database after restart of PC or Server.

Installing Oracle Database 11g R2 on a Linux Server does not provide the database the possibility to preform an automatic startup/shutdown when the system is starts or shutdown, we need to do it manually!

so here is a few steps to make it happen automatically.

The automatic startup and shutdown of the Oracle database can be achieved with the files dbstart and dbshut both provided by Oracle. These files rely on the existence of the file /etc/oratab to work.

The format of the /etc/oratab file is as follows:

    SID:ORACLE_HOME:AUTO

or in my example:

    ORCL:/opt/oracle/app/oracle/product/11.2.0/dbhome_1:Y

To start and stop the database when the machine comes up and goes down by modifying the startup routines for the Linux machine. This is quite easy, although I should point out here that this may change depending on which flavor of Linux (slackware, debian, redhat, etc). I will show examples which work for Oracle Linux 5.x. To modify these for your own flavor of Linux, please see your Linux documentation sets.

Note: /etc/init.d is the official location for placing start up scripts and most, but not all distros follow this convention. /etc/rc.d/init.d is where Red Hat (which Oracle Linux is based on) places startup scripts, but in order to comply with modern convention, they make /etc/init.d a symlink to /etc/rc.d/init.d.

Firstly, we need to create the script which will run dbshut and dbstart in the /etc/rc.d/init.d directory. Create the following file as /etc/init.d/oracle:

Note1: The parts in red are optional where if you like to have Oracle Enterprise Manager starting/shutting down with the system.
Note2: If you copy and paste the script you may/will get errors because of the double quotation and the (-) chars, please read Mike’s comment, here is the script with the correct chars.

it’s important to remember to make the script executable by simply run the command:

    $ chmod +x /etc/init.d/oracle

this file's coding is given below, just copy and paste code in file "oracle".

It is worth checking that this file actually correctly stops and starts the databases for your system. Check the log file, /var/log/oracle for error messages.

Once this script is working we need to create start and kill symbolic links in the appropriate runlevel directories /etc/rc.d/rcX.d.

The following commands will ensure that the databases will come up in runlevels 2,3,4 and 5:

    $ ln -s /etc/rc.d/init.d/oracle /etc/rc.d/rc2.d/S99oracle
    $ ln -s /etc/rc.d/init.d/oracle /etc/rc.d/rc3.d/S99oracle
    $ ln -s /etc/rc.d/init.d/oracle /etc/rc.d/rc4.d/S99oracle
    $ ln -s /etc/rc.d/init.d/oracle /etc/rc.d/rc5.d/S99oracle

To stop the databases on reboot or restart we need the following links:

    $ ln -s /etc/rc.d/init.d/oracle /etc/rc.d/rc0.d/K01oracle # Halting
    $ ln -s /etc/rc.d/init.d/oracle /etc/rc.d/rc6.d/K01oracle # Rebooting

Oracle autostart shell script file I named : "oracle". do not append ".sh" extension, and is as follows copy and paste these code in to text file named "oracle"  and set it as executable permission. 

File is :- "oracle" :-

------------------------------------------------------------------------------------------------------------------

#!/bin/sh
#
# /etc/rc.d/init.d/oracle
# Description: Starts and stops the Oracle database, listeners and Enterprise Manager
# See how we were called.
case "$1" in
    start)
        echo "Starting Oracle"
        echo "—————————————————-" >> /var/log/oracle
        date +"! %T %a %D : Starting Oracle Databases as part of system up." >> /var/log/oracle
        echo "—————————————————-" >> /var/log/oracle
        echo -n "Starting Oracle Listeners: "
        su - oracle -c "lsnrctl start" >> /var/log/oracle
        echo "Done."
        echo -n "Starting Oracle Databases: "
        su - oracle -c "dbstart $ORACLE_HOME" >> /var/log/oracle
        echo "Done."
        echo -n "Starting Oracle Enterprise Manager: "
        su - oracle -c "emctl start dbconsole" >> /var/log/oracle
        echo "Done."
        echo ""
        echo "—————————————————-" >> /var/log/oracle
        date +"! %T %a %D : Finished." >> /var/log/oracle
        echo "—————————————————-" >> /var/log/oracle
        touch /var/lock/subsys/oracle
        ;;
         stop)
        echo "Shutting Down Oracle"
        echo "—————————————————-" >> /var/log/oracle
        date +"! %T %a %D : Shutting Down Oracle Databases as part of system down." >> /var/log/oracle
        echo "—————————————————-" >> /var/log/oracle
        echo -n "Shutting Down Oracle Enterprise Manager: "
        su - oracle -c "emctl stop dbconsole" >> /var/log/oracle
        echo "Done."
        echo -n "Shutting Down Oracle Listeners: "
        su - oracle -c "lsnrctl stop" >> /var/log/oracle
        echo "Done."
        rm -f /var/lock/subsys/oracle
        echo -n "Shutting Down Oracle Databases: "
        su - oracle -c "dbshut $ORACLE_HOME">> /var/log/oracle
        echo "Done."
        echo ""
        echo "—————————————————-" >> /var/log/oracle
        date +"! %T %a %D : Finished." >> /var/log/oracle
        echo "—————————————————-" >> /var/log/oracle
        ;;
      restart)
        echo "Restarting Oracle"
        echo "—————————————————-" >> /var/log/oracle
        date +"! %T %a %D : Restarting Oracle Databases as part of system up." >> /var/log/oracle
        echo "—————————————————-" >> /var/log/oracle
        echo -n "Restarting Oracle Listeners: "
        su - oracle -c "lsnrctl stop" >> /var/log/oracle
        su - oracle -c "lsnrctl start" >> /var/log/oracle
        echo "Done."
        echo -n "Restarting Oracle Databases: "
        su - oracle -c "dbshut $ORACLE_HOME">> /var/log/oracle
        su - oracle -c "dbstart $ORACLE_HOME">> /var/log/oracle
        echo "Done."
        echo -n "Restarting Oracle Enterprise Manager: "
        su - oracle -c "emctl stop dbconsole" >> /var/log/oracle
        su - oracle -c "emctl start dbconsole" >> /var/log/oracle
        echo "Done."
        echo ""
        echo "—————————————————-" >> /var/log/oracle
        date +"! %T %a %D : Finished." >> /var/log/oracle
        echo "—————————————————-" >> /var/log/oracle
        touch /var/lock/subsys/oracle
        ;;
       status)
               if [ -f  /var/lock/subsys/oracle ] ; then
                    echo " Oracle Enterprise Manager running"
               else
                   echo " Oracle Enterprise Manager is not running"
        fi                  
        ;;

        *)
        echo "Usage: oracle {start|stop|restart|status}"
        exit 1
esac

------------------------------------------------------------------------------------------------------------------

Now to restart oracle database server fire this command as root user :-

# service oracle restart 

 to access enterprise manager open url as follows :-

https://oel11gr2.oraclehomenet.com:1158/em/

where "oel11gr2.oraclehomenet.com" is oracle database server FQDN( fully qualified domain name ).