Oct 13, 2022

How to check the installed python version?

Check the python version your machine currently using by typing the following commands in your terminal.

bash-5.1$ python --version
Python 3.9.12

Check the python version via the python script.


 #import sys module in python sys module contain tuple of strings containing all the built in modules and constants
import sys

print(sys.version) #get the python version

Check which version you are using if you have multiple python versions installed.


You can check what version of python you are using by typing python in the terminal.

bash-5.1$ python
Python 3.9.12 (main, Apr  5 2022, 06:56:58) 
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Check the python interpreter location using the terminal.


To check the python interpreter location type command which python command. 

(base) bash-5.1$ which python
/home/username/anaconda3/bin/python

Oct 6, 2022

Graphing with Python using Matplotlib

 Introduction


Matplotlib is a graphing and plotting library that can be useful for creating different types of graphs and plots. Such as line charts, pie charts, scatter plots and 3D plots. Matplotlib can also be used for creating animated and interactive visualizations. It can also generate output in a variety of formats which includes PNG, SVG and PDF etc.

Installing Matplotlib


Matplotlib is not built into python. First, we need to install Matplotlib using the PIP package manager.
pip install matplotlib
If you are using Conda you can use the below command.
conda install matplotlib
You can refer to more about installation options on the Matplotlib installation page.

Plotting Simple Graph using Matplotlib


First, we need to import pyplot from Matplotlib library.  After that line, we give 2 python lists as arguments to plot() function specifying Y values and X values for the graph. then we set the label for both the x and y axis and the title. Finally, we call the show() function that displays our plot in a window.
#importing pyplot from matplotlib library
import matplotlib.pyplot as pyplot

# plot the graph using given values
pyplot.plot(
	[1, 2, 3, 4], # Y values
	[0.5, 1.0, 1.5, 2.0] # X values
)

# setting x and y axis labels
pyplot.xlabel('x-axis-label') 
pyplot.ylabel('y-axis-label')

# setting the title
pyplot.title('This is the title')

# display the chart in a window
pyplot.show()
Simple graph using matplotlib
 simple graph using matplotlib

Plotting Multiple Graphs Same Plane.


When plotting multiple graphs we need to add different styles, and colours, and more importantly, we need to add a legend to identify each graph clearly. In the below code sample, we add a legend using legend() method and pass arguments for legend background colour, location and title. we also add a descriptive label for each graph, change the colour and set the style of the one graph to a dashed line.
    
import matplotlib.pyplot as pyplot

# plot the graph 1
pyplot.plot(
	[0, 1, 2, 3], # Y values
	[1, 3, 5, 7], # X values
	label = 'y = 2x + 1', # set the label
	color = 'blue' # set the color
)

# plot the graph 2
pyplot.plot(
	[0, 1, 2, 3], # Y values
	[3, 6, 9, 12], # X values
	ls = '--', # set the line style
	label = 'y = 3x + 3', # set the label 
	color = '#995789' # set color color
)
# setting x and y axis labels
pyplot.xlabel('x-axis-label') 
pyplot.ylabel('y-axis-label')

# setting the title
pyplot.title('This is the title')

# setting the legend
pyplot.legend(
	facecolor = 'gray', # legend background
	title = 'legend', # legend title
	loc = 'upper left' # legend location
)

# setting the grid line
pyplot.grid(True)

# display the chart in a window
pyplot.show()
multiple graphs same plane
multiple graphs in the same plane

Plotting Bar Chart


We use the matplotlib pyplot bar() function to draw bar graphs. In the below examples, we pass the x-coordinates, heights of each bar,  bar width, and colours of each bar.

import matplotlib.pyplot as plt

languages= ['Rust', 'Python', 'Kotlin', 'Javascript', 'C#']
#setting values for bar labels
Salary = [76000, 60000, 55000, 56000, 61000]
# bar colors
bar_colors = ['blue', 'orange', 'cyan', 'brown', 'purple']

# setting the bar chart
plt.bar(
	languages, # x coordinates 
	Salary, # heights of the bars
	width = 0.7, # width of the bars
	color = bar_colors # bar colors
)

