Learning python3

Photo by Hitesh Choudhary on Unsplash

I started learning python back in 2017 and since then I am still learning it and using it and almost everyday I write some python code. Python is an interpreter based language, you can write the code directly in the interpreter or in a separate file(extension is .py) and run it.

Using the interpreter

Fire up your terminal and type python3. And you will see something like this below code snippet.

$ python3
Python 3.6.8 (default, Jan 14 2019, 11:02:34) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Now we are going to print “Hello World!” using the interpreter.

>>> print("Hello World!")
Hello World!

Using a source file

Create a file called helloWorld.py and enter the following text:

print("Hello World!")

We can run this file by python3 command.

$ python3 helloWorld.py 
Hello World!

Whitespaces and indentation

Language like c/c++ use pair of curly brackets to divide different identifiers. In the python it uses indentation for that. The whitespaces at the beginning of the line is known as indentation. If you give wrong whitespaces then it will give you errors. Python use 4 whitespaces for a single indentation. Below there is an example.

>>> a = "Aniruddha"
>>>  b = "Basak"
  File "<stdin>", line 1
    b = "Basak"
    ^
IndentationError: unexpected indent

Comments

Comment is a line in python that will start with # and the interpreter of python will just ignores the lines. You can write anything here to describe your code.

>>> # This is a comment
>>> # The next line will multiply two numbers
>>> a = 12 * 34
>>> print(a) # Printing the value of a

If your description is long then it is recommended that you use multiline comments. There is two options for that.

# This is option 1
# Multiline comment
"""
This is option 2
Multiline comment
"""

Modules

The reason why python is loved by so many people is it gives so many modules to work on almost everything you can imagine. Basically modules are python files that contains different functions classes and variable that you can reuse.

>>> import os
>>> print(os.name)
posix

Keywords and Identifiers

Below the following identifiers are main keywords of python. They must exactly types as it is.

False      class      finally    is         return
None       continue   for        lambda     try
True       def        from       nonlocal   while
and        del        global     not        with
as         elif       if         or         yield
assert     else       import     pass
break      except     in         raise

Variables and Datatypes

In python we don’t specify the type of the variable while declaring it.If we declare a = 1 then a will become an integer type and if we define b = "Hii" then b will become an string type variable.

>>> a = "Hi "
>>> b = "how you doing?"
>>> a + b
'Hi how you doing?'

Taking input from keyboard

We can take input from users while executing the program. We can use the input() function given by python for this. Let’s see an example of taking input from user.

number = int(input("Enter number: "))
print(number)

Here is the result –

$ python3 input.py 
Enter number: 25
25

Operators and Expressions

Python language supports the following types of operators.

  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators

Arithmetic operator:

It is used to perform common mathematical operations.

>>> a = 2
>>> b = 4
>>> a + b
6
>>> a - b
-2
>>> a * b
8
>>> a / b
0.5
>>> a % b
2
>>> a ** b
16
>>> a // b
0

Comparison operator:

It is used for comparing two values and returns either True or False.

>>> a = 2
>>> b = 4
>>> a == b
False
>>> a != b
True
>>> a > b
False
>>> a < b
True
>>> a >= b
False
>>> a <= b
True

Assignment operator:

This operator is used to assign values to some variable.

>>> x = 5
>>> x += 5
>>> x -= 5
>>> x *= 5
>>> x /= 5

Logical operators:

Logical operators are the and, or, not operators.

>>> x = True
>>> y = False
>>> print('x and y is ', x and y)
x and y is  False
>>> print('x or y is', x or y)
x or y is True
>>> print('not x is', not x)
not x is False

Bitwise operators:

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60 and b = 13. Now in binary format they will be as follows –

>>> a = 60
>>> b = 30
>>> a & b
28
>>> a | b
62
>>> a ^ b
34
>>> ~a
-61
>>> a >> 2
15
>>> a << 2
240

Membership Operators:

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below −

a = 'Hello World'
print('H' in a)

Identity Operator:

Identity operators compare the memory locations of two objects. There are two Identity operators explained below −

>>> a = 5
>>> b = 5
>>> c = 10
>>> print(a is not b)
False
>>> print(a is b)
True
>>> print(a is c)
False

How To Create a Pull Request on GitHub

What is pull request?

Pull request let you tell others about changes you’ve pushed to a github repository. Once a pull request is sent, the maintainers of that project can review the changes and discuss for modifications, and even push commits if necessary and once everything is ok they can accept that pull request and all your changes will be merged with the upstream project. Below there are set of instructions that will describe how to create pull request.

Photo by Brina Blum on Unsplash

Fork the Repository

The first step should be creating a copy of a repository. You can fork a repository on GitHub by navigating with your browser to the GitHub URL of the open-source project you would like to contribute to.

GitHub repository URL contains both the username of the owner of the repository and the name of the repository. For example, below github url aniruddha2000 is the username and the hello-world is the name of the repository.

https://github.com/aniruddha2000/hello-world

When you go to that url on your browser you will see a “Fork” button on your upper right hand side of the page.

