Uncategorized

22
Jun

Remove Duplicate words and Sort the string

Question:
Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.

Program:

Explanation:

The string is accepted to s and split to a list using s.split. the list is then sorted and then joined to form the output string

Output:

 

21
Jun

Print multiples of 7 using yield

Question:
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.Use yield.

Program:

Explanation

The yield statement is used to define generators, replacing the return of a function to provide a result to its caller without destroying local variables. Unlike a function, where on each call it starts with new set of variables, a generator will resume the execution where it was left off.

Output:

20
Jun

Sort Student details

Question:

Write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers.

1: Sort based on name;

2: Then sort based on age;

3: Then sort by score.

The priority is that name > age > score.

We use itemgetter to enable multiple sort keys.

Program:

Explanation:

operator is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.

Output:

19
Jun

Python Program: Frequency of words

Question:
Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.

Program:

Explanation:

The sort() method sorts the elements of a given list in a specific order – Ascending or Descending.

Output:

 

18
Jun

Python Program to Sort string

Question:

Write a program to sort the string accepted from the user

Program:

Explanation:

The sort function returns the sorted data item.

Output:

17
Jun

Web Application Framework Flask

FLASK

Flask is a micro web framework written in Python

What is Web Framework?

Web Application Framework or simply Web Framework represents a collection of libraries and modules that enables a web application developer to write applications without having to bother about low-level details such as protocols, thread management etc.

Installation:

virtualenv which is a virtual Python environment builder, is used to help a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries.

The following command installs virtualenv

Once installed, a new virtual environment is created in a folder.

So now we have a virtual environment Test created in the FlaskTest folder

We now install Flask in this environment.

Now we have Flask installed in our system and we can import it in our projects.

As we have setup environment to work with Flask library, lets run a sample code to test Flask. Let’s create a python file HelloWorld.py and write the following code:

  • The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function.In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is opened in browser, the output of this function will be displayed.
  • The run() method of Flask class runs the application on the local development server.

All parameters for the run function are optional

host

Hostname to listen on. Defaults to 127.0.0.1 (localhost). You have to set it to ‘0.0.0.0’ to have server available externally

port

Default value is 5000

debug

Default value is false. If it is set to true, we get debug information

options

To be forwarded to underlying Werkzeug server.

Now we can execute the program and see its working. Execute the program using the command

You will get the following output.

Now if you open your browser and type in your localhost address that is, 127.0.0.1 along with the port number 5000

127.0.0.1:5000

You can see HELLO WORLD being printed on your browser.

You can use Ctrl+C to stop running the program.

Now if you need to set a specific URL other than the homepage of localhost, you can specify it in the route() function.

If you change the route function in the above code to:

And run the program again, you can see that opening the homepage of localhost renders no output, but instead if you add the URL specified in route function to the homepage address:

127.0.0.1:5000/hello

Now you can see your program being run…

Benefits of Flask:

  • Extensibility
  • Faster development
  • Easier to read, write and maintain

Have fun working with Flask library

16
Jun

Serverless Architecture: Zappa

Maintaining the backends or servers is always a part of the headache for the programer. And here walk in the solution, serverless Architectures.

What are Serverless architectures?

It refer to applications that significantly depend on third-party services (known as Backend as a Service or “BaaS”) or on custom code that’s run in ephemeral containers (Function as a Service or “FaaS”), the best known vendor host of which currently is AWS Lambda

Using an amazing library called Zappa, it is now easy to deploy in AWS Lambda.

What is Zappa?

Zappa is a system for running “serverless” Python web applications using AWS Lambda and AWS API Gateway. It handles all of the configuration and deployment automatically . Now it is easy to deploy an infinitely scalable application to the cloud with a just single command at the least possible cost often just a small fraction of the cost of a traditional web server.

Installation:

You can install zappa easily using

To install AWS command tools,

Let’s get started

So before we start using Zappa, let’s create a simple hello world website using flask and run it on our locla server

At a directory of your choice, save the following program as Prg.py

And run it on your local server using the following commands at your cmd

Now check out http://127.0.0.1.5000/. You can see a simple webpage like below.

Before we get our hands on some zappa, we need to ensure we have a valid AWS account.

You can create a AWS account by following the steps one by one here.