plt.xlabel('Language')
plt.ylabel('Salary')
plt.title('Median Developer Salary By Language')

plt.show()

bar plot matplotlib
Bar chart matplotlib




Horizontal Bar Charts


You can create the above graph horizontal by using barh() matplotlib pyplot function instead of bar() function. The below code demonstrates it.

import matplotlib.pyplot as plt

languages= ['Rust', 'Python', 'Kotlin', 'Javascript', 'C#']
#setting values for bar labels
Salary = [76000, 60000, 55000, 56000, 61000]
# bar colors
bar_colors = ['blue', 'orange', 'cyan', 'brown', 'purple']

# setting the bar chart
plt.barh(
	languages, # y coordinates 
	Salary, # width of the bars
	height = 0.7, # height of the bars
	color = bar_colors # bar colors
)

plt.xlabel('Salary')
plt.ylabel('Language')
plt.title('Median Developer Salary By Language')

plt.show()
horizontal bar graph using matplotlib
Horizontal bar graph matplotlib


Line Graphs using Matplotlib


In the below line graph example, we pass the argument 'bo-' to the function. in this argument 'bo-' first character 'b' indicates the colour of the line and second character 'o' indicates the marker of each point being plotted and the third character  '-' indicates the line style of the graph. In our case, it sets to a blue solid line with circle markers.

import matplotlib.pyplot as plt

month = ['January', 'February', 'March', 'April', 'May', 'June']
profit = [10000, 28000, 13400, 14000, 24400, 21000]

# setting titles and axes headings.
plt.title('Profit in year 2022')
plt.xlabel('Month')
plt.ylabel('Profit')

plt.plot(
	month, # setting x values 
	profit, # setting y values
	'bo-' # style of the graph(color, marker, line style)
)

plt.show()
Line graph using Matplotlib
Line Graph Matplotlib

Scatter plot


we use Matplotlib scatter() function to draw a scatter plot. below code sample demonstrates a scatter plot.

import matplotlib.pyplot as plt

iq = [
	[43, 45, 57, 20, 30, 75, 29, 60, 27, 80], # Age
	[22, 46, 43, 23, 45, 76, 44, 56, 41, 62] # IQ score
]

maths = [
	[29, 70, 20, 57, 30, 44, 60, 25, 32, 62], # Age
	[40, 23, 90, 55, 80, 39, 74, 65, 87, 48] # Maths score
]

# plot iq data
plt.scatter(
	x = iq[0], 
	y = iq[1],
	color='darkorange',
	marker='o',
	label='IQ'
)

# plot maths data
plt.scatter(
	x = maths[0], 
	y = maths[1],
	color='green',
	marker='^',
	label='Mathematics'
)

plt.xlabel('Age')
plt.ylabel('Score')
plt.title('Marks Two Subjects')
plt.legend()

plt.show()

Scatter plot using matplotlib
Scatter Plot

Pie chart


Matplotlib pyplot pie() function was used to draw below the pie chart. 

import matplotlib.pyplot as plt

language = ['Python', 'Rust', 'Java', 'C#', 'Javascript']
precentage = [33.50, 15.30, 22.30, 12.45, 16.45]

plt.pie(
	precentage,
	labels = language,
	autopct = '%1.2f%%', # format the numeric values in wedges
	counterclock = False, # wedges plot direction
	startangle = 90 # starting angle 
)

plt.title('Language Popularity')

plt.show()
Pie chart using matplotlib
Pie chart


Conclusion


In this article, we show you how to draw simple graphs using the Matplotlib library. Matplotlib is a very flexible option for creating graphs in python. 

References

Oct 2, 2022

Your First Rust Program - Hello World!

 Introduction 


Rust is a robust, reliable, productive language(check rust language benchmarks). The language has all the tools to write program efficiently and It also has a well written userfriendly documentation. In this tutorial, we will write our first Rust programme on a Linux machine and Introduce some syntax rules in Rust language.

Installing Rust in Linux.


