Thursday, 27 April 2017

Password Generator and Validation

Password Generator and Validation

Today, we will be writing code for password generator or creator, and also a validation of the given password.

We will be creating three different programs today.

1st : Password Generator


Code:

#using random function to take characters from given set, though it can generate week passwords also.

import random

s = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"

#make sure output password is 8 character long


passlen = 8
p =  "".join(random.sample(s,passlen ))
print p

2nd : Password Generator

Using inbuilt libraries




Code:
import string
import random

#creating a function to create a password using string and random function.


def pw_gen(size, chars=string.ascii_letters + string.digits + string.punctuation):
    return ''.join(random.choice(chars) for _ in range(size))
print(pw_gen(int(input('How many characters in your password?:\t'))))

3rd : Password validation

This forces, to put below specification in given password
  • At least 8 character long.
  • Have at least 1 digit, 1 lower, 1 capital letter.
  • Have at least 1 special character in it
Code:

import re

def validate():
    while True:
        password = raw_input("Enter a password: ")
        if len(password) < 8:
            print("Make sure your password is at lest 8 letters")
        elif re.search('[0-9]',password) is None:
            print("Make sure your password has a number in it")
        elif re.search('[A-Z]',password) is None: 
            print("Make sure your password has a capital letter in it")
        elif re.search('[@#$%^&+=]',password) is None: 
            print("Make sure your password has a Special character in it")
        else:
            print("Strong password")
            break

validate()

Saturday, 22 April 2017

Caesar Cipher

--- Caesar Cipher---

Hi,
    Today we will be implementing Caesar cipher algorithm for encryption. Caesar cipher is one of the basic encryption technique. that uses a make shift number to interchange the position of text. 

for E.g. 

if the shift value is 2,
A --> C, B--> D, c-->e, d-->f and so on...
and if shift value is -2
A --> Y, B--> Z, c-->a, d-->b and so on...


Code:


#getting input from use for text to encrypt and shift value

text = raw_input("Please enter the text to be converted..!! : \n");
change=input("Enter the shift number for encryption: \n")

#using list to save the conversion, for end result

new_text = []

#using Caesar cipher algo, we are converting upper and lower case alphabets separately, and ignoring others


for x in text:
        if x.islower():
                new_text.append(chr((ord(x) + change - 97) %26  + 97))
        elif x.isupper():
                new_text.append(chr((ord(x) + change - 65) % 26 + 65))
        else:
                new_text.append(x)

print "Text : \t\t"+text

#using join inbuilt function for text join from list

print "New Text :\t"+''.join(new_text)



E.g:
Please enter the text to be converted..!! :
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Enter the shift number for encryption:
2
Text :          THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
New Text :      VJG SWKEM DTQYP HQZ LWORU QXGT VJG NCBA FQI

We can use to decipher the encrypted code  by same algorithm. we need the shift value or key by which it was encrypted earlier. for above example we use shift of 2. so, for decryption we need to use same algorithm with reverse shift value, for this case -2.

E.g:
Please enter the text to be converted..!! :
VJG SWKEM DTQYP HQZ LWORU QXGT VJG NCBA FQI
Enter the shift number for encryption:
-2
Text :          VJG SWKEM DTQYP HQZ LWORU QXGT VJG NCBA FQI
New Text :      THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG



Friday, 21 April 2017

MasterMind

--- MasterMind --- 

Number guessing game

The player enters 4 digit number, and the computer tells the player how many(but not which) of the 4 digits are correct.

Number changes randomly every time, when new game starts.

E.g.

Guess the number in few tries as possible

Enter the number :      1234
Enter the number :      4567
*
Enter the number :      7533
***
Enter the number :      7593
you used 25 chances, to guess.


CODE

#imports required for validation, i was using older python version for print, i used below import

from __future__ import print_function
import re
from random import randint

print ("Guess the number in few tries as possible\n");
number=[]
inp=str(randint(0000,9999))
for x in inp:
        number.append(x)

check = True
count=0

#loop until guess is correct

while check == True:
        guess=[]
        input=raw_input("\nEnter the number :\t");
        count+=1

#validation if the input is numeric 
        if not re.match("^[0-9]*$", input):
                print ("\nError! Only numeric value allowed")
                continue

# validation if the number is 4 digit longs or not
        if len(input) != 4:
                print ("\nError! Must be 4 digit long number")
                continue

        for x in input:
                guess.append(x)

        if guess == number:
                check = False
                break

        for i in range(4):
                if number[i] == guess[i]:
                        print ("*", end='')

print ("\nYou used {0} chances, to guess".format(count))


Monday, 9 May 2016

Live score from Cricbuzz


In this script we are going to get live update from any website, i am using cricbuzz just for the purpose of this tutorial.

Requirements:
requests           - Install Requests
BeautifulSoup - Install bs4 (search for installation instruction on page) -Web scrapping tools for python
Notify - To send update on desktop notification.

Use below script and save as .py file, call script with while loop and u will get update on timely manner.


###Script###

import requests
from bs4 import BeautifulSoup
from gi.repository import Notify
Notify.init("Test")
url="http://www.cricbuzz.com/cricket-match/live-scores"
r = requests.get(url)
soup = BeautifulSoup(r.content)
title = soup.find_all("div", {"class": "cb-col-50 cb-col cb-schdl"})
score = soup.find_all("div", {"class": "cb-col-50 cb-col"})
i=0
for x, y in zip(title, score):
if i >= 3:
break;
print y.contents[0].text
msg = x.contents[0].text.encode('ascii', 'ignore') + " " +y.contents[0].text.encode('ascii', 'ignore')
print msg
notice=Notify.Notification.new("Live-Scores", msg)
notice.show()
i+=1             



Monday, 18 April 2016

