diff --git a/Examples/Session01/schedule.txt b/Examples/Session01/schedule.txt index 58208c91..db59a6e9 100644 --- a/Examples/Session01/schedule.txt +++ b/Examples/Session01/schedule.txt @@ -18,8 +18,8 @@ week 6: Adam Hollis week 6: Nachiket Galande week 6: Paul A Casey week 7: Charles E Robison +week 7: Paul S Briant week 7: Paul Vosper -week 8: Paul S Briant week 8: Brandon Chavis week 8: Jay N Raina week 8: Josh Hicks diff --git a/Examples/Session01/students.txt b/Examples/Session01/students.txt index e69f6c60..6aa51e01 100644 --- a/Examples/Session01/students.txt +++ b/Examples/Session01/students.txt @@ -28,5 +28,5 @@ Vosper, Paul: C#, macscript, python Weidner, Matthew T: German, python, html Williams, Marcus D: python Wong, Darryl: perl, php -Yang, Minghao +Yang, Minghao: None Hagi, Abdishu: python, bash diff --git a/Examples/Session04/__main__example.py b/Examples/Session04/__main__example.py old mode 100644 new mode 100755 index 563c8981..603f2e57 --- a/Examples/Session04/__main__example.py +++ b/Examples/Session04/__main__example.py @@ -4,9 +4,10 @@ print("What it is depends on how it is used") -print("right now, this module's __name is: {}".format(__name__)) +print("right now, this module's __name__ is: {}".format(__name__)) # so if you want coce to run only when a module is a top level script, # you use this clause: -if __name__ == "__main__": - print("I must be running as a top-level script") +#if __name__ == "__main__": + +print("I must be running as a top-level script") diff --git a/Examples/Session06/cigar_party.py b/Examples/Session06/cigar_party.py new file mode 100644 index 00000000..992d99bd --- /dev/null +++ b/Examples/Session06/cigar_party.py @@ -0,0 +1,15 @@ + +""" +When squirrels get together for a party, they like to have cigars. +A squirrel party is successful when the number of cigars is between +40 and 60, inclusive. Unless it is the weekend, in which case there +is no upper bound on the number of cigars. + +Return True if the party with the given values is successful, +or False otherwise. +""" + + +def cigar_party(num, weekend): + return num >= 40 and (num <= 60 or weekend) + diff --git a/Examples/Session06/codingbat.py b/Examples/Session06/codingbat.py new file mode 100644 index 00000000..25865839 --- /dev/null +++ b/Examples/Session06/codingbat.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + +""" +Examples from: http://codingbat.com + +Put here so we can write unit tests for them ourselves +""" + +# Python > Warmup-1 > sleep_in + +# The parameter weekday is True if it is a weekday, and the parameter +# vacation is True if we are on vacation. +# +# We sleep in if it is not a weekday or we're on vacation. +# Return True if we sleep in. + + +def sleep_in(weekday, vacation): + return not weekday or vacation + + +# We have two monkeys, a and b, and the parameters a_smile and b_smile +# indicate if each is smiling. + +# We are in trouble if they are both smiling or if neither of them is +# smiling. + +# Return True if we are in trouble. + +def monkey_trouble(a_smile, b_smile): + return a_smile is b_smile diff --git a/Examples/Session06/safe_input.py b/Examples/Session06/safe_input.py new file mode 100644 index 00000000..81785375 --- /dev/null +++ b/Examples/Session06/safe_input.py @@ -0,0 +1,25 @@ +def safe_input(): + try: + the_input = input("\ntype something >>> ") + except (KeyboardInterrupt, EOFError) as error: + print("the error: ", error) + error.extra_info = "extra info for testing" + # raise + return None + return the_input + +def main(): + safe_input() + +def divide(x,y): + try: + return x/y + except ZeroDivisionError as err: + print("you put in a zero!!!") + print("the exeption:", err) + err.args = (("very bad palce for a zero",)) + err.extra_stuff = "all kinds of things" + raise + +# if __name__ == '__main__': +# main() \ No newline at end of file diff --git a/Examples/Session06/test_cigar_party.py b/Examples/Session06/test_cigar_party.py index b3d76446..80bc0920 100644 --- a/Examples/Session06/test_cigar_party.py +++ b/Examples/Session06/test_cigar_party.py @@ -61,3 +61,4 @@ def test_10(): def test_11(): assert cigar_party(39, True) is False + diff --git a/Examples/Session06/test_codingbat.py b/Examples/Session06/test_codingbat.py new file mode 100755 index 00000000..354dcb34 --- /dev/null +++ b/Examples/Session06/test_codingbat.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python + +""" +test file for codingbat module + +This version can be run with nose or py.test +""" + +from codingbat import sleep_in, monkey_trouble + + +# tests for sleep_in +def test_false_false(): + assert sleep_in(False, False) + + +def test_true_false(): + assert not (sleep_in(True, False)) + + +def test_false_true(): + assert sleep_in(False, True) + + +def test_true_true(): + assert sleep_in(True, True) + + +# put tests for monkey_trouble here +# monkey_trouble(True, True) → True +# monkey_trouble(False, False) → True +# monkey_trouble(True, False) → False + +def test_monkey_true_true(): + assert monkey_trouble(True, True) + +def test_monkey_false_false(): + assert monkey_trouble(False, False) + +def test_monkey_true_false(): + assert monkey_trouble(True, False) is False + +# more! diff --git a/Examples/Session06/test_pytest_parameter.py b/Examples/Session06/test_pytest_parameter.py new file mode 100644 index 00000000..4e82a3ab --- /dev/null +++ b/Examples/Session06/test_pytest_parameter.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python + +""" +pytest example of a parameterized test + +NOTE: there is a failure in here! can you fix it? + +""" +import pytest + + +# a (really simple) function to test +def add(a, b): + """ + returns the sum of a and b + """ + return a + b + +# now some test data: + +test_data = [((2, 3), 5), + ((-3, 2), -1), + ((2, 0.5), 2.5), + (("this", "that"), "this that"), + (([1, 2, 3], [6, 7, 8]), [1, 2, 3, 6, 7, 8]), + ] + + +@pytest.mark.parametrize(("input", "result"), test_data) +def test_add(input, result): + assert add(*input) == result diff --git a/Examples/Session06/test_random_pytest.py b/Examples/Session06/test_random_pytest.py new file mode 100644 index 00000000..441f239a --- /dev/null +++ b/Examples/Session06/test_random_pytest.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python + +""" +port of the random unit tests from the python docs to py.test +""" + +import random +import pytest + + +seq = list(range(10)) + + +def test_shuffle(): + # make sure the shuffled sequence does not lose any elements + random.shuffle(seq) + # seq.sort() # commenting this out will make it fail, so we can see output + print("seq:", seq) # only see output if it fails + assert seq == list(range(10)) + + +def test_shuffle_immutable(): + """should get a TypeError with an imutable type """ + with pytest.raises(TypeError): + random.shuffle((1, 2, 3)) + + +def test_choice(): + """make sure a random item selected is in the original sequence""" + element = random.choice(seq) + assert (element in seq) + + +def test_sample(): + """make sure all items returned by sample are there""" + for element in random.sample(seq, 5): + assert element in seq + + +def test_sample_too_large(): + """should get a ValueError if you try to sample too many""" + with pytest.raises(ValueError): + random.sample(seq, 20) diff --git a/Examples/Session06/test_random_unitest.py b/Examples/Session06/test_random_unitest.py new file mode 100644 index 00000000..f825be5b --- /dev/null +++ b/Examples/Session06/test_random_unitest.py @@ -0,0 +1,30 @@ +import random +import unittest + + +class TestSequenceFunctions(unittest.TestCase): + + def setUp(self): + self.seq = list(range(10)) + + def test_shuffle(self): + # make sure the shuffled sequence does not lose any elements + random.shuffle(self.seq) + self.seq.sort() + self.assertEqual(self.seq, list(range(10))) + + # should raise an exception for an immutable sequence + self.assertRaises(TypeError, random.shuffle, (1, 2, 3)) + + def test_choice(self): + element = random.choice(self.seq) + self.assertTrue(element in self.seq) + + def test_sample(self): + with self.assertRaises(ValueError): + random.sample(self.seq, 20) + for element in random.sample(self.seq, 5): + self.assertTrue(element in self.seq) + +if __name__ == '__main__': + unittest.main() diff --git a/Examples/Session07/html_render/run_html_render.py b/Examples/Session07/html_render/run_html_render.py index 663e5ff8..d282fdc9 100644 --- a/Examples/Session07/html_render/run_html_render.py +++ b/Examples/Session07/html_render/run_html_render.py @@ -42,12 +42,16 @@ def render_page(page, filename): page = hr.Element() -page.append("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text") +page.append("Here is a paragraph of text -- there could be more of them, " + "but this is enough to show that we can do some text") page.append("And here is another piece of text -- you should be able to add any number") render_page(page, "test_html_output1.html") +# The rest of the steps have been commented out. +# Uncomment them a you move along with the assignment. + # ## Step 2 # ########## @@ -55,7 +59,8 @@ def render_page(page, filename): # body = hr.Body() -# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, " +# "but this is enough to show that we can do some text")) # body.append(hr.P("And here is another piece of text -- you should be able to add any number")) @@ -75,7 +80,8 @@ def render_page(page, filename): # body = hr.Body() -# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text")) +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, " +# "but this is enough to show that we can do some text")) # body.append(hr.P("And here is another piece of text -- you should be able to add any number")) # page.append(body) @@ -94,7 +100,8 @@ def render_page(page, filename): # body = hr.Body() -# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, " +# "but this is enough to show that we can do some text", # style="text-align: center; font-style: oblique;")) # page.append(body) @@ -113,7 +120,8 @@ def render_page(page, filename): # body = hr.Body() -# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, " +# "but this is enough to show that we can do some text", # style="text-align: center; font-style: oblique;")) # body.append(hr.Hr()) @@ -134,7 +142,8 @@ def render_page(page, filename): # body = hr.Body() -# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, " +# "but this is enough to show that we can do some text", # style="text-align: center; font-style: oblique;")) # body.append(hr.Hr()) @@ -161,7 +170,8 @@ def render_page(page, filename): # body.append( hr.H(2, "PythonClass - Class 6 example") ) -# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, " +# "but this is enough to show that we can do some text", # style="text-align: center; font-style: oblique;")) # body.append(hr.Hr()) @@ -200,7 +210,8 @@ def render_page(page, filename): # body.append( hr.H(2, "PythonClass - Class 6 example") ) -# body.append(hr.P("Here is a paragraph of text -- there could be more of them, but this is enough to show that we can do some text", +# body.append(hr.P("Here is a paragraph of text -- there could be more of them, " +# "but this is enough to show that we can do some text", # style="text-align: center; font-style: oblique;")) # body.append(hr.Hr()) diff --git a/Examples/Session07/simple_classes.py b/Examples/Session07/simple_classes.py index 267f0d5e..4f996061 100644 --- a/Examples/Session07/simple_classes.py +++ b/Examples/Session07/simple_classes.py @@ -46,6 +46,18 @@ def __init__(self, x, y): def get_color(self): return self.color + def get_size(self): + return self.size + +class Rect: + + def __init__(self, w, h): + self.w = w + self.h = h + + def get_size(self): + return self.w * self.h + p3 = Point3(4, 5) print(p3.size) diff --git a/Examples/Session08/circle.py b/Examples/Session08/circle.py index 88ee5240..6d2d6018 100644 --- a/Examples/Session08/circle.py +++ b/Examples/Session08/circle.py @@ -9,4 +9,16 @@ class Circle: - pass + @staticmethod + def a_method(x): + return x**2 + + def regular_method(self): + print(self) + + @classmethod + def class_method(cls): + print(cls) + + + diff --git a/Examples/Session09/capitalize/capitalize/__init__.py b/Examples/Session09/capitalize/capitalize/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/Examples/Session09/capitalize/capitalize/capital_mod.py b/Examples/Session09/capitalize/capitalize/capital_mod.py deleted file mode 100644 index 352f0874..00000000 --- a/Examples/Session09/capitalize/capitalize/capital_mod.py +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env python - -""" -A really simple module, just to demonstrate disutils -""" - -def capitalize(infilename, outfilename): - """ - reads the contents of infilename, and writes it to outfilename, but with - every word capitalized - - note: very primitive -- it will mess some files up! - - this is called by the capitalize script - """ - infile = open(infilename, 'U') - outfile = open(outfilename, 'w') - - for line in infile: - outfile.write( " ".join( [word.capitalize() for word in line.split() ] ) ) - outfile.write("\n") - - return None \ No newline at end of file diff --git a/Examples/Session09/capitalize/capitalize/test/__init__.py b/Examples/Session09/capitalize/capitalize/test/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/Examples/Session09/capitalize/capitalize/test/test_text_file.txt b/Examples/Session09/capitalize/capitalize/test/test_text_file.txt deleted file mode 100644 index a64b50f7..00000000 --- a/Examples/Session09/capitalize/capitalize/test/test_text_file.txt +++ /dev/null @@ -1,7 +0,0 @@ -This is a really simple Text file. -It is here so that I can test the capitalize script. - -And that's only there to try out distutils. - -So there. - \ No newline at end of file diff --git a/Examples/Session09/capitalize/scripts/cap_script.py b/Examples/Session09/capitalize/scripts/cap_script.py deleted file mode 100755 index 08f999e3..00000000 --- a/Examples/Session09/capitalize/scripts/cap_script.py +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env python - -""" -A really simple script just to demonstrate disutils -""" - -import sys, os -from capitalize import capital_mod - - -if __name__ == "__main__": - try: - infilename = sys.argv[1] - except IndexError: - print "you need to pass in a file to process" - - root, ext = os.path.splitext(infilename) - outfilename = root + "_cap" + ext - - # do the real work: - print "Capitalizing: %s and storing it in %s"%(infilename, outfilename) - capital_mod.capitalize(infilename, outfilename) - - print "I'm done" - \ No newline at end of file diff --git a/Examples/Session09/capitalize/setup.py b/Examples/Session09/capitalize/setup.py deleted file mode 100755 index d7acd8eb..00000000 --- a/Examples/Session09/capitalize/setup.py +++ /dev/null @@ -1,24 +0,0 @@ -#!/usr/bin/env python - -""" -This is about as simple a setup.py as you can have - -It installs the capitalize module and script - -""" - -# classic distutils -#from distutils.core import setup - -## uncomment to support "develop" mode -from setuptools import setup - -setup( - name='Capitalize', - version='0.1.0', - author='Chris Barker', - py_modules=['capitalize/capital_mod',], - scripts=['scripts/cap_script.py',], - description='Not very useful capitalizing module and script', -) - diff --git a/Examples/Session09/closure.py b/Examples/Session09/closure.py new file mode 100644 index 00000000..a7e7d07d --- /dev/null +++ b/Examples/Session09/closure.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python + +""" +Example code for closures / currying +""" + +from functools import partial + + +def counter(start_at=0): + count = [start_at] + + def incr(): + count[0] += 1 + return count[0] + return incr + + +def power(base, exponent): + """returns based raised to the given exponent""" + return base ** exponent + +# now some specialized versions: + +square = partial(power, exponent=2) +cube = partial(power, exponent=3) diff --git a/Examples/Session10/p_wrapper.py b/Examples/Session10/p_wrapper.py new file mode 100644 index 00000000..f80c4d15 --- /dev/null +++ b/Examples/Session10/p_wrapper.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +""" +p_wrapper decorator +""" + + +def p_wrapper(function): + def func(*args, **kwargs): + string = function(*args, **kwargs) + string = "

