Repository: wzpan/Learn-Python-The-Hard-Way Branch: master Commit: cdda9e82ed63 Files: 203 Total size: 277.1 KB Directory structure: gitextract_07osmigk/ ├── .directory ├── Python2/ │ ├── ex01.py │ ├── ex02.py │ ├── ex03-new.py │ ├── ex03.py │ ├── ex04.py │ ├── ex05.py │ ├── ex06.py │ ├── ex07.py │ ├── ex08.py │ ├── ex09.py │ ├── ex10.py │ ├── ex11.py │ ├── ex12.py │ ├── ex13-less.py │ ├── ex13-more.py │ ├── ex13-raw_input.py │ ├── ex13.py │ ├── ex14.py │ ├── ex15.py │ ├── ex16.py │ ├── ex16_read.py │ ├── ex17.py │ ├── ex18.py │ ├── ex19.py │ ├── ex20.py │ ├── ex21.py │ ├── ex24.py │ ├── ex25.py │ ├── ex26.py │ ├── ex29.py │ ├── ex30.py │ ├── ex31.py │ ├── ex32.py │ ├── ex33.py │ ├── ex34.py │ ├── ex35.py │ ├── ex37.py │ ├── ex38.py │ ├── ex39.py │ ├── ex40.py │ ├── ex41.py │ ├── ex42.py │ ├── ex43.py │ ├── ex44.py │ ├── ex46/ │ │ └── skeleton/ │ │ ├── NAME/ │ │ │ └── __init__.py │ │ ├── setup.py │ │ └── tests/ │ │ ├── NAME_test.py │ │ └── __init__.py │ ├── ex47/ │ │ └── skeleton/ │ │ ├── ex47/ │ │ │ ├── __init__.py │ │ │ └── game.py │ │ ├── setup.py │ │ └── tests/ │ │ ├── __init__.py │ │ └── ex47_test.py │ ├── ex48/ │ │ └── skeleton/ │ │ ├── ex48/ │ │ │ ├── __init__.py │ │ │ └── lexicon.py │ │ ├── setup.py │ │ └── test/ │ │ ├── __init__.py │ │ └── lexicon_tests.py │ ├── ex49/ │ │ └── skeleton/ │ │ ├── ex49/ │ │ │ ├── __init__.py │ │ │ └── parser.py │ │ ├── setup.py │ │ └── test/ │ │ ├── __init__.py │ │ └── parser_test.py │ ├── game/ │ │ └── skeleton/ │ │ ├── README │ │ ├── bin/ │ │ │ ├── MultipartPostHandler.py │ │ │ ├── __init__.py │ │ │ ├── app.py │ │ │ └── map.py │ │ ├── setup.py │ │ ├── static/ │ │ │ ├── css/ │ │ │ │ ├── marketing.css │ │ │ │ ├── modal.css │ │ │ │ └── pure-min.css │ │ │ └── js/ │ │ │ ├── modal.js │ │ │ └── validate.js │ │ ├── templates/ │ │ │ ├── entry.html │ │ │ ├── foo.html │ │ │ ├── hello.html │ │ │ ├── hello_form.html │ │ │ ├── index.html │ │ │ ├── layout.html │ │ │ ├── show.html │ │ │ ├── show_room.html │ │ │ ├── upload_form.html │ │ │ └── you_died.html │ │ └── test/ │ │ ├── __init__.py │ │ ├── app_test.py │ │ ├── game_test.py │ │ ├── map_test.py │ │ └── tools.py │ └── sample.txt ├── Python3/ │ ├── ex01-studydrills.py │ ├── ex01.py │ ├── ex02.py │ ├── ex03-studydrills.py │ ├── ex03.py │ ├── ex04-studydrills.py │ ├── ex04.py │ ├── ex05-studydrills.py │ ├── ex05.py │ ├── ex06-studydrills.py │ ├── ex06.py │ ├── ex07-studydrills.py │ ├── ex07.py │ ├── ex08.py │ ├── ex09.py │ ├── ex10-studydrills.py │ ├── ex10.py │ ├── ex11-studydrills.py │ ├── ex11.py │ ├── ex12.py │ ├── ex13-studydrills1.py │ ├── ex13-studydrills2.py │ ├── ex13-studydrills3.py │ ├── ex13.py │ ├── ex14-studydrills.py │ ├── ex14.py │ ├── ex15-studydrills.py │ ├── ex15.py │ ├── ex16-studydrills.py │ ├── ex16-studydrills2.py │ ├── ex16.py │ ├── ex17-studydrills.py │ ├── ex17.py │ ├── ex18.py │ ├── ex19-studydrills.py │ ├── ex19.py │ ├── ex20-studydrills.py │ ├── ex20.py │ ├── ex21-studydrills.py │ ├── ex21.py │ ├── ex24-studydrills.py │ ├── ex24.py │ ├── ex25.py │ ├── ex26.py │ ├── ex29-studydrills.py │ ├── ex29.py │ ├── ex30-studydrills.py │ ├── ex30.py │ ├── ex31-studydrills.py │ ├── ex31.py │ ├── ex32.py │ ├── ex33-studydrills.py │ ├── ex33.py │ ├── ex34.py │ ├── ex35.py │ ├── ex37.py │ ├── ex38.py │ ├── ex39-studydrills.py │ ├── ex39.py │ ├── ex40-studydrills.py │ ├── ex40.py │ ├── ex41.py │ ├── ex42.py │ ├── ex43.py │ ├── ex44.py │ ├── ex46/ │ │ └── skeleton/ │ │ ├── NAME/ │ │ │ └── __init__.py │ │ ├── setup.py │ │ └── tests/ │ │ ├── NAME_test.py │ │ └── __init__.py │ ├── game/ │ │ └── skeleton/ │ │ ├── README │ │ ├── bin/ │ │ │ ├── MultipartPostHandler.py │ │ │ ├── __init__.py │ │ │ ├── app.py │ │ │ └── map.py │ │ ├── ex47/ │ │ │ ├── __init__.py │ │ │ └── game.py │ │ ├── ex48/ │ │ │ ├── __init__.py │ │ │ └── lexicon.py │ │ ├── ex49/ │ │ │ ├── __init__.py │ │ │ └── parser.py │ │ ├── sessions/ │ │ │ ├── 245c9a181ce6cc24de4e9c19d9f449d416ab940d │ │ │ ├── 4d0905855a35a119c78d375479d0fe05b1778265 │ │ │ ├── 58d0f5dc7cf6255fd5afc974df29abc610530f54 │ │ │ ├── 6f14bd73122b385dea9a602e62982da36457a9c0 │ │ │ ├── 8f517a270c46a0127095766db27a8f9541c464f9 │ │ │ └── f72f2c47cd5454a04ec03a630fe296ea257619eb │ │ ├── setup.py │ │ ├── static/ │ │ │ ├── css/ │ │ │ │ ├── marketing.css │ │ │ │ ├── modal.css │ │ │ │ └── pure-min.css │ │ │ └── js/ │ │ │ ├── modal.js │ │ │ └── validate.js │ │ ├── templates/ │ │ │ ├── entry.html │ │ │ ├── foo.html │ │ │ ├── hello.html │ │ │ ├── hello_form.html │ │ │ ├── index.html │ │ │ ├── layout.html │ │ │ ├── show.html │ │ │ ├── show_room.html │ │ │ ├── upload_form.html │ │ │ └── you_died.html │ │ └── test/ │ │ ├── __init__.py │ │ ├── app_test.py │ │ ├── game_test.py │ │ ├── lexicon_test.py │ │ ├── map_test.py │ │ ├── parser_test.py │ │ ├── setup_test.py │ │ └── tools.py │ └── sample.txt └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .directory ================================================ [Dolphin] PreviewsShown=true Timestamp=2013,9,6,11,48,45 Version=3 [Settings] HiddenFilesShown=true ================================================ FILE: Python2/ex01.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex01: A Good First Program print "Hello World!" print "Hello Again" print "I like typing this." print "This is fun." print 'Yay! Printing.' print "I'd much rather you 'not'." # print 'I "said" do not touch this.' print 'This is another line!' ================================================ FILE: Python2/ex02.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex2: Comments and Pound Characters # A comment, this is so you can read you program later. # Anything after the # is ignored by python. print "I could have code like this." # and the comment after is ignored # You can also use a comment to "disable" or comment out a piece of code: # print "This won't run." print "This will run." ================================================ FILE: Python2/ex03-new.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # Find something you need to calculate and write a new .py file that # does it. # integer print 50 * 2 print 1/500 print 4 * 3 - 1 # float print 3.14 * 2 * 200 print 1.0/20 # The following expressions are more complicated calculations. # Ignore them if you haven't learned anything about each type. # decimal: more accurate than float # import decimal # print (decimal.Decimal(9876) + decimal.Decimal("54321.012345678987654321")) # fraction # import fractions # print fractions.Fraction(1, 3) # print fractions.Fraction(4, 6) # print 3 * fractions.Fraction(1, 3) # complex # print(1j * 1J) # print(3 + 1j * 3)j ================================================ FILE: Python2/ex03.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex3: Numbers and Math # Print "I will now count my chickens:" print "I will now count my chickens:" # Print the number of hens print "Hens", 25 + 30.0 / 6 # Print the number of roosters print "Roosters", 100 - 25 * 3 * 4 # Print "Now I will count the eggs:" print "Now I will count the eggs:" # Number of eggs, Notice that '/' operator returns int value in Python2 print 3 + 2 + 1 - 5 + 4 % 2 - 1.0 / 4 + 6 # use floating point numbers so it's more accurate # Print "Is it true that 3 + 2 < 5 - 7?" print "Is it true that 3 + 2 < 5 - 7?" # Print whether 3+2 is smaller than 5-7(True or False) print 3 + 2 < 5 - 7 # Calculate 3+2 and print the result print "What is 3 + 2?", 3 + 2 # Calculate 5-7 and print the result print "What is 5 - 7?", 5 - 7 # Print "Oh, that's why it's False." print "Oh, that's why it's False." # Print "Oh, that's why it's False." print "How about some more." # Print whether 5 is greater than -2(True or False) print "Is it greater?", 5 > -2 # Print whether 5 is greater than or equal to -2?(True or False) print "Is it greater or equal?", 5 >= -2 # Print whether 5 is less than or equal to -2 (True or False) print "Is it less or equal?", 5 <= -2 ================================================ FILE: Python2/ex04.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex4: Variables And Names # number of cars cars = 100 # space in a car. Give it a float value, otherwise we can only get int results after division. space_in_a_car = 4.0 # number of drivers drivers = 30 # number of passengers passengers = 90 # number of cars that are empty(without driver) cars_not_driven = cars - drivers # number of cars that are diven cars_driven = drivers # number of cars carpool_capacity = cars_driven * space_in_a_car # average number of passengers in each car average_passengers_per_car = passengers / cars_driven print "There are", cars, "cars available." print "There are only", drivers, "drivers available." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "We have", passengers, "to carpool today." print "We need to put about", average_passengers_per_car, "in each car." ================================================ FILE: Python2/ex05.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex5: More Variables and Printing name = 'Zed A. Shaw' age = 35 # not a lie height = 74 # inches weight = 180 # lbs eyes = "Blue" teeth = 'White' hair = 'Brown' print "Let's talk about %s" % name print "He's %d years old." % age print "He's %d inches tall." % height print "He's %d pounds heavy." % weight print "Actually that's not too heavy" print "He's got %s eyes and %s hair." % (eyes, hair) print "His teeth are usually %s depending on the coffee." % (teeth) # this line is tricky, try to get it exactly right print 'If I add %d, %d and %d I get %d.' % (age, height, weight, age + height + weight) # try more format characters my_greeting = "Hello,\t" my_first_name = 'Joseph' my_last_name = 'Pan' my_age = 24 # Print 'Hello,\t'my name is Joseph Pan, and I'm 24 years old. print "%rmy name is %s %s, and I'm %d years old." % (my_greeting, my_first_name, my_last_name, my_age) # Try to write some variables that convert the inches and pounds to centimeters and kilos. inches_per_centimeters = 2.54 pounds_per_kilo = 0.45359237 print "He's %f centimeters tall." % (height * inches_per_centimeters) print "He's %f kilos heavy." % (weight * pounds_per_kilo) ================================================ FILE: Python2/ex06.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex6: String and Text # Assign the string with 10 replacing the formatting character to variable 'x' x = "There are %d types of people." % 10 # Assign the string with "binary" to variable 'binary' binary = "binary" # Assign the string with "don't" to variable 'do_not' do_not = "don't" # Assign the string with 'binary' and 'do_not' replacing the formatting character to variable 'y' y = "Those who know %s and those who %s." % (binary, do_not) # Two strings inside of a string # Print "There are 10 types of people." print x # Print "Those who know binary and those who don't." print y # Print "I said 'There are 10 types of people.'" print "I said %r." % x # One string inside of a string # Print "I also said: 'Those who know binary and those who don't.'." print "I also said: '%s'." % y # One string inside of a string # Assign boolean False to variable 'hilarious' hilarious = False # Assign the string with an unevaluated formatting character to 'joke_evaluation' joke_evaluation = "Isn't that joke so funny?! %r" # Print "Isn't that joke so funny?! False" print joke_evaluation % hilarious # One string inside of a string # Assign string to 'w' w = "This is the left side of..." # Assign string to 'e' e = "a string with a right side." # Print "This is the left side of...a string with a right side." print w + e # Concatenate two strings with + operator ================================================ FILE: Python2/ex07.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex7: More Printing # Print "Mary had a little lamb" print "Mary had a little lamb" # Print "Its fleece was white as snow. print "Its fleece was white as %s." % 'snow' # one string inside of another # Print "And everywhere that Mary went." print "And everywhere that Mary went." # Print ".........." print "." * 10 # what'd that do? - "*" operator for strings is used to repeat the same characters for certain times # Assign string value for each variable end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" end10 = "g" end11 = "e" end12 = "r" # watch that comma at the end. try removing it to see what happens print end1 + end2 + end3 + end4 + end5 + end6, print end7 + end8 + end9 + end10 + end11 + end12 ================================================ FILE: Python2/ex08.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex8: Printing, Printing formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4) print formatter % ("one", "two", "three", "four") print formatter % (True, False, False, True) print formatter % (formatter, formatter, formatter, formatter) print formatter % ( "I had this thing.", "That you could type up right.", "But it didn't sing.", # This line contains a apostrophe "So I said goodnight." ) ================================================ FILE: Python2/ex09.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex9: Printing, Printing, Printing # Here's some new strange stuff, remember type it exactly. days = "Mon Tue Wed Thu Fri Sat Sun" months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" print "Here are the days: ", days print "Here are the months: ", months print"I said 'Here are the months: %r'" % months print """ There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """ ================================================ FILE: Python2/ex10.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex10: What Was That? tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." test = "I will insert a \newline haha." fat_cat = ''' I'll do a list: \t* Cat food \t* Fishies \t* Catnip \n\t* Grass ''' print tabby_cat print persian_cat print backslash_cat print fat_cat # Assign string value for each variable intro = "I'll print a week" mon = "Mon" tue = "Tue" wed = "Wed" thu = "Thu" fri = "Fri" sat = "Sat" sun = "Sun" print "%s\n%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (intro, mon, tue, wed, thu, fri, sat, sun) print "%r" % intro print "%r" % "She said \"I'll print a week\"" print "%s" % intro print "%s" % "She said \"I'll print a week\"" ================================================ FILE: Python2/ex11.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex11: Asking Questions # input(): Read a value from standard input. Equivalent to eval(raw_input(prompt)). # raw_input(): Read a string from standard input. The trailing newline is stripped. print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % (age, height, weight) print "Enter a integer: ", num = int(raw_input()) print "The number you've input is: %d" % num print "Enter a name: ", name = raw_input() print "What's %s's age?" % name, age = input() print "What's %s's height?" % name, height = input() print "What's %s's weight?" % name, weight = input() print "What's the color of %s's eyes?" % name, eyes = raw_input() print "What's the color of %s's teeth?" % name, teeth = raw_input() print "What's the color of %s's hair?" % name, hair = raw_input() type(name) # the data type of name will be type(age) # the data type of age will be print "Let's talk about %s" % name print "He's %d years old." % age print "He's %d inches tall." % height print "He's %d pounds heavy." % weight print "Actually that's not too heavy" print "He's got %s eyes and %s hair." % (eyes, hair) print "His teeth are usually %s depending on the coffee." % (teeth) print 'If I add %d, %d and %d I get %d.' % (age, height, weight, age + height + weight) ================================================ FILE: Python2/ex12.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex12: Prompting People age = raw_input("How old are you?") height = raw_input("How tall are you? ") weight = raw_input("How much do you weigh? ") print "So, you're %r old, %r tall and %r heavy." % (age, height, weight) ================================================ FILE: Python2/ex13-less.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex13: Parameters, Unpacking, Variables # Write a script that has fewer arguments from sys import argv script, first_name, last_name = argv print "The script is called:", script print "Your first name is:", first_name print "Your last name is:", last_name ================================================ FILE: Python2/ex13-more.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex13: Parameters, Unpacking, Variables # Write a script that has more arguments from sys import argv script, name, age, height, weight = argv print "The script is called:", script print "Your name is:", name print "Your age is:", age print "Your height is %d inches" % int(height) print "Your weight is %d pounds" % int(weight) ================================================ FILE: Python2/ex13-raw_input.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex13: Parameters, Unpacking, Variables # Combine raw_input with argv to make a script that gets more input from a user. from sys import argv script, first_name, last_name = argv middle_name = raw_input("What's your middle name?") print "Your full name is %s %s %s." % (first_name, middle_name, last_name) ================================================ FILE: Python2/ex13.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex13: Parameters, Unpacking, Variables from sys import argv script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third ================================================ FILE: Python2/ex14.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex14: Prompting and Passing from sys import argv # Add another argument and use it in your script script, user_name, city = argv # prompt = '> ' # Change the prompt variable to something else prompt = 'Please type the answer: ' print "Hi %s from %s, I'm the %s script." % (user_name, city, script) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name likes = raw_input(prompt) print "What's the whether like today in %s?" % city weather = raw_input(prompt) print "What kind of computer do you have?" computer = raw_input(prompt) print """ Alright, so you said %r about liking me. The weather in your city is %s. But I can't feel it because I'm a robot. And you have a %r computer. Nice. """ % (likes, weather, computer) ================================================ FILE: Python2/ex15.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex15: Reading Files # import argv variables from sys submodule from sys import argv # get the argv variables script, filename = argv # open a file txt = open(filename) # print file name # print all the contents of the file print txt.read() # close the file txt.close() # prompt to type the file name again print "Type the filename again:" # input the new file name file_again = raw_input("> ") # open the new selected file txt_again = open(file_again) # print the contents of the new selected file print txt_again.read() # close the file txt_again.close() ================================================ FILE: Python2/ex16.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex16: Reading and Writing Files from sys import argv script, filename = argv from sys import argv script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." # Open this file in 'write' mode target = open(filename, 'w') # Not neccessary if opening the file with 'w' mode # target.truncate() print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "I'm going to write these to the file." target.write("%s\n%s\n%s\n" % (line1, line2, line3)) print "And finally, we close it." target.close() ================================================ FILE: Python2/ex16_read.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # A script similar to ex16 that uses read and argv to read the file from sys import argv script, filename = argv print "The contents of the file %s:" % filename target = open(filename) contents = target.read() print contents target.close() ================================================ FILE: Python2/ex17.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex17: More Files from sys import argv from os.path import exists script, from_file, to_file = argv open(to_file, 'w').write(open(from_file).read()) ================================================ FILE: Python2/ex18.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex18: Names, Variables, Code, Functions # this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # ok, that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1, arg2) # this just takes one argument def print_one(arg1): print "arg1: %r" % arg1 # this one takes no arguments def print_none(): print "I got nothin'." print_two("Zed","Shaw") print_two_again("Zed","Shaw") print_one("First!") print_none() ================================================ FILE: Python2/ex19.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex19: Functions and Variables # Define a function named "cheese_and_crackers" def cheese_and_crackers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print "Get a blanket.\n" # Print "We can just give the function numbers directly:" print "We can just give the function numbers directly:" # Call the function, with 2 numbers as the actual parameters cheese_and_crackers(20, 30) # Print "OR, we can use variables from our script:" print "OR, we can use variables from our script:" # assign 10 to a variable named amount_of_cheese amount_of_cheese = 10 # assign 50 to a variable named amount_of_crackers amount_of_crackers = 50 # Call the function, with 2 variables as the actual parameters cheese_and_crackers(amount_of_cheese, amount_of_crackers) # Print "We can even do math inside too:" print "We can even do math inside too:" # Call the function, with two math expression as the actual # parameters. Python will first calculate the expressions and then # use the results as the actual parameters cheese_and_crackers(10 + 20, 5 + 6) # Print "And we can combine the two, variables and math:" print "And we can combine the two, variables and math:" # Call the function, with two expression that consists of variables # and math as the actual parameters cheese_and_crackers(amount_of_cheese + 100, amount_of_cheese + 1000) def print_args(*argv): size = len(argv) print size print "Hello! Welcome to use %r!" % argv[0] if size > 1: for i in range(1, size): print "The param %d is %r" % (i, argv[i]) return 0 return -1 # 1. use numbers as actual parameters print_args(10, 20, 30) # 2. use string and numbers as actual parameters print_args("print_args", 10, 20) # 3. use strings as actual parameters print_args("print_args", "Joseph", "Pan") # 4. use variables as actual parameters first_name = "Joseph" last_name = "Pan" print_args("print_args", first_name, last_name) # 5. contain math expressions print_args("print_args", 5*4, 2.0/5) # 6. more complicated calculations print_args("print_args", '.'*10, '>'*3) # 7. more parameters print_args("print_args", 10, 20, 30, 40, 50) # 8. tuples as parameters nums1 = (10, 20, 30) nums2 = (40, 50, 60) print_args("print_args", nums1, nums2) # 9. more complicated types nums3 = [70, 80, 90] set1 = {"apple", "banana", "orange"} dict1 = {'id': '0001', 'name': first_name+" "+last_name} str1 = "Wow, so complicated!" print_args("print args", nums1, nums2, nums3, set1, dict1, str1) # 10. function as parameter and return values if print_args(cheese_and_crackers, print_args) != -1: print "You just send more than one parameter. Great!" ================================================ FILE: Python2/ex20.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex20: Functions and Files # Import argv variables from the sys module from sys import argv # Assign the first and the second arguments to the two variables script, input_file = argv # Define a function called print_call to print the whole contents of a # file, with one file object as formal parameter def print_all(f): # print the file contents print f.read() # Define a function called rewind to make the file reader go back to # the first byte of the file, with one file object as formal parameter def rewind(f): # make the file reader go back to the first byte of the file f.seek(0) # Define a function called print_a_line to print a line of the file, # with a integer counter and a file object as formal parameters def print_a_line(line_count, f): # Test whether two variables are carrying the same value print "line_count equal to current_line?:", (line_count == current_line) # print the number and the contents of a line print line_count, f.readline() # Open a file current_file = open(input_file) # Print "First let's print the whole file:" print "First let's print the whole file:\n" # call the print_all function to print the whole file print_all(current_file) # Print "Now let's rewind, kind of like a tape." print "Now let's rewind, kind of like a tape." # Call the rewind function to go back to the beginning of the file rewind(current_file) # Now print three lines from the top of the file # Print "Let's print three lines:" print "Let's print three lines:" # Set current line to 1 current_line = 1 print "current_line = %d" % current_line # Print current line by calling print_a_line function print_a_line(current_line, current_file) # Set current line to 2 by adding 1 current_line += 1 print "current_line is equal to:%d" % current_line # Print current line by calling print_a_line function print_a_line(current_line, current_file) # Set current line to 3 by adding 1 current_line += 1 print "current_line is equal to:%d" % current_line # Print current line by calling print_a_line function print_a_line(current_line, current_file) ================================================ FILE: Python2/ex21.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex21: Functions Can Return Something def add(a, b): print "ADDING %d + %d" % (a, b) return a + b def subtract(a, b): print "SUBTRACTING %d - %d" % (a, b) return a - b def multiply(a, b): print "MULTIPLYING %d * %d" % (a, b) return a * b def divide(a, b): print "DIVIDING %d / %d" % (a, b) return a / b # my function to test return def isequal(a, b): print "Is %r equal to %r? - " % (a, b) , return (a == b) print "Let's do some math with just functions!" age = add(30, 5) height = subtract(78, 4) weight = multiply(92, 2) iq = divide(100, 2) print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq) # A puzzle for the extra credit, type it in anyway. print "Here is a puzzle." # switch the order of multiply and divide what = add(age, subtract(height, divide(weight, multiply(iq, 2)))) print "That becomes: ", what, "Can you do it by hand?" # test the return value of isequal() num1 = 40 num2 = 50 num3 = 50 print isequal(num1, num2) print isequal(num2, num3) # A new puzzle. print "Here is a new puzzle." # write a simple formula and use the function again uplen = 50 downlen = 100 height = 80 what_again = divide(multiply(height, add(uplen, downlen)), 2) print "That become: ", what_again, "Bazinga!" ================================================ FILE: Python2/ex24.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex24: More Practice print "Let's practice everything." print "You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs." poem = """ \t The lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\t\twhere there is none. """ print "--------------------" print poem print "--------------------" five = 10 - 2 + 3 - 6 print "This should be five: %s" % five def secret_formala(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates start_point = 1000 beans, jars, crates = secret_formala(start_point) print "With a starting point of: %d" % start_point # use the tuple as the parameters for the formatter print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates) start_point = start_point / 10 # call the function and use its return values as the parameters for the formatter print "We can also do that this way:" print "We'd have %d beans, %d jars, and %d crates." % secret_formala(start_point) ================================================ FILE: Python2/ex25.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex: even more practice def break_words(stuff): """ This function will break up words for us. """ words = stuff.split(' ') return words def sort_words(words): """ Sorts the words. """ return sorted(words) def print_first_word(words): """ Prints the first word after popping it off. """ word = words.pop(0) print word def print_last_word(words): """ Prints the last word after popping it off. """ word = words.pop(-1) print word def sort_sentence(sentence): """ Takes in a full sentence and returns the sorted words. """ words = break_words(sentence) return sort_words(words) def print_first_and_last(senence): """ Prints the first and last words of the sentences. """ words = break_words(senence) print_first_word(words) print_last_word(words) def print_first_and_last_sorted(sentence): """ Sorts the words then prints the first and last one. """ words = sort_sentence(sentence) print_first_word(words) print_last_word(words) ================================================ FILE: Python2/ex26.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') return words def sort_words(words): """Sorts the words.""" return sorted(words) # bug: def print_first_word(words) def print_first_word(words): """Prints the first word after popping it off.""" # bug: word = words.poop(0) word = words.pop(0) print word def print_last_word(words): """Prints the last word after popping it off.""" # bug: word = words.pop(-1 word = words.pop(-1) print word def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words) def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words) print "Let's practice everything." print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explantion \n\t\twhere there is none. """ print "--------------" print poem print "--------------" # warning: it's not five five = 10 - 2 + 3 - 5 print "This should be five: %s" % five def secret_formula(started): jelly_beans = started * 500 # bug: jars = jelly_beans \ 1000 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates start_point = 10000 # bug: beans, jars, crates == secret_formula(start-point) beans, jars, crates = secret_formula(start_point) print "With a starting point of: %d" % start_point print "We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates) start_point = start_point / 10 print "We can also do that this way:" # bug: print "We'd have %d beans, %d jars, and %d crabapples." % # secret_formula(start_pont print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point) # bug: sentence = "All god\tthings come to those who weight." sentence = "All good things come to those who weight." # bug: words = ex25.break_words(sentence) words = break_words(sentence) # bug: sorted_words = ex25.sort_words(words) sorted_words = sort_words(words) print_first_word(words) print_last_word(words) # bug: .print_first_word(sorted_words) print_first_word(sorted_words) print_last_word(sorted_words) # bug: sorted_words = ex25.sort_sentence(sentence) sorted_words = sort_sentence(sentence) # bug: prin sorted_words print sorted_words # bug: print_irst_and_last(sentence) print_first_and_last(sentence) # bug: print_first_a_last_sorted(senence) print_first_and_last_sorted(sentence) ================================================ FILE: Python2/ex29.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex29: What If people = 20 cats = 30 dogs = 15 if people < cats: print "Too many cats! The world is doomed!" if people > cats: print "Not many cats! The world is saved!" if people < dogs: print "The world is drooled on!" if people > dogs: print "The world is dry!" dogs += 5 if people >= dogs: print "People are greater than or equal to dogs." if people <= dogs: print "People are less than or equal to dogs." if people == dogs: print "People are dogs." if (dogs < cats) and (people < cats): print "Cats are more than people and dogs. People are scared by cats!" if (dogs < cats) and not (people < cats): print "Cats are more than dogs. Mice are living a hard life!" if (dogs == cats) or (cats < 10): print "Cats are fighting against dogs! Mice are happy!" if cat != 0: print "Cats are still exist. Mice cannot be too crazy." ================================================ FILE: Python2/ex30.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex30: Else and If # assign 30 to variable people people = 30 # assign 40 to variable cars cars = 40 # assign 15 to variable buses buses = 15 # if cars are more than people if cars > people: # print "We should take the cars." print "We should take the cars." # if cars are less than people elif cars < people: # print "We should not take the cars" print "We should not take the cars" # if cars are equal to people else: print "We can't decide." # if buses are more than cars if buses > cars: # print "That's too many buses." print "That's too many buses." # if buses are less than cars elif buses < cars: # print "Maybe we could take the buses." print "Maybe we could take the buses." # if buses are equal to cars else: # print "We still can't decide." print "We still can't decide." # if people are more than buses if people > buses: # print "Alright, let's just take the buses." print "Alright, let's just take the buses." # if people are less than buses else: # print "Fine, let's stay home then." print "Fine, let's stay home then." # if people are more than cars but less than buses if people > cars and people < buses: # print "There are many Busses but few cars." print "There are many Busses but few cars." # if people are less than cars but more than buses elif people < cars and people > buses: # print "There are many cars but few busses." print "There are many cars but few busses." # if people are more than cars and buses elif people > cars and people > buses: # print "There are few busses and cars." print "There are few busses and cars." # if people are less than cars and buses else: # print "There are many busses and cars." print "There are many busses and cars." ================================================ FILE: Python2/ex31.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex31: Making Decisions print "You enter a dark room with two doors. Do you go through...?" print "door #1" print "door #2" print "door #3" door = raw_input("> ") if door == "1": print "There's a giant bear here eating a cheese cake. What do you do?" print "1. Take the cake." print "2. Scream at the bear." bear = raw_input("> ") if bear == "1": print "The bear eats your face off. Good job!" elif bear == "2": print "The bear eats your legs off. Good job!" else: print "Well, doing %s is probably better. Bear runs away." % bear elif door == "2": print "You stare into the endless abyss at Cthulhu's retina." print "1. Blueberries." print "2. Yellow jacket clothespins." print "3. Understanding revolvers yelling melodies." insanity = raw_input("> ") if insanity == "1" or insanity == "2": print "Your body survives powered by a mind of jello. Good job!" else: print "The insanity rots you " elif door == "3": print "You are asked to select one pill from two and take it. One is red, and the other is blue." print "1. take the red one." print "2. take the blue one." pill = raw_input("> ") if pill == "1": print "You wake up and found this is just a ridiculous dream. Good job!" elif pill == "2": print "It's poisonous and you died." else: print "The man got mad and killed you." else: print "You wake up and found this is just a ridiculous dream." print "However you feel a great pity haven't entered any room and found out what it will happens!" ================================================ FILE: Python2/ex32.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex32: Loops and Lists the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit # also we can go through mixed lists too # notice we have to use %r since we don't know what's in it for i in change: print "I got %r" % i # we can also build lists, first start with an empty one elements = [] # then use the range function to generate a list elements = range(0, 6) # now we can print them out too for i in elements: print "Element was: %d" % i ================================================ FILE: Python2/ex33.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex33: While Loops def createNumbers(max, step): i = 0 numbers = [] for i in range(0, max, step): print "At the top i is %d" % i numbers.append(i) print "Numbers now: ", numbers print "At the bottom i is %d" % i return numbers numbers = createNumbers(10, 2) print "The numbers: " for num in numbers: print num ================================================ FILE: Python2/ex34.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex34: Accessing Elements of Lists animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus'] def printAnimal(index): if index == 1: num2en = "1st" elif index == 2: num2en = "2nd" elif index == 3: num2en = "3rd" else: num2en = str(index)+"th" print "The %s animal is at %d and is a %s" % (num2en, index-1, animals[index-1]) print "The animal at %d is the %s animal and is a %s" % (index-1, num2en, animals[index-1]) for i in range(1, 7): printAnimal(i) ================================================ FILE: Python2/ex35.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex35: Branches and Functions from sys import exit def gold_room(): ''' A room with full of god. ''' print "This room is full of gold. How much do you take?" next = raw_input("> ") try: how_much = int(next) except ValueError: dead("Man, learn to type a number.") if how_much < 50: print "Nice, you're not greedy, you win!" exit(0) else: dead("You greedy bastard!") def bear_room(): ''' A room with a bear ''' print "There is a bear here." print "The bear has a bunch of honey." print "The fat bear is in front of another door." print "How are you going to move the bear?" bear_moved = False while True: next = raw_input("> ") if next == "take honey": dead("The bear looks at you then slaps your face off.") elif next == "taunt bear" and not bear_moved: print "The bear has moved from the door. You can go through it now." bear_moved = True elif next == "taunt bear" and bear_moved: dead("The bear gets pissed off and chews your leg off.") elif next == "open door" and bear_moved: gold_room() else: print "I got no idea what that means." def cthulhu_room(): ''' A room with evil Cthulhu ''' print "Here you see the great evil Cthulhu." print "He, it, whatever stares at you and you go insane." print "Do you flee for your life or eat your head?" next = raw_input("> ") if "flee" in next: start() elif "head" in next: dead("Well that was tasty!") else: cthulhu_room() def dead(why): ''' Call this when the hero dead ''' print why, "Good job!" exit(0) def start(): ''' Begining of the story ''' print "You are in a dark room." print "There is a door to your right and left." print "Which one do you take?" next = raw_input("> ") if next == "left": bear_room() elif next == "right": cthulhu_room() else: dead("You stumble around the room until you starve.") start() ================================================ FILE: Python2/ex37.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex37: Symbol Review # and, or, not, if, elif, else print "#1##############################" if True and False: print "#1 can't be printed" if False and False: print "#2 can't be printed" if True and True: print "#3 can be printed!" if False or True: print "#4 can be printed!" if True or False: print "#5 can be printed!" if True or No_Matter_What: print "#6 can be printed!" if not(False and No_Matter_What): print "#7 can be printed!" rainy = True sunny = False if rainy: print "It's rainny today!" elif sunny: print "It's sunny today!" else: print "It's neither rainny nor sunny today!" # del, try, except, as print "#2##############################" x = 10 print x del x try: print x except NameError as er: print er # from, import print "#3##############################" from sys import argv script = argv print "The script name is %s " % script # for, in for i in range(0, 10): print i, # assert try: assert True, "\nA True!" assert False, "\nA false!" except AssertionError as er: print er # global, def print "#4##############################" x = 5 def addone(): # annouce that x is the global x global x x += 1 addone() print "x is %d", x # finally print "#4##############################" import time try: f = open('sample.txt') while True: # our usual file-reading idiom line = f.readline() if len(line) == 0: break print line except KeyboardInterrupt: print '!! You cancelled the reading from the file.' finally: f.close() print '(Cleaning up: Closed the file)' # with print "#5##############################" with open("sample.txt") as f: print f.read() # pass, class print "#6##############################" class NoneClass: ''' Define an empty class. ''' pass empty = NoneClass() print(empty) class Droid: ''' Define a robot with a name. ''' def __init__(self, name): self.name = name print "Robot %s initialized." % self.name def __del__(self): print "Robot %s destroyed." % self.name def sayHi(self): print "Hi, I'm %s." % self.name r2d2 = Droid('R2D2') r2d2.sayHi() del r2d2 # exec print "#7##############################" print "Here I will use exec function to calculate 5 + 2" exec("print '5 + 2 = ' , 5 + 2") # while, break print "#8##############################" while True: try: num = int(raw_input("Let's guess an integer:")) if num > 10: print "too big!" elif num < 10: print "too small!" else: print("Congrats! You will!") break except ValueError: print "Please insert a value!" # raise print "#9##############################" class ShortInputException(Exception): ''' A user-defined exception class. ''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: text = raw_input('Enter something long enough --> ') if len(text) < 3: raise ShortInputException(len(text), 3) # Other work can continue as usal here except EOFError: print 'Why did you do an EOF on me?' except ShortInputException as ex: print 'ShortInputException: The input was {0} long, expected at least {1}'\ .format(ex.length, ex.atleast) else: print('No exception was raised.') # yield print "#10##############################" print "Now we counter from 1 to 99: " def make_counter(max): x = 1 while x < max: yield x x = x + 1 for i in make_counter(100): print i, print "\n\nNow we calculate fibonacci series: " def fib(max): ''' A fibonacci secries generator. Calculates fibonacci numbers from 0 to max. ''' a, b = 0, 1 while a < max: yield a a, b = b, a+b for num in fib(100): print num, # lambda print "\n#11##############################" def makeDouble(): ''' double given value ''' return lambda x:x * 2 adder = makeDouble() num_list = [5, 10, 15, 'hello'] print '\nNow we multiples each elements in num_list with 2:' for num in num_list: print adder(num) ================================================ FILE: Python2/ex38.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex38: Doing Things To Lists ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there's not 10 things in that list, let's fix that." stuff = ten_things.split(' ') more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: next_one = more_stuff.pop() print "Adding: ", next_one stuff.append(next_one) print "There's %d items now." % len(stuff) print "There we go: ", stuff print "Let's do some things with stuff." print stuff[1] print stuff[-1] # whoa! fancy print stuff.pop() print ' '.join(stuff) # what? cool! print '#'.join(stuff[3:5]) # super stellar! ================================================ FILE: Python2/ex39.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex39: Dictionaries, Oh Lovely Dictionaries # create a mapping of state to abbreviation states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } # create a basic set of states and some cities in them cities = { 'CA': 'San Fransisco', 'MI': 'Detroit', 'FL': 'Jacksonville' } # add some more cities cities['NY'] = 'New York' cities['OR'] = 'Portland' # print out some cities print '-' * 10 print "NY State has: ", cities['NY'] print 'OR State has: ', cities['OR'] # do it by using the state then cities dict print '-' * 10 print "Michigan has: ", cities[states['Michigan']] print "Florida has:", cities[states['Florida']] # print every state abbreviation print '-' * 10 for state, abbrev in states.items(): print "%s is abbreviated %s" % (state, abbrev) # print every city in state print '-' * 10 for abbrev, city in cities.items(): print "%s has the city %s" % (abbrev, city) # now do both at the same time print '-' * 10 for state, abbrev in states.items(): print "%s state is abbreviated %s and has city %s" % ( states, abbrev, cities[abbrev]) print '-' * 10 # safely get a abbreviation by state that might not be there state = states.get('Texas', None) if not state: print "Sorry, no Texas." # get a city with a default value city = cities.get('TX', 'Does Not Exist') print "The city for the state 'TX' is %s" % city # create a mapping of province to abbreviation cn_province = { '广东': '粤', '湖南': '湘', '四川': '川', '云南': '滇', } # create a basic set of provinces and some cities in them cn_cities = { '粤': '广州', '湘': '长沙', '川': '成都', } # add some more data cn_province['台湾'] = '台' cn_cities['滇'] = '昆明' cn_cities['台'] = '高雄' print '-' * 10 for prov, abbr in cn_province.items(): print "%s省的缩写是%s" % (prov, abbr) print '-' * 10 cn_abbrevs = {values: keys for keys, values in cn_province.items()} for abbrev, prov in cn_abbrevs.items(): print "%s是%s省的缩写" % (abbrev, prov) print '-' * 10 for abbrev, city in cn_cities.items(): print "%s市位于我国的%s省" % (city, cn_abbrevs[abbrev]) ================================================ FILE: Python2/ex40.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex40: Modules, Classes, and Objects # a first class example class Song(object): def __init__(self, disk): self.index = 0 self.disk = disk self.jump() def next(self): ''' next song. ''' self.index = (self.index + 1) % len(self.disk) self.jump() def prev(self): ''' prev song. ''' self.index = (self.index - 1) % len(self.disk) self.jump() def jump(self): ''' jump to the song. ''' self.lyrics = self.disk[self.index] def sing_me_a_song(self): for line in self.lyrics: print line # construct a disk song1 = ["Happy birthday to you", "I don't want to get sued", "So I'll stop right there"] song2 = ["They rally around the family", "With pockets full of shells" ] song3 = ["Never mind I find", "Some one like you" ] disk = [song1, song2, song3] mycd = Song(disk) mycd.sing_me_a_song() mycd.next() mycd.sing_me_a_song() mycd.next() mycd.sing_me_a_song() mycd.next() mycd.sing_me_a_song() mycd.prev() mycd.sing_me_a_song() mycd.prev() mycd.sing_me_a_song() mycd.prev() mycd.sing_me_a_song() mycd.prev() mycd.sing_me_a_song() ================================================ FILE: Python2/ex41.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex41: Learning To Speak Object Oriented import random from urllib import urlopen import sys WORD_URL = "http://learncodethehardway.org/words.txt" WORDS = [] PHRASES = { "class %%%(%%%):": "Make a class named %%% that is-a %%%.", "class %%%(object):\n\tdef __init__(self, ***)" : "class %%% has-a __init__ that takes self and *** parameters.", "class %%%(object):\n\tdef ***(self, @@@)": "class %%% has-a function named *** that takes self and @@@ parameters.", "*** = %%%()": "Set *** to an instance of class %%%.", "***.***(@@@)": "From *** get the *** function, and call it with parameters self, @@@.", "***.*** = '***'": "From *** get the *** attribute and set it to '***'." } # do they want to drill phrases first PHRASE_FIRST = False if len(sys.argv) == 2 and sys.argv[1] == "english": PHRASE_FIRST = True # load up the words from the website for word in urlopen(WORD_URL).readlines(): WORDS.append(word.strip()) def convert(snippet, phrase): class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))] other_names = random.sample(WORDS, snippet.count("***")) results = [] param_names = [] for i in range(0, snippet.count("@@@")): param_count = random.randint(1,3) param_names.append(', '.join(random.sample(WORDS, param_count))) for sentence in snippet, phrase: result = sentence[:] # fake class names for word in class_names: result = result.replace("%%%", word, 1) # fake other names for word in other_names: result = result.replace("***", word, 1) # fake parameter lists for word in param_names: result = result.replace("@@@", word, 1) results.append(result) return results # keep going until they hit CTRL-D try: while True: snippets = PHRASES.keys() random.shuffle(snippets) for snippet in snippets: phrase = PHRASES[snippet] question, answer = convert(snippet, phrase) if PHRASE_FIRST: question, answer = answer, question print question raw_input("> ") print "ANSWER: %s\n\n" % answer except EOFError: print "\nBye" ================================================ FILE: Python2/ex42.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex42: Is-A, Has-A, Objects, and Classes ## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a Animal class Dog(Animal): def __init__(self, name): ## Dog has-a name self.name = name ## Cat is-a animal class Cat(Animal): def __init__(self, name): ## Cat has-a name self.name = name ## Person is-a object class Person(object): def __init__(self, name): ## Person has-a name self.name = name ## Person has-a pet of some kind self.pet = None ## Employee is-a person class Employee(Person): def __init__(self, name, salary): ## run the __init__ method of a parent class reliably super(Employee, self).__init__(name) ## Employee has-a salary self.salary = salary ## Fish is-a object class Fish(object): pass ## Salmon is-a Fish class Salmon(Fish): pass ## Halibut is-a fish class Halibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## satan is-a Cat satan = Cat("Satan") ## mary is-a Person mary = Person("Mary") ## mary's pet is satan mary.pet = satan ## frank is-a Employee, his salary is 120000 frank = Employee("Frank", 120000) ## frank's pet is rover frank.pet = rover ## flipper is-a Fish flipper = Fish() ## crouse is-a Salmon crouse = Salmon() ## harry is-a Halibut harry = Halibut() ================================================ FILE: Python2/ex43.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex43: Basic Object-Oriented Analysis and Design # Class Hierarchy # * Map # - next_scene # - opening_scene # * Engine # - play # * Scene # - enter # * Death # * Central Corridor # * Laser Weapon Armory # * The Bridge # * Escape Pod # * Human # - attack # - defend # * Hero # * Monster from sys import exit from random import randint import time import math class Engine(object): def __init__(self, scene_map, hero): self.scene_map = scene_map self.hero = hero def play(self): current_scene = self.scene_map.opening_scene() while True: print "\n--------" next_scene_name = current_scene.enter(self.hero) current_scene = self.scene_map.next_scene(next_scene_name) class Scene(object): def enter(self): print "This scene is not yet configured. Subclass it and implement enter()." exit(1) class Death(Scene): quips = [ "You died. You kinda suck at this.", "Your mom would be proud...if she were smarter.", "Such a luser.", "I have a small puppy that's better at this." ] def enter(self, hero): print Death.quips[randint(0, len(self.quips)-1)] exit(1) class CentralCorridor(Scene): def enter(self, hero): print "The Gothons of Planet Percal #25 have invaded your ship and destroyed" print "your entire crew. You are the last surviving member and your last" print "mission is to get the neutron destruct bomb from the Weapons Armory," print "put it in the bridge, and blow the ship up after getting into an " print "escape pod." print "\n" print "You're running down the central corridor to the Weapons Armory when" print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume" print "flowing around his hate filled body. He's blocking the door to the" print "Armory and about to pull a weapon to blast you." action = raw_input("> ") if action == "shoot!": print "Quick on the draw you yank out your blaster and fire it at the Gothon." print "His clown costume is flowing and moving around his body, which throws" print "off your aim. Your laser hits his costume but misses him entirely. This" print "completely ruins his brand new costume his mother bought him, which" print "makes him fly into an insane rage and blast you repeatedly in the face until" print "you are dead. Then he eats you." return 'death' elif action == "dodge!": print "Like a world class boxer you dodge, weave, slip and slide right" print "as the Gothon's blaster cranks a laser past your head." print "In the middle of your artful dodge your foot slips and you" print "bang your head on the metal wall and pass out." print "You wake up shortly after only to die as the Gothon stomps on" print "your head and eats you." return 'death' elif action == "tell a joke": print "Lucky for you they made you learn Gothon insults in the academy." print "You tell the one Gothon joke you know:" print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr." print "The Gothon stops, tries not to laugh, then busts out laughing and can't move." print "While he's laughing you run up and shoot him square in the head" print "putting him down, then jump through the Weapon Armory door." return 'laser_weapon_armory' else: print "DOES NOT COMPUTE!" return 'central_corridor' class LaserWeaponArmory(Scene): def enter(self, hero): print "You do a dive roll into the Weapon Armory, crouch and scan the room" print "for more Gothons that might be hiding. It's dead quiet, too quiet." print "You stand up and run to the far side of the room and find the" print "neutron bomb in its container. There's a keypad lock on the box" print "and you need the code to get the bomb out. If you get the code" print "wrong 10 times then the lock closes forever and you can't" print "get the bomb. The code is 3 digits." code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9)) print code guesses = 0 while guesses < 10: guess = raw_input("[keypad]> ") if guess == code: break print "BZZZZEDDD!" guesses += 1 if guess == code: print "The container clicks open and the seal breaks, letting gas out." print "You grab the neutron bomb and run as fast as you can to the" print "bridge where you must place it in the right spot." return 'the_bridge' else: print "The lock buzzes one last time and then you hear a sickening" print "melting sound as the mechanism is fused together." print "You decide to sit there, and finally the Gothons blow up the" print "ship from their ship and you die." return 'death' class TheBridge(Scene): def enter(self, hero): print "You burst onto the Bridge with the netron destruct bomb" print "under your arm and surprise 5 Gothons who are trying to" print "take control of the ship. Each of them has an even uglier" print "clown costume than the last. They haven't pulled their" print "weapons out yet, as they see the active bomb under your" print "arm and don't want to set it off." action = raw_input("> ") if action == "throw the bomb": print "In a panic you throw the bomb at the group of Gothons" print "and make a leap for the door. Right as you drop it a" print "Gothon shoots you right in the back killing you." print "As you die you see another Gothon frantically try to disarm" print "the bomb. You die knowing they will probably blow up when" print "it goes off." return 'death' elif action == "slowly place the bomb": print "You point your blaster at the bomb under your arm" print "and the Gothons put their hands up and start to sweat." print "You inch backward to the door, open it, and then carefully" print "place the bomb on the floor, pointing your blaster at it." print "You then jump back through the door, punch the close button" print "and blast the lock so the Gothons can't get out." print "Now that the bomb is placed you run to the escape pod to" print "get off this tin can." return 'escape_pod' else: print "DOES NOT COMPUTE!" return "the_bridge" class EscapePod(Scene): def enter(self, hero): print "You rush through the ship desperately trying to make it to" print "the escape pod before the whole ship explodes. It seems like" print "hardly any Gothons are on the ship, so your run is clear of" print "interference. You get to the chamber with the escape pods, and" print "now need to pick one to take. Some of them could be damaged" print "but you don't have time to look. There's 5 pods, which one" print "do you take?" good_pod = randint(1,5) print good_pod guess = raw_input("[pod #]> ") if int(guess) != good_pod: print "You jump into pod %s and hit the eject button." % guess print "The pod escapes out into the void of space, then" print "implodes as the hull ruptures, crushing your body" print "into jam jelly." return 'death' else: print "You jump into pod %s and hit the eject button." % guess print "The pod easily slides out into space heading to" print "the planet below. As it flies to the planet, you look" print "back and see your ship implode then explode like a" print "bright star, taking out the Gothon ship at the same" print "time. You won!" return 'final_fight' class Win(Scene): ''' Win ''' def enter(self, hero): print ''' You Win! Good Job! ''' exit(0) class Final(Scene): ''' final fight ''' def enter(self, hero): # initialize a monster monster = Monster("Gothon") print "%s, You now came across the final boss %s! Let's fight!!!" % (hero.name, monster.name) a_combat = Combat() next_stage = a_combat.combat(hero, monster) return next_stage class Combat(object): def combat(self, hero, monster): ''' combat between two roles ''' round = 1 while True: print '='*30 print 'round %d' % round print '='*30 print "Your HP: %d" % hero.hp print "%s's HP: %d" % (monster.name, monster.hp) print 'Which action do you want to take?' print '-'*10 print '1) attack - Attack the enemy' print '2) defend - Defend from being attacked, also will recover a bit' try: action = int(raw_input('> ')) except ValueError: print "Please enter a number!!" continue # defending should be done before attacking if action == 2: hero.defend() # action of monster, 1/5 possibility it will defends monster_action = randint(1, 6) if monster_action == 5: monster.defend() if action == 1: hero.attack(monster) elif action == 2: pass else: print "No such action!" if monster_action < 5: monster.attack(hero) # whether win or die if hero.hp <= 0: return 'death' if monster.hp <= 0: return 'win' hero.rest() monster.rest() round += 1 class Map(object): scenes = { 'central_corridor': CentralCorridor(), 'laser_weapon_armory': LaserWeaponArmory(), 'the_bridge': TheBridge(), 'escape_pod': EscapePod(), 'death': Death(), 'final_fight': Final(), 'win': Win() } def __init__(self, start_scene): self.start_scene = start_scene def next_scene(self, scene_name): return Map.scenes.get(scene_name) def opening_scene(self): return self.next_scene(self.start_scene) class Human(object): ''' class for human ''' defending = 0 def __init__(self, name): self.name = name def attack(self, target): ''' attack the target ''' percent = 0 time.sleep(1) if target.defending == 1: percent = float(self.power) / 10.0 + randint(0, 10) target.hp = math.floor(target.hp - percent) else: percent = float(self.power) / 5.0 + randint(0, 10) target.hp = math.floor(target.hp - percent) print "%s attack %s. %s's HP decreased by %d points." % (self.name, target.name, target.name, percent) def defend(self): ''' be in the defending state. ''' self.defending = 1 print "%s is trying to defend." % self.name def rest(self): ''' recover a bit after each round ''' if self.defending == 1: percent = self.rate * 10 + randint(0, 10) else: percent = self.rate * 2 + randint(0, 10) self.hp += percent print "%s's HP increased by %d after rest." % (self.name, percent) self.defending = 0 class Hero(Human): ''' class for hero ''' hp = 1000 power = 200 rate = 5 class Monster(Human): ''' class for monster ''' hp = 5000 power = 250 rate = 5 a_map = Map('central_corridor') a_hero = Hero('Joe') a_game = Engine(a_map, a_hero) a_game.play() ================================================ FILE: Python2/ex44.py ================================================ #!/bin/python2 # -*- coding: utf-8 -*- # ex44: Inheritance vs. Composition class Other(object): def override(self): print "OTHER override()" def implicit(self): print "OTHER implicit()" def altered(self): print "OTHER altered()" class Child(object): def __init__(self): self.other = Other() def implicit(self): self.other.implicit() def override(self): print "CHILD override()" def altered(self): print "CHILD, BEFORE OTHER altered()" self.other.altered() print "CHILD, AFTER OTHER altered()" son = Child() son.implicit() son.override() son.altered() ================================================ FILE: Python2/ex46/skeleton/NAME/__init__.py ================================================ ================================================ FILE: Python2/ex46/skeleton/setup.py ================================================ try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'A tiny game', 'author': 'Joseph Pan', 'url': 'URL to get it at.', 'download_url': 'Where to download it.', 'author_email': 'cs.wzpan@gmail.com', 'version': '0.1', 'install_requires': ['nose'], 'packages': ['NAME'], 'scripts': [], 'name': 'projectname' } setup(**config) ================================================ FILE: Python2/ex46/skeleton/tests/NAME_test.py ================================================ from nose.tools import * import NAME def setup(): print "SETUP!" def teardown(): print "TEAR DOWN!" def test_basic(): print "I RAN!" ================================================ FILE: Python2/ex46/skeleton/tests/__init__.py ================================================ ================================================ FILE: Python2/ex47/skeleton/ex47/__init__.py ================================================ ================================================ FILE: Python2/ex47/skeleton/ex47/game.py ================================================ class Room(object): def __init__(self, name, description): self.name = name self.description = description self.paths = {} def go(self, direction): return self.paths.get(direction, None) def add_paths(self, paths): self.paths.update(paths) ================================================ FILE: Python2/ex47/skeleton/setup.py ================================================ try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'My Project', 'author': 'Joseph Pan', 'url': 'URL to get it at.', 'download_url': 'Where to download it.', 'author_email': 'cs.wzpan@gmail.com', 'version': '0.1', 'install_requires': ['nose'], 'packages': ['ex47'], 'scripts': [], 'name': 'projectname' } setup(**config) ================================================ FILE: Python2/ex47/skeleton/tests/__init__.py ================================================ ================================================ FILE: Python2/ex47/skeleton/tests/ex47_test.py ================================================ from nose.tools import * from ex47.game import Room def test_room(): gold = Room("GoldRoom", """ This room has gold in it you can grab. There's a \ door to the north.""" ) assert_equal(gold.name, "GoldRoom") assert_equal(gold.paths, {}) def test_room_paths(): center = Room("Center", "Test room in the center.") north = Room("North", "Test room in the north.") south = Room("South", "Test room in the south.") center.add_paths({'north': north, 'south': south}) assert_equal(center.go('north'), north) assert_equal(center.go('south'), south) def test_map(): start = Room("Start", "You can go west and down a hole.") west = Room("Trees", "There are trees here, you can go east.") down = Room("Dungeon", "It's dark down here, you can go up.") start.add_paths({'west': west, 'down': down}) west.add_paths({'east': start}) down.add_paths({'up': start}) assert_equal(start.go('west'), west) assert_equal(start.go('west').go('east'), start) assert_equal(start.go('down').go('up'), start) ================================================ FILE: Python2/ex48/skeleton/ex48/__init__.py ================================================ ================================================ FILE: Python2/ex48/skeleton/ex48/lexicon.py ================================================ class Lexicon(object): def convert_number(s): try: return int(s) except ValueError: return None def scan(s): directions = ['north', 'south', 'west', 'east'] verbs = ['go', 'kill', 'eat'] stops = ['the', 'in', 'of'] nouns = ['bear', 'princess'] result = [] words = s.lower().split() for word in words: if word in directions: result.append(('direction', word)) elif word in verbs: result.append(('verb', word)) elif word in stops: result.append(('stop', word)) elif word in nouns: result.append(('noun', word)) elif Lexicon.convert_number(word): result.append(('number', int(word))) else: result.append(('error', word)) return result ================================================ FILE: Python2/ex48/skeleton/setup.py ================================================ from distutils.core import setup setup( name = "lexicon", packages = ["ex48"], version = "1.0", description = "lexicon example", author = "Joseph Pan", author_email = "cs.wzpan@gmail.com", url = "http://hahack.com/", download_url = "", keywords = ["lexicon"], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Linguistic", ], long_description = """ Put a long description here. """ ) ================================================ FILE: Python2/ex48/skeleton/test/__init__.py ================================================ ================================================ FILE: Python2/ex48/skeleton/test/lexicon_tests.py ================================================ from nose.tools import * from ex48 import lexicon def text_directions(): assert_equal(lexicon.scan("north"), [('direction', 'north')]) result = lexicon.scan("north South EAST west dOwn up left right back") assert_equal(result, [('direction', 'north'), ('direction', 'South'), ('direction', 'EAST'), ('direction', 'west'), ('direction', 'dOwn'), ('direction', 'up'), ('direction', 'left'), ('direction', 'right'), ('direction', 'back') ]) def test_verbs(): assert_equal(lexicon.scan("go"), [('verb', 'go')]) result = lexicon.scan("go KILL eat stop") assert_equal(result, [('verb', 'go'), ('verb', 'KILL'), ('verb', 'eat'), ('verb', 'stop') ]) def test_stops(): assert_equal(lexicon.scan("the"), [('stop', 'the')]) result = lexicon.scan("the in of FROM at it") assert_equal(result, [('stop', 'the'), ('stop', 'in'), ('stop', 'of'), ('stop', 'FROM'), ('stop', 'at'), ('stop', 'it'), ]) def test_numbers(): assert_equal(lexicon.scan("1234"), [('number', '1234')]) result = lexicon.scan("3 91234 23098 8128 0") assert_equal(result, [('number', '3'), ('number', '91234'), ('number', '23098'), ('number', '8128'), ('number', '0'), ]) def test_errors(): assert_equal(lexicon.scan("ASDFADFASDF"), [('error', 'ASDFADFASDF')]) result = lexicon.scan("Bear IAS princess") assert_equal(result, [('noun', 'Bear'), ('error', 'IAS'), ('noun', 'princess') ]) ================================================ FILE: Python2/ex49/skeleton/ex49/__init__.py ================================================ ================================================ FILE: Python2/ex49/skeleton/ex49/parser.py ================================================ class ParserError(Exception): pass class Sentence(object): def __init__(self, subject, verb, object): # remember we take ('noun','princess') tuples and convert them self.subject = subject[1] self.verb = verb[1] self.object = object[1] def peek(word_list): if word_list: word = word_list[0] return word[0] else: return None def match(word_list, expecting): if word_list: # notice the pop function here word = word_list.pop(0) if word[0] == expecting: return word else: return None else: return None def skip(word_list, word_type): while peek(word_list) == word_type: # remove words that belongs to word_type from word_list match(word_list, word_type) class Parser(object): def parse_verb(self, word_list): skip(word_list, 'stop') if peek(word_list) == 'verb': return match(word_list, 'verb') else: raise ParserError("Expected a verb next.") def parse_object(self, word_list): skip(word_list, 'stop') next = peek(word_list) if next == 'noun': return match(word_list, 'noun') if next == 'direction': return match(word_list, 'direction') else: raise ParserError("Expected a noun or direction next.") def parse_subject(self, word_list, subj): verb = self.parse_verb(word_list) obj = self.parse_object(word_list) return Sentence(subj, verb, obj) def parse_sentence(self, word_list): skip(word_list, 'stop') start = peek(word_list) if start == 'noun': subj = match(word_list, 'noun') return self.parse_subject(word_list, subj) elif start == 'verb': # assume the subject is the player then return self.parse_subject(word_list, ('noun', 'player')) else: raise ParserError("Must start with subject, object, or verb not: %s" % start) ================================================ FILE: Python2/ex49/skeleton/setup.py ================================================ from distutils.core import setup setup( name = "MakeSentences", packages = ["ex49"], version = "1.0", description = "Making Sentences", author = "Joseph Pan", author_email = "cs.wzpan@gmail.com", url = "http://hahack.com/", download_url = "", keywords = ["lexicon"], classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Development Status :: 4 - Beta", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Linguistic", ], long_description = """ Put a long description here. """ ) ================================================ FILE: Python2/ex49/skeleton/test/__init__.py ================================================ ================================================ FILE: Python2/ex49/skeleton/test/parser_test.py ================================================ from nose.tools import * from ex49.parser import * from ex48.lexicon import * from copy import deepcopy # construct a test set that consists of several test lists global_test_lists = [ scan('south'), scan('door'), scan('go'), scan('to'), scan('234'), scan('error123'), scan('the east door'), scan('go to east'), scan('bear go to the door'), scan('the princess kill 10 bears') ] # the type of the the first tuple for each test list test_types = ['direction', 'noun', 'verb', 'stop', 'number', 'error', 'stop', 'verb', 'noun', 'stop', None] list_len = len(global_test_lists) def test_peek(): ''' test peek function ''' test_lists = deepcopy(global_test_lists) for i in range(list_len): test_list = test_lists[i] expected_word = test_types[i] assert_equal(peek(test_list), expected_word) def test_match(): ''' test match function ''' test_lists = deepcopy(global_test_lists) for i in range(list_len): test_list = test_lists[i] test_type = test_types[i] if len(test_list) > 0: expected_tuple = test_list[0] else: expected_tuple = None assert_equal(match(test_list, test_type), expected_tuple) def test_skip(): ''' test skip function ''' test_lists = deepcopy(global_test_lists) expected_lists1 = [scan('south'), scan('door'), scan('go'), [], scan('234'), scan('error123'), scan('east door'), scan('go to east'), scan('bear go to the door'), scan('princess kill 10 bear'), []] for i in range(list_len): test_list = test_lists[i] expected_list = expected_lists1[i] skip(test_list, 'stop') assert_equal(test_list, expected_list) test_list2 = [('error', 'error123')] expected_list2 = [] skip(test_list2, 'error') assert_equal(test_list2, expected_list2) def test_parse_verb(): ''' test parse_verb function ''' parser = Parser() # test good situations test_lists_good = [scan('go'), scan('go to east'), scan('to error123 eat')] expected_lists = [scan('go'), scan('go'), scan('eat')] for i in range(len(test_lists_good)): test_list = test_lists_good[i] expected_list = expected_lists[i] assert_equal(parser.parse_verb(test_list), *expected_list) # test bad situations test_lists_bad = [scan('south'), scan('door'), scan('234'), scan('east door'), scan('error123'), scan('to'), scan('bear go to the door'), scan('the princess kill 10 bear'), []] for i in range(len(test_lists_bad)): test_list = test_lists_bad[i] assert_raises(ParserError, parser.parse_verb, test_list) def test_parse_num(): ''' test parse_num function ''' parser = Parser() # test good situations test_lists_good = [scan('302'), scan('to error123 302')] expected_lists = [scan('302'), scan('302')] for i in range(len(test_lists_good)): test_list = test_lists_good[i] expected_list = expected_lists[i] assert_equal(parser.parse_num(test_list), *expected_list) # test bad situations test_lists_bad = [scan('south'), scan('door'), scan('to'), scan('error123'), scan('east door'), scan('bear go to the door'), scan('the princess kill 10 bear'),[]] for i in range(len(test_lists_bad)): test_list = test_lists_bad[i] assert_equal(parser.parse_num(test_list), None) def test_parse_object(): ''' test parse_object function ''' parser = Parser() # test good situations test_lists_good = [scan('south'), scan('door'), scan('the bear'), scan('east door'), scan('bear go to the door'), scan('the princess kill 10 bear')] expected_lists = [scan('south'), scan('door'), scan('bear'), scan('east'), scan('bear'), scan('princess')] for i in range(len(test_lists_good)): test_list = test_lists_good[i] expected_list = expected_lists[i] assert_equal(parser.parse_object(test_list), *expected_list) # test bad situations test_lists_bad = [scan('go'), scan('to'), scan('234'), scan('error123'), scan('go to east'), []] for i in range(len(test_lists_bad)): test_list = test_lists_bad[i] assert_raises(ParserError, parser.parse_object, test_list) def test_class_sentence(): # test good situations test_lists_good = [scan('bear go east'), scan('princess kill bear'), scan( 'princess kill 10 bears')] expected_nums = [1, 1, 10] expected_objects = ['east', 'bear', 'bear'] for i in range(len(test_lists_good)): test_list = test_lists_good[i] test_num = expected_nums[i] test_object = expected_objects[i] sentence = Sentence(*test_list) assert_equal(sentence.subject, test_list[0][1]) assert_equal(sentence.verb, test_list[1][1]) assert_equal(sentence.num, test_num) assert_equal(sentence.object, test_object) # test bad situations, for more restrict checking test_lists_bad = [scan('south'), scan('bear'), scan('go'), scan('to'), scan('the'), scan('door'), scan('bear go to the door'), scan('the princess kill 10 bears'), []] for i in range(len(test_lists_good)): test_list = test_lists_bad[i] assert_raises(TypeError, Sentence, *test_list) def test_parse_subject(): ''' test parse_subject function ''' parser = Parser() test_lists = [scan('error123 eat princess'), scan('go to east'), scan('go error123 to the carbinet door'), scan('kill 10 bears')] test_subjects = [scan('bear'), scan('princess'), scan('carbinet'), scan('princess')] expected_verbs = ['eat', 'go', 'go', 'kill'] expected_objects = ['princess', 'east', 'carbinet', 'bear'] expected_nums = [1, 1, 1, 10] for i in range(len(test_lists)): test_list = test_lists[i] test_subject = test_subjects[i] expected_verb = expected_verbs[i] expected_object = expected_objects[i] expected_num = expected_nums[i] sentence = parser.parse_subject(test_list, test_subject[0]) assert_equal(sentence.subject, test_subject[0][1]) assert_equal(sentence.verb, expected_verb) assert_equal(sentence.object, expected_object) assert_equal(sentence.num, expected_num) def test_parse_sentence(): ''' test parse_sentence function ''' parser = Parser() # test good situations test_lists1 = [scan('bear go to the door'), scan('the princess kill 10 bears'), scan('kill the bear')] expected_subjects = ['bear', 'princess', 'player'] expected_verbs = ['go', 'kill', 'kill'] expected_objects = ['door', 'bear', 'bear'] expected_nums = [1, 10, 1] for i in range(len(test_lists1)): test_list = test_lists1[i] sentence = parser.parse_sentence(test_list) expected_subject = expected_subjects[i] expected_verb = expected_verbs[i] expected_object = expected_objects[i] expected_num = expected_nums[i] assert_equal(sentence.subject, expected_subject) assert_equal(sentence.verb, expected_verb) assert_equal(sentence.object, expected_object) assert_equal(sentence.num, expected_num) # test bad situations test_lists2 = [scan('234')] for i in range(len(test_lists2)): test_list = test_lists2[i] assert_raises(ParserError, parser.parse_object, test_list) ================================================ FILE: Python2/game/skeleton/README ================================================ A little python site 1) For Linux/MacOSX user Please execute ``` export PYTHONPATH=$PYTHONPATH:. python2 bin/app.py ``` then visit to browse the site! 1) For Windows user Please execute ``` $env:PYTHONPATH = "$env:PYTHONPATH;." python2 bin/app.py ``` then visit to browse the site! ================================================ FILE: Python2/game/skeleton/bin/MultipartPostHandler.py ================================================ #!/usr/bin/python #### # 02/2006 Will Holcomb # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # 7/26/07 Slightly modified by Brian Schneider # in order to support unicode files ( multipart_encode function ) """ Usage: Enables the use of multipart/form-data for posting forms Inspirations: Upload files in python: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 urllib2_file: Fabien Seisen: Example: import MultipartPostHandler, urllib2, cookielib cookies = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies), MultipartPostHandler.MultipartPostHandler) params = { "username" : "bob", "password" : "riviera", "file" : open("filename", "rb") } opener.open("http://wwww.bobsite.com/upload/", params) Further Example: The main function of this file is a sample which downloads a page and then uploads it to the W3C validator. """ import urllib import urllib2 import mimetools, mimetypes import os, stat from cStringIO import StringIO class Callable: def __init__(self, anycallable): self.__call__ = anycallable # Controls how sequences are uncoded. If true, elements may be given multiple values by # assigning a sequence. doseq = 1 class MultipartPostHandler(urllib2.BaseHandler): handler_order = urllib2.HTTPHandler.handler_order - 10 # needs to run first def http_request(self, request): data = request.get_data() if data is not None and type(data) != str: v_files = [] v_vars = [] try: for(key, value) in data.items(): if type(value) == file: v_files.append((key, value)) else: v_vars.append((key, value)) except TypeError: systype, value, traceback = sys.exc_info() raise TypeError, "not a valid non-string sequence or mapping object", traceback if len(v_files) == 0: data = urllib.urlencode(v_vars, doseq) else: boundary, data = self.multipart_encode(v_vars, v_files) contenttype = 'multipart/form-data; boundary=%s' % boundary if(request.has_header('Content-Type') and request.get_header('Content-Type').find('multipart/form-data') != 0): print "Replacing %s with %s" % (request.get_header('content-type'), 'multipart/form-data') request.add_unredirected_header('Content-Type', contenttype) request.add_data(data) return request def multipart_encode(vars, files, boundary = None, buf = None): if boundary is None: boundary = mimetools.choose_boundary() if buf is None: buf = StringIO() for(key, value) in vars: buf.write('--%s\r\n' % boundary) buf.write('Content-Disposition: form-data; name="%s"' % key) buf.write('\r\n\r\n' + value + '\r\n') for(key, fd) in files: file_size = os.fstat(fd.fileno())[stat.ST_SIZE] filename = fd.name.split('/')[-1] contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' buf.write('--%s\r\n' % boundary) buf.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)) buf.write('Content-Type: %s\r\n' % contenttype) # buffer += 'Content-Length: %s\r\n' % file_size fd.seek(0) buf.write('\r\n' + fd.read() + '\r\n') buf.write('--' + boundary + '--\r\n\r\n') buf = buf.getvalue() return boundary, buf multipart_encode = Callable(multipart_encode) https_request = http_request def main(): import tempfile, sys validatorURL = "http://validator.w3.org/check" opener = urllib2.build_opener(MultipartPostHandler) def validateFile(url): temp = tempfile.mkstemp(suffix=".html") os.write(temp[0], opener.open(url).read()) params = { "ss" : "0", # show source "doctype" : "Inline", "uploaded_file" : open(temp[1], "rb") } print opener.open(validatorURL, params).read() os.remove(temp[1]) if len(sys.argv[1:]) > 0: for arg in sys.argv[1:]: validateFile(arg) else: validateFile("http://www.google.com") if __name__=="__main__": main() ================================================ FILE: Python2/game/skeleton/bin/__init__.py ================================================ ================================================ FILE: Python2/game/skeleton/bin/app.py ================================================ import web import datetime import os from bin import map urls = ( '/', 'Index', '/hello', 'SayHello', '/image', 'Upload', '/game', 'GameEngine', '/entry', 'Entry' ) app = web.application(urls, locals()) # little hack so that debug mode works with sessions if web.config.get('_session') is None: store = web.session.DiskStore('sessions') session = web.session.Session(app, store, initializer={'room': None, 'name': 'Jedi'}) web.config._session = session else: session = web.config._session render = web.template.render('templates/', base="layout") class Index: def GET(self): return render.index() class SayHello: def GET(self): return render.hello_form() def POST(self): form = web.input(name="Nobody", greet="hello") if form.name == '': form.name = "Nobody" if form.greet == '': form.greet = "Hello" greeting = "%s, %s" % (form.greet, form.name) return render.hello(greeting = greeting) class Upload: ''' using cgi to upload and show image ''' def GET(self): return render.upload_form() def POST(self): form = web.input(myfile={}) # web.debug(form['myfile'].file.read()) # get the folder name upload_time = datetime.datetime.now().strftime("%Y-%m-%d") # create the folder folder = os.path.join('./static', upload_time) if not os.access(folder, 1): os.mkdir(folder) # get the file name filename = os.path.join(folder, form['myfile'].filename) print(type(form['myfile'])) with open(filename, 'wb') as f: f.write(form['myfile'].file.read()) f.close() return render.show(filename = filename) class count: def GET(self): session.count += 1 return str(session.count) class reset: def GET(self): session.kill() return "" class Entry(object): def GET(self): return render.entry() def POST(self): form = web.input(name="Jedi") if form.name != '': session.name = form.name session.room = map.START #session.description = session.room.description web.seeother("/game") class GameEngine(object): def GET(self): if session.room: return render.show_room(room=session.room, name=session.name) else: # why is there here? do you need it? return render.you_died() def POST(self): form = web.input(action=None) # there is a bug here, can you fix it? web.debug(session.room.name) if session.room and session.room.name != "The End" and form.action: session.room = session.room.go(form.action) web.seeother("/game") if __name__ == "__main__": app.run() ================================================ FILE: Python2/game/skeleton/bin/map.py ================================================ from random import randint class RoomError(Exception): pass class Room(object): def __init__(self, name, description): self.name = name self.description = description self.paths = {} def go(self, direction): return self.paths.get(direction, None) def add_paths(self, paths): self.paths.update(paths) central_corridor = Room("Central Corridor", """ The Gothons of Planet Percal #25 have invaded your ship and destroyed your entire crew. You are the last surviving member and your last mission is to get the neutron destruct bomb from the Weapons Armory, put it in the bridge, and blow the ship up after getting into an escape pod. You're running down the central corridor to the Weapons Armory when a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume flowing around his hate filled body. He's blocking the door to the Armory and about to pull a weapon to blast you. """ ) laser_weapon_armory = Room("Laser Weapon Armory", """ Lucky for you they made you learn Gothon insults in the academy. You tell the one Gothon joke you know: Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr. The Gothon stops, tries not to laugh, then busts out laughing and can't move. While he's laughing you run up and shoot him square in the head putting him down, then jump through the Weapon Armory door. You do a dive roll into the Weapon Armory, crouch and scan the room for more Gothons that might be hiding. It's dead quiet, too quiet. You stand up and run to the far side of the room and find the neutron bomb in its container. There's a keypad lock on the box and you need the code to get the bomb out. If you get the code wrong 10 times then the lock closes forever and you can't get the bomb. The code is 3 digits. """ ) the_bridge = Room("The Bridge", """ The container clicks open and the seal breaks, letting gas out. You grab the neutron bomb and run as fast as you can to the bridge where you must place it in the right spot. You burst onto the Bridge with the netron destruct bomb under your arm and surprise 5 Gothons who are trying to take control of the ship. Each of them has an even uglier clown costume than the last. They haven't pulled their weapons out yet, as they see the active bomb under your arm and don't want to set it off. """) escape_pod = Room("Escape Pod", """ You point your blaster at the bomb under your arm and the Gothons put their hands up and start to sweat. You inch backward to the door, open it, and then carefully place the bomb on the floor, pointing your blaster at it. You then jump back through the door, punch the close button and blast the lock so the Gothons can't get out. Now that the bomb is placed you run to the escape pod to get off this tin can. You rush through the ship desperately trying to make it to the escape pod before the whole ship explodes. It seems like hardly any Gothons are on the ship, so your run is clear of interference. You get to the chamber with the escape pods, and now need to pick one to take. Some of them could be damaged but you don't have time to look. There's 5 pods, which one do you take? """) the_end_winner = Room("The End", """ You jump into pod 2 and hit the eject button. The pod easily slides out into space heading to the planet below. As it flies to the planet, you look back and see your ship implode then explode like a bright star, taking out the Gothon ship at the same time. You won! """) the_end_loser = Room("The End", """ You jump into a random pod and hit the eject button. The pod escapes out into the void of space, then implodes as the hull ruptures, crushing your body into jam jelly. """ ) generic_death = Room("death", "You died") escape_pod.add_paths({ '2': the_end_winner, '*': the_end_loser }) the_bridge.add_paths({ 'throw the bomb': generic_death, 'slowly place the bomb': escape_pod }) laser_weapon_armory.add_paths({ '0132': the_bridge, '*': generic_death }) central_corridor.add_paths({ 'shoot!': generic_death, 'dodge!': generic_death, 'tell a joke': laser_weapon_armory }) START = central_corridor ================================================ FILE: Python2/game/skeleton/setup.py ================================================ try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'My Project', 'author': 'Joseph Pan', 'url': 'URL to get it at.', 'download_url': 'Where to download it.', 'author_email': 'cs.wzpan@gmail.com', 'version': '0.1', 'install_requires': ['nose'], 'packages': ['ex47'], 'scripts': [], 'name': 'projectname' } setup(**config) ================================================ FILE: Python2/game/skeleton/static/css/marketing.css ================================================ * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body { margin: 0 auto; line-height: 1.7em; } .l-box { padding: 1em; } .header { margin: 0 0; } .header .pure-menu { padding: 0.5em; } .header .pure-menu li a:hover, .header .pure-menu li a:focus { background: none; border: none; color: #aaa; } body .primary-button { background: #02a6eb; color: #fff; } .splash { margin: 2em auto 0; padding: 3em 0.5em; background: #eee; } .splash .splash-head { font-size: 300%; margin: 0em 0; line-height: 1.2em; } .splash .splash-subhead { color: #999; font-weight: 300; line-height: 1.4em; } .splash .primary-button { font-size: 150%; } .content .content-subhead { color: #999; padding-bottom: 0.3em; text-transform: uppercase; margin: 0; border-bottom: 2px solid #eee; display: inline-block; } .content .content-ribbon { margin: 3em; border-bottom: 1px solid #eee; } .ribbon { background: #eee; text-align: center; padding: 2em; color: #999; } .ribbon h2 { display: inline; font-weight: normal; } .footer { background: #111; color: #666; text-align: center; padding: 1em; font-size: 80%; } .pure-button-success, .pure-button-error, .pure-button-warning, .pure-button-secondary { color: white; border-radius: 4px; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2); } .pure-button-success { background: rgb(28, 184, 65); /* this is a green */ } .pure-button-error { background: rgb(202, 60, 60); /* this is a maroon */ } .pure-button-warning { background: rgb(223, 117, 20); /* this is an orange */ } .pure-button-secondary { background: rgb(66, 184, 221); /* this is a light blue */ } .content .content-quote { font-family: "Georgia", serif; color: #666; font-style: italic; line-height: 1.8em; border-left: 5px solid #ddd; padding-left: 1.5em; } ================================================ FILE: Python2/game/skeleton/static/css/modal.css ================================================ /*! * Bootstrap v2.3.2 * * Copyright 2012 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */ .modal-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1040; background-color: #000000; } .modal-backdrop.fade { opacity: 0; } .modal-backdrop, .modal-backdrop.fade.in { opacity: 0.8; filter: alpha(opacity=80); } .modal { position: fixed; top: 10%; left: 50%; z-index: 1050; width: 560px; margin-left: -280px; background-color: #ffffff; border: 1px solid #999; border: 1px solid rgba(0, 0, 0, 0.3); *border: 1px solid #999; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; outline: none; -webkit-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); -moz-box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3); -webkit-background-clip: padding-box; -moz-background-clip: padding-box; background-clip: padding-box; } .modal.fade { top: -25%; -webkit-transition: opacity 0.3s linear, top 0.3s ease-out; -moz-transition: opacity 0.3s linear, top 0.3s ease-out; -o-transition: opacity 0.3s linear, top 0.3s ease-out; transition: opacity 0.3s linear, top 0.3s ease-out; } .modal.fade.in { top: 10%; } .modal-header { padding: 9px 15px; border-bottom: 1px solid #eee; } .modal-header .close { margin-top: 2px; } .modal-header h3 { margin: 0; line-height: 30px; } .modal-body { position: relative; max-height: 400px; padding: 15px; overflow-y: auto; } .modal-form { margin-bottom: 0; } .modal-footer { padding: 14px 15px 15px; margin-bottom: 0; text-align: right; background-color: #f5f5f5; border-top: 1px solid #ddd; -webkit-border-radius: 0 0 6px 6px; -moz-border-radius: 0 0 6px 6px; border-radius: 0 0 6px 6px; *zoom: 1; -webkit-box-shadow: inset 0 1px 0 #ffffff; -moz-box-shadow: inset 0 1px 0 #ffffff; box-shadow: inset 0 1px 0 #ffffff; } .modal-footer:before, .modal-footer:after { display: table; line-height: 0; content: ""; } .modal-footer:after { clear: both; } .modal-footer .btn + .btn { margin-bottom: 0; margin-left: 5px; } .modal-footer .btn-group .btn + .btn { margin-left: -1px; } .modal-footer .btn-block + .btn-block { margin-left: 0; } .hide { display: none; } .show { display: block; } .fade { opacity: 0; -webkit-transition: opacity 0.15s linear; -moz-transition: opacity 0.15s linear; -o-transition: opacity 0.15s linear; transition: opacity 0.15s linear; } .fade.in { opacity: 1; } ================================================ FILE: Python2/game/skeleton/static/css/pure-min.css ================================================ /*! Pure v0.2.1 Copyright 2013 Yahoo! Inc. All rights reserved. Licensed under the BSD License. https://github.com/yui/pure/blob/master/LICENSE.md */ /*! normalize.css v1.1.2 | MIT License | git.io/normalize Copyright (c) Nicolas Gallagher and Jonathan Neal */ /*! normalize.css v1.1.2 | MIT License | git.io/normalize */article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-size:100%;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}html,button,input,select,textarea{font-family:sans-serif}body{margin:0}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{font-size:2em;margin:.67em 0}h2{font-size:1.5em;margin:.83em 0}h3{font-size:1.17em;margin:1em 0}h4{font-size:1em;margin:1.33em 0}h5{font-size:.83em;margin:1.67em 0}h6{font-size:.67em;margin:2.33em 0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}blockquote{margin:1em 40px}dfn{font-style:italic}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}mark{background:#ff0;color:#000}p,pre{margin:1em 0}code,kbd,pre,samp{font-family:monospace,serif;_font-family:'courier new',monospace;font-size:1em}pre{white-space:pre;white-space:pre-wrap;word-wrap:break-word}q{quotes:none}q:before,q:after{content:'';content:none}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}dl,menu,ol,ul{margin:1em 0}dd{margin:0 0 0 40px}menu,ol,ul{padding:0 0 0 40px}nav ul,nav ol{list-style:none;list-style-image:none}img{border:0;-ms-interpolation-mode:bicubic}svg:not(:root){overflow:hidden}figure{margin:0}form{margin:0}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0;white-space:normal;*margin-left:-7px}button,input,select,textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}button,input{line-height:normal}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer;*overflow:visible}button[disabled],html input[disabled]{cursor:default}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0;*height:13px;*width:13px}input[type=search]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0} .pure-button{display:inline-block;*display:inline;zoom:1;line-height:normal;white-space:nowrap;vertical-align:baseline;text-align:center;cursor:pointer;-webkit-user-drag:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.pure-button::-moz-focus-inner{padding:0;border:0}.pure-button{font-size:100%;*font-size:90%;*overflow:visible;padding:.5em 1.5em;color:#444;color:rgba(0,0,0,.8);*color:#444;border:1px solid #999;border:0 rgba(0,0,0,0);background-color:#E6E6E6;text-decoration:none;border-radius:2px;-webkit-font-smoothing:antialiased;-webkit-transition:.1s linear -webkit-box-shadow;-moz-transition:.1s linear -moz-box-shadow;-ms-transition:.1s linear box-shadow;-o-transition:.1s linear box-shadow;transition:.1s linear box-shadow}.pure-button-hover,.pure-button:hover,.pure-button:focus{filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#1a000000', GradientType=0);background-image:-webkit-gradient(linear,0 0,0 100%,from(transparent),color-stop(40%,rgba(0,0,0,.05)),to(rgba(0,0,0,.1)));background-image:-webkit-linear-gradient(transparent,rgba(0,0,0,.05) 40%,rgba(0,0,0,.1));background-image:-moz-linear-gradient(top,rgba(0,0,0,.05) 0,rgba(0,0,0,.1));background-image:-ms-linear-gradient(transparent,rgba(0,0,0,.05) 40%,rgba(0,0,0,.1));background-image:-o-linear-gradient(transparent,rgba(0,0,0,.05) 40%,rgba(0,0,0,.1));background-image:linear-gradient(transparent,rgba(0,0,0,.05) 40%,rgba(0,0,0,.1))}.pure-button:focus{outline:0}.pure-button-active,.pure-button:active{box-shadow:0 0 0 1px rgba(0,0,0,.15) inset,0 0 6px rgba(0,0,0,.2) inset}.pure-button[disabled],.pure-button-disabled,.pure-button-disabled:hover,.pure-button-disabled:focus,.pure-button-disabled:active{border:0;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);filter:alpha(opacity=40);-khtml-opacity:.4;-moz-opacity:.4;opacity:.4;cursor:not-allowed;box-shadow:none}.pure-button-hidden{display:none}.pure-button::-moz-focus-inner{padding:0;border:0}.pure-button-primary,.pure-button-selected,a.pure-button-primary,a.pure-button-selected{background-color:#0078e7;color:#fff} .pure-form{margin:0}.pure-form fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}.pure-form legend{border:0;padding:0;white-space:normal;*margin-left:-7px}.pure-form button,.pure-form input,.pure-form select,.pure-form textarea{font-size:100%;margin:0;vertical-align:baseline;*vertical-align:middle}.pure-form button,.pure-form input{line-height:normal}.pure-form button,.pure-form input[type=button],.pure-form input[type=reset],.pure-form input[type=submit]{-webkit-appearance:button;cursor:pointer;*overflow:visible}.pure-form button[disabled],.pure-form input[disabled]{cursor:default}.pure-form input[type=checkbox],.pure-form input[type=radio]{box-sizing:border-box;padding:0;*height:13px;*width:13px}.pure-form input[type=search]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}.pure-form input[type=search]::-webkit-search-cancel-button,.pure-form input[type=search]::-webkit-search-decoration{-webkit-appearance:none}.pure-form button::-moz-focus-inner,.pure-form input::-moz-focus-inner{border:0;padding:0}.pure-form textarea{overflow:auto;vertical-align:top}.pure-form input[type=text],.pure-form input[type=password],.pure-form input[type=email],.pure-form input[type=url],.pure-form input[type=date],.pure-form input[type=month],.pure-form input[type=time],.pure-form input[type=datetime],.pure-form input[type=datetime-local],.pure-form input[type=week],.pure-form input[type=number],.pure-form input[type=search],.pure-form input[type=tel],.pure-form input[type=color],.pure-form select,.pure-form textarea{padding:.5em .6em;display:inline-block;border:1px solid #ccc;font-size:.8em;box-shadow:inset 0 1px 3px #ddd;border-radius:4px;-webkit-transition:.3s linear border;-moz-transition:.3s linear border;-ms-transition:.3s linear border;-o-transition:.3s linear border;transition:.3s linear border;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-font-smoothing:antialiased}.pure-form input[type=text]:focus,.pure-form input[type=password]:focus,.pure-form input[type=email]:focus,.pure-form input[type=url]:focus,.pure-form input[type=date]:focus,.pure-form input[type=month]:focus,.pure-form input[type=time]:focus,.pure-form input[type=datetime]:focus,.pure-form input[type=datetime-local]:focus,.pure-form input[type=week]:focus,.pure-form input[type=number]:focus,.pure-form input[type=search]:focus,.pure-form input[type=tel]:focus,.pure-form input[type=color]:focus,.pure-form select:focus,.pure-form textarea:focus{outline:0;outline:thin dotted \9;border-color:#129FEA}.pure-form input[type=file]:focus,.pure-form input[type=radio]:focus,.pure-form input[type=checkbox]:focus{outline:thin dotted #333;outline:1px auto #129FEA}.pure-form .pure-checkbox,.pure-form .pure-radio{margin:.5em 0;display:block}.pure-form input[type=text][disabled],.pure-form input[type=password][disabled],.pure-form input[type=email][disabled],.pure-form input[type=url][disabled],.pure-form input[type=date][disabled],.pure-form input[type=month][disabled],.pure-form input[type=time][disabled],.pure-form input[type=datetime][disabled],.pure-form input[type=datetime-local][disabled],.pure-form input[type=week][disabled],.pure-form input[type=number][disabled],.pure-form input[type=search][disabled],.pure-form input[type=tel][disabled],.pure-form input[type=color][disabled],.pure-form select[disabled],.pure-form textarea[disabled]{cursor:not-allowed;background-color:#eaeded;color:#cad2d3}.pure-form input[readonly],.pure-form select[readonly],.pure-form textarea[readonly],.pure-form input[readonly]:focus,.pure-form select[readonly]:focus,.pure-form textarea[readonly]:focus{background:#eee;color:#777;border-color:#ccc}.pure-form input:focus:invalid,.pure-form textarea:focus:invalid,.pure-form select:focus:invalid{color:#b94a48;border:1px solid #ee5f5b}.pure-form input:focus:invalid:focus,.pure-form textarea:focus:invalid:focus,.pure-form select:focus:invalid:focus{border-color:#e9322d}.pure-form input[type=file]:focus:invalid:focus,.pure-form input[type=radio]:focus:invalid:focus,.pure-form input[type=checkbox]:focus:invalid:focus{outline-color:#e9322d}.pure-form select{border:1px solid #ccc;background-color:#fff}.pure-form select[multiple]{height:auto}.pure-form label{margin:.5em 0 .2em;font-size:90%}.pure-form fieldset{margin:0;padding:.35em 0 .75em;border:0}.pure-form legend{display:block;width:100%;padding:.3em 0;margin-bottom:.3em;font-size:125%;color:#333;border-bottom:1px solid #e5e5e5}.pure-form-stacked input[type=text],.pure-form-stacked input[type=password],.pure-form-stacked input[type=email],.pure-form-stacked input[type=url],.pure-form-stacked input[type=date],.pure-form-stacked input[type=month],.pure-form-stacked input[type=time],.pure-form-stacked input[type=datetime],.pure-form-stacked input[type=datetime-local],.pure-form-stacked input[type=week],.pure-form-stacked input[type=number],.pure-form-stacked input[type=search],.pure-form-stacked input[type=tel],.pure-form-stacked input[type=color],.pure-form-stacked select,.pure-form-stacked label,.pure-form-stacked textarea{display:block;margin:.25em 0}.pure-form-aligned input,.pure-form-aligned textarea,.pure-form-aligned select,.pure-form-aligned .pure-help-inline,.pure-form-message-inline{display:inline-block;*display:inline;*zoom:1;vertical-align:middle}.pure-form-aligned .pure-control-group{margin-bottom:.5em}.pure-form-aligned .pure-control-group label{text-align:right;display:inline-block;vertical-align:middle;width:10em;margin:0 1em 0 0}.pure-form-aligned .pure-controls{margin:1.5em 0 0 10em}.pure-form input.pure-input-rounded,.pure-form .pure-input-rounded{border-radius:2em;padding:.5em 1em}.pure-form .pure-group fieldset{margin-bottom:10px}.pure-form .pure-group input{display:block;padding:10px;margin:0;border-radius:0;position:relative;top:-1px}.pure-form .pure-group input:focus{z-index:2}.pure-form .pure-group input:first-child{top:1px;border-radius:4px 4px 0 0}.pure-form .pure-group input:last-child{top:-2px;border-radius:0 0 4px 4px}.pure-form .pure-group button{margin:.35em 0}.pure-form .pure-input-1{width:100%}.pure-form .pure-input-2-3{width:66%}.pure-form .pure-input-1-2{width:50%}.pure-form .pure-input-1-3{width:33%}.pure-form .pure-input-1-4{width:25%}.pure-form .pure-help-inline,.pure-form-message-inline{display:inline-block;padding-left:.3em;color:#666;vertical-align:middle;font-size:90%}.pure-form-message{display:block;color:#666;font-size:90%}@media only screen and (max-width :480px){.pure-form button[type=submit]{margin:.7em 0 0}.pure-form input[type=text],.pure-form input[type=password],.pure-form input[type=email],.pure-form input[type=url],.pure-form input[type=date],.pure-form input[type=month],.pure-form input[type=time],.pure-form input[type=datetime],.pure-form input[type=datetime-local],.pure-form input[type=week],.pure-form input[type=number],.pure-form input[type=search],.pure-form input[type=tel],.pure-form input[type=color],.pure-form label{margin-bottom:.3em;display:block}.pure-group input[type=text],.pure-group input[type=password],.pure-group input[type=email],.pure-group input[type=url],.pure-group input[type=date],.pure-group input[type=month],.pure-group input[type=time],.pure-group input[type=datetime],.pure-group input[type=datetime-local],.pure-group input[type=week],.pure-group input[type=number],.pure-group input[type=search],.pure-group input[type=tel],.pure-group input[type=color]{margin-bottom:0}.pure-form-aligned .pure-control-group label{margin-bottom:.3em;text-align:left;display:block;width:100%}.pure-form-aligned .pure-controls{margin:1.5em 0 0}.pure-form .pure-help-inline,.pure-form-message-inline,.pure-form-message{display:block;font-size:80%;padding:.2em 0 .8em}} .pure-g{letter-spacing:-.31em;*letter-spacing:normal;*word-spacing:-.43em;text-rendering:optimizespeed}.opera-only :-o-prefocus,.pure-g{word-spacing:-.43em}.pure-u{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.pure-u-1,.pure-u-1-2,.pure-u-1-3,.pure-u-2-3,.pure-u-1-4,.pure-u-3-4,.pure-u-1-5,.pure-u-2-5,.pure-u-3-5,.pure-u-4-5,.pure-u-1-6,.pure-u-5-6,.pure-u-1-8,.pure-u-3-8,.pure-u-5-8,.pure-u-7-8,.pure-u-1-12,.pure-u-5-12,.pure-u-7-12,.pure-u-11-12,.pure-u-1-24,.pure-u-5-24,.pure-u-7-24,.pure-u-11-24,.pure-u-13-24,.pure-u-17-24,.pure-u-19-24,.pure-u-23-24{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.pure-u-1{width:100%}.pure-u-1-2{width:50%}.pure-u-1-3{width:33.33333%}.pure-u-2-3{width:66.66666%}.pure-u-1-4{width:25%}.pure-u-3-4{width:75%}.pure-u-1-5{width:20%}.pure-u-2-5{width:40%}.pure-u-3-5{width:60%}.pure-u-4-5{width:80%}.pure-u-1-6{width:16.666%}.pure-u-5-6{width:83.33%}.pure-u-1-8{width:12.5%}.pure-u-3-8{width:37.5%}.pure-u-5-8{width:62.5%}.pure-u-7-8{width:87.5%}.pure-u-1-12{width:8.3333%}.pure-u-5-12{width:41.6666%}.pure-u-7-12{width:58.3333%}.pure-u-11-12{width:91.6666%}.pure-u-1-24{width:4.1666%}.pure-u-5-24{width:20.8333%}.pure-u-7-24{width:29.1666%}.pure-u-11-24{width:45.8333%}.pure-u-13-24{width:54.1666%}.pure-u-17-24{width:70.8333%}.pure-u-19-24{width:79.1666%}.pure-u-23-24{width:95.8333%}.pure-g-r{letter-spacing:-.31em;*letter-spacing:normal;*word-spacing:-.43em}.opera-only :-o-prefocus,.pure-g-r{word-spacing:-.43em}.pure-g-r img{max-width:100%}@media (min-width:980px){.pure-visible-phone{display:none}.pure-visible-tablet{display:none}.pure-hidden-desktop{display:none}}@media (max-width:480px){.pure-g-r>.pure-u,.pure-g-r>[class *="pure-u-"]{width:100%}}@media (max-width:767px){.pure-g-r>.pure-u,.pure-g-r>[class *="pure-u-"]{width:100%}.pure-hidden-phone{display:none}.pure-visible-desktop{display:none}}@media (min-width:768px) and (max-width:979px){.pure-hidden-tablet{display:none}.pure-visible-desktop{display:none}} .pure-menu ul{position:absolute;visibility:hidden}.pure-menu.pure-menu-open{visibility:visible;z-index:2;width:100%}.pure-menu ul{left:-10000px;list-style:none;margin:0;padding:0;top:-10000px;z-index:1}.pure-menu>ul{position:relative}.pure-menu-open>ul{left:0;top:0;visibility:visible}.pure-menu-open>ul:focus{outline:0}.pure-menu li{position:relative}.pure-menu a,.pure-menu .pure-menu-heading{display:block;color:inherit;line-height:1.5em;padding:5px 20px;text-decoration:none;white-space:nowrap}.pure-menu.pure-menu-horizontal>.pure-menu-heading{display:inline-block;*display:inline;zoom:1;margin:0;vertical-align:middle}.pure-menu.pure-menu-horizontal>ul{display:inline-block;*display:inline;zoom:1;vertical-align:middle;height:2.4em}.pure-menu li a{padding:5px 20px}.pure-menu-can-have-children>.pure-menu-label:after{content:'\25B8';float:right;font-family:'Lucida Grande','Lucida Sans Unicode','DejaVu Sans',sans-serif;margin-right:-20px;margin-top:-1px}.pure-menu-can-have-children>.pure-menu-label{padding-right:30px}.pure-menu-separator{background-color:#dfdfdf;display:block;height:1px;font-size:0;margin:7px 2px;overflow:hidden}.pure-menu-hidden{display:none}.pure-menu-fixed{position:fixed;top:0;left:0;width:100%}.pure-menu-horizontal li{display:inline-block;*display:inline;zoom:1;vertical-align:middle}.pure-menu-horizontal li li{display:block}.pure-menu-horizontal>.pure-menu-children>.pure-menu-can-have-children>.pure-menu-label:after{content:"\25BE"}.pure-menu-horizontal>.pure-menu-children>.pure-menu-can-have-children>.pure-menu-label{padding-right:30px}.pure-menu-horizontal li.pure-menu-separator{height:50%;width:1px;margin:0 7px}.pure-menu-horizontal li li.pure-menu-separator{height:1px;width:auto;margin:7px 2px}.pure-menu.pure-menu-open,.pure-menu.pure-menu-horizontal li .pure-menu-children{background:#fff;border:1px solid #b7b7b7}.pure-menu.pure-menu-horizontal,.pure-menu.pure-menu-horizontal .pure-menu-heading{border:0}.pure-menu a{border:1px solid transparent;border-left:0;border-right:0}.pure-menu a,.pure-menu .pure-menu-can-have-children>li:after{color:#777}.pure-menu .pure-menu-can-have-children>li:hover:after{color:#fff}.pure-menu .pure-menu-open{background:#dedede}.pure-menu li a:hover,.pure-menu li a:focus{background:#eee}.pure-menu li.pure-menu-disabled a:hover,.pure-menu li.pure-menu-disabled a:focus{background:#fff;color:#bfbfbf}.pure-menu .pure-menu-disabled>a{background-image:none;border-color:transparent;cursor:default}.pure-menu .pure-menu-disabled>a,.pure-menu .pure-menu-can-have-children.pure-menu-disabled>a:after{color:#bfbfbf}.pure-menu .pure-menu-heading{color:#565d64;text-transform:uppercase;font-size:90%;margin-top:.5em;border-bottom-width:1px;border-bottom-style:solid;border-bottom-color:#dfdfdf}.pure-menu .pure-menu-selected a{color:#000}.pure-menu.pure-menu-open.pure-menu-fixed{border:0;border-bottom:1px solid #b7b7b7}.pure-paginator{letter-spacing:-.31em;*letter-spacing:normal;*word-spacing:-.43em;text-rendering:optimizespeed;list-style:none;margin:0;padding:0}.opera-only :-o-prefocus,.pure-paginator{word-spacing:-.43em}.pure-paginator li{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.pure-paginator .pure-button{border-radius:0;padding:.8em 1.4em;vertical-align:top;height:1.1em}.pure-paginator .pure-button:focus,.pure-paginator .pure-button:active{outline-style:none}.pure-paginator .prev,.pure-paginator .next{color:#C0C1C3;text-shadow:0 -1px 0 rgba(0,0,0,.45)}.pure-paginator .prev{border-radius:2px 0 0 2px}.pure-paginator .next{border-radius:0 2px 2px 0}@media (max-width:480px){.pure-menu-horizontal{width:100%}.pure-menu-children li{display:block;border-bottom:1px solid #000}} .pure-table{border-collapse:collapse;border-spacing:0;empty-cells:show;border:1px solid #cbcbcb}.pure-table caption{color:#000;font:italic 85%/1 arial,sans-serif;padding:1em 0;text-align:center}.pure-table td,.pure-table th{border-left:1px solid #cbcbcb;border-width:0 0 0 1px;font-size:inherit;margin:0;overflow:visible;padding:6px 12px}.pure-table td:first-child,.pure-table th:first-child{border-left-width:0}.pure-table thead{background:#e0e0e0;color:#000;text-align:left;vertical-align:bottom}.pure-table td{background-color:transparent}.pure-table-odd td{background-color:#f2f2f2}.pure-table-striped tr:nth-child(2n-1) td{background-color:#f2f2f2}.pure-table-bordered td{border-bottom:1px solid #cbcbcb}.pure-table-bordered tbody>tr:last-child td,.pure-table-horizontal tbody>tr:last-child td{border-bottom-width:0}.pure-table-horizontal td,.pure-table-horizontal th{border-width:0 0 1px;border-bottom:1px solid #cbcbcb}.pure-table-horizontal tbody>tr:last-child td{border-bottom-width:0} ================================================ FILE: Python2/game/skeleton/static/js/modal.js ================================================ /* ======================================================================== * Bootstrap: modal.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#modals * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================================== */ +function ($) { "use strict"; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element) this.$backdrop = this.isShown = null if (this.options.remote) this.$element.load(this.options.remote) } Modal.DEFAULTS = { backdrop: true , keyboard: true , show: true } Modal.prototype.toggle = function (_relatedTarget) { return this[!this.isShown ? 'show' : 'hide'](_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.$element.on('click.dismiss.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one($.support.transition.end, function () { that.$element.focus().trigger(e) }) .emulateTransitionEnd(300) : that.$element.focus().trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('