Install Basic software/tool/app in ubuntu/linux

1: Install Google Chrome on Ubuntu

Add Key:

> wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -

Set repository:

> echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | sudo tee /etc/apt/sources.list.d/google-chrome.list

Install package:

>sudo apt-get update

>sudo apt-get install google-chrome-stable

2: Install Slack from the command line with snap

> sudo snap install slack

> sudo apt-get update

> sudo apt-get upgrade slack-desktop

3: Install lampp from the command line

https://vitux.com/ubuntu-xampp/

sudo /opt/lampp/lampp start

4: Install vscode

https://code.visualstudio.com/docs/setup/linux

5: Install pycharm

sudo snap install pycharm-community --classic

6: install git

sudo apt update

sudo apt install git

git --version

View More...

Get Logs error message, linenumber and path files using flask

  • Create Simple Log file
import logging
logging.basicConfig(filename="logs.txt",
                    filemode='a',
                    format='%(asctime)s\t%(lineno)d\t%(levelname)s\t%(pathname)s\t%(name)s\t%(message)s',
                    datefmt='%H:%M:%S',
                    level=logging.DEBUG)
msg = "NameError: name filename' is not defined "
logging.info(msg)
logging.warn(msg)
logging.error(msg)
logging.critical(msg)
  • Logs file created in logs.txt like as: 20:05:16 10 INFO C:\Users\vishavjeet\Documents\mywork_space\flask_demo\python_log.py root NameError: name filename' is not defined 20:05:16 11 WARNING C:\Users\vishavjeet\Documents\mywork_space\flask_demo\python_log.py root NameError: name filename' is not defined 20:05:16 12 ERROR C:\Users\vishavjeet\Documents\mywork_space\flask_demo\python_log.py root NameError: name filename' is not defined 20:05:16 13 CRITICAL C:\Users\vishavjeet\Documents\mywork_space\flask_demo\python_log.py root NameError: name filename' is not defined

write the code for post api using flask

from flask import Flask, request, jsonify
import os
# Create a Flask app for post api
app = Flask(__name__)
@app.route('/logs', methods= ['POST', 'GET'])
def logs_func():

    response = {
        "status": True,
        "message": "Logs data found!",
        "data":[]
    }

    if request.method == 'POST':
        file_name = request.json['filename']
        i = 1
        result = {}
        if os.path.exists(file_name):
            with open('logs.txt') as f:
                lines = f.readlines()
                for line in lines:
                    r = line.split('\t')

                    if r[2]== 'ERROR':

                        result[i] = {
                            'timestamp': r[0], 
                            'linenumber' : r[1],
                            'name': r[4],
                            'pathname': r[3],

                            'message': r[5]
                            }
                        i += 1
            response['data']= result
            return jsonify(response)
        else:
            response['status']= False
            response['message']= "File not found!"
            return jsonify(response)
    else:
        response['status']= False
        response['message']= "Only Post method is not allow"
        return jsonify(response)


if __name__ == '__main__':
    app.run(debug = True)

  • API Response:
{
    "data": {
        "1": {
            "linenumber": "12",
            "message": "NameError: name filename' is not defined \n",
            "name": "root",
            "pathname": "C:\\Users\\vishavjeet\\Documents\\mywork_space\\flask_demo\\python_log.py",
            "timestamp": "20:05:16"
        },
        "2": {
            "linenumber": "12",
            "message": "NameError: name filename' is not defined \n",
            "name": "root",
            "pathname": "C:\\Users\\vishavjeet\\Documents\\mywork_space\\flask_demo\\python_log.py",
            "timestamp": "20:05:18"
        },
        "3": {
            "linenumber": "12",
            "message": "NameError: name filename' is not defined \n",
            "name": "root",
            "pathname": "C:\\Users\\vishavjeet\\Documents\\mywork_space\\flask_demo\\python_log.py",
            "timestamp": "20:05:20"
        },
        "4": {
            "linenumber": "13",
            "message": "NameError: name filename' is not defined \n",
            "name": "root",
            "pathname": "C:\\Users\\vishavjeet\\Documents\\mywork_space\\flask_demo\\python_log.py",
            "timestamp": "20:08:12"
        }
    },
    "message": "Logs data found!",
    "status": true
}