We can install Rust in Linux easily. To download and install Rust you just need to copy and paste the below command and press enter key then it will download and install Rust into your machine using a tool called rustup. rustup is a command line tool for rust installer and version management.
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
terminal:
bash-5.1$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
info: downloading installer

Welcome to Rust!

This will download and install the official compiler for the Rust
programming language, and its package manager, Cargo.

Rustup metadata and toolchains will be installed into the Rustup
home directory, located at:

  /home/user/.rustup

This can be modified with the RUSTUP_HOME environment variable.

The Cargo home directory is located at:

  /home/user/.cargo

This can be modified with the CARGO_HOME environment variable.

The cargo, rustc, rustup and other commands will be added to
Cargo's bin directory, located at:

  /home/user/.cargo/bin

This path will then be added to your PATH environment variable by
modifying the profile files located at:

  /home/user/.profile
  /home/user/.bash_profile
  /home/user/.bashrc

You can uninstall at any time with rustup self uninstall and
these changes will be reverted.

Current installation options:


   default host triple: x86_64-unknown-linux-gnu
     default toolchain: stable (default)
               profile: default
  modify PATH variable: yes

1) Proceed with installation (default)
2) Customize installation
3) Cancel installation

when executing this command it will prompt you to enter installation options with a list of three options like below. 

terminal:
1) Proceed with installation (default)
2) Customize installation
3) Cancel installation
>1

info: profile set to 'default'
info: default host triple is x86_64-unknown-linux-gnu
info: syncing channel updates for 'stable-x86_64-unknown-linux-gnu'
info: latest update on 2022-09-22, rust version 1.64.0 (a55dd71d5 2022-09-19)
info: downloading component 'cargo'
  6.4 MiB /   6.4 MiB (100 %) 809.6 KiB/s in  7s ETA:  0s
info: downloading component 'clippy'
  2.8 MiB /   2.8 MiB (100 %) 1023.7 KiB/s in  3s ETA:  0s
info: downloading component 'rust-docs'
 18.8 MiB /  18.8 MiB (100 %)   1.1 MiB/s in 17s ETA:  0s
info: downloading component 'rust-std'
 27.4 MiB /  27.4 MiB (100 %)   1.2 MiB/s in 25s ETA:  0s 
info: downloading component 'rustc'
 54.2 MiB /  54.2 MiB (100 %)   1.2 MiB/s in  1m  1s ETA:  0s
info: downloading component 'rustfmt'
  4.3 MiB /   4.3 MiB (100 %)   1.2 MiB/s in  4s ETA:  0s
info: installing component 'cargo'
  6.4 MiB /   6.4 MiB (100 %)   6.4 MiB/s in  1s ETA:  0s
info: installing component 'clippy'
info: installing component 'rust-docs'
 18.8 MiB /  18.8 MiB (100 %) 424.0 KiB/s in 41s ETA:  0s
info: installing component 'rust-std'
 27.4 MiB /  27.4 MiB (100 %)   3.2 MiB/s in 11s ETA:  0s
  6 IO-ops /   6 IO-ops (100 %)   0 IOPS in 15s ETA: Unknown
info: installing component 'rustc'
 54.2 MiB /  54.2 MiB (100 %)   4.7 MiB/s in 19s ETA:  0s
info: installing component 'rustfmt'
info: default toolchain set to 'stable-x86_64-unknown-linux-gnu'

  stable-x86_64-unknown-linux-gnu installed - rustc 1.64.0 (a55dd71d5 2022-09-19)


Rust is installed now. Great!

To get started you may need to restart your current shell.
This would reload your PATH environment variable to include
Cargo's bin directory ($HOME/.cargo/bin).

To configure your current shell, run:
source "$HOME/.cargo/env"

choose the default option for your installation, and then it will download the necessary components and show you the message Rust is installed. After that enter the following command to set the environment variable.
source "$HOME/.cargo/env"
now type rustc --version and cargo --version commands on your terminal to check whether Rust has been installed successfully. In this commands rustc stands for Rust compiler and cargo is a Rust package manager.

Writing Your First Rust Program