After creating an account, run the following command to configure your AWS account in your command line and and fill in the access key id, the secret access key and the default region..

Let’s configure Zappa now.

Run the follwing command in your project directory

This creates a file named zappa_settings.json inside our project directory with the following content.

Now deploy zappa using

And it’s done!!Thtat’s all it takes.!Just a single command!

Benefits of Zappa:

  • No more tedious web server configuration!
  • No more paying for 24/7 server uptime!
  • No more worrying about load balancing / scalability!
  • No more worrying about web server security!
  • Scalability since we can have as many responses processed in parallel as we need. Since AWS Lambda handles all of the requests
  • 100 function executions per second,and if you scale beyond that you only need to ask Amazon to raise your limit.
  • Inexpensive since we pay by the millisecond.. Not to mention the cost saving on not having to spend time on deployment, operations and maintenance!
  • Maintainability and Ease of Use
  • Easy to deploy.- deployed in a single command

Challenges of Zappa

  • Integration with the other services of the cloud platform is often said to raise an issue.

To learn more of zappa, which I am sure you would want to, check out these sites:

15
Jun

Python Matplotlib Library

Introduction:

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shell, the jupyter notebook, web application servers, and four graphical user interface toolkits.

Matplotlib tries to make easy things easy and hard things possible. You can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc., with just a few lines of code

For simple plotting the pyplot module provides a MATLAB-like interface, particularly when combined with IPython. For the power user, you have full control of line styles, font properties, axes properties, etc, via an object oriented interface or via a set of functions familiar to MATLAB users.

Installation:

In debian or Ubuntu systems, you can install matplotlib using

or use yum in fedora or Redhat:

For more installation guidelines, check out  https://matplotlib.org/users/installing.html

Let’s get started!

Let’s import  matplotlib

Let’s draw a simple graph

You obtain the following figure 1

How did python decide the x axis values?

If you provide a single list or array to the plot() command, matplotlib assumes it is a sequence of y values, and automatically generates the x values for you. Since python ranges start with 0, the default x vector has the same length as y but starts with 0. Hence the x data are [0,1,2,3].

Sample Question:

Draw the graph of y=x2

Program:

Output:

Now lets say you wanted red dots instead of lines of say a graph y=5*x

You get the following graph

MatPlotLib is not limited to just using list. Usually it is used in combination to numpy, and hence it has varied effective uses that makes analysing large amount of data easy.

Benefits of MatPlotlib:

  • Rapid prototyping
  • Research code
  • Large numerical or matrix computations
  • Data analysis
  • FREE when compared to the huge cost of MATLAB, it rules!

For more of matplotlib like drawing histograms or multiple graphs on a single plot etc, check out https://matplotlib.org/users/pyplot_tutorial.html

For more examples, check out https://matplotlib.org/examples/index.html

Checkout matplotlib cheatsheet at following link:

https://www.globalsqa.com/data-visualisation-in-python-matplotlib-cheat-sheet

Have fun with matplotlib!

14
Jun

Decimal to binary, octal and hexadecimal using inbuilt functions

Question:

Write a program to convert decimal to binary, octal and hexadecimal using inbuilt functions

Program:

Explanation:

A binary number is a number expressed in the binary numeral system or base-2 numeral system which represents numeric values using two different symbols: typically 0 (zero) and 1 (one). The base-2 system is a positional notation with a radix of 2.

The octal numeral system, or oct for short, is the base-8 number system, and uses the digits 0 to 7. Octal numerals can be made from binary numerals by grouping consecutive binary digits into groups of three (starting from the right). For example, the binary representation for decimal 74 is 1001010.

Hexadecimal (also base 16, or hex) is a positional numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 0–9 to represent values zero to nine, and A, B, C, D, E, F (or alternatively a, b, c, d, e, f) to represent values ten to fifteen.

Output:

13
Jun

nth Line of Pascal’s Triangle

Question:

Write a program to print the nth line of the Pascal’s Triangle

Program:

Explanation:

Pascal’s triangle is a triangle where each number is equal to the sum of the one or two numbers above it:

Output:

12
Jun

Print squares of numbers till 15 (lambda, map, list comprehension)

Question:

Write a single line of code to print squares of numbers till 15 using lambda, map and list comprehension

