Saturday, 6 June 2020

Expense Handler Application with advance technologies

Budget Planner 

One of the application developed with Ionic 4 and Python-Flask. 



Here we have used a new technologies to understand how it works and the advantages.

Saturday, 25 April 2020

Sample code for Authorization in Python

Achieving Authorization using JWT in Python


Here we are going to access an get API using python authorization by checking the username, password and generating JWT token.

kindly install below packages to proceed with the code.
install flask_jwt 
install flask_restful 
install flask 

once the above steps has been completed, we will be created three files 
app.py - main application file
security.py - security file
user.py - user

Code: app.py


Code: security.py


Code: user.py



If you need further explanation, kindly mention in the comments so that i can give a brief on code flow.
   



Wednesday, 15 April 2020

Windows BCD error code 0x0000098


Windows BCD error and it works and your files will be safe

File:\BCD
Error code: 0x0000098


Note:
If you are using windows genuine version kindly insert the installation media and follow the below steps:
-Start up your computer with the USB or DVD Windows 10 recovery media.
-Select your language time format and keyboard and click next.
-Click (repair now) then (troubleshoot), windows will automatically try to repair your system.

If you are using non-licensed version:


Start your computer and enter F11 and select the trouble shoot option



select Command prompt and enter the below commands:

C:\diskpart 
and press enter.

DISKPART> list disk 
and press enter to know which drive to target.

DISKPART> sel disk 0 
assuming your drive with windows is disk 0 and press enter.

DISKPART> list vol 
to view all the partitions and press enter.

Select the EFI partition volume which is using FAT32 next to the NTFS volume

DISKPART> sel vol 2
to select the fat32 EFI volume and press enter.

DISKPART> assign letter=m 
to assign an arbitrary drive letter to it and press enter.

DISKPART> Exit 
to exit the diskpart tool and press enter.


> cd /d m:\EFI\Microsoft\Boot\  
press enter

> bootrec /fixboot 
press enter

> ren BCD BCD.old 
and enter to backup the existing Boot Configuration Data
(BCD) store.

> bcdboot c:\Windows /l en-us /s m: /f ALL 
press enter to recreate the BCD store.

Close the command prompt windows then turn off pc and restart the computer.



Sunday, 12 April 2020

parameters are of unsupported type sqlite python

Details:

This is one of the common error a beginner will be facing when he is working on Python and SQLite bridging. Below is a scenario provided for better understanding with example.

Error:

insert_data = "INSERT INTO users VALUES (?, ?, ?)"
    user = [
        {1"Ram""abc@123"},
        {2"Rahim""wel@123"},
        {3"Raju""pass@123"}
    ]
    cursor.executemany(insert_data, user)

When you run the above code you will get the error:
(venv) D:\python\Course_sample\source_database>python dataBase.py
parameters are of unsupported type

This is because when ever we try to insert into database from python, they data has to be a tuple.
In the above code you can see list of set which we try to insert.

Fixed:

#insert data query
    insert_data = "INSERT INTO users VALUES (?, ?, ?)"
    user = [
        (1"Ram""abc@123"),
        (2"Rahim""wel@123"),
        (3"Raju""pass@123")
    ]
    cursor.executemany(insert_data, user)

The above code will get executed and the data will get inserted into the database properly.

Sunday, 5 April 2020

Lambda in python with example

Lambda:

In the below example you can see two methods have been created and clearly explained to show how Lambda works

friends =  [
    {"name""Ram""age":26}, 
    {"name""Raju""age":30}
]