{}

".format(string) + return string + return func + + +class tag_wrapper: + def __init__(self, tag): + self.tag = tag + + def __call__(self, orig_func): + def func(*args, **kwargs): + string = orig_func(*args, **kwargs) + string = "<{tag}> {s} ".format(tag=self.tag, s=string) + return string + return func diff --git a/Examples/Session10/test_p_wrapper.py b/Examples/Session10/test_p_wrapper.py index 40ba0fde..12603692 100644 --- a/Examples/Session10/test_p_wrapper.py +++ b/Examples/Session10/test_p_wrapper.py @@ -4,7 +4,7 @@ test code for the p_wrapper assignment """ -from p_wrapper import p_wrapper #, tag_wrapper +from p_wrapper import p_wrapper, tag_wrapper def test_p_wrapper(): @@ -22,7 +22,7 @@ def f_string(a, b, this=45 ): assert f_string(2, 3, this=54) == "

the numbers are: 2, 3, 54

" -#Extra credit: +# #Extra credit: def test_tag_wrapper(): @tag_wrapper('html') diff --git a/Examples/Session10/timer.py b/Examples/Session10/timer.py new file mode 100644 index 00000000..3a07bd75 --- /dev/null +++ b/Examples/Session10/timer.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python + +""" +timing context manager +""" + +import sys +import time + +class Timer: + def __init__(self, outfile=sys.stdout): + self.outfile = outfile + + def __enter__(self): + self.start = time.time() + + def __exit__(self, exc_type, exc_val, exc_tb): + self.outfile.write("elapsed time:{} seconds".format(time.time() - self.start)) \ No newline at end of file