Program:

Explanation:

The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce().

The map function is the simplest one among Python built-ins used for functional programming. These tools apply functions to sequences and other iterables. The filter filters out items based on a test function which is a filter and apply functions to pairs of item and running result which is reduce.

So here the output of the anonymous function for squaring x when x ranges from 1 to 15 is recieved.

Output:

11
Jun

Program using Lambda Function

Question:

Consider variable  x. do the following operation. Add 2 to x and square the result. Again add 3 to x and square the result. Do using anonymous functions in python

Program:

Explanation:

The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce().

Output:

17
Aug

Python Django

What is Django?

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Python Django takes care of the repetitive work for you so that you don’t have to reinvent the wheel all over again.

 

Lets install Django

 

You can install Django using

For other ways of installation, visit this.

 

Let’s get started

Since this is the first time we are using Django there is some  initial setup to do. We need to auto generate some code that establishes  the Django project.

From the command line,

This will create a folder ‘mysite ‘ in your current directory. Do avoid python names of different functionalities as names for the folder. Ex. Django and test are not good choices since they create conflict on calling.

Also, with Django you do not put your code under your web server’s root directory. We always place it outside.

Let’s look at what startproject created:

mysite/

manage.py

mysite/

__init__.py

settings.py

urls.py

wsgi.py

 

These files are:

  • The outer mysite/ root directory is just a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.
  • py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.py in django-admin and manage.py.
  • The inner mysite/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. urls).
  • mysite/__init__.py: An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, read more about packages in the official Python docs.
  • mysite/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.
  • mysite/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in URL dispatcher.
  • mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.

 

Let’s verify whether our Django works.

You can safely ignore the warning for now.

 

Yipppe! We  have started the Django server! Let’s go see how it looks like.

 

Note This is only for studying. When it  comes to production setting, use Apache servers or similar.

By default the port is 8000. But you can change it using the command line. Say you want to change it to 8080

Full docs for the development server can be found in the runserver reference

 

But why Python Django?

  • It’s the best choice for quick web development
  • Transparent and clean code.
  • Fewer lines of code
  • Saves time and money on development
  • works well with high loads

Why not Django?

  1. Doesn’t support real-time applications
  2. Broad knowledge of the system is required
  3. ORM is very monolithic compared to SQLAlchemy.

 

To know how to edit and configure your webpages, check out https://docs.djangoproject.com/en/1.11/intro/tutorial01/

 

For more details visit,

https://www.djangoproject.com/

https://docs.djangoproject.com/en/1.11/#index-first-steps

https://www.djangoproject.com/start/

https://docs.djangoproject.com/en/1.11/

https://tutorial.djangogirls.org/en/django_start_project/

 

 

 

 

15
Aug

Python Execution Time

Question:

Write a program to print the running time of execution of “1+1” for 100 times. Use timeit() function to measure the running time.

Program:

Explanation:

Runtime or execution time is the time during which a program is running (executing), in contrast to other program lifecycle phases such as compile time, link time and load time.

The Timer function keeps track of the time

Output:

13
Aug

Best Python Books

Quora brings up a lot of interesting questions from all around the world. An avid Quora reader myself, I absolutely love reading through the different questions and answers there. One of the questions that interested me was “To learn a programming language is it better to learn from a book or on-line courses on the Internet?”

Well, that answer would totally depend on how you intend to learn. If you just want to learn the syntax then some online classes would be more than fine. If you really want to learn the real power behind the language, then an in-depth online course or better you could grab a good book on it. So to all those Python learners out there, here we have compiled a list of the best python books out there for you to learn.

BEGINNER:

1. Learning Python

Written by Mark Lutz and David Ascher, Learning Python offers a comprehensive in-depth introduction to the core of Python language for any beginner. It covers basic topics of both 2.7.X as well as 3.X in much detail. Some of the topics covered are Types & Operations, statements and Syntax, Functions and Generators, Modules and packages and much more. The beginner chapter, a Q&A session on Python and especially why Python is a major highlight. The end chapter quizzes enable the reader to challenge himself on the topics covered. Therefore leaning Python is one of the best choices to get started in Python.

2.Learn Python the Hard way