For writing our program we use VS Code IDE. we assume you already installed the VS code. In vs code first, go to the extensions and install the rust-analyzer extension which includes the support for Rust programming language. Then create a file called hello_world.rs in a directory and write or paste the below code.
fn main() {
    println!("Hello world!");
}

Running Your Program


Rust source file compilation and execution steps
Rust compilation and execution steps

To run the program first you need to compile your program using the Rust compiler, to do that navigate to the directory which contains hello_world.rs then you need to run the below command in your terminal. 

bash-5.1$ rustc hello_world.rs

After the compilation process is over you can see a new file created in the directory named hello_world This is a binary file created by the compilation process. then you can execute the program in Linux by running the below command.

bash-5.1$ ./hello_world
Hello world!

Dissecting Your First Rust Program


in our hello world rust program first, you see an outer block of the program as fn main(){}. fn is the keyword used in Rust to declare a function and the main is the name of the function followed by pair of opening and closing parentheses and then pair of curly brackets which specify the main function body.

This main function is the starting point of our program. In Rust function main holds a special place like java and C++ Because It’s the first thing to run in a Rust program.

Inside the main function body, there is a single line println!("Hello world!"); that prints the output to the terminal  Hello world!.  In this line println! is called a Rust macro. We’ll discuss Rust macro in another lesson. We pass a string hello world! To Rust macro as the argument.
Rust statement end by typing a (;) semicolon at the end. In Rust, we indicate the end of the statements by typing a semicolon(;) 

Reference:

Sep 27, 2022

Pulling the important data out of html using BeautifulSoup

Introduction 

This tutorial introduces a small recipe to extract important textual content from a webpage using the Beautiful Soup web scrapper. 

What is important in a webpage and what is not important?


In an HTML page, there are some HTML tags we need to remove when extracting the data such as script tags, style tags, link tags, and some meta tags. The navbar and footer element content is also not much important. so we exclude those elements in our extraction process.

Importing Libraries


we import beautiful soup and python request module.
import requests
from bs4 import BeautifulSoup as bs

Get the webpage content


we use a simple webpage hosted on GitHub for this process. Click this link to look at the webpage. Let's get and load the webpage content to a BeautifulSoup object.
page = requests.get("https://gayan830.github.io/bs_tutorial/fruits_vegetables.html")
soup = bs(page.content)
print(soup.prettify())