View More...

Python script for find next monitoring/appointment/birthday ect

Using Function

from datetime import datetime, timedelta

def get_remaining_days(review_date, frequency):
    date_formate = '%Y-%m-%d'
    review_date = datetime.strptime(str(review_date), date_formate)
    today_date = datetime.strptime(str(datetime.now()).split(" ")[0], date_formate)

    difference = today_date - review_date
    if difference.days <= 0:
        next_monitoring = review_date + timedelta(days=frequency)
    else:
        flag = True
         next_monitoring = review_date + timedelta(days=0)
        while flag:
            next_monitoring = next_monitoring + timedelta(days=frequency)
            difference = next_monitoring - today_date
            if difference.days >= 0:
                flag = False
    remaining = next_monitoring - today_date

    print(f'Next Monitoring date will be  {next_monitoring} or after {remaining.days} days')
    return remaining.days, next_monitoring

get_remaining_days("2022-04-15", 20)

Using Class

from datetime import datetime, timedelta
class RemaningDayFinder():

    DATETIME_FORMAT = '%Y-%m-%d'

    def __init__(self, review_date, frequency):
        self.review_date = datetime.strptime(str(review_date), self.DATETIME_FORMAT)
        self.today_date = datetime.strptime(str(datetime.now()).split(" ")[0], self.DATETIME_FORMAT)
        self.frequency = frequency

    def get_remaining_days(self):

        difference = self.today_date - self.review_date

        if difference.days <= 0:
            next_monitoring = self.review_date + timedelta(days=self.frequency)
        else:
            flag = True
           next_monitoring = self.review_date + timedelta(days=0)
            while flag:
                next_monitoring = next_monitoring  + timedelta(days=self.frequency)
                difference = next_monitoring - self.today_date
                if difference.days >= 0:
                    flag = False

        remaining = next_monitoring - self.today_date
        return remaining.days, next_monitoring

    def __str__(self):
        remaining_days, next_monitoring = self.get_remaining_days()
        return f'Next Monitoring date will be  {next_monitoring} or after {remaining_days} days'

remaining_days = RemaningDayFinder("2022-04-15", 20) print(remaining_days)

Best Logic Based on Performance

def get_remaining_days(review_date, frequency): date_formate = '%Y-%m-%d' review_date = datetime.strptime(str(review_date), date_formate) today_date = datetime.strptime(str(datetime.now()).split(" ")[0], date_formate)

difference = today_date - review_date
if difference.days <= 0:
    next_monitoring = review_date + timedelta(days=frequency)
else:
    pass_days = ((difference.days//frequency)*frequency)+frequency
    next_monitoring = review_date + timedelta(days=pass_days)

remaining = next_monitoring - today_date

print(f'Next Monitoring date will be  {next_monitoring} or after {remaining.days} days')
return remaining.days, next_monitoring
View More...

Coding Style Guide

  1. Are variables/db/collection/functions/class/api names sensible?
  2. Is my database structure thought for & optimized?
  3. Do i have proper indexes in places.
  4. Do in have duplications in my code, ex duplicate statements/expressions/conditions?
  5. Is some part of code hitting/querying db in loop?
  6. Are apis returing coorrect status codes for different scenarios?
  7. Are functions clearly defined?
  8. Is code easy to understand/comphrend?
  9. Does code has proper try catch blocks? 10: function arguments handled properly? 11.Make sure not using a generic except while using try catch.

(bad) try: 10/0 except Exception as e: pass

(good) try: 10/0 except DivideByZero as e: pass

12.Make sure not using multiple statements inside single try catch.

View More...

Pipenv Installation

What is Pipenv??

pipenv is a better package.

It contain pipfile.lock which contain all require package & dependencies

pipfile is automatically installed.

pipenv can work with requirement.txt file too. If there is one automatically detect it & convert into a pipfile.

Install Pipenv

Before installation get to know python is already installed

$python -V

$pip -V

$pip install pipenv or pipenv install --dev

$pipenv -h (to check the pipenv correctly installed)

$pipenv shell

$exit or deactivate

If showing pipenv not recognized as internal or external command , have to set Path in environment variable.

View More...

1 2 3 Next Last