Written by Zed Shaw and offered for free as pdfs. Learn python the hard way will give beginners with a perfect insight to the very basics. You can also learn a variety of basic things such as how to use the terminal or the text editor. This book focuses on more on learning by doing than subject theory. therefore for an absolute beginner, Learn Python the hard way is a good choice.

3.A Byte of Python

Targeted for the absolute beginners in programming, author Swaroop C. H has kept it short and brief. With a user-friendly introduction, and focus on scripting simple but meaningful programs. A Byte of Python is the best choice for a beginner to learn Python briefly.

INTERMEDIATE:

1.Python Essential Reference

Written by David M. Beazley, this book is the perfect go to reference book on Python. All the new features such as new style classes, unification of types and classes, xmlrpclip, intertools, bz2 and optparse the new library modules are all covered in the updated edition of this book which makes it the most up-to date book on Python in the market. Written in a clear and organized manner, it gives you a detailed overview and an insight to the real power of programming. For someone with a bit of basics and want to learn Python, Python Essential Reference is a must read.

2.Python CookBook

Written by David Beazley and Brian K. Jones, Python CookBook is for readers with a basic knowledge of Python. Readers who want to learn more on concepts such as data structure, data encoding and processing, functions, algorithms, classes and objects, system administration, modern tools and idioms, generators and iteration methods would find Python CookBook to be the best guide. Each recipe contains code samples written and tested in python 3.3, so that you can get to using them right away. For someone who wants to be good on Python, Python CookBook is a must read.

3. Scientific Computing in Python

Authored by Claus FührerJan Erik SolemOlivier Verdie, Scientic Computing in Python3 demonstrates how to use Python for computing purposes such as in linear algebra, arrays, plotting, iterating, functions, polynomials, and much more. You get to explore numerical computing and mathematical libraries with SciPy and NumPy modules. Covering all major concepts and tools in scientific computing, this book is your go to guide and best reference for the same.

ADVANCED:

1.Black Hat python

Author Justin Seitz has aced how to teach security skills in python in his book Black Hat python. Targeted only for advanced Python users, this book comes as a huge boon for hackers and penetration testers to write better networking sniffers, infect virtual machines and manipulate packets and develop better hacker tools using python. A must have for any wanna be Hacker in Python.

2.Python for Data Analysis

Data Anaysis is all about collecting, cleaning, processing, crunching and studying raw data to bring out better insights on the subject matter. One of the best tools used in Python for the same is the pandas library and Wes Mckinney, one of the main authors of the pandas library has brought out a hands on book packed with practical case studies to guide you through understanding and implementing various tools and libraries used for the same. Easy to read and targeted for advanced Python users, Python for Data Analysis is your comprehensive guide to data analysis in Python.

3.Violent Python: A Cookbook For Hackers, Forensic Analysts, Penetration Testers And Security Engineers

TJ O’Connor in his book Violent Python: A Cookbook For Hackers, Forensic Analysts, Penetration Testers And Security Engineers teaches you concepts in security, hacking, forensics, tool integration for complicated protocols etc in the most simple and easy to understand style. You can also learn how to automate large network attacks, extract meta data, intercept and analyze network traffic, spoof wireless frames to attack wireless and bluetooth devices, data mine social media websites and so on. In terms of language and concepts, TJ O’Connor has aced how to teach the advanced topics in python in simple terms, bringing out the perfect go to book for the same.

Have more books to add-on to this list? Comment them below, we would love to hear from you.

Meanwhile, Have fun with Python!

11
Jul

Graphics in Python

Question:

Write a program implementing basic graphic functionalities such as draw,getMouse, circle etc

Program:

Explanation:

Graphic Functionalities are implemented in python by importing graphics.py

Output:

14
May

Linux SU Command

Linux SU Command


 

Usage of Linux SU Command:

This command is used to become another user in his own session. By default, user without username will login as super-user (i.e. Root).

Syntax:

Example1 : Login as “guest “user.

Example2 : Run specific command with another user privilege say govind.

-c option is used to return back to the command line of former user after execution is completed.

Example3 : Login as root user.

Or

Note: In Linux while giving password it won’t be visible because of security reason.


 







10
May

Linux Introduction

Linux Introduction


 

Some historical fact for Linux:

