Full Circle Magazine 'Programming in Python' Series. Volume 9.
Full Circle Magazine 'Programming in Python' Series. Volume 9.
PROGRAM
IN PYTHON
Volume Nine
Six
Parts 43
39-5
2-338
Full Circle Magazine is neither ailiated, with nor endorsed by, Canonical Ltd.
Full Circle Magazine Specials
About Full Circle
Full Circle is a free, Find Us
independent, magazine Website:
dedicated to the Ubuntu http://www.fullcirclemagazine.org/
family of Linux operating
systems. Each month, it Forums:
contains helpful how-to http://ubuntuforums.org/
articles and reader- forumdisplay.php?f=270
submitted stories. Welcome to another 'single-topic special' IRC: #fullcirclemagazine on
Full Circle also features a In response to reader requests, we are assembling the chat.freenode.net
companion podcast, the Full content of some of our serialised articles into dedicated Editorial Team
Circle Podcast which covers
editions. Editor: Ronnie Tucker
the magazine, along with
other news of interest. For now, this is a straight reprint of the series (aka: RonnieTucker)
'Programming in Python', Parts 49-53 from issues #79 ronnie@fullcirclemagazine.org
Please note: this Special through #84, allowing peerless Python professor Gregg Webmaster: Rob Keria
Edition is provided with Walters #83 as time of for good behaviour. (aka: admin / linuxgeekery-
absolutely no warranty admin@fullcirclemagazine.org
Please bear in mind the original publication date; current
whatsoever; neither the Editing & Proofreading
contributors nor Full Circle versions of hardware and software may difer from those
Mike Kennedy, Lucas Westermann,
Magazine accept any illustrated, so check your hardware and software versions Gord Campbell, Robert Orsino,
responsibility or liability for before attempting to emulate the tutorials in these special Josh Hertel, Bert Jerred
loss or damage resulting from editions. You may have later versions of software installed
readers choosing to apply this Our thanks go to Canonical and the
or available in your distributions' repositories.
content to theirs or others many translation teams around the
computers and equipment. Enjoy! world.
The articles contained in this magazine are released under the Creative Commons Attribution-Share Alike 3.0
Unported license. This means you can adapt, copy, distribute and transmit the articles but only under the following conditions:
You must attribute the work to the original author in some way (at least a name, email or URL) and to this magazine by name ('full circle magazine') and
the URL www.fullcirclemagazine.org (but not attribute the article(s) in any way that suggests that they endorse you or your use of the work). If you alter,
transform, or build upon this work, you must distribute the resulting work under the same, similar or a compatible license.
Full Circle Magazine is entirely independent of Canonical, the sponsor of Ubuntu projects and the views and opinions in the magazine should in
no way be assumed to have Canonical endorsement.
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\
astr = “The time has come” x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABC
DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`1bcd2fgh3jklmn4pqrst5vwxyz{|}~\x7f\x80\x81\x82\x83
astr.translate(None,’aeiou’) \x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97
\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab
will return: \xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf
\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3
\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7
“Th tm hs cm” \xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb
\xfc\xfd\xfe\xff'
full circle magazine #80 8 contents ^
HOWTO - PYTHON PT50
matter, he would use a cipher that that Caesar used. For simplicity from string import maketrans
would shift all the letters of the sake, let’s only use uppercase #----------------------
alphabet three characters to the characters (shown top right). intab = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
outtab = "DEFGHIJKLMNOPQRSTUVWXYZABC"
right. So, using todays english EncTrantab = maketrans(intab,outtab) #Encode
alphabet: Everything in the above code is DecTrantab = maketrans(outtab,intab) #Decode
ABCDEFGHIJKLMNOPQRSTUVWXYZabc
defghijklmnopqrstuvwxyz
pretty much what we’ve covered instring = raw_input("Enter the plaintext string -> ")
EncString = instring.translate(EncTrantab)
above or in earlier Python articles, DecString = EncString.translate(DecTrantab)
becomes: but I’ll go over it quickly. print("Encoded string is - %s" % EncString)
DEFGHIJKLMNOPQRSTUVWXYZabcdef print("Decoded string is - %s" % DecString)
ghijklmnopqrstuvwxyzABC The first two lines are the in and
out strings. We’ve just shifted the between the “Z” and the “A” in the COME
While this seems very simple by characters and wrapped around to outtab string. This helps keep the Encoded string is -
WKHCWLPHCKDVCFRPH
today’s standards, when I was a create the out string. The next two actual words from being too
school kid, we used this all the time lines create a table for encoding obvious in the encrypted string. And to test the decode side of
to send messages to each other. and one for decoding. Line 5 The next change is where we ask if things:
We used a different index into the prompts the user to enter a string the user wants to encode or Encode or Decode (E or D) -> D
string to start the encryption to encode. We then encode that decode the string. Finally we added Enter the string ->
WKHCWLPHCKDVCFRPH
string, the logic behind it was the string (EncString) in the next line. an if statement to control what we Decoded string is - THE TIME HAS
same. To decode it, we simply use the print (shown bottom right). COME
us to enter a string of “plain text” the same with a few exceptions. if which == "E":
and get back an encrypted string First, we have added a space to the print("Encoded string is - %s" % EncString)
using the same side right method end of the intab string and in else:
print("Decoded string is - %s" % DecString)
Python-Quick-Syntax- time ago, so I thought I'd share the Assume we have a database
Reference/dp/1 430264780) as well information with you. It is the that has multiple tables in it. One
as others. It is, as the title suggests, CREATE TABLE AS SELECT of the tables is named "study" that
a syntax reference that will help command, which allows us to pull a holds data from a receiving
those of us who program in other query from one table (or joined operation. There are six fields
languages as well as Python, to tables) and create another table on which are shown below.
remember how a certain command the fly. The general syntax is:
works and the requirements for One of the datasets that we will
that command. Please help a poor CREATE TABLE [IF NOT EXISTS]
{New Table Name} AS SELECT need to produce from this raw data
old programmer make a living by {query} is a grouping of package count and
buying the book, if you can.
B
the number of days within the
efore we get started on this The part in square brackets (IF study that quantity of packages
month’s actual python subject, Now on to bigger and better NOT EXISTS) is totally optional, came in on, assuming that the days
let me toot my own horn for just a things. which will create the table only if it are weekdays (Monday thru Friday)
minute. In late December and early doesn’t exist already. The part in and that the day is not a holiday,
January, my first book on Python While I was working on my curly brackets, however, is not. The since holidays have less than
was published by Apress. It is latest book for Apress, I first is the new table name and the normal number of packages. Our
named "The Python Quick Syntax rediscovered a SQL command that I second is the query that you want query is shown above.
Reference", and is available from a didn't discuss when we were to use to pull data and create the
number of places. You can find it working with SQL databases a long new table. This then provides us with data
on the Apress site
(http://www.apress.com/9781 4302 pkID - Integer, Primary Key, AutoIncrement
64781 ), Springer.com DOM - Integer - Day of the month (1-31)
(http://www.springer.com/comput DOW - Integer - Day of week (1-7 (Sunday = 1, Monday = 2, etc))
pkgs - Integer - Number of packages received that day
er/book/978-1 -4302-6478-1 ) and DayName - TEXT - "Sunday","Monday", etc
Amazon Holiday - Integer 0 or 1 (Is this day considered a holiday or not) 1 means yes
(http://www.amazon.com/The-
full circle magazine #82 11 contents ^
HOWTO - PYTHON PT52
that would look something like
this: CREATE TABLE IF NOT EXISTS weekdays AS
SELECT pkgs, Count(DOW) as CountOfDOW FROM study
WHERE (Holiday <> 1)
pkgs CountOfDow AND DayName in ("Monday","Tuesday","Wednesday","Thursday","Friday")
31 1 GROUP BY pkgs
32 2
33 1
... can begin our code. Assuming we def OpenDB():
48 3
already have the study table global connection
global cursor
created and populated, we can use
So the data is showing that Python to then create our new
connection = apsw.Connection("labpackagestudy.db3")
cursor = connection.cursor()
during the study of 65 days, only table in the main database. Just as
one weekday had 31 packages but an FYI, I am using the APSW SQLite
3 weekdays had 48 packages and calculations. on the “study” table.
library to do the database work.
so on. Similar queries could be
created that would cover holidays As you can see, we want to Now we create three more
We, of course, have to open a create a second cursor, so that we columns (shown below) within the
and weekends. connection (right) and create a don’t run any risk of the first cursor weekdays table named
cursor to the SQLite database. We having data we need to maintain. “probability”, “lower” and “upper”.
While having the data simply as have covered this in a number of
a returned dataset from the query, We will be using it in the final part We do this by using the “ALTER
past articles. of the code. We then drop the TABLE” SQL command.
we might want to do further
analysis on the data, so we want to table if it exists and run our query
Now we need to create
put the resulting data from the the routine that will actually addcolquery = 'ALTER TABLE weekdays ADD COLUMN probability REAL'
query into a table. That's why we create the table with the cursor.execute(addcolquery)
would create a table from the returned dataset from the
addcolquery = 'ALTER TABLE weekdays ADD COLUMN lower REAL'
cursor.execute(addcolquery)
query. So in the following example, query, shown below, then addcolquery = 'ALTER TABLE weekdays ADD COLUMN upper REAL'
shown above right, we create a alter it and run some
cursor.execute(addcolquery)
table named "weekdays" using the
same query we just showed above. def DoWeekDays():
# Create a second cursor for updating the new table
Now anytime we need the data cursor2 = connection.cursor()
for that weekday result set, we can q1 = "DROP TABLE IF EXISTS weekdays"
cursor.execute(q1)
just run a query on the weekdays query = '''CREATE TABLE IF NOT EXISTS weekdays AS SELECT pkgs,
table. Count(DOW) as CountOfDOW FROM study WHERE (Holiday <> 1)
AND DayName in
("Monday","Tuesday","Wednesday","Thursday","Friday")
Once we know what we need, GROUP BY pkgs'''
and have tested the query, then we cursor.execute(query)
routine. One thing you might a random number rather than the Offset = csum - 68
if debug == 1:
notice here is that in the first ‘if ‘D’ (68). If you do that, set a seed in print("Offset is %d" % Offset)
debug’ statement of this function, I the code so that it will always NewEmail = ""
used ‘!= 0’ rather than ‘== 1 ’, simply generate the same random for cntr in range(0,len(email)):
ch = ord(email[cntr]) + Offset
to remind you that the two can be number. You could also go a bit if cntr == 1:
interchangeable. deeper and put the offset value chr(ch)
NewEmail = NewEmail + (chr(len(email)+68)) +
somewhere into the license key, elif cntr == 2:
The DoIt function (below) asks maybe the last character so you NewEmail = NewEmail + chr(csum) + chr(ch)
for an email address using could use that as the decryption else:
NewEmail = NewEmail + chr(ch)
‘raw_input’, then calls the offset. if debug == 1:
print cntr, NewEmail
functions in order to create the
license key. As always, the full source is return NewEmail
available at
Lastly, we call the DoIt routine. http://pastebin.com/MH9nVTNK. def DecodeKey(s,debug = 0):
Until next time, enjoy. global Offset
eml = ""
if __name__ == "__main__": for cntr in range(0,len(s)):
DoIt() if debug != 0:
print cntr,s[cntr],ord(s[cntr])-
Now, obviously the output is Offset,chr(ord(s[cntr])-Offset)
if cntr == 0:
not super-encrypted, and if Greg Walters is owner of RainyDay eml = eml + chr(ord(s[cntr])-Offset)
someone were to put in a fair Solutions, LLC, a consulting company elif cntr == 1:
in Aurora, Colorado, and has been
amount of time, they could figure programming since 1 972. He enjoys
emllen = ord(s[cntr])-Offset
elif cntr == 3:
out what we used to create the key cooking, hiking, music, and spending csumchr=s[cntr]
fairly easily. However, it should time with his family. His website is else:
give you enough of a starting point www.thedesignatedgeek.net. eml = eml + chr(ord(s[cntr])-Offset)
if debug == 1:
print eml
return eml
def DoIt():
email = raw_input("Please enter email address -> ")
isok = IsValidEmail(email,0)
if isok == True:
csum,csumchr = CheckSum(email)
ke = EncodeKey(email,csum,0)
print("License Key = %s" % ke)
print("Original email = %s" % DecodeKey(ke,0))