Basic Mp3 Player in Python

You'll need to test for below modules if present in your linux machines
  1. Python - Just type python and you'll get something like below if you already have python installed.

     2. gst-launch-0.10 - Try below command and you will hear a Bell ringing, if not try to install it.
               gst-launch-0.10 audiotestsrc ! audioconvert ! audioresample ! pulsesink

     3. Python curses module - Try import curses in python.


Snapshot of the player:






Code:

#list all songs from the given directory    
def song_input():
    songs = (subprocess.check_output(["locate","-e","-L","*.mp3"]).split('\n'))
    return songs

#Play arugmented passed song using Popen and gst-launch-0.10
def player(Song):

    #Check if any process is running song, if yes then kills it before starting new one
    if processes:
        processes.pop().terminate()
    song="location="+Song
    song_process = subprocess.Popen(["gst-launch-0.10","-q", "filesrc", song," ! mad ! audioconvert ! alsasink"])
    processes.append(song_process)
    return

#curses used to select song from terminal based UI, then sends request to play to played function
def song_selection():
    screen.border()
    screen.nodelay(0)
    curses.noecho()
    selection = -1
    song_name = []
    count = 0
    song_name = song_input()
    while selection < 0:
        screen.clear()
        screen.addstr(dims[0]/2-2,dims[1]/2-len(song_name[count - 2].split('/')[-1])/2,(song_name[count - 2]).split('/')[-1])
        screen.addstr(dims[0]/2-1,dims[1]/2-len(song_name[count - 1].split('/')[-1])/2,(song_name[count - 1]).split('/')[-1])
        screen.addstr(dims[0]/2  ,dims[1]/2-len(song_name[count    ].split('/')[-1])/2,(song_name[count    ].split('/')[-1]),curses.A_BOLD|curses.A_REVERSE)
        screen.addstr(dims[0]/2+1,dims[1]/2-len(song_name[(count + 1) % len(song_name)].split('/')[-1])/2,(song_name[(count + 1) % len(song_name)]).split('/')[-1])
        screen.addstr(dims[0]/2+2,dims[1]/2-len(song_name[(count + 2) % len(song_name)].split('/')[-1])/2,(song_name[(count + 2) % len(song_name)]).split('/')[-1])
        screen.refresh()
        action = screen.getch()
        if action == curses.KEY_UP:
            count = (count - 1) % (len(song_name)-1)
        elif action == curses.KEY_DOWN:
            count = (count + 1) % (len(song_name)-1)
        elif action == ord('\n'):
                player(song_name[count])
        else:
            return


#Script starts Here
#required imports

import curses
import subprocess

processes=[]

screen = curses.initscr()
dims = screen.getmaxyx()
screen.keypad(1)
curses.curs_set(0)
song_selection()
while processes:
    processes.pop().terminate()
curses.endwin()

Linux - Where to start

I wanted to try Linux too, when i show my show my friends doing great things on it. But what always stopped me the lack of knowledge regarding Linux, and tons of choice to choose from.

Today i will be sharing few tips so that it will be easier for for you. I think below points will be enough to start with Linux and its wonder full world.

  • How to install Linux
  • Which Distro to choose from
  • Installed it, now what ?
  • How to be Linux expert

How to Install Linux

Earlier back in my days, when i started using linux, the biggest challenge for me was, how to install it. We were needed to created the partition manually, and coming from windows it was a tedious task to do it from command-line. 
          Over the years, developer tackled it, and now many of Distribution's use simple GUI based installer, which is more easier than installing Windows i guess.
There are thousands of tutorial over the net, on how to install it. just google it. (Will be posting in future for same)
But the best part is live CD. where you can test a Linux distro from a live CD or USB. One of the best option to start with, use can use linux os without installing it with your system and others.

Which Distro to choose from

Most annoying part for someone who wants to start with this wonderful thing. There are lots of Distribution's out there with lot's of Desktop Environment and lot and lots of forks for all kind of softwares in it. This becomes pain when needed to decide what to choose. Below is the list i thought appropriate for all kind of linux users.
  1. Newcomers - Ubuntu, Mint, Elementry OS, Chalet OS and other Ubuntu based derivatives. 
    • Why Ubuntu - It is more user friendly GUI based OS than others, and you will easily find solutions for it over the net, if you face any kind of problem
  2. Low end PC - For low specs PC or net books, i would go with Linux lite, elementry OS, Lubuntu.
I would suggest more, but i think this article will be more useful.
https://www.linux.com/news/best-linux-distros-2016

 Alternate to install it to your computer, is to either install it to Virtual Box's or to install cygwin.

Installed it, now what ?

First thing would be to get familiar with command line as well as you are familiar with you GUI. There are inbuilt commands for most of the things you want to do. Try using them or take a tour of beginners tutorial from educational sites, like TutorailsPoint and EDX .

How to be Linux expert

The hardest part is to start, once you get familiar with it, you have many options to decide on which direction you want to go. 

How to take Data EXTRACT of a database table in a text file using shell script

In this tutorial , you will learn how we can take extract of a database table and save it in a text file by using Shell Script in Linux.

sqlplus dbuser/dbpasswd@dbinstance<< EOF
set pagesize 0;
set trims on;
set linesize 32767;
set feedback 0;
set colsep ",";
set timing off;
set serveroutput on;
set autocommit off;
set heading on;
spool fileName.txt

select COLUMN_1||','||COLUMN_2||','||COLUMN_3 from MYDBTABLE;

spool off;

exit;

EOF

Save above code in a file (i.e DBEXTRACT.sh) , and run that file. Make sure to provide  execute permission on the file. 
(For Execute Permission, run command chmod 777  DBEXTRACT.sh )

For explanation of these SET statement : please check Oracle docs. I will explain these above set statements in my next post.