output:
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="utf-8"/>
  <meta content="IE=edge" http-equiv="X-UA-Compatible"/>
  <meta content="Find out what nutrients are in most common Fruits and Vegetables." name="description"/>
  <meta content="Fruits, vegitable list, Fruit Vegetables vitamin" name="keywords"/>
  <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
  </script>
  <title>
   Fruits and Vegetables
  </title>
  <link crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" rel="stylesheet"/>
  <script crossorigin="anonymous" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.min.js">
  </script>
  <link href="https://fonts.googleapis.com" rel="preconnect"/>
  <link crossorigin="" href="https://fonts.gstatic.com" rel="preconnect"/>
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100&amp;display=swap" rel="stylesheet"/>
  <link href="style.css" rel="stylesheet"/>
  <style>
   body {
            width: 700px;
        }

        nav {
            background-color: #2596be;
            margin-bottom: 40px;
        }
  </style>
 </head>
 <body class="center">
  <header>
   <h1>
    Fruits and Vegetables
   </h1>
   <nav>
    <ul>
     <li>
      <a href="#home">
       Home
      </a>
     </li>
     <li>
      <a href="#foods">
       Fruits and Vegetables
      </a>
     </li>
     <li>
      <a href="#contact">
       Contact
      </a>
     </li>
     <li>
      <a href="#about">
       About
      </a>
     </li>
    </ul>
   </nav>
  </header>
  <main class="main-text">
   <h2>
    Fruits and Vegetables contain lot of Vitamins, minerals.
            Eating fresh food and Vegetables can protect you from cancer and heart diseases.
   </h2>
  </main>
  <section>
   <div class="container center">
    <figure>
     <img alt="Fruit and Vegetables" src="Fruit_and_Vegetables.jpg"/>
     <figcaption>
      Fruit and Vegetables
     </figcaption>
    </figure>
   </div>
   <div class="container center">
    <b>
     List of common Fruits
    </b>
    <ol id="veg-list">
     <li>
      Banana
     </li>
     <li>
      Mango
     </li>
     <li>
      Guava
     </li>
     <li>
      Jack Fruit
     </li>
     <li>
      Grapes
     </li>
    </ol>
   </div>
   <div class="container center">
    <b>
     List of common Vegetables
    </b>
    <ol id="fruit-list">
     <li>
      Carrot
     </li>
     <li>
      Beans
     </li>
     <li>
      Chille
     </li>
     <li>
      Potatoes
     </li>
     <li>
      Tomatoes
     </li>
    </ol>
   </div>
  </section>
  <section>
   <h1>
    Fruits Vitamins
   </h1>
   <table class="center">
    <thead>
     <tr>
      <th colspan="2">
       Fruits Vitamin Table
      </th>
     </tr>
     <tr>
      <th>
       Name
      </th>
      <th>
       Vitamins and minerals
      </th>
     </tr>
    </thead>
    <tbody>
     <tr>
      <td>
       Banana
      </td>
      <td>
       Potassium, Vitamin B6, Vitamin C
      </td>
     </tr>
     <tr>
      <td>
       Mango
      </td>
      <td>
       Iron, Calcium, Vitamin C, Vitamin B6, Vitamin A
      </td>
     </tr>
     <tr>
      <td>
       Guava
      </td>
      <td>
       Calcium, Vitamin C, Vitamin D, Vitamin A
      </td>
     </tr>
    </tbody>
   </table>
  </section>
  <hr/>
  <footer>
   <p>
    <b>
     Contact the author of this page:
    </b>
   </p>
   <aside>
    <address>
     <a href="123@xyz.com">
      123@xyz.com
     </a>
     <br/>
     <a href="tel:+000000000">
      (000) 000-0000
     </a>
    </address>
   </aside>
   <aside>
    <address>
     <b>
      Address:
     </b>
     <br/>
     addres line 1
     <br/>
     addres line 2
     <br/>
     City, State
    </address>
   </aside>
  </footer>
 </body>
</html>

prettify() method format the HTML markup when outputting.

Remove unwanted tags and get the values of some of the important attributes 


Some of the meta tag attributes contain relevant information about the page such as keywords and descriptions. For example, the following meta tags have important information. so we have to extract the values of the content attribute of the below meta tags and alt attribute value from the image.
<meta content="Find out what nutrients are in most common Fruits and Vegetables." name="description"/>
<meta content="Fruits, vegitable list, Fruit Vegetables vitamin" name="keywords"/>
<img alt="Fruit and Vegetables" src="Fruit_and_Vegetables.jpg"/>