In 1991, in Helsinki, Linus Torvalds began a project that later became the Linux kernel. He wrote the program specifically for the hardware as he wanted to use the functions of his new PC with an 80386 processor.

What is Linux?

Linux is an Operating System.

What is Operating System?

Low level software that supports a computer’s primitive function such as scheduling tasks and controlling peripherals.

Types of Operating System:

  1. System Software: System software are those software which incorporate the programs that are dedicated to manage the computer itself, such as the operating system, file management utilities, and disk operating system.For instance : Linux , Windows etc
  1. Application Software: Application software or simply applications, are often called productivity programs or end-user programs because they enable the user to complete. Specific examples of application software incorporate Microsoft Office, Excel and Outlook, Google Chrome, Mozilla Firefox and Skype.
  1. Utilized Software: Utilized Software or a business application is any software or set of computer programs used by business users to perform variety of business functions.  For instance: Antivirus, McAfee etc.

Finally we conclude: Linux is Open Source Operating System. Specifically Linux is System Software providing an interface between user and computer.

Advantages of Linux:

  • Linux is very durable.
  • Linux is less susceptible to computer malware.
  • Linux as compared to other OS is fast and does not slow down over time.
  • Old desktop/Laptops can be given new life using Linux OS
  • Linux has variety of distributors so we have many varieties in Linux.
  • Because there are many distributors you can freely access this software.
  • It’s a superior method of upgrading software

Disadvantages of Linux:

  • Many windows programs will not run in Linux thus requires a change.
  • There is a smaller selection of peripheral hardware drivers for Linux.
  • People who are new to Linux requires to learn this skill thoroughly in order to use the Operating System.

Features of Linux OS:

  • There are two prompts in Linux
    • $ -> Local user prompt
    • # -> Admin user prompt or Root Prompt
  • Commands are followed by switches but it does not matter in which order we are using switch.
    Example: ls –lrt is same as ls –rtl same as ls -l -r -t
  • Linux is case sensitive so using upper case will give different output and lower case different.
  • Linux is Open source operating system.
  • Several program are running at same time.
  • Several users on same machine at same time

Wild characters in Linux

S. No. Wild Characters Description
1 * Asterisk find any number of characters in a filename, including none.
2 ? Question mark find any single character.
3 [] Square brackets enclose a set of characters, any one of which may match single character at that position.
4 Hyphen used within [ ] denotes a range of characters
5 ~ Tilde at the beginning of a word expands to the name of home directory.


 







12
Jun

Endorsement Framework

Endorsement Framework


 

Endorsement Framework:

  • Validation by a second user of an action taken on a “static data entity” (e.g. Bank) by a first user.
  • Provides functionality to generate endorsement events when a User performs an action on an endorsable entity.
  • Manages endorsement events while they await approval by a User.
  • Examples of static data entities for which endorsement can be setup:
    • Bank
    • Bank User Role
    • Business Calendar
    • Participant
    • Exchange condition
    • Products
  • Endorsement activation depends on a configuration file setup:
    • Either all entities or no entities require endorsement
    • Setup is done on the level of Bank Group
  • Actions that trigger the creation of an endorsement event are:
    • Creation of an entity
    • Update to an entity
    • Activation of an entity
    • Suspension of an entity
    • Deletion of an entity
  • For each endorsement audit records, capturing the modifications made by the User, are created.
  • The default behaviour for endorsement is to hide the modified details from the user until endorsement is done successfully.
  • Each instance of an endorse-able entity has an endorsement status:.
    • Pending endorsement for Modification
    • Pending endorsement for Deletion
    • Pending endorsement for Creation
    • Pending endorsement for Suspension
    • Pending endorsement for Activation
    • No Endorsement outstanding
  • Only a single active endorsement event can be pending against an entity.


 




 





12
Jun

Warehouse

Warehouse


 

Warehouse:

  • The processing of some transactions must be split in two steps.
  • This typically applies to Transactions that are received before the day they are executed.
    • Some validations are performed the day the Transaction is received, to make sure it is valid.
    • Extra validations are performed the day the Transaction is executed, for instance, to make sure the account still exists, or funds are available.
  • Based on the Exchange Timings computed by the router, and on the type of Transaction, the system determines if the Transaction must be held or not.