lastnames/d>fist names/td> | emsil adessStr>
-lastname<>fist nameemal adress <>
last name | fist name | emall address |
<>
Each of our input fields becomes an output field sandwiched in between and | . In this
‘case, we uses phrases like last name, first name and email address to show where real data would
‘be inserted, The other HTML elements like have tobe printed as they're shown in this‘Your final program should open two files: name_add.csv and addressbook:html. Your program
should write the intial HTML material (up co the first ) tothe output file. It should then ead
the CSV records, writing a complete address line between to . After it finishes reading
nd writing names and addresses, it has to write the lst of the HTML file, from to
.CHAPTER 6
DISCOVER VARIABLES, STRINGS, INTEGERS, AND
MORE TO DESIGN CONVERSATIONAL PROGRAMS
Before we tat to write the program, we need to generate a token for our bot. The oken is
needed to access the Telegram API, and install the necessary dependencies.
1, Create a new bot in BotFather
If you want to make a bot in Telegram, you have to “register” your bot frst before using it.
‘When we “register” our bot, we will et the token to access the Telegram API.
Go tothe BotFather (if you open it in desktop, make sure you have the Telegram app) den
create new bot by sending the /newbot command. Follow the steps unl you get the username
ad token for your bot. You can go to your bot by accessing this URL:
Iatpsuitelegram.me/YOUR_BOT_USERNAME and your token should looks like thisTOAABO3I:AAEICZ**eereneees
2. Install the library
Since weare going to use a library for this tutorial, instal it using this command,
pip3 install python-telegram-bot
If the library is successfully installed then we are good to go.
‘Write the program
Let's make our firs bot. This bot should return a dog image when we send the bop command.
‘To be able to do this, we can use the public API from RandomDog to help us generate random
dog images.
“The workflow of our bot is as simple as this
access the API-> get the image URL -> send the image
1 Import the libraries
First, import all the Mbraries we need.
from telegram ext import Updater, CommandHandler
impor req uests
import re
2. Access the APL and ge the image URL.
Let's create a function to get the URL. Using there quests library, we can access the APL and
‘get the jon data
‘contents = req uestsget(htps:/irandom.dog/woot json’) json()
‘You can check the json data by accessing that URL: htps:/random.dog/woof,json in yourbrowser. You will see something ike this on your screen:
‘(ur”s"hups:trandom.dog/***** JPG")
Get the image URL since we need that parameter 1 be able to send the Image.
image_l = contents ur)
‘Wrap this code into a function called get_uel
def get_urld:
contents = req uests. gets: random. dog/woot json) json)
vl = contents[ut)
recurn url
3, Send the image
‘To send a messagefimage we need two parameters, the image URL and the recipient's ID—his
‘can be group ID oF user ID.
‘We can get the image URL. by calling our get_url0 function,
url= get_url
Got the recipient's ID using this code:
chat id = update,messagechat_id
[After we get the image URL. and the recipient's ID, it’s time to send the message, which is an
Image.
bot.send_photo(chat_id=chat_ photo=url)‘Wrap that code in a function called bop , and make sure your code looks lke this
def bop(bot, update):
vu = get_urlo
chat_id = update:messagechat_id
bot send_photo(chat_id=chat_d, photo=url)
4, Main program
Lastly, create another function called main to run our program. Don't forget to change
YOUR_TOKEN with the token that we generated earlier in this tutorial.
def main:
‘updater = Updater(' YOUR TOKEN)
dp = updater dispatcher
5:
se:
selX train, :]= np random.random(d) + meansty,
selfYtain{i] =2.0* y-1sell X_test = mp.zeros((N, ))
for in vange(N
if mp.random.randnQ) > 5:
else:
yoo
selfX_test(i,:] = np.andom.random(d) + meansfy, :]
self testi] = 2.0 *y-1
lass LogisticRegression():
© A simple logistic regression model with L2 regularization (zero-mean
Gaussian priors on parameters).
defi
t_ (elf, x tain=
lone, y_train-None, x_test=None, y_test=None,4 Set L2 regularization strength
selfalpha = alpha
1 Set the data
self.set_data(x train, y_train, x test, y_test)
4 Initialize parameters to zero, fr lack of a better choice
p.zeres(self.x_tainshapel 1)
def negative_lik(elf, betas):
return -1 *sel.uk(betas)
def like, betas)"™ Likelihood ofthe data under the current settings of parameters.
4 Data likelihood
for {in range(self.n):
1 log(sigmoie(selfy_train(i]*
padorbetas, slf.x_saini:)))
# Prior likelihood
fork in range(t, selfx train shape( 1
= (selfalpha /2.0)* self.betas{k]**2def train(self):
*" Define the gradient and hand it off to a scipy gradient-based
‘optimizer
4 Define the derivative ofthe likelihood with respect to beta_k.
+ Need to multiply by -I because we will be minimizing
{dB _ke= lambda B, ke: np.sum({-self.alpha * Btk] +
sel,y train) * sel£x tain, k] *
sigmoid(sel.y-train{i]*
pdot(, sex tai)
for ‘in range(self.n)) * -1
+# The fll gradient is just an array of componentwise derivatives«dB = lambda B : npartay((aB_K(B, k)
for cin range(selfx train shapel1)))
# Optimize
self.bet
imin_bfgs(self.negative_lik, self.betas,fprime=dB)
def set_data(self, x_tain, y_train, x test, y_tes)
‘Take data that’s already been generated."
self train
train
selfy trai
selfx_test = x test
selfy_test= y_test
self = y-train shape( 0)def training reconstruction(selt):
p_yl = np.zeros(self.n)
for {in range(selt.n:
p_ylll] = sigmotd(np dotself. beta, selfx_tranli))
return py
def test_predictionsself):
yl = np.zeros(self.n)
for iin range(self.n):
yl = sigmoid(ap douse betas sex testi)
return p_yldef plot_training_reconstruction(sel)
plotinp.arange(sel.n),.5 +5 * selty_teain, "bo.
plot(np.arange(selfn, self.raining_reconstuction(), x’)
ylim((-1, 1.1),
def plot_test_predictions(sl)
plog(np.arange(self.n), 5 +5 sey test, yo')
plow(np.arange(selfn), self.est_predictions), 1x)
slim((-1, 1.10,
if __ame__=="_main_’
{rom pylab import *
‘Create 20 dimensional data set with 25 points ~ this will be
4 susceptible to overfittngdata
yntheticClassifierData(25, 20)
1# Run fora variety of regularization strengths
alphas = [0,.001, 01, .1]
for j, ain enumerate(alphas)
‘# Create a new learner, but use the same data for each run
logisticRegression(x_trel
x test=data.X_tst, y_te
alpha=a)
print "Initial likelihood
print rstk(ibetas)Train the model
Iearain)
4 Display execution info
print "Final betas:
print Inbetas
print "Final lk
print rsik(icbetas)
4 Plot the results
subplot(len(alphas), 2, 2+] + 1)
Ir-plot_training_reconstruction()
‘ylabel("Alpha=%s" 96 a)sile("Training set reconstructions")
subplot(len(alphas), 2, 24) +2)
Irplot_test_predictions()
tile("Test set predictions")
show)CHAPTER 12
CAN PYTHON WEB APPLICATIONS BE TESTED USING
SELENIUM?
Python is
currently more popular than other modem programming languages. The interpreted and object-
oriented programming language is also hugely popular among developers across the world as a
strong server side scripting language. As Python enables developers to express concepts by
‘writing less and readable code, it becomes easier for programmers to reduce the development
time significantly. At the same time, the developers also have option to use popular web
frameworks like Django to create high-performing and complex Python web applications
rapidly. However, the developers stll need 10 assess the look, feel and performance of the
Python web application thoroughly to boost its popularity and profitability
‘While testing the intemet applications the developers have option to choose from a number of
browser automation tools like PAMIE, PyXPCOM, windmill, SST and Selenium. But most
‘developers prefer Selenium to other frameworks to tes thelr Python web applications efficiently
Unlike other web browser automation tools, Selenium allows testing professionals to write test
Scripts in a number of languages including Python, Ct, Java, PHP, Ruby and Python. So the
testers have option to test the Python web application by writing test scripts in Python. There are
also a number of reasons why developers across the world use Selenium for testing Python webapplications
‘Why QA Professionals Prefer Using Selenium for Testing Python Web Applications?
‘Supports Major Operating Systems and Web Browsers
At present, Selenium supports all major operating systems and web browsers. The framework
‘curently supports both Microsoft Windows and Linux. Likewise, itis compatible with most
popular web browsers like Firefox, Chrome, Internet Explorer, Safari and Opera. The
‘compatibility makes it easier for QA professionals to test the Python web application tools across
multiple platforms and web browsers without writing separate codes, or using addi
automation tools. Selenium further comes with features to generate and execute test scripts
nal test.
automatically across different web browsers and systems simultaneously
Allows Users to Create Complete Test Automation Suite
‘The Selenium testing professionals can create a complete test automation suite by combining
Selenium WebDriver and Selenium IDE. They can use Selenium WebDriver to quickly create
browser-based regression automation suites and tests Further, they can scale and distribute the
test crip across multiple environments. The Selenium IDE, on the other hand, makes it easier
for testers to create bug-reproducton scripts rapidly. Thus, the QA professionals can combine
listinct parts of Selenium to create a complete est automation too, without req ulring any
licensed or third-party APIs.EXECUTES TESTS FASTER.
‘To identify all bugs and performance issues in the web applications, QA professionals have to
perform tests repeatedly and freq wently. But the testers also have to complete all tests within a
limited amount of time, Selenium allows testing professionals to take advantage of cloud-based
testing grids to boost the performance of thelr test uns. In alton to optimizing the test
Infrastructure, these tools further enable testes to run parallel tess. Thus, it becomes easier for
the testers to execute tests quickly and repeatedly. The testers also have option to choose from
several open source cloud-based functional testing grids to avoid increased project overheads.
Requires Basic HTML Concepts
Selenium supports a number of modern programming languages. But while testing a Python web
application, i re q wires only basic HTML concepts. HTML is used for describing a web page,
whereas individual HTML tags represent document content. Thus, HTTML tags decide how the
‘content is appears on the web browsers. Selenium divides the HTML. elements or attributes into
three distinct categories, i, single, group and customized. I locates single elements by their id,
link or link text, whereas the group elements are identified based on combined values or index
property, So it becomes easier for testers to find out the location of the defector bug. The feature
makes it easier for them to identify the exact bugs and performance issues q uickly.
Helps Testers to Address Maintainability Issues
{Im addition to creating and executing test scripts quickly, QA professionals are also re q uired to
‘maintain the test cases effectively. Selenium helps testers co overcome maintainability issues by
structuring the automated test code using a pater called page objects. The page objects focuses
‘onthe structure of HTML code of a particular web page instead of checking how the services are
implemented. Thus, testers can take advantage of page objects to locate the code easily, navigate
between vatious web pages smoothly, and making changes only once. As most Selenium code
ill be located inside page objects, the testers can easily increase the code base without adding,
fresh Selenium code.
Provides Selenium Python API
‘As noted earlier, Python supports several programming languages including Python. So thetesters have option to write test scripts in Python. Also, they can use Selenium Python APL to
‘write acceptance and functional tests by accessing Selenium WebDrivers like common, suppor,
chrome, Firefox, ie, emote and phantomjs, The most recent version of the API further supports
‘multiple versions of Python including 3.2, 3.3, 3.4 and 2.7, I can further be accessed simply by
downloading and installing the Selenium Python bindings. Thus, an organization can leverage
the skills of existing Python programmers to perform acceptance and functional testing
efficiently
‘Works wih several esting frameworks
‘While testing the Python web application with Selenium, QA professionals have option to use a
numberof tes framework. At present, the portable web browser automation framework works
‘with Pytest,PyUnit, unittest, and robot framework. As a part of Python 2.1 standard library,
PyUnit enables testers to write tests easily, and execute multiple tests in text or GUL mode.
Likewise, pytest comes with a number of features that help testers to write beter programs. So
the QA professional can take advantage ofthese test frameworks to ensure thatthe Python web
application delivers flawless user experience across many web browsers.
Python isan open source programming language, whereas Selenium is an open source web
‘browser automation tool. Thus, organizations can use the programming language and web testing
tool together to bring down the project costs. However, the combination will further enable them
{est the application across major web browsers within a stipulated amount of time,CHAPTER 13
PERL AND PYTHON
Both Python and Perl are mature, open source, general purpose, high level, and interpreted
programming languages. Bur de usage stalstcs posted on various websites depict ”hat Python Is
ccarently more popu
bby switching form Perl co Python.
than Perl, Hence, a software developer can enhance his carver prospects
A beginner can further learn and use Python programming language without potting extra time
and effort. However, vou must not switch to a new programming language just because its
popalarty and usage. You must keepin mind the major differences between the reo
programming languages while deciding about migrating from Pet! to Python,
Points You Must Keep in Mind while Switching, from Perl ta Python
1) Design Goal
Perl was originally designed as a scripting language to simplify report processing capabilities.
Hence, it comes with built-in text processing capability. On the other hand, Python was designed
inigally asa bobby programming language. But it was designed with features to help‘programmers build applications with concise, readable and reusable code. The two programming
languages still diffe in the category of features and performance.
2) Symtax Rules
‘The syntax rules of both Python and Perl are influenced by several other programming,
languages. For instance, Perl borrows features from a number of programming languages
including C, shell script, sed, AWK and Lisp. Likewise, Python implements functional
‘rogramming features in a manner similar to Lisp. But Python is hugely popular among modem
programming languages due to its simple syntax rules. In addition to being easy to use, the
‘syntax rules of Python further enable programmers to except many concepts with less and
readable code.
3) Family of Languages
Perl belongs o a family of high-level programming languages that includes Perl and Perl 6
“The versions 5 and 6 of Perl are compatible with each other. A developer can easily migrate from
Perl Sto Perl 6 without putting extra time and effort. The programmers have option to choose
from two distinct versions of Python - Python 2 and Python 2. But the wo versions of Python are
not compatible with each other. Hence, a programmer has to choose from two distinct versions
‘of the programming language
4) Ways to Achieve Same Results
Python enables programmers to express concepts without writing longer lines of code, But it
req uites programmers to accomplish asks or achieve results in a specific and single way. ON
the other hand, Per! enable programmers to accomplish a single task or achieve the same results
ina number of ways. Hence, many programmers find Per! 10 be more flexible than Python. But
the multiple ways to achieve the same result often make the code written in Perl messy and
application difficult to maintain,
'5) Web Scripting Language
Perl was originally designed as a UNIX scripting language. Many developers use Perl asa
‘scripting language to avail ts builtin text processing capabilities. However, there are many web
{developers who complain that Perl is slower than other widely used scripting language. Python is
also used widely by programmers for web application development. But it lacks built-in webdevelopment capabilities. Hence, developers have to avail various frameworks and tools to write
Python efficiently and rapidly.
‘web application
{6) Web Application Frameworks
Most developers nowadays aval the tools and features provided by various
neworks to build
‘web applications efficiently and rapidly. Perl web programmers have option to choose from an
array of frameworks including Catalyst, Dancer, Mojoliciou, Poet, Imerchange,Jfty, and
Gantry, Likewise, the web developers also have option to use a numberof Python web
frameworks including Django, Flask, Pyramid, Botle and Cherrypy. However, the number of
Pytlion web framework is much higher than the number of Peel web frameworks,
7) Usage
‘As mentioned earlier, both Python and Perl are general-purpose programt
ing languages. Hence,
‘each programming language is used for developing a variety of software applications. Pet is,
used widely for graphic and network programming, system administration, and development of
finance and biometic applications. But Python comes with a robust standard library simplifies
artificial
g Python for development of advanced and
‘web application developmen, scientific computing, big data solution development, a
ielligence tasks. Hence, developers prefer
mission-critical software applications.
£8) Performance and Speed
‘A number of studies have shown than Python is slower than other programming languages like
Java and C++. Hence, developers frequently explore ways to enhance the execution speed of
Python code. Some developers even replace default Python runtime
their own custom
runtime to make the Python applications run faster. Many programmers even find Perl to be
faster than Python. Many web developers use Petl asa scripting language make the web
applications faster, and deliver enhanced user experience
9) Structured Data Analysis
At present, big data is one of the hottest trends in software development. Many enterprises
nowadays build custom applications for collecting, storing, and analyzing huge amount of
structured and unstructured data. The PDL provided by Pet! enables developers to analyze big,data. The built-in text processing capability of Perl further simplifies and speeds up analysis of,
huge amount of structured data, But Python is used widely by programmers for data analysis
The developers further take advantage of robust Python libraries like Numpy t process and,
analyze huge volumes of data in a faster and more efficient way.
10) JVM Interoperability
At present, Java is one of the programming languages that are used widely for development of
desktop, web, and mobile applications. In comparison to Per, Python Interoperates with Java
Virtual Machine (IVM) seamlessly and efficiently. Hence, the developers have option to write
Python code than runs smoothly on JVM, while taking advantage of robust Java APIs and
objects. The interoperability helps programmers to build application by targeting the popular
Java platform, while writing code in Python instead of Java.
11) Advanced Object Oriented Programming
Both Per! and Python are object-oriented programming languages. But Python implements
advanced object oriented programming languages in a better way than Perl. While writing code
ln Perl, programmers still need to use packages instead of classes. Python programmers can write
high quality and modular code by using classes and abjects. Many developers find i difficult to
keep the code simple and readable while writing object oriented code in Perl. But Pet! makes it
easier for programmers to accomplish a variety of tasks simply by using one lines on the
command line.
12) Text Processing Capability
Unlike Python, Perl was designed with built-in ext processing capabilites. Hence, many
programmers prefer using Perl for report generation, Perl Further makes it easier for
programmers to perform regex and string comparison operations like matching, replacement, and
substitution. Ic further does notre q wire developers to write additional code to perform exception
handling and 1/0 operations. Hence, many programmers prefer Per to Python while building
applications that need to process te
3 data or generate reports
(On the whole, a large number of modem software developers prefer Python to Perl. But there are
a number of programming languages - Java, C, C++ and CH which are currently more popular
| |