Friday, March 31, 2017

Best practices while using multiprocessing in Python

As we know that python threads can't explore the true parallel processing because of GIL. So to achieve the same we often use multiprocessing.
While using multiprocessing, one of the best practices is to pass the cpu affinity. It will be useful in below scenarios:
Example:
There is a four core processor and we are running 4 python processes. So here we can utilise all the four core available. Down side of not using cpu affinity is that processor will keep scheduling the processes among available core causing additional context switching overhead. Suppose we have allocated different core to all the four processes resulting no context switching and leading a better throughput.
Please be thoughtful when using the same, otherwise you could end up restricting the core for a given process.

Python code sample to demonstrate the cpu affinity
---------------------------------------------------------------------------

>>> import psutil
>>> psutil.cpu_count()
4
>>> p = psutil.Process()
>>> # get
>>> p.cpu_affinity()
[0, 1, 2, 3]
>>> # set; from now on, process will run on CPU #0 and #1 only
>>> p.cpu_affinity([0, 1])
>>> p.cpu_affinity()
[0, 1]
>>> # reset affinity against all eligible CPUs
>>> p.cpu_affinity([])

Monday, May 23, 2016

Longest Increasing Sub sequence (LIS) Analysis



Brute Force Solution for LIS

#include <iostream>
#include <algorithm>
#include <limits.h>
#include <stdio.h>
using namespace std;
int Arr[]={ 10, 22, 9, 33, 21, 50, 41, 60 };

int L(int i){
 int result = -1, flag =0;
     for( int j=i-1;j>=0;j--)
  if(Arr[i]>Arr[j]){
   result = max(result,1 + L(j));
   flag = 1;
  } 
 if (flag == 0)
  return 1;
 else
  return result;
   
}
int lcs(int n){
 int result = -1;
 for(int i=0;i<n;i++)
  result = max(result, L(i));
 return result; 
}

int main() {
 printf("%d\n",lcs(8));
 return 0;
}

Here the time complexity is n!

Moving ahead, we can use memoization to optimize the solution.


#include <iostream>
#include <algorithm>
#include <limits.h>
#include <stdio.h>
using namespace std;
int Arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int Mem[] = { 0, 0, 0, 0, 0, 0, 0, 0 };

int L(int i){
 int result = -1, flag =0;
     for( int j=i-1;j>=0;j--)
  if(Arr[i]>Arr[j]){
   if (Mem[j] > 0)
    result = max(result,1+Mem[j]);
   else 
    result = max(result,1 + L(j));
   flag = 1;
  } 
 if (flag == 0){
  Mem[i] = 1;
  return 1;
 }
 else{
  Mem[i] = result;
  return result;
 }
   
}
int lcs(int n){
 int result = -1;
 for(int i=0;i<n;i++)
  result = max(result, L(i));
 return result; 
}

Here I have used Mem[] to remember the result. With this optimization, 
the complexity goes to O(N^2) 

We can also solve this problem using DP (Bottom up approach)
#include <iostream>
#include <algorithm>
#include <limits.h>
#include <stdio.h>
using namespace std;
int Arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int dp[8];

int L(int n){
    int max2 = -1;
    for(int i=1;i<n;i++){
         for( int j=i-1;j>=0;j--){
            if(Arr[i] > Arr[j] && dp[i] < dp[j]+1){
                dp[i] = dp[j]+1;
            } 
             
         }
        max2 = max(max2,dp[i]);
    }
    
    return max2; 
}

int main() {
 for(int i=0;i<8;i++) dp[i] = 1;
 printf("%d\n",L(8));
 return 0;
}


priority queue implementation in c++

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <queue>
using namespace std;
class Foo
{
  public:
int key;
int value;
};

class Compare
{
public:
    bool operator() (Foo Foo1, Foo Foo2)
    {
        return Foo1.value < Foo2.value;
    }
};

int main()
{
    srand(time(NULL));
    std::priority_queue<Foo, std::vector<Foo>, Compare> pq;
    for (int i=0;i<5;i++){
Foo tmp;
tmp.key = i;
tmp.value = rand()%100;
        printf("key %d = value %d\n",tmp.key, tmp.value);
pq.push(tmp);
    }
    while (!pq.empty()){
      Foo tmp = pq.top();
printf("%d = %d\n",tmp.key,tmp.value);
pq.pop();
}
    return 0;
}

output
=====
Success time: 0 memory: 3456 signal:0
key 0 = value 76
key 1 = value 62
key 2 = value 57
key 3 = value 74
key 4 = value 74
0 = 76
3 = 74
4 = 74
1 = 62
2 = 57

