Monday, September 23, 2019

Modern Cpp features used

shared_ptr, unique_ptr, weak_ptr
auto


lambda

auto pred = [&] (const class &obj)
                   {
                       if(checks on the obj data)
                           return true/false;
                   };

soemthing::instance().process(pred);

std::make_tuple(params)

std::tie(3 variables) = [&] () {
                                                if(something) return make_tuple(3 variables)
                                                else if(soething else) return make_tuple(3 variables);
                                  };


Boost ::optional
Boost::none
boost::noncopyable
boost::static_pointer_castoldTypeVariable
boost::shared_ptr
boost::dynamic_pointer_castoldTypeVariable
boost::lexical_castoldTypeVariable - mostly used for numeric/alphabetic cast
inheriting from private boost::noncopyable

clang++ 1.0 is used.

Python features/libs used

import logging
import logging.handlers
import os
import pwd
import sys
import time
import functools
import traceback

time.localtime
functools.partial
sys.exit(1)
_________________________

import cx_Oracle
import csv
import datetime
from optparse import OptionParser
from report_utils import write_cursor_to_file, send_email

writer = csv.writer(filename)
text = 'something'
writer.writerow(text)

db = cx_Oracle.connect(connection_stirng)
cursor = db.cursor
sproc = os.path.expandvars($DataBaseName.storedProcName)
cursor.callfunc(sproc, int, [refcursor])


opt_parser = OptionParser()
opt_parser.add_option(variables)

_________________________

import subprocess
import sys
import threading

subprocess.Popen()

listening_event = treading.Event()
async_waiter = threading.Thread()
async_waiter.daemon = true/false;
async_waiter.start()

thread_handle.join
thread_handle.isAlive()

_________________________

import argparse
import os
import db_utils
import solace_utils as solace
import xml.etree.ElementTree as ET
import stringIO

arg_parser = argparse.ArgumentParser
arg_parser.add_argument();

global args
args = arg_parser.parse_args()

sql = "some select statement with where clause'
db_utils.DBConnection(database='STATIC_DB') as db:
    return db.get_single_value_from_db(sql=sql)


root = ET.Element("ElementName")
sub1 = ET.SubElement(root, "SubElem name")
sub2 = ET.SubElement(root, "SubElem name2")

root = ET.fromstring(Str)
Str = ET.tostring(root)

listener = solace.listenForMsgAsync()
solace.sendMsg()
solace.waitForResponse()


import mplotlib
import math
matplotlib.use('Agg')
import mplotlib.pyplot as plt
import mplotlib.ticker as mtick
from mplotlib import dates
from mplotlib.dates import date2num
from mplotlib.font_manager import FontProperties

writer.writerow(string)

graph -
x_axis = []
y_axis = []
y_axis2 = []
y_axis3 = []

x_axis = x_axis + (units - could be dates)
y_axis = y_axis + (units - could be prices)
y_axis2 = y_axis + (units - could be vol)
y_axis3 = y_axis + (units - could be moving average)

plt.gcf().clear()

plt1 = plt.subplot(111)
plt.gca().set_xlim([x[0], x[-1]])

ax = None
ax = plt.gcf().axes[0]

line1 = plt.plot(x, y_axis, label = "", color = "")
line1 = plt.plot(x, y_axis2, label = "", color = "")
line1 = plt.plot(x, y_axis3, label = "", color = "")
plt.suptitle('some title', fontsize)

plt.bar(x[:1], y_axis[0], width = 'decide', align = 'centre', label = 'soomething', color = '')

fontP = FontProperties()
fontP.set_size('small')
ax.legend(, , , use fontP here)

plt.savefig(filename)








String reversals


Fibs


Palindromes


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).