Click the fork button and start the forking process.

Once the process is done, your browser will go to a screen similar to the repository image above, except that at the top you will see your username before the repository name, and in the URL you will see your username before the repository name.

https://github.com/your-username/hello-world

Clone the forked repository

Now you have to clone the repository in your local machine that you have forked. In order to do that you have to use git clone command. Execute below command in your terminal.

$ git clone https://github.com/your-username/hello-world.git

Create a New Branch

Whenever you work on a collaborative project you and other programmers contribute to the repository will have different ideas for new features or fixes. So it is recommended that you should always work on a new branch and make pull request to the upstream project from that branch and this process will help you to work nicely will all contributors. Execute below command to create a new branch.

$ git checkout -b new-branch
Switched to branch 'new-branch'

Make changes locally

Once you have modified all necessary files you should add them git add and commit by git commit -m. After committing you have to push the changes in the ‘new-branch’. Execute below command for this operation.

$ git push origin new-branch

Create Pull Request

Now you can create a pull request to the upstream project. You can navigate to your forked repository and click the “New pull request”.

Once you have chosen, for example, the master branch of the original repository on the left-hand side, and the new-branch of your forked repository of the right-hand side, you should see a screen that looks like this:

Add the necessary comment and then click the “Create pull request” button. Now go the pull request section of the upstream repository and you will see your pull request is there.

Thank you 🙂

Send emails through ansible

Recently I was watching this video and got to know about `mail` attribute in ansible and we can send emails through it and I gave it a try and finally after some hacks I sent an email from my one account to another.

Here below code I have written to send the email –

---
- hosts: webservers
  tasks:
  - name: Sending an e-mail using Gmail SMTP servers
    mail:
      host: smtp.gmail.com
      port: 587
      username: your@email.com
      password: yourPassword
      to: Aniruddha Basak <some@email.com>
      subject: Ansible check email
      body: I am using {{ ansible_facts['os_family'] }}.
    delegate_to: localhost

Above we are using gmail SMTP server. In case you are using 2FA of google then you have to add a device password for that and write the password in the password field.

Understanding various git commands

If you are working on a project then you have to maintain it properly and that’s why we use git as our VCS(version control system) and github or gitlab as our cloud service where we store all our code remotely. Below there will be some basic git command and their description.

Photo by Yancy Min on Unsplash

Initializing git repository

When you first start a project using git you have to initialize the git in side your project directory.

$ cd my_folder
$ git init
Initialized empty git repository in my_folder/.git/

Cloning repository

Suppose if you want to work on a project that is already on github so in order to contribute to that project first you have to clone that repo to your local machine. Here git clone comes to help you in that.

$ git clone ssh://git@github.com/[username]/[repository-name].git

Status of a repository

If you want to check the status of a repository like which files have added and deleted and modified then you have to execute the below commands. It will also show the tracked and untracked files of the repository.

$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout –– <file>..." to discard changes in working directory)
modified: tasks.txt
no changes added to commit (use "git add" and/or "git commit –a")

Adding files to staging area

If you add a new file to your repository or you have modified some files then before committing you have to move those files to staging area. Here you have certain cases like you want to add files to staging area by one by on or you want to add all files to staging or you want to add all tracked files to staging area except untracked files. Below commands for all cases.

$ #Add specific file to staging area
$ git add [file_name]
$
$ #Add all new and changed file to staging area
$ git add -A
$
$ #Add all tracked files to staging area
$ git add -u

Committing changes

After adding files to staging area you have to commit those changes. Basically you are saving those changes as commits. Every commits has it’s commit message and unique commit ID.

$ git commit -m [commit message]

Removing files or folders

Suppose you have to delete some files from index which is not needed then you have to tell git to remove those and here git rm comes to help you.

$ git rm -r [file-name]

Branching

It is recommended that you should not change directly in the master branch. When you are experimenting something or adding any feature then always you should create a new branch and make changes there. So bellow command is showing you how to create a new branch.

$ git checkout -b <your_branch>
Switched to a new branch "your_branch"

Now type git branch to see all local branches. And if you want to see all the branches include local and remote then you have to type git branch -a. Now if you again want to come back to your master branch then you have to type below command.

$ git checkout master
Switched to branch 'master'

If you want to switch to the last checkout branch then type git checkout -. Now sometimes you have to delete a specific branch so in this case you have two branches one is in your local machine and one is in your server.

$ #delete your local branch
$ git branch -d <your_local_branch>
Deleted branch <your_local_branch> (was 4335a0a).
$
$ #delete your remote branch
$ git push origin --delete <your_remote_branch>

Merging

When you have finished your all features and changes in your branch it is now ok to merge with master branch. In order to merge any branch with master branch there we execute the below command.

$ git checkout master
Switched to branch 'master'
$ git merge <your_branch>