#method with for loop 
def findAge(name):
    for friend in friends:
        if(friend["name"== name):
            return friend
    
    return f"{name} not found"

#method with Lambda expression 
def findAgeLambda(name):
    friend = next(filter(lambda x: x["name"== name, friends))
    return friend

print(findAge("Ram"))
print(findAgeLambda("Raju"))  

Output:

{'name': 'Ram', 'age': 26}
{'name': 'Raju', 'age': 30}

Difference between Set, List and Tuple in python


Set:
  • (regressive)unordered list of data
  • Mutable unordered(regressive) set of values
  • initialized using emptySet = set()
  • Every element is unique
  • A set is created by placing all items inside {}
  • Eg: my_set = {1, 2, 3}
List:
  • Ordered list of data
  • Mutable ordered set of values
  • Initialized using list = []
  • can contain duplicate
  • A list is created by placing all items inside []
  • Eg: my_list = [1,2,3]
Tuple:
  • Ordered list of data
  • Immutable set of values
  • Initialized using tuple = ()
  • can contain duplicate
  • A tuple is created by placing all items inside ()
  • Eg: my_tuple = (1,2,3)



class composition in python with example

Composition is a concept that models a has a relationship. It enables creating complex types by combining objects of other types. This means that a class Composite can contain an object of another class Component. This relationship means that a Composite has a Component.

Example:

class Garage:
    def __init__(self*cars):
        self.cars = cars

    def __str__(self):
        return (f"Total {len(self.cars)} cars in the Garage")

class Cars:
    def __init__(selfnameyear):
        self.name = name
        self.year = year

    def __str__(self):
        return ("{} is moving to Garage in {}".format(self.name, self.year))


car = Cars("Ferrari""2019")
car2 = Cars("Rolls""2020")
car3 = Cars("Benz""2021")
garage = Garage(car, car2, car3)

print(car)
print(car2)
print(car3)
print(garage)

Output:
Ferrari is moving to Garage in 2019
Rolls is moving to Garage in 2020
Benz is moving to Garage in 2021

Total 3 cars in the Garage

Try Except in python with example

Error handling in Python using Try.. Except..

Consider the below example for your reference, you can see the TRY block followed by the EXCEPT and below that there are two additional blocks ELSE and FINALLY.

Try:
The try block will get executed first and will perform the operations given under it. If there is any exception  during the operation then the try block will be stopped else the try block will completed its execution and by pass the EXCEPT block. Compulsory block 

Except:
This block will get executed only if there is any exception in the try block. This Except block will handle the exception and provide a useful message to user regarding the error that has been occurred. Compulsory block 

Else:
This block will be performed if there are no exception and over successful completion of the try block. This is an optional block.

Finally:
This is a final block and this block will definitely get executed even though if there is any exception and optional block in try except.

Example:

students =[
    {"name":"Ram""marks":[50,40,80]},
    {"name":"Raju""marks":[]},
    {"name":"Babu""marks":[90,80,70]}
]

try:
    for student in students:
        name = student["name"]
        marks = student["marks"]
        total = sum(marks)
        average = sum(marks)/len(marks)

        print(f"{name} has scored: Total={total} & Average={average}")
except Exception as e:
    print("There is error in student")
    print(e)
else:
    print("Student list completed")
finally:
    print("done")

Output:
Ram has scored: Total=170 & Average=56.666666666666664
There is error in student
division by zero
done

Dunder or Magic methods in python with example

Magic methods are usually represented by two underscores at front and two at the back of method names. The name Dunder is because of these underscores. Also mainly used for operator overloading.

In the below example you can see two methods "str" and "repr" with two underscore at the front and two at the back. These two methods are used to give user a output if there are no proper return methods in a class. These can also be used to give a message on the function that has been performed in a class.

Example:

class Cars:
    def __init__(selfnamemodel):
        self.name = name
        self.model = model

    def __str__(self):
        return (f"{self.name} is manufactured in the year {self.model}")

    def __repr__(self):
        return (f"<{self.name} is manufactured in the year {self.model}/>")


car = Cars("Ferrari""2019")
print(car)

Output:
Ferrari is manufactured in the year 2019

list indices must be integers or slices, not str error in python

Below is an example to elaborate the error and for an better understanding.

Eg:

shops = [{
    "name""Anand Motors",
    "cars": [
        {
            "name":"Ferrari",
            "Price"25000
        },
        {
            "name""Benz",
            "price"15000
        }
    ]}  
]

The above dictionary is referred as list, when to try to access the dictionary data using string.

name = "Anand Motors"
print(shops[name])

The above code gives error.

Solution or fix:

name = "Anand Motors"
print(next(shop for shop in shops if shop["name"== name))

The above code will fix this error.


Friday, 3 April 2020

Difference between Method and Function in python with example

Function:

A function is a set of code or block of code which process data and return or create a output for the given input.

Eg:
def addValues(xy):
    return x+y

x=int(input("Enter your x value:"))
y=int(input("Enter your y value:"))
print(addValues(x, y))

When you consider the above python code, addValues() is a function.

Method:

A method is similar to function where has a set of code or a block of code, which is represented by a name. When the name is called the entire block of code will be executed. 

Eg:
class mathis:
    def addValues(xy):
        return x+y

x=int(input("Enter your x value:"))
y=int(input("Enter your y value:"))
print(mathis.addValues(x, y))

In the above python code, the same addValues() is defined into a class which is referred as a method.

Here the difference between method and function is:

  • If a function is defined inside a class then it is called as method.
(note: Method and function has similar properties where both is used to perform an operation with block of code.)

Tuesday, 31 March 2020

Error: No module named flask in python

Error: No Module named flask, for python application

(venv) C:\Python\sandbox>py -m flask run
C:\Python\sandbox\venv\Scripts\python.exe: No module named flask

When you try to run the python application using flask you may get the above error: 
root cause: There is no flask installation found in the directory you are currently trying to access the application.
Solution:
When you over come the above error first install flask using below command:
py -m pip install Flask

Then try: py -m flask run 

Now your system will recognize your command and run the flask application.

Sunday, 29 March 2020

Mat Autocomplete list in Angular 7

How to create an Autocomplete list in Angular 7:


Here I am going to show how to get and display an autocomplete list of contents based on the input given by user.

Create a Form with Input and Mat Autocomplete in the .html file:

<form [formGroup]="serviceForm" (ngSubmit)="addService()" data-automation-attribute="form-op-service">
    <mat-grid-list cols="12" rowHeight="65px">
       <mat-grid-tile [colspan]="9">
          <mat-form-field *ngIf="searchType == '1'" class="full-width" appearance="outline">
             <mat-label>Service Name</mat-label>
             <input                  
                    cdk-focus-initial
                    type="text"
                    placeholder="Service Name"
                    matInput
                    [matAutocomplete]="auto"
                    formControlName="serviceName"
                    [(ngModel)]="serviceName"
                    (input)="getserviceOnSearch()"
                    data-automation-attribute="text-service-name" />
                  <mat-autocomplete #auto="matAutocomplete" (optionSelected)="serviceOnSelect($event.option.value)">
                    <mat-option *ngFor="let service of filteredOptions | async"
                      [value]="service.serviceName">
                      {{ service.serviceName }}
                    </mat-option>
                  </mat-autocomplete>
                </mat-form-field>
</mat-grid-tile>
</mat-grid-list>
</Form>

Explanation:

Main code in the input field:
matAutocomplete set as auto.
input: to get the input entered by the user
under mat-option set the filtered option to get the latest list based on the user key.
Once the user enter the key then using ngModel it will be captured in the method getserviceOnSearch(). The functionality of this method is given below in detail.


Add below code into .TS file:

serviceName: string = "";

//This method is used to filter using the user key and return a customized list
searchedText: string = "";
  getserviceOnSearch() {
    let splitText: any;
    if (
      this.serviceName &&
      //this.searchedText != this.serviceName &&
      (this.serviceName.length == 3 ||
        this.serviceName.length == 5 ||
        this.serviceName.length > 7)
    ) {
      this.searchedText = this.serviceName;

      this.http.get<any>('https://api.io/')
        .getResource(
          "billing-masters/unit-wise-services?searchKey=" + this.serviceName
        )
        .subscribe(res => {
          if (res) {
            this.services = res;
            this.filteredOptions = this.serviceControl.valueChanges.pipe(
              startWith(""),
              map(value => this._filter(value))
            );
          }
        });
    } else if (this.serviceName.length <= 2) {
      this.filteredOptions = new Observable<string[]>();
    }
  }

private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();
    return this.services.filter(option =>
      option.serviceName.toLowerCase().includes(filterValue)
    );
  }

The above code is very simple just need to add this method and the list will populate based on the key entered. If you want to populate the complete list during the application start then add the below code in OnInit method to load the complete API response into the list.

ngOnInit() {
this.http.get<any>('https://api.io/')
        .getResource(
          "billing-masters/unit-wise-services?searchKey=" + this.serviceName=""
        )
        .subscribe(res => {
          if (res) {
            this.services = res;
            this.filteredOptions.next(this.services.slice());
          }
        });
    } else if (this.serviceName.length <= 2) {
      this.filteredOptions = new Observable<string[]>();
    }
}

The above code will add the complete response into the list which will show user all the options that are available and once the key is entered it will filter the options and refresh the list based on the key.

Cannot read property 'nativeElement' of undefined angular 7

This error is one of the common error which we get when there is a mismatch in the typescript and html in Angular 7.

To avoid this error kindly notice the below code for reference

In example.component.ts        
@ViewChild("nameField")nameField:ElementRef;

In example.component.html
<input                      
             cdk-focus-initial 
             #nameField
             type="text" 
             placeholder="Service Name" 
             matInput
             [matAutocomplete]="auto" 
             formControlName="serviceName" 
             [(ngModel)]="serviceName"
             (input)="getserviceOnSearch()" 
  data-automation-attribute="text-service-name" />

COVID-19 - Information about corona, symptoms and how it spread

About COVID-19:

COVID-19 as Corona is a virus which now can attack humans. this virus has been infecting animals for over years which have now evolved or have been evolved to infect humans. This virus is also like similar to HIV which start attacking the immunity system first and once it has weaken the system then spread to lungs and give server damage to lunch. This is a deadly virus and a well developed human will get infected and will be developing in the host for over 1 week to 14 days. During these period your body before start recognizing the virus will get developed and it will start spreading to your lungs.

Symptoms:

During the first attack of this virus, you will get sore throat (server). And this is the first symptom which is also common when we get cold.
1. Tiredness
2. Sore throat and irritation
3. Cough
4. Fever
5. difficult in breathing (once it attack your lungs)

How it spread?

The virus can spread through below process:
1. Hand to hand contact
2. Victim sneeze
3. Hope the virus can be alive for 8 days outside
4. Even if there is a heavy moist in air the virus can be alive and spread through air

How to avoid this?

Currently we have to stay in closed place, not to roam in open space also avoid going to places where the Corona positive victims have been spotted.

Expense Handler Application with advance technologies

Budget Planner  One of the application developed with Ionic 4 and Python-Flask.  Ionic 4 code:  https://github.com/logeshbuiltin/Expense...