In the below code snippet clean up all the types of tags specified in the find_all method list argument while extracting the necessary information. Beautifulsoup find_all() method loops through all the HTML elements in the Beautifulsoup object and the decompose() method removes HTML elements from the Beautifulsoup object. we store all the extracted information in the webpage_content list.
webpage_content = []
for element in soup.find_all(['meta', 'img', 'script','link','style', 'nav', 'footer', 'form', 'svg]):
  # extracting meta tag descriptions and keywords
  if element.get('name') in ['keywords', 'description']:
    webpage_content.append(element.get('content'))
  # getting alt text from images
  elif element.get('alt'):
    webpage_content.append(element.get('alt'))
  element.decompose() #remove element
After extracting the information from the above-specified type of tags let's look at the webpage_content list: 
print(webpage_content)
output:

['Find out what nutrients are in most common Fruits and Vegetables.',
 'Fruits, vegitable list, Fruit Vegetables vitamin',
 'Fruit and Vegetables']

Extracting remaining content


we extract the content from the remaining tags using the following code snippet:
for string in soup.stripped_strings:
  webpage_content.append(string)
Now our webpage_content list has all the essential text content extracted from the webpage.
print(webpage_content)
output:
['Find out what nutrients are in most common Fruits and Vegetables.',
 'Fruits, vegitable list, Fruit Vegetables vitamin',
 'Fruit and Vegetables',
 'Fruits and Vegetables',
 'Fruits and Vegetables',
 'Fruits and Vegetables contain lot of Vitamins, minerals.\n            Eating fresh food and Vegetables can protect you from cancer and heart diseases.',
 'Fruit and Vegetables',
 'List of common Fruits',
 'Banana',
 'Mango',
 'Guava',
 'Jack Fruit',
 'Grapes',
 'List of common Vegetables',
 'Carrot',
 'Beans',
 'Chille',
 'Potatoes',
 'Tomatoes',
 'Fruits Vitamins',
 'Fruits Vitamin Table',
 'Name',
 'Vitamins and minerals',
 'Banana',
 'Potassium, Vitamin B6, Vitamin C',
 'Mango',
 'Iron, Calcium, Vitamin C, Vitamin B6, Vitamin A',
 'Guava',
 'Calcium, Vitamin C, Vitamin D, Vitamin A',
 'Fruits and Vegetables',
 'Fruits and Vegetables',
 'Fruits and Vegetables contain lot of Vitamins, minerals.\n            Eating fresh food and Vegetables can protect you from cancer and heart diseases.',
 'Fruit and Vegetables',
 'List of common Fruits',
 'Banana',
 'Mango',
 'Guava',
 'Jack Fruit',
 'Grapes',
 'List of common Vegetables',
 'Carrot',
 'Beans',
 'Chille',
 'Potatoes',
 'Tomatoes',
 'Fruits Vitamins',
 'Fruits Vitamin Table',
 'Name',
 'Vitamins and minerals',
 'Banana',
 'Potassium, Vitamin B6, Vitamin C',
 'Mango',
 'Iron, Calcium, Vitamin C, Vitamin B6, Vitamin A',
 'Guava',
 'Calcium, Vitamin C, Vitamin D, Vitamin A',
 'Fruits and Vegetables',
 'Fruits and Vegetables',
 'Fruits and Vegetables contain lot of Vitamins, minerals.\n            Eating fresh food and Vegetables can protect you from cancer and heart diseases.',
 'Fruit and Vegetables',
 'List of common Fruits',
 'Banana',
 'Mango',
 'Guava',
 'Jack Fruit',
 'Grapes',
 'List of common Vegetables',
 'Carrot',
 'Beans',
 'Chille',
 'Potatoes',
 'Tomatoes',
 'Fruits Vitamins',
 'Fruits Vitamin Table',
 'Name',
 'Vitamins and minerals',
 'Banana',
 'Potassium, Vitamin B6, Vitamin C',
 'Mango',
 'Iron, Calcium, Vitamin C, Vitamin B6, Vitamin A',
 'Guava',
 'Calcium, Vitamin C, Vitamin D, Vitamin A',
 'Fruits and Vegetables',
 'Fruits and Vegetables',
 'Fruits and Vegetables contain lot of Vitamins, minerals.\n            Eating fresh food and Vegetables can protect you from cancer and heart diseases.',
 'Fruit and Vegetables',
 'List of common Fruits',
 'Banana',
 'Mango',
 'Guava',
 'Jack Fruit',
 'Grapes',
 'List of common Vegetables',
 'Carrot',
 'Beans',
 'Chille',
 'Potatoes',
 'Tomatoes',
 'Fruits Vitamins',
 'Fruits Vitamin Table',
 'Name',
 'Vitamins and minerals',
 'Banana',
 'Potassium, Vitamin B6, Vitamin C',
 'Mango',
 'Iron, Calcium, Vitamin C, Vitamin B6, Vitamin A',
 'Guava',
 'Calcium, Vitamin C, Vitamin D, Vitamin A']

Conclusion

Extracting the important text content using Beautiful Soup is an easy task. Before scraping the webpage it's important to remove unnecessary content from the webpage. scraping is a popular method for getting data. However, scraping website content without proper permission is unethical and sometimes illegal. so we need to have proper permission before scraping any website. 

reference