`Basically in merging there is two branches one is source branch and another is target branch and in the above scenario the master branch is target branch and other is source branch. If you want to do the above operation in one line then you can do –

git merge [target branch]

Stashing

Use git stash when you want to record the current state of the working directory and the index, but want to go back to a clean working directory. The command saves your local modifications away and reverts the working directory to match the HEAD commit.
And use git stash clear to remove all stashed entries.

Sharing & updating project

After all committing stuff it is the time to push the changed to the remote server or otherwise if your local computer get disturbed you will loose all changes. Use the below command –

$ git push origin <your_branch>

Sometimes you are just working on a specific branch for a long time and it is possible that git will remember the branch name for you. Use git push -u origin <your_branch> to make git remember your branch name. After this you just have to execute the command
git push and it will automatically push the commits in the remembered branch.

Now suppose you have two laptops and from both you are maintaining the project so it is very necessary for you that you keep updated the project in the both laptops. So git pull will update the local repository to the latest commits.

So git has local repository and remote repository so when ever we push something it will go to the remote repository. So it is very important to tell git that what is our remote repository. In order to add the remote repository we execute the bellow commands –

$ git remote add origin ssh://git@github.com/[username]/[repository-name].git

Sometimes we clone the repository in the https format url or we have set the remote url in https format but we are planning to switch to ssh. Then we will execute the below command and everything is changed . Below we are switching to ssh remote url.

$ git remote set-url origin ssh://git@github.com/[username]/[repository-name].git

Inspection & Comparison

If you wand to see commit history then I already published a blog about git log you should checkout. Now if you want to see what you have changed after the last commit then do
git diff. It is good to see the changes you have made in the feature branch before merging to the target branch. Execute the below command for that –

$ git diff [source branch] [target branch]

Filter your commits through git log

The purpose of any version control system is to record changes to your code. This gives you the power to go back into your project history and see who contributed what and when and figure out where bugs were introduced. But, having all of this history available is useless if you don’t know how to navigate it. That’s where the git log command comes in. Below various git log options that will be very helpful while maintaining a big project:

Photo by Brina Blum on Unsplash

Oneline

The --oneline option will give you a output of commits to a single line. By default it will show you the commit ID and first line of the commit message.

aniruddha ~/Desktop/foobar master 
$ git log --oneline 
505a2c6 (HEAD -> master) Add the file hellomars.txt and update helloworld.txt
fb8c32d First commit

By amount

The most basic filter that git gives us the limit the number of commits. You can pass -<n> after the git log.

$ git log -3

By author

When you are looking for commits created by a specific person then --author="name" will be the option you have to use. This will return all commits matches with the author name you have given.

$ git log --author="Aniruddha"

You can use regular expressions to search for commits. In the below example the following commands searches for commits by either Aniruddha or Sayan.

$ git log --author="Aniruddha\|Sayan"

By commit message

To filter the commits by their commit message, use the --grep flag. This works like the --author flag discussed in the above but it matches against the commit message instead of the author.

$ git log --grep="First"

By file

Some times you are only interested in changes that happened to a particular file. To see the history related to a file you just have to to pass the file path. Below we want to see the commits related to foo.py.

$ git log -- foo.py

See changed file names

If you want to see the files you have changed according to your git commit then execute the below git command.

$ git log --name-only

Thank you 🙂

Authenticate github using ssh

SSH is a tool by which we can create a secure connection between the client and server. Basically it is an asymmetric type encryption that creates two key one is public and one is private. Public key can be distributed publicly and it is used for encrypt the data and the private key have to be kept secret for decrypting the data. Below commands will create the ssh keys:

$ ssh-keygen -t rsa -C "your_email@example.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ani/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/ani/.ssh/id_rsa.
Your public key has been saved in /home/ani/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Up6KjbnEV4Hgfo75YM393QdQsK3Z0aTNBz0DoirrW+c ylo@klar
The key's randomart image is:
+---[RSA 2048]----+
|    .      ..oo..|
|   . . .  . .o.X.|
|    . . o.  ..+ B|
|   .   o.o  .+ ..|
|    ..o.S   o..  |
|   . %o=      .  |
|    @.B...     . |
|   o.=. o. . .  .|
|    .oo  E. . .. |
+----[SHA256]-----+

Now you have created a pair of keys and you have to add the public key in the github. Follow below instructions after doing the above the task –

  1. Go to your github page and open settings.
  2. Now click the SSH and GPG keys.
  3. Now click New SSH key.
  4. In the title field add a relevant title fr your key. Like if you are using Linux on your PC the give a title like “Linux PC”.
  5. Then paste your public key in the box.
  6. Then click Add SSH key.
  7. If it ask for your password then confirm your password.

Thank you 🙂

Approve all your blog comment using javascript magic

I usually check and reply all my blog comments on friday night and approve the spam comments. Last friday I was checking my spam comments and saw that there was almost more than 70 comments and I thought approving all comments will be a hectic process and I was thinking of a process that I can do it with one click. Then I came up with the solution of writing a JavaScript script to approve all comments.

Here below the script –

var x = document.getElementsByClassName('comment__action comment__action-approve');
for (var i = 0; i < x.length; i++) {
    x[i].click();
}

The above code actually select the approve button and gives me an array then x[i].click(); this will click each approve button one by one.

Thank you 🙂