Monday, May 16, 2016

Lambda interacting with Redshift #AWS #LAMBDA #REDSHIFT #SNS #Python

'''
Here I am sharing methods to interact with Redshift or Arora DB in AWS, posting message to a given topic in SNS
'''

import json
import urllib2

import hmac
import hashlib
import base64
import string
import psycopg2
from time import strftime,gmtime,time

ACCESS  = 'XXXXXXXXXXXXXXXXXXX'
SECRET  = 'uxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
                     

REGION  = 'xxxx'
TOPIC   =  'xxxx'
MSG    = 'This is test message xxxxx'
SUBJECT = 'demo2'

'''
Here, the function fetchData will establish a connection with Redshift, execute a query and fetch the data.
'''

def fetchData():
       
    conn = psycopg2.connect(
        host="host_name_apearing_at_aws_console_excluding_port",
        user='myuser',
        port=5439,
        password='password',
        dbname='rdb')

    cur = conn.cursor()
   
    column_names = [];
    cur.execute("select * from dummy limit 10;");
    tmp=cur.fetchall();
   
   #conn.commit()
    conn.close()

'''
Below function will post to SNS
'''
def publishAmazonSnsMsg(Subject,TopicArn,Message,AWSAccessKeyId,privatekey):
  #http://docs.amazonwebservices.com/AWSSimpleQueueService/2008-01-01/SQSDeveloperGuide/
  amzsnshost = REGION
  params = {'Subject' : Subject,
            'TopicArn' : TopicArn,
            'Message' :Message,
            'Timestamp' : strftime("%Y-%m-%dT%H:%M:%S.000Z", gmtime(time())),
            'AWSAccessKeyId' : AWSAccessKeyId,
            'Action' : 'Publish',
            'SignatureVersion' : '2',
            'SignatureMethod' : 'HmacSHA256',
            }
 
  cannqs=string.join(["%s=%s"%(urllib2.quote(key),urllib2.quote(params[key], safe='-_~')) \
                                for key in sorted(params.keys())],'&')
  string_to_sign=string.join(["GET",amzsnshost,"/",cannqs],'\n')
  sig=base64.b64encode(hmac.new(privatekey,string_to_sign,digestmod=hashlib.sha256).digest())
  url="http://%s/?%s&Signature=%s"%(amzsnshost,cannqs,urllib2.quote(sig))
  print url
 
  try:
    return urllib2.urlopen(url).read()
  except urllib2.HTTPError, exception:
    return "Error %s (%s):\n%s"%(exception.code,exception.msg,exception.read())

def lambda_handler(event, context):
    fetchData()
    try:
        ret = publishAmazonSnsMsg(SUBJECT, TOPIC ,MSG , ACCESS, SECRET)
    except:
        pass

'''
# To test the function from cli
if __name__ == '__main__':
lambda_handler(None, None)
'''
'''

The above method running inside a lamba fuction will connect with the db and post to the SNS. There are some modules which are not available in AWS enviornment. We need to attach the the module folder in the root directory while zipping the module. As example for the above code psycopg2 was not available. So I have attached the module while zipping the source code.

Ex: ++lambda_function.py
       ++ psycopg2
               ++
               ++
In the same way we can attach the custom module too. For the psycopg2, it requires to be statically compiled. I am sharing a git link having the compiled module as well as listing method to compile the same. https://github.com/prrs/awslambda-psycopg2. courtsey: https://github.com/jkehler/awslambda-psycopg2
'''

Sunday, January 17, 2016

django_sentinel

https://github.com/prrs/django_sentinel

Redis sentinel implementation for django redis.

Wednesday, August 12, 2015

reading and writing from standard input/output in python


Here I am sharing a couple of ways that I use to perform I/O in python.

import sys
import fileinput
# working read a line from stdin
#x=sys.stdin.readline()
#print x

#working read the input from stdin, terminated by Ctrl + D
#x=sys.stdin.read()
#print x

#raw_input take an input and move ahead
#x=raw_input()
#name=raw_input()
#print x, name

# fileinput take the input from the file from command line argument, if the argument is null
# it take input from stdin

#for line in fileinput.input():
#    print line

x=0
mylist=[None]*10
while x<10:
   mylist[x]=raw_input()
   x=x+1


for a in mylist:
   print a+"  "




Tuesday, July 14, 2015

Why E-Commerce Giants Are Shutting Websites


Got a technical post, trying to answer the question that why e-commerce giant are shutting their website....

http://www.techgig.com/tech-news/editors-pick/Why-E-Commerce-Giants-Are-Shutting-Websites-33433