├── .gitignore ├── Examination ├── _1.md ├── _2.md ├── _3.md ├── theory_1.md └── theory_2.md ├── Exercises ├── 2048.py ├── Asyncio │ ├── compute.py │ ├── play.py │ ├── polls │ │ ├── Makefile │ │ ├── README.rst │ │ ├── aiohttpdemo_polls │ │ │ ├── __init__.py │ │ │ ├── __main__.py │ │ │ ├── db.py │ │ │ ├── main.py │ │ │ ├── routes.py │ │ │ ├── utils.py │ │ │ └── views.py │ │ ├── config │ │ │ └── polls.yaml │ │ ├── requirements.txt │ │ ├── setup.py │ │ ├── sql │ │ │ ├── create_tables.sql │ │ │ ├── install.sh │ │ │ └── sample_data.sql │ │ └── static │ │ │ └── style.css │ ├── server.py │ ├── show_date.py │ ├── test.py │ ├── test2.py │ └── test3.py ├── Blinker │ ├── blinker_signal.py │ ├── flask_signal.py │ ├── initialize.py │ └── self-defining.py ├── CRUDAPIeg │ ├── app │ │ ├── __init__.py │ │ ├── admin │ │ │ ├── __init__.py │ │ │ └── views.py │ │ ├── api_1_0 │ │ │ ├── __init__.py │ │ │ ├── authentication.py │ │ │ ├── decorators.py │ │ │ ├── errors.py │ │ │ └── users.py │ │ ├── auth │ │ │ ├── __init__.py │ │ │ ├── forms.py │ │ │ └── views.py │ │ ├── decorators.py │ │ ├── exceptions.py │ │ ├── main │ │ │ ├── __init__.py │ │ │ ├── forms.py │ │ │ └── views.py │ │ ├── models.py │ │ ├── static │ │ │ └── css │ │ │ │ └── sign.css │ │ └── templates │ │ │ ├── admin │ │ │ ├── index.html │ │ │ └── logout.html │ │ │ └── auth │ │ │ └── login.html │ ├── config.py │ ├── data-dev.sqlite │ ├── manage.py │ ├── migrations │ │ ├── README │ │ ├── alembic.ini │ │ ├── env.py │ │ ├── script.py.mako │ │ └── versions │ │ │ ├── 125e88d00d03_.py │ │ │ └── 3dad725dafa3_.py │ └── requirement.txt ├── CeleryTest │ ├── proj │ │ └── celery.py │ └── tasks.py ├── Cookbook │ ├── Class │ │ ├── context.py │ │ ├── format.py │ │ └── repr.py │ ├── DataEncode │ │ ├── _hugexml.py │ │ ├── _rwbyte.py │ │ ├── base64.py │ │ ├── data.json │ │ ├── dictxml.py │ │ ├── getxml.py │ │ ├── hex.py │ │ ├── modifyxml.py │ │ ├── mysql.py │ │ ├── newpred.xml │ │ ├── pred.xml │ │ ├── rwcsv.py │ │ ├── rwjson.py │ │ ├── stocks.csv │ │ └── stocks2.csv │ ├── Function │ │ ├── _inlined_async.py │ │ ├── annoymouscatch.py │ │ ├── anyargs.py │ │ ├── callback.py │ │ ├── defannoymous.py │ │ ├── extrainfo.py │ │ ├── onlykeyword.py │ │ ├── reducecallableargs.py │ │ └── returnalot.py │ ├── IterateGenerate │ │ ├── ACiter.py │ │ ├── _pipe.py │ │ ├── foldnest.py │ │ ├── iterGenerator.py │ │ ├── itercombine.py │ │ ├── itercrossset.py │ │ ├── iterproto.py │ │ ├── iterslice.py │ │ ├── manualiter.py │ │ ├── outgenerate.py │ │ ├── proxy.py │ │ ├── reversed.py │ │ ├── skipiter.py │ │ ├── yieldinfinite.py │ │ └── zip.py │ ├── attrgetter.py │ ├── counter.py │ ├── dedupe.py │ ├── dictcommon.py │ ├── fileIO │ │ ├── BytetoTxt.py │ │ ├── _ChangeEncode.py │ │ ├── _UniERR.py │ │ ├── _descriptor.py │ │ ├── _membin.py │ │ ├── byte.py │ │ ├── data.bin │ │ ├── file.bin │ │ ├── file.txt │ │ ├── file2.txt │ │ ├── fileexist.py │ │ ├── filename.py │ │ ├── ignoreencode.py │ │ ├── iterhistory.py │ │ ├── jalapaeño.txt │ │ ├── listdir.py │ │ ├── mktemporary.py │ │ ├── printsepend.py │ │ ├── readwrite.py │ │ ├── rwzip.py │ │ ├── somefile │ │ ├── stringIO.py │ │ ├── tofile.py │ │ ├── wbtobuffer.py │ │ └── writenull.py │ ├── filter.py │ ├── groupby.py │ ├── headq.py │ ├── orderdict.py │ ├── slice.py │ └── zip.py ├── CorePythonExercises │ ├── 25lines.py │ ├── ForMathModel.py │ ├── PigLatin.py │ ├── add.py │ ├── add_from_1_to_79.py │ ├── bird.py │ ├── class.py │ ├── class2.py │ ├── creditcard │ │ ├── carddata.txt │ │ ├── cardlog.txt │ │ └── cardrun.py │ ├── deco.py │ ├── decorator │ │ ├── deco.py │ │ ├── deco2.py │ │ ├── deco3.py │ │ ├── deco4.py │ │ ├── property.py │ │ └── staticmethod.py │ ├── define.py │ ├── easymath.py │ ├── eg.py │ ├── fibonacci.py │ ├── generate_pyc.py │ ├── hr.py │ ├── idcheck2.py │ ├── kick_the_ball.py │ ├── leap_year.py │ ├── list&tuple&dict.py │ ├── login.py │ ├── ltd.py │ ├── makeTextFile.py │ ├── maxfactor.py │ ├── moneyfmt.py │ ├── randint.py │ ├── readTextFile.py │ ├── readwrite.py │ ├── strcalculate.py │ ├── stringtemplate.py │ ├── strip.py │ ├── sumletter.py │ ├── super.py │ ├── test.py │ ├── tsTserv.py │ ├── urlopen.py │ └── while&if.py ├── Decorator │ ├── cls-dec.py │ ├── common.py │ ├── dec-cls.py │ └── with-args.py ├── Descriptor │ └── des.py ├── FrozenTest │ ├── app │ │ ├── __init__.py │ │ ├── build │ │ │ └── test │ │ │ │ └── index.html │ │ ├── forms.py │ │ └── views.py │ ├── freeze.py │ ├── manage.py │ └── requirement.txt ├── LearnCython │ ├── build │ │ └── temp.macosx-10.11-x86_64-2.7 │ │ │ └── helloworld.o │ ├── helloworld.c │ ├── helloworld.pyx │ ├── helloworld.so │ └── setup.py ├── LearnDjango │ └── mysite │ │ ├── db.sqlite3 │ │ ├── manage.py │ │ ├── mysite │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ │ └── polls │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py ├── LearnFlask │ ├── .gitignore │ ├── Flask-Web-Development │ │ ├── __init__.py │ │ ├── test_api.py │ │ ├── test_basics.py │ │ ├── test_client.py │ │ ├── test_selenium.py │ │ ├── test_user_model.py │ │ └── webtest │ │ │ ├── ListConverter.py │ │ │ ├── app_api.py │ │ │ ├── app_response.py │ │ │ ├── app_subdomain.py │ │ │ ├── hello.py │ │ │ └── settings.py │ └── FlaskUploadFiles │ │ ├── mysql-python │ │ ├── .example1.py.swp │ │ ├── consts.py │ │ ├── curd.py │ │ └── example1.py │ │ ├── test.py │ │ └── upload-review-demo │ │ ├── __init__.py │ │ ├── app.py │ │ ├── config.py │ │ ├── databases │ │ └── schema.sql │ │ ├── ext.py │ │ ├── mimes.py │ │ ├── models.py │ │ ├── requirements.txt │ │ ├── templates │ │ └── r │ │ │ └── index.html │ │ └── utils.py ├── LearnGevent │ ├── event.py │ ├── event2.py │ ├── group.py │ ├── group2.py │ ├── monkey.py │ ├── queue.py │ ├── queue2.py │ ├── test.py │ ├── test2.py │ ├── test3.py │ ├── test4.py │ ├── test5.py │ ├── test6.py │ ├── test7.py │ ├── test8.py │ ├── test9.py │ ├── threadtimeout.py │ └── timeout.py ├── LearnTornado │ ├── Burt │ │ ├── main.py │ │ ├── static │ │ │ └── style.css │ │ └── templates │ │ │ ├── index.html │ │ │ ├── main.html │ │ │ ├── modules │ │ │ └── book.html │ │ │ └── recommended.html │ ├── C2 │ │ ├── main.py │ │ ├── static │ │ │ └── style.css │ │ └── templates │ │ │ ├── index.html │ │ │ └── munged.html │ ├── C3 │ │ ├── main.py │ │ └── templates │ │ │ ├── index.html │ │ │ └── main.html │ ├── burtbook │ │ ├── burts_books_db.py │ │ ├── static │ │ │ └── style.css │ │ └── templates │ │ │ ├── book_edit.html │ │ │ ├── index.html │ │ │ ├── main.html │ │ │ ├── modules │ │ │ └── book.html │ │ │ └── recommended.html │ ├── cookie │ │ ├── cookies.py │ │ └── templates │ │ │ ├── index.html │ │ │ └── login.html │ ├── cookie_counter.py │ ├── definitions_readonly.py │ ├── definitions_readwrite.py │ ├── hello-errors.py │ ├── hello.py │ ├── hello_module.py │ ├── module │ │ ├── hello_module.py │ │ └── templates │ │ │ └── hello.html │ ├── nginx.conf │ ├── poemmaker.py │ ├── shopping │ │ └── shopping_cart.py │ ├── sslnginx.conf │ ├── string_service.py │ ├── templates │ │ ├── index.html │ │ └── poem.html │ ├── test.py │ ├── tornado.conf │ ├── tweet │ │ ├── tweet_rate.py │ │ ├── tweet_rate_async.py │ │ └── tweet_rate_gen.py │ └── twitter │ │ ├── templates │ │ ├── home.html │ │ └── logout.html │ │ └── twitter.py ├── MapReduce │ ├── map_reduce.py │ └── parallel.py ├── Marsh │ ├── deserialize.py │ ├── load.py │ ├── test.py │ └── validator.py ├── MessageQueue │ └── amqp_producer.py ├── MultiThread │ ├── _1.py │ ├── _2.py │ ├── _3.py │ ├── _4.py │ ├── _5.py │ ├── _6.py │ ├── _7.py │ ├── _8.py │ ├── _9.py │ ├── global.py │ ├── globaldict.py │ ├── local.py │ ├── lock.py │ └── threadlocal.py ├── Pickle │ ├── stream.py │ ├── test.py │ └── test2.py ├── PyQueryTest │ ├── hello.html │ └── test.py ├── PythonHardWay │ ├── ex151028.py │ ├── ex151029.py │ ├── ex44d.py │ ├── exercise10.py │ ├── exercise11.py │ ├── exercise12.py │ ├── exercise13.py │ ├── exercise14.py │ ├── exercise15.py │ ├── exercise16.py │ ├── exercise7.py │ └── exercise8.py ├── PythonRobot │ ├── cookie.py │ ├── cookie.txt │ ├── demo.py │ ├── getdemo.py │ ├── getjpg.py │ ├── getjpg2.py │ ├── hasattr.py │ ├── httperror.py │ ├── httperror2.py │ ├── postdemo.py │ ├── proxy.py │ ├── readcookie.py │ ├── savecookie.py │ ├── urlerror.py │ ├── withheader │ └── withheader.py ├── QiniuPythonDemo │ └── test.py ├── Recursion │ ├── solve.py │ ├── test.py │ └── test2.py ├── RedirectBackWithWTF │ ├── app.py │ ├── redirect.py │ └── templates │ │ ├── index.html │ │ └── login.html ├── RedirectDemo │ ├── app.py │ ├── redirect_urls.py │ └── templates │ │ └── index.html ├── Request │ └── test.py ├── ScrapyDemo │ ├── pic │ │ ├── 1.png │ │ ├── 2.png │ │ └── 3.png │ ├── scrapy.cfg │ └── scrial │ │ ├── __init__.py │ │ ├── items.py │ │ ├── pipelines.py │ │ ├── settings.py │ │ └── spiders │ │ ├── __init__.py │ │ └── dmoz_spider.py ├── Shell │ ├── array.sh │ ├── cal.sh │ ├── para.sh │ ├── para2.sh │ ├── stable-shell.sh │ └── test.sh ├── Singleton │ ├── decorator.py │ ├── metaclass.py │ ├── module.py │ └── new.py ├── Socket │ ├── chatroom │ │ ├── server-demo.py │ │ ├── server.py │ │ ├── telnet.py │ │ └── test.py │ ├── client.py │ ├── keep-alive.py │ ├── permanet-alive.py │ └── server.py ├── SortAlgorithm │ ├── bubble.py │ ├── comb_sort.py │ ├── heap.py │ ├── insertion.py │ ├── merge.py │ ├── quick.py │ ├── readme.md │ ├── selection.py │ └── shell.py ├── Thread │ ├── c1.py │ ├── c2.py │ ├── c3.py │ ├── c4.py │ ├── c5.py │ ├── c6.py │ ├── threading_multi1.py │ ├── threading_multi2.py │ └── threading_multi3.py ├── TwoDimensioBarCode │ ├── TwoDimensionalBarCode.py │ ├── app │ │ ├── __init__.py │ │ ├── forms.py │ │ ├── templates │ │ │ └── index.html │ │ └── views.py │ ├── manage.py │ └── requirement.txt ├── UnitTest │ ├── client.py │ ├── test_mock.py │ ├── test_pytest.py │ ├── ut_case.py │ ├── ut_suite.py │ └── ut_suite_with_case.py ├── WSGI │ ├── hello.py │ └── server.py ├── aiohttp │ ├── client.py │ └── server.py ├── attrs.py ├── changePermission.py ├── cheerleader.py ├── custom.js ├── fork.py ├── forkp.py ├── iOSDemoWithPython │ ├── app │ │ ├── README │ │ └── apptest │ │ │ └── __main__.py │ ├── app_packages │ │ ├── README │ │ └── rubicon │ │ │ ├── __init__.py │ │ │ └── objc │ │ │ ├── __init__.py │ │ │ ├── core_foundation.py │ │ │ ├── objc.py │ │ │ └── types.py │ ├── apptest.xcodeproj │ │ ├── project.pbxproj │ │ ├── project.xcworkspace │ │ │ ├── contents.xcworkspacedata │ │ │ └── xcuserdata │ │ │ │ └── fujun.xcuserdatad │ │ │ │ └── UserInterfaceState.xcuserstate │ │ └── xcuserdata │ │ │ └── fujun.xcuserdatad │ │ │ ├── xcdebugger │ │ │ └── Breakpoints_v2.xcbkptlist │ │ │ └── xcschemes │ │ │ ├── apptest.xcscheme │ │ │ └── xcschememanagement.plist │ ├── apptest │ │ ├── Images.xcassets │ │ │ ├── AppIcon.appiconset │ │ │ │ ├── Contents.json │ │ │ │ ├── icon-120.png │ │ │ │ ├── icon-152.png │ │ │ │ ├── icon-167.png │ │ │ │ ├── icon-180.png │ │ │ │ ├── icon-29.png │ │ │ │ ├── icon-40.png │ │ │ │ ├── icon-58.png │ │ │ │ ├── icon-76.png │ │ │ │ ├── icon-80.png │ │ │ │ └── icon-87.png │ │ │ └── LaunchImage.launchimage │ │ │ │ ├── Contents.json │ │ │ │ ├── launch-1024x768.png │ │ │ │ ├── launch-1536x2048.png │ │ │ │ ├── launch-2048x1536.png │ │ │ │ ├── launch-640x1136.png │ │ │ │ ├── launch-640x960.png │ │ │ │ └── launch-768x1024.png │ │ ├── apptest-Info.plist │ │ ├── apptest-Prefix.pch │ │ ├── en.lproj │ │ │ └── InfoPlist.strings │ │ └── main.m │ └── untitled.py ├── iterator_and_generator │ ├── countdown.py │ ├── generator_read_file.py │ ├── iteration.py │ └── recv_count.py ├── muxitestanswer.py ├── sieveEratosthenes.py └── stack.py └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.pyc 3 | __pycache__/ 4 | -------------------------------------------------------------------------------- /Exercises/Asyncio/compute.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import asyncio 4 | 5 | 6 | async def compute(x, y): 7 | print("Computing {} + {}".format(x, y)) 8 | await asyncio.sleep(1) 9 | return x + y 10 | 11 | async def print_sum(x, y): 12 | result = await compute(x, y) 13 | print("{} + {} = {}".format(x, y, result)) 14 | 15 | 16 | loop = asyncio.get_event_loop() 17 | loop.run_until_complete(print_sum(1, 2)) 18 | loop.close() 19 | -------------------------------------------------------------------------------- /Exercises/Asyncio/play.py: -------------------------------------------------------------------------------- 1 | from types import coroutine 2 | 3 | @coroutine 4 | def read_await(sock): 5 | yield 'read_await', sock 6 | 7 | @coroutine 8 | def write_await(sock): 9 | yield 'write_await', sock 10 | 11 | class Loop: 12 | async def sock_recv(self, sock, maxbytes): 13 | await read_wait(sock) 14 | return sock.recv(maxbytes) 15 | 16 | async def sock_accept(self, sock): 17 | await read_wait(sock) 18 | return sock.accept() 19 | 20 | async def sock_sendall(self, sock, data): 21 | while data: 22 | await write_wait(sock) 23 | nsent = sock.send(data) 24 | data = data[nsent:] 25 | -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/Makefile: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Asyncio/polls/Makefile -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/README.rst: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Asyncio/polls/README.rst -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/aiohttpdemo_polls/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Asyncio/polls/aiohttpdemo_polls/__init__.py -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/aiohttpdemo_polls/__main__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Asyncio/polls/aiohttpdemo_polls/__main__.py -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/aiohttpdemo_polls/db.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Asyncio/polls/aiohttpdemo_polls/db.py -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/aiohttpdemo_polls/main.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from aiohttp import web 3 | from routes import setup_routes 4 | 5 | loop = asyncio.get_event_loop() 6 | app = web.Application(loop=loop) 7 | setup_routes(app) 8 | web.run_app(app, host='127.0.0.1', port=8080) 9 | -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/aiohttpdemo_polls/routes.py: -------------------------------------------------------------------------------- 1 | from views import index 2 | 3 | 4 | def setup_routes(app): 5 | app.router.add_get('/', index) 6 | -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/aiohttpdemo_polls/utils.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Asyncio/polls/aiohttpdemo_polls/utils.py -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/aiohttpdemo_polls/views.py: -------------------------------------------------------------------------------- 1 | from aiohttp import web 2 | 3 | 4 | async def index(request): 5 | return web.Response(text='Hello Aiohttp!') 6 | -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/config/polls.yaml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Asyncio/polls/config/polls.yaml -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/requirements.txt: -------------------------------------------------------------------------------- 1 | appdirs==1.4.0 2 | packaging==16.8 3 | pyparsing==2.1.10 4 | six==1.10.0 5 | SQLAlchemy==1.1.5 6 | -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/setup.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Asyncio/polls/setup.py -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/sql/create_tables.sql: -------------------------------------------------------------------------------- 1 | import sqlalchemy as sa 2 | 3 | meta = sa.MetaData() 4 | 5 | question = sa.Table( 6 | 'question', meta, 7 | sa.Column('id', sa.Integer, nullable=False), 8 | sa.Column('question_text', sa.String(200), nullable=False), 9 | sa.Column('pub_date', sa.Date, nullable=False), 10 | 11 | # Indexes # 12 | sa.PrimaryKeyConstraint('id', name='question_id_pkey')) 13 | 14 | choice = sa.Table( 15 | 'choice', meta, 16 | sa.Column('id', sa.Integer, nullable=False), 17 | sa.Column('question_id', sa.Integer, nullable=False), 18 | sa.Column('choice_text', sa.String(200), nullable=False), 19 | sa.Column('votes', sa.Integer, server_default="0", nullable=False), 20 | 21 | # Indexes # 22 | sa.PrimaryKeyConstraint('id', name='choice_id_pkey'), 23 | sa.ForeignKeyConstraint(['question_id'], [question.c.id], 24 | name='choice_question_id_fkey', 25 | ondelete='CASCADE'), 26 | ) 27 | -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/sql/install.sh: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Asyncio/polls/sql/install.sh -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/sql/sample_data.sql: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Asyncio/polls/sql/sample_data.sql -------------------------------------------------------------------------------- /Exercises/Asyncio/polls/static/style.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Asyncio/polls/static/style.css -------------------------------------------------------------------------------- /Exercises/Asyncio/server.py: -------------------------------------------------------------------------------- 1 | from aiohttp import web 2 | 3 | async def handle(request): 4 | name = request.match_info.get('name', "Anonymous") 5 | text = "Hello, " + name 6 | return web.Response(text=text) 7 | 8 | app = web.Application() 9 | app.router.add_get('/', handle) 10 | app.router.add_get('/{name}', handle) 11 | 12 | web.run_app(app) 13 | -------------------------------------------------------------------------------- /Exercises/Asyncio/show_date.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import asyncio 4 | import datetime 5 | 6 | async def show_date(loop): 7 | end_time = loop.time() + 5.0 8 | while True: 9 | print(datetime.datetime.now()) 10 | if loop.time() + 1.0 > end_time: 11 | break 12 | else: 13 | await asyncio.sleep(1) 14 | 15 | loop = asyncio.get_event_loop() 16 | loop.run_until_complete(show_date(loop)) 17 | loop.close() 18 | -------------------------------------------------------------------------------- /Exercises/Asyncio/test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | import asyncio 5 | 6 | 7 | # 把一个generator标记为coroutine类型,放入EventLoop中 8 | @asyncio.coroutine 9 | def hello(): 10 | print("Hello World!") 11 | # 调用另一个generator 12 | r = yield from asyncio.sleep(1) 13 | print("Hello again!") 14 | 15 | # 获取EventLoop 16 | loop = asyncio.get_event_loop() 17 | # 执行coroutine 18 | loop.run_until_complete(hello()) 19 | loop.close() 20 | -------------------------------------------------------------------------------- /Exercises/Asyncio/test2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | import threading 5 | import asyncio 6 | 7 | 8 | @asyncio.coroutine 9 | def hello(): 10 | print('Hello World! (%s)' % threading.currentThread()) 11 | yield from asyncio.sleep(1) 12 | print('Hello Again! (%s)' % threading.currentThread()) 13 | 14 | loop = asyncio.get_event_loop() 15 | tasks = [hello(), hello()] 16 | loop.run_until_complete(asyncio.wait(tasks)) 17 | loop.close() 18 | -------------------------------------------------------------------------------- /Exercises/Asyncio/test3.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | import asyncio 5 | 6 | 7 | @asyncio.coroutine 8 | def wget(host): 9 | print('wget %s...' % host) 10 | connect = asyncio.open_connection(host, 80) 11 | reader, writer = yield from connect 12 | header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host 13 | writer.write(header.encode('utf-8')) 14 | yield from writer.drain() 15 | while True: 16 | line = yield from reader.readline() 17 | if line == b'\r\n': 18 | break 19 | print('%s header > %s' % (host, line.decode('utf-8').rstrip())) 20 | writer.close() 21 | 22 | loop = asyncio.get_event_loop() 23 | tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']] 24 | loop.run_until_complete(asyncio.wait(tasks)) 25 | loop.close() 26 | -------------------------------------------------------------------------------- /Exercises/Blinker/blinker_signal.py: -------------------------------------------------------------------------------- 1 | from blinker import signal 2 | 3 | started = signal('test-started') 4 | 5 | def each(round): 6 | print 'Round {}!'.format(round) 7 | 8 | def round_two(round): 9 | print 'Only {}'.format(round) 10 | 11 | started.connect(each) 12 | started.connect(round_two, sender=2) 13 | 14 | for round in range(1, 4): 15 | started.send(round) 16 | -------------------------------------------------------------------------------- /Exercises/Blinker/self-defining.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | from blinker import Namespace 4 | web_signals = Namespace() 5 | large_file_saved = web_signals.signal('large-file-saved') 6 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/admin/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/CRUDAPIeg/app/admin/__init__.py -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/api_1_0/__init__.py: -------------------------------------------------------------------------------- 1 | from flask import Blueprint 2 | 3 | api = Blueprint('api', __name__) 4 | 5 | from . import authentication, users, errors 6 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/api_1_0/decorators.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | from flask import g 3 | from .errors import forbidden 4 | 5 | 6 | def permission_required(permission): 7 | def decorator(f): 8 | @wraps(f) 9 | def decorated_function(*args, **kwargs): 10 | if not g.current_user.can(permission): 11 | return forbidden('Insufficient permissions') 12 | return f(*args, **kwargs) 13 | return decotated_function 14 | return decotator 15 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/api_1_0/errors.py: -------------------------------------------------------------------------------- 1 | from flask import jsonify 2 | from . import api 3 | 4 | 5 | def unauthorized(message): 6 | response = jsonify({'error': 'unauthorized', 'message': message}) 7 | response.status_code = 401 8 | return response 9 | 10 | def forbidden(message): 11 | response = jsonify({'error': 'forbidden', 'message': message}) 12 | response.status_code = 403 13 | return response 14 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/auth/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from flask import Blueprint 4 | 5 | auth = Blueprint( 6 | 'auth', 7 | __name__, 8 | template_folder = 'templates', 9 | static_folder = 'static' 10 | ) 11 | 12 | from . import views, forms 13 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/auth/forms.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from flask_wtf import Form 4 | from wtforms import StringField, PasswordField, SubmitField 5 | from wtforms.validators import DataRequired 6 | 7 | 8 | class LoginForm(Form): 9 | username = StringField('username', validators=[DataRequired()]) 10 | password = PasswordField('password', validators=[DataRequired()]) 11 | submit = SubmitField('login!') 12 | 13 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/auth/views.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from . import auth 4 | from flask import render_template, url_for, redirect, flash 5 | from flask_login import login_user, logout_user, current_user, login_required 6 | from app.models import User 7 | from .forms import LoginForm 8 | 9 | 10 | @auth.route('/login', methods=['GET', 'POST']) 11 | def login(): 12 | form = LoginForm() 13 | if form.validate_on_submit(): 14 | user = User.query.filter_by(username = form.username.data).first() 15 | if user is not None and user.verify_password(form.password.data): 16 | login_user(user) 17 | return redirect('/admin') 18 | return render_template('auth/login.html', form=form) 19 | 20 | 21 | @login_required 22 | @auth.route('/logout') 23 | def logout(): 24 | logout_user() 25 | return redirect(url_for('auth.login')) 26 | 27 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | class ValidationError(ValueError): 4 | pass 5 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/main/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from flask import Blueprint 4 | 5 | main = Blueprint( 6 | 'main', 7 | __name__, 8 | template_folder = 'templates', 9 | static_folder = 'static' 10 | ) 11 | 12 | from . import views, forms 13 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/main/forms.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from flask_wtf import Form 3 | # from wtforms import 4 | # from wtforms.validators import 5 | 6 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/main/views.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from . import main 3 | from flask import render_template 4 | 5 | 6 | # test views 7 | @main.route('/test/') 8 | def test(): 9 | return "

just tell you everything is ok!

" 10 | 11 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/templates/admin/index.html: -------------------------------------------------------------------------------- 1 | 2 | {% extends 'admin/master.html' %} 3 | {% block body %} 4 | {{ super() }} 5 |
6 |

admin site

7 |
8 | {% endblock body %} 9 | 10 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/app/templates/admin/logout.html: -------------------------------------------------------------------------------- 1 | 2 | {% extends 'admin/base.html' %} 3 | 4 | {% block access_control %} 5 | {% if current_user.is_authenticated %} 6 |
7 | 8 | {{ current_user.login }} 9 | 10 | 13 |
14 | {% endif %} 15 | {% endblock %} 16 | 17 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/data-dev.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/CRUDAPIeg/data-dev.sqlite -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/migrations/README: -------------------------------------------------------------------------------- 1 | Generic single-database configuration. -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/migrations/alembic.ini: -------------------------------------------------------------------------------- 1 | # A generic, single database configuration. 2 | 3 | [alembic] 4 | # template used to generate migration files 5 | # file_template = %%(rev)s_%%(slug)s 6 | 7 | # set to 'true' to run the environment during 8 | # the 'revision' command, regardless of autogenerate 9 | # revision_environment = false 10 | 11 | 12 | # Logging configuration 13 | [loggers] 14 | keys = root,sqlalchemy,alembic 15 | 16 | [handlers] 17 | keys = console 18 | 19 | [formatters] 20 | keys = generic 21 | 22 | [logger_root] 23 | level = WARN 24 | handlers = console 25 | qualname = 26 | 27 | [logger_sqlalchemy] 28 | level = WARN 29 | handlers = 30 | qualname = sqlalchemy.engine 31 | 32 | [logger_alembic] 33 | level = INFO 34 | handlers = 35 | qualname = alembic 36 | 37 | [handler_console] 38 | class = StreamHandler 39 | args = (sys.stderr,) 40 | level = NOTSET 41 | formatter = generic 42 | 43 | [formatter_generic] 44 | format = %(levelname)-5.5s [%(name)s] %(message)s 45 | datefmt = %H:%M:%S 46 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/migrations/script.py.mako: -------------------------------------------------------------------------------- 1 | """${message} 2 | 3 | Revision ID: ${up_revision} 4 | Revises: ${down_revision} 5 | Create Date: ${create_date} 6 | 7 | """ 8 | 9 | # revision identifiers, used by Alembic. 10 | revision = ${repr(up_revision)} 11 | down_revision = ${repr(down_revision)} 12 | 13 | from alembic import op 14 | import sqlalchemy as sa 15 | ${imports if imports else ""} 16 | 17 | def upgrade(): 18 | ${upgrades if upgrades else "pass"} 19 | 20 | 21 | def downgrade(): 22 | ${downgrades if downgrades else "pass"} 23 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/migrations/versions/125e88d00d03_.py: -------------------------------------------------------------------------------- 1 | """empty message 2 | 3 | Revision ID: 125e88d00d03 4 | Revises: 3dad725dafa3 5 | Create Date: 2016-03-03 12:47:06.967010 6 | 7 | """ 8 | 9 | # revision identifiers, used by Alembic. 10 | revision = '125e88d00d03' 11 | down_revision = '3dad725dafa3' 12 | 13 | from alembic import op 14 | import sqlalchemy as sa 15 | 16 | 17 | def upgrade(): 18 | ### commands auto generated by Alembic - please adjust! ### 19 | op.add_column('users', sa.Column('confirmed', sa.Boolean(), nullable=True)) 20 | ### end Alembic commands ### 21 | 22 | 23 | def downgrade(): 24 | ### commands auto generated by Alembic - please adjust! ### 25 | op.drop_column('users', 'confirmed') 26 | ### end Alembic commands ### 27 | -------------------------------------------------------------------------------- /Exercises/CRUDAPIeg/requirement.txt: -------------------------------------------------------------------------------- 1 | 2 | Flask==0.10.1 3 | Flask-Migrate 4 | Flask-Login 5 | Flask-Admin 6 | Flask-SQLAlchemy==1.0 7 | Flask-WTF==0.10.0 8 | 9 | -------------------------------------------------------------------------------- /Exercises/CeleryTest/proj/celery.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | from __future__ import absolute_import 5 | 6 | from celery import Celery 7 | 8 | app = Celery('proj', include=['proj.tasks']) 9 | app.config_from_object('proj.celeryconfig') 10 | 11 | 12 | if __name__ == '__main__': 13 | app.start() 14 | -------------------------------------------------------------------------------- /Exercises/CeleryTest/tasks.py: -------------------------------------------------------------------------------- 1 | # -*- coidng: utf-8 -*- 2 | 3 | from celery import Celery 4 | 5 | # app = Celery('tasks', backend='redis://localhost', broker='redis://localhost') 6 | 7 | # @app.task 8 | # def add(x, y): 9 | # return x + y 10 | 11 | from __future__ import absolute_import 12 | from celery.utils.log import get_task_logger 13 | from proj.celery import app 14 | 15 | logger = get_task_logger(__name__) 16 | 17 | @app.task 18 | def add(x, y): 19 | return x + y 20 | 21 | @app.task(bind=True) 22 | def div(self, x, y): 23 | logger.info(('Executing task id {0.id}, args: {0.args!r} ''kwargs: {0.kwargs!r}').format(self.request)) 24 | try: 25 | result = x / y 26 | except ZeroDivisionError as e: 27 | raise self.retry(exc=e, countdown=5, max_retries=3) 28 | return result 29 | -------------------------------------------------------------------------------- /Exercises/Cookbook/Class/format.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | 4 | _formats = { 5 | 'ymd': '{d.year}-{d.month}-{d.day}', 6 | 'mdy': '{d.month}/{d.day}/{d.year}', 7 | 'dmy': '{d.day}/{d.month}/{d.year}' 8 | } 9 | 10 | class Date: 11 | def __init__(self, year, month, day): 12 | self.year = year 13 | self.month = month 14 | self.day = day 15 | 16 | def __format__(self, code): 17 | if code == '': 18 | code = 'ymd' 19 | fmt = _formats[code] 20 | return fmt.format(d=self) 21 | 22 | # __format__()方法给Python的字符串格式化提供了一个钩子 23 | -------------------------------------------------------------------------------- /Exercises/Cookbook/Class/repr.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | 4 | class Pair: 5 | def __init__(self, x, y): 6 | self.x = x 7 | self.y = y 8 | 9 | def __repr__(self): 10 | # 0指的是self本身 11 | return 'Pair({0.x!r}, {0.y!r})'.format(self) 12 | 13 | def __str__(self): 14 | return '({0.x!s}, {0.y!s})'.format(self) 15 | 16 | # !r 格式化代码指明输出使用__repr__()代替默认的__str__() 17 | # 自定义__repr__()和__str__()写详细的说明,如果__str__()未被定义就会使用__repr__() 18 | # 来代替输出 19 | -------------------------------------------------------------------------------- /Exercises/Cookbook/DataEncode/_hugexml.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 6.4 3 | 4 | 5 | from xml.etree.ElementTree import iterparse 6 | 7 | def parse_and_remove(filename, path): 8 | path_parts = path.split('/') 9 | doc = iterparse(filename, ('start', 'end')) 10 | # Skip the root element 11 | next(doc) 12 | 13 | tag_stack = [] 14 | elem_stack = [] 15 | for event, elem in doc: 16 | if event == 'start': 17 | tag_stack.append(elem.tag) 18 | elem_stack.append(elem) 19 | elif event == 'end': 20 | if tag_stack == path_parts: 21 | yield elem 22 | elem_stack[-2].remove(elem) 23 | try: 24 | tag_stack.pop() 25 | elem_stack.pop() 26 | except IndexError: 27 | pass 28 | -------------------------------------------------------------------------------- /Exercises/Cookbook/DataEncode/_rwbyte.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 6.11 3 | 4 | 5 | from struct import Struct 6 | 7 | def write_records(records, format, f): 8 | """Write a sequence of tuples to a binary file""" 9 | record_struct = Struct(format) 10 | for r in records: 11 | f.write(record_struct.pack(*r)) 12 | 13 | 14 | if __name__ == '__main__': 15 | records = [(1, 2.3, 4.5), 16 | (6, 7.8, 9.0), 17 | (12, 13.4, 56.7)] 18 | with open('data.b', 'wb') as f: 19 | write_records(records, '= ?', (min_price, )): 19 | print(row) 20 | -------------------------------------------------------------------------------- /Exercises/Cookbook/DataEncode/newpred.xml: -------------------------------------------------------------------------------- 1 | 2 | 14791 3 | Clark & Balmoral 4 | This is a test
 5 |         5 MIN
 6 |         Howard
 7 |         1378
 8 |         22
 9 |     
10 |
11 |         15 MIN
12 |         Howard
13 |         1867
14 |         22
15 |     
16 |
17 | -------------------------------------------------------------------------------- /Exercises/Cookbook/DataEncode/pred.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 14791 4 | Clark & Balmoral 5 | 6 | 22 7 | North Bound 8 |
North Bound
9 |
10 | 22 11 |
12 |         5 MIN
13 |         Howard
14 |         1378
15 |         22
16 |     
17 |
18 |         15 MIN
19 |         Howard
20 |         1867
21 |         22
22 |     
23 |
24 | -------------------------------------------------------------------------------- /Exercises/Cookbook/DataEncode/stocks.csv: -------------------------------------------------------------------------------- 1 | Symbol,Price,Date,Time,Change,Volume 2 | "AA",39.48,"6/11/2007","9:36am",-0.18,181800 3 | "AIG",71.38,"6/11/2007","9:36am",-0.15,195500 4 | "AXP",62.58,"6/11/2007","9:36am",-0.46,935000 5 | "BA",98.31,"6/11/2007","9:36am",+0.12,104800 6 | "C",53.08,"6/11/2007","9:36am",-0.25,360900 7 | "CAT",78.29,"6/11/2007","9:36am",-0.23,225400 8 | -------------------------------------------------------------------------------- /Exercises/Cookbook/DataEncode/stocks2.csv: -------------------------------------------------------------------------------- 1 | Symbol,Price,Date,Time,Change,Volume 2 | AA,39.48,6/11/2007,9:36am,-0.18,181800 3 | AIG,71.38,6/11/2007,9:36am,-0.15,195500 4 | AXP,62.58,6/11/2007,9:36am,-0.46,935000 5 | -------------------------------------------------------------------------------- /Exercises/Cookbook/Function/annoymouscatch.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | x = 10 4 | a = lambda y: x + y 5 | x = 20 6 | b = lambda y: x + y 7 | print(a(10)) 8 | print(b(10)) 9 | print('Both return 30') 10 | # x is a free parameter and will be bound when executed 11 | -------------------------------------------------------------------------------- /Exercises/Cookbook/Function/anyargs.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | # * for positional parameter 5 | def avg(first, *rest): 6 | return (first + sum(rest)) / (1 + len(rest)) 7 | 8 | print(avg(1, 2)) 9 | print(avg(1, 2, 3, 4)) 10 | 11 | import html 12 | 13 | # ** for keyword parameter, attrs is a dict 14 | def make_element(name, value, **attrs): 15 | keyvals = [' %s="%s"' % item for item in attrs.items()] 16 | attr_str = ''.join(keyvals) 17 | element = '<{name}{attrs}>{value}'.format( 18 | name=name, 19 | attrs=attr_str, 20 | value=html.escape(value)) 21 | return element 22 | 23 | def anyargs(*args, **kwargs): 24 | print(args) 25 | print(kwargs) 26 | 27 | # * parameter should be the last but one 28 | # ** parameter should be the last one 29 | -------------------------------------------------------------------------------- /Exercises/Cookbook/Function/callback.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | def apply_async(func, args, *, callback): 5 | # Compute the result 6 | result = func(*args) 7 | # Invoke the callback 8 | callback(result) 9 | 10 | def print_result(result): 11 | print('Got:', result) 12 | 13 | def add(x, y): 14 | return x + y 15 | 16 | apply_async(add, (2, 3), callback=print_result) 17 | -------------------------------------------------------------------------------- /Exercises/Cookbook/Function/defannoymous.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | add = lambda x, y: x + y 5 | print(add(2,3)) 6 | print(add('hello', 'world')) 7 | -------------------------------------------------------------------------------- /Exercises/Cookbook/Function/extrainfo.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | # the arguments won't be checked, only useful for readers 5 | def add(x:int, y:int) -> int: 6 | return x + y 7 | -------------------------------------------------------------------------------- /Exercises/Cookbook/Function/onlykeyword.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | def recv(maxsize, *, block): 5 | """Receive a message""" 6 | pass 7 | 8 | recv(1024, block=True) 9 | 10 | def minimum(*values, clip=None): 11 | m = min(values) 12 | if clip is not None: 13 | m = clip if clip > m else m 14 | return m 15 | 16 | minimum(1, 5, 2, -5, 10) 17 | minimum(1, 5, 2, -5, 10, clip=0) 18 | 19 | -------------------------------------------------------------------------------- /Exercises/Cookbook/Function/reducecallableargs.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | def spam(a, b, c, d): 4 | print(a, b, c, d) 5 | 6 | 7 | from functools import partial 8 | s1 = partial(spam, 1) 9 | print(s1(2, 3, 4)) 10 | print(s1(4, 5, 6)) 11 | 12 | s2 = partial(spam, d=42) 13 | print(s2(1, 2, 3)) 14 | print(s2(4, 5, 5)) 15 | -------------------------------------------------------------------------------- /Exercises/Cookbook/Function/returnalot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | def myfun(): 5 | return 1, 2, 3 6 | 7 | a, b, c = myfun() 8 | print('{a}{b}{c}'.format(a=a,b=b,c=c)) 9 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/ACiter.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | items = ['a', 'b', 'c'] 4 | ### 5 | ### PERMUTATIONS 6 | from itertools import permutations 7 | for p in permutations(items): 8 | print(p) 9 | 10 | # With optional length 11 | for p in permutations(items, 2): 12 | print(p) 13 | 14 | ### COMBINATIONS 15 | from itertools import combinations 16 | for c in combinations(items, 3): 17 | print(c) 18 | 19 | for c in combinations(items, 2): 20 | print(c) 21 | 22 | ### COMBINATIONS WITH REPLACEMENT 23 | from itertools import combinations_with_replacement 24 | for c in combinations_with_replacement(items, 3): 25 | print(c) 26 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/_pipe.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import os 4 | import fnmatch 5 | import gzip 6 | import bz2 7 | import re 8 | 9 | def gen_find(filepat, top): 10 | for path, dirlist, filelist in os.walk(top): 11 | for name in fnmatch.filter(filelist, filepat): 12 | yield os.path.join(path,name) 13 | 14 | def gen_opener(filenames): 15 | for filename in filenames: 16 | if filename.endswith('.gz'): 17 | f = gzip.open(filename, 'rt') 18 | elif filename.endswith('.bz2'): 19 | f = bz2.open(filename, 'rt') 20 | else: 21 | f = open(filename, 'rt') 22 | yield f 23 | f.close() 24 | 25 | def gen_concatenate(iterators): 26 | for it in iterators: 27 | yield from it 28 | 29 | def gen_grep(pattern, lines): 30 | pat = re.compile(pattern) 31 | for line in lines: 32 | if pat.search(line): 33 | yield line 34 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/foldnest.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | from collections import Iterable 5 | 6 | def flatten(items, ignore_types=(str, bytes)): 7 | for x in items: 8 | if isinstance(x, Iterable) and not isinstance(x, ignore_types): 9 | yield from flatten(x) 10 | # for i in flatten(x): 11 | # yield i 12 | else: 13 | yield x 14 | 15 | 16 | items = [1, 2, [3, 4, [5, 6], 7], 8] 17 | for x in flatten(items): 18 | print(x) 19 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/iterGenerator.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | def frange(start, stop, increment): 5 | x = start 6 | while x < stop: 7 | yield x 8 | x += increment 9 | 10 | for n in frange(0, 4, 0.5): 11 | print(n) 12 | 13 | alist = list(frange(0, 1, 0.125)) 14 | 15 | def countdown(n): 16 | print('Starting to count from', n) 17 | while n > 0: 18 | yield n 19 | n -= 1 20 | print('Done!') 21 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/itercombine.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import heapq 4 | 5 | a = [1, 4, 7, 10] 6 | b = [2, 5, 6, 11] 7 | 8 | for c in heapq.merge(a, b): 9 | print(c) 10 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/itercrossset.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from itertools import chain 4 | 5 | a = [1, 2, 3, 4] 6 | b = ['x', 'y', 'z'] 7 | 8 | # for x in a+b 9 | for x in chain(a, b): 10 | print(x) 11 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/iterslice.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | def count(n): 4 | while True: 5 | yield n 6 | n += 1 7 | 8 | c = count(0) 9 | # Standard slice would cast a TypeError 10 | import itertools 11 | for x in itertools.islice(c, 10, 20): 12 | print(x) 13 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/manualiter.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | def manual_iter(): 4 | with open('/etc/passwd') as f: 5 | try: 6 | while True: 7 | line = next(f) 8 | print(line, end='') 9 | except StopIteration: 10 | pass 11 | 12 | def manual_ter2(): 13 | with open('/etc/passwd') as f: 14 | while True: 15 | line = next(f, None) 16 | if line is None: 17 | break 18 | print(line, end='') # end default: '\n' 19 | 20 | 21 | items = [1, 2, 3] 22 | # Get the iterator 23 | it = iter(items) 24 | next(it) 25 | next(it) 26 | next(it) 27 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/outgenerate.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | from collections import deque 5 | 6 | 7 | class linehistory: 8 | def __init__(self, lines, histlen=3): 9 | self.lines = lines 10 | # deque: elements could be appended or removed from both sides 11 | self.history = deque(maxlen=histlen) 12 | 13 | def __iter__(self): 14 | # The second argument should be the start index 15 | for lineno, line in enumerate(self.lines, 1): 16 | self.history.append((lineno, line)) 17 | yield line 18 | 19 | def clear(self): 20 | self.history.clear() 21 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/proxy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class Node: 5 | def __init__(self, value): 6 | self._value = value 7 | self._children = [] 8 | 9 | def __repr__(self): 10 | return 'Node({!r})'.format(self._value) 11 | 12 | def add_child(self, node): 13 | self._children.append(node) 14 | 15 | def __iter__(self): 16 | return iter(self._children) 17 | 18 | 19 | if __name__ == '__main__': 20 | root = Node(0) 21 | child1 = Node(1) 22 | child2 = Node(2) 23 | root.add_child(child1) 24 | root.add_child(child2) 25 | for ch in root: 26 | print(ch) 27 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/reversed.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | class Countdown: 5 | def __init__(self, start): 6 | self.start = start 7 | 8 | def __iter__(self): 9 | n = self.start 10 | while n > 0: 11 | yield n 12 | n -= 1 13 | 14 | def __reversed__(self): 15 | n = 1 16 | while n <= self.start: 17 | yield n 18 | n += 1 19 | 20 | for rr in reversed(Countdown(30)): 21 | print(rr) 22 | 23 | for rr in Countdown(30): 24 | print(rr) 25 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/skipiter.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from itertools import dropwhile 4 | with open('/etc/passwd') as f: 5 | for line in dropwhile(lambda line: line.sartwith('#'), f): 6 | print(line, end='') 7 | 8 | 9 | # Known the specific index 10 | from itertools import islice 11 | items = ['a', 'b', 'c', 1, 4, 10, 15] 12 | for x in islice(items, 3, None): 13 | print(x) 14 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/yieldinfinite.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | CHUNKSIZE = 8192 5 | 6 | def reader(s): 7 | while True: 8 | data = s.recv(CHUNKSIZE) 9 | if data == b'': 10 | break 11 | process_data(data) 12 | 13 | def reader2(s): 14 | for chunk in iter(lambda: s.recv(CHUNKSIZE), b''): 15 | pass 16 | -------------------------------------------------------------------------------- /Exercises/Cookbook/IterateGenerate/zip.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | xpts = [1, 5, 4, 2, 10, 7] 4 | ypts = [101, 78, 37, 15, 62, 99] 5 | for x, y in zip(xpts, ypts): 6 | print(x, y) 7 | 8 | 9 | # length not equal 10 | a = [1, 2, 3] 11 | b = ['w', 'x', 'y', 'z'] 12 | 13 | for i in zip(a, b): 14 | print(i) 15 | 16 | from itertools import zip_longest 17 | for i in zip_longest(a, b): 18 | print(i) 19 | -------------------------------------------------------------------------------- /Exercises/Cookbook/attrgetter.py: -------------------------------------------------------------------------------- 1 | class User: 2 | def __init__(self, user_id): 3 | self.user_id = user_id 4 | 5 | def __repr__(self): 6 | return 'User({})'.format(self.user_id) 7 | 8 | def sort_notcompare(): 9 | print users 10 | print sorted(users, key=lambda u: u.user_id) 11 | 12 | def sort_attrget(): 13 | from operator import attrgetter 14 | # attrgetter could get more than one parameter 15 | print sorted(users, key=attrgetter('user_id')) 16 | 17 | if __name__ == '__main__': 18 | users = [User(23), User(3), User(99)] 19 | sort_notcompare() 20 | sort_attrget() 21 | -------------------------------------------------------------------------------- /Exercises/Cookbook/counter.py: -------------------------------------------------------------------------------- 1 | words = [ 2 | 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 3 | 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 4 | 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 5 | 'my', 'eyes', "you're", 'under' 6 | ] 7 | 8 | from collections import Counter 9 | word_counts = Counter(words) 10 | 11 | top_three = word_counts.most_common(3) 12 | print top_three 13 | 14 | print word_counts['not'] 15 | print word_counts['eyes'] 16 | 17 | # add count by yourself 18 | word_counts['not'] += 1 19 | print word_counts['not'] 20 | # or function update() 21 | word_counts.update(['not']) 22 | print word_counts['not'] 23 | -------------------------------------------------------------------------------- /Exercises/Cookbook/dedupe.py: -------------------------------------------------------------------------------- 1 | def dedupe(items): 2 | seen = set() 3 | for item in items: 4 | if item not in seen: 5 | yield item 6 | seen.add(item) 7 | 8 | 9 | def dedupe(items, key): 10 | seen = set() 11 | for item in items: 12 | """if not hashable""" 13 | val = item if key is None else key(item) 14 | if val not in seen: 15 | yield item 16 | seen.add(val) 17 | -------------------------------------------------------------------------------- /Exercises/Cookbook/dictcommon.py: -------------------------------------------------------------------------------- 1 | a = { 2 | 'x' : 1, 3 | 'y' : 2, 4 | 'z' : 3 5 | } 6 | 7 | b = { 8 | 'w' : 10, 9 | 'x' : 11, 10 | 'y' : 2 11 | } 12 | 13 | # find keys in common 14 | print (a.keys() & b.keys()) 15 | 16 | # find keys in a that are not in b 17 | print (a.keys() - b.keys()) 18 | 19 | # find (key, value pairs in common 20 | print (a.items() & b.items()) 21 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/BytetoTxt.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | # Use buffer to read data in binary 5 | sys.stdout.buffer.write(b'Hello\n') 6 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/_ChangeEncode.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 5.16 3 | 4 | import urllib.request 5 | import io 6 | 7 | u = urllib.request.urlopen('http://www.python.org') 8 | f = io.TextIOWrapper(u, encoding='utf-8') 9 | text = f.read() 10 | 11 | # Change encode 12 | import sys 13 | sys.stdout.encoding 14 | sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='latin-1') 15 | sys.stdout.encoding 16 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/_UniERR.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Coming across `surrogates not allowed 3 | 4 | import sys 5 | 6 | def bad_filename(filename): 7 | return repr(filename)[1:-1] 8 | 9 | def bad_filename2(filename): 10 | temp = filename.encode(sys.getfilesystemencoding(), errors='surrogateescape') 11 | return temp.decode('latin-1') 12 | 13 | try: 14 | print(filename) 15 | except UnicodeEncodeError: 16 | print(bad_filename(filename)) 17 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/_descriptor.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 5.18 3 | 4 | import os 5 | # Open descriptor 6 | fd = os.open('somefile.txt', os.O_WRONLY | os.O_CREAT) 7 | 8 | f = open(fd, 'wt') 9 | f.write('hello world\n') 10 | f.close() 11 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/_membin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 5.10 3 | 4 | 5 | import os 6 | import mmap 7 | 8 | 9 | def memory_map(filename, access=mmap.ACCESS_WRITE): 10 | size = os.path.getsize(filename) 11 | fd = os.open(filename, os.O_RDWR) 12 | return mmap.mmap(fd, size, access=access) 13 | 14 | size = 1000000 15 | with open('data', 'wb') as f: 16 | # seek(off, whence=0), pointer & starting index 17 | f.seek(size-1) 18 | f.write(b'\x00') 19 | 20 | m = memory_map('data') 21 | len(m) 22 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/byte.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Read binary 4 | with open('file.bin', 'rb') as f: 5 | data = f.read() 6 | 7 | # Write binary 8 | with open('file.bin', 'wb') as f: 9 | f.write(b'Hello World') 10 | 11 | with open('file.bin', 'wb') as f: 12 | text = 'Hello World' 13 | f.write(text.encode('utf-8')) 14 | 15 | import array 16 | a = array.array('i', [0, 0, 0, 0, 0, 0, 0, 0]) 17 | with open('data.bin', 'rb') as f: 18 | # Read into memory 19 | f.readinto(a) 20 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/data.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/Cookbook/fileIO/data.bin -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/file.bin: -------------------------------------------------------------------------------- 1 | Hello World -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/file.txt: -------------------------------------------------------------------------------- 1 | statement 1 2 | statement 2 3 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/file2.txt: -------------------------------------------------------------------------------- 1 | Hello -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/fileexist.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | import os 5 | 6 | os.path.exists('/etc/passwd') 7 | os.path.exists('/tmp/spam') 8 | 9 | 10 | # Whether a file 11 | os.path.isfile('/etc/passwd') 12 | # Whether a dir 13 | os.path.isdir('/etc/passwd') 14 | # Whether link 15 | os.path.islink('/usr/local/bin/python3') 16 | # Get link to 17 | os.path.realpath('/usr/local/bin/python3') 18 | 19 | 20 | # file size 21 | os.path.getsize('/etc/passwd') 22 | 23 | os.path.getmtime('/etc/passwd') 24 | 25 | import time 26 | time.ctime(os.path.getmtime('/etc/passwd')) 27 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/filename.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | import os 5 | path = '/Users/kasheemlew/Data/data.csv' 6 | 7 | os.path.basename(path) 8 | os.path.dirname(path) 9 | 10 | os.path.join('tmp', 'data', os.path.basename(path)) 11 | 12 | 13 | # Expand 14 | path = '~/Data/data.csv' 15 | os.path.expanduser(path) 16 | 17 | # Split extension 18 | os.path.splitext(path) 19 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/ignoreencode.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | sys.getfilesystemencoding() 5 | 6 | with open('jalapae\xf1o.txt', 'w') as f: 7 | f.write('Spicy!') 8 | 9 | import os 10 | # Raw listing 11 | os.listdir('.') 12 | 13 | os.listdir(b'.') 14 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/iterhistory.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | from functools import partial 5 | 6 | RECORD_SIZE = 32 7 | 8 | with open('somefile.data', 'rb') as f: 9 | # partial read certain nums of bytes from a file 10 | records = iter(partial(f.read, RECORD_SIZE), b'') 11 | for r in records: 12 | print(i) 13 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/jalapaeño.txt: -------------------------------------------------------------------------------- 1 | Spicy! -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/listdir.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | import os 5 | names = os.listdir('somedir') 6 | 7 | # Get files 8 | names = [name for name in os.listdir('somedir') 9 | if os.path.isfile(os.path.join('somedir', name))] 10 | 11 | # Get dirs 12 | dirnames = [name for name in os.listdir('somedir') 13 | if os.path.isdir(os.path.join('somedir', name))] 14 | 15 | pyfiles = [name for name in os.listdir('somedir') 16 | if name.endwith('.py')] 17 | 18 | # Match 19 | import glob 20 | pyfiles = glob.glob('somedir/*.py') 21 | 22 | from fnmatch import fnmatch 23 | pyfiles = [name for name in os.listdir('somedir') 24 | if fnmatch(name, '*.py')] 25 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/mktemporary.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | from tempfile import TemporaryFile 5 | 6 | with TemporaryFile('w+t') as f: 7 | f.write('Hello World\n') 8 | f.write('Testing\n') 9 | 10 | # seek back to beginning 11 | f.seek(0) 12 | data = f.read() 13 | 14 | # with TemporaryFile('w+t', encoding='utf-8', errors='ignore') as f 15 | 16 | # Named temporary file 17 | from tempfile import NamedTemporaryFile 18 | 19 | with NamedTemporaryFile('w+t') as f: 20 | print('filename is:', f.name) 21 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/printsepend.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | print('ACME', 50, 91.5) 5 | print('ACME', 50, 91.5, sep=',') 6 | print('ACME', 50, 91.5, sep=',', end='!\n') 7 | 8 | 9 | for i in range(5): 10 | print(i) 11 | 12 | for i in range(5): 13 | print(i, ' ') 14 | 15 | 16 | row = ('ACME', 50, 91.5) 17 | print(*row, sep=',') 18 | print(row, sep=',') 19 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/readwrite.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | # Read the file as single string 5 | with open('file.txt', 'rt') as f: 6 | data = f.read() 7 | 8 | # Iterate over the lines of the file 9 | with open('file.txt', 'rt', encoding='latin-1') as f: 10 | for line in f: 11 | print(line) 12 | 13 | # Write chunks of text data 14 | with open('file.txt', 'wt') as f: 15 | f.write('write line 1') 16 | f.write('write line 2') 17 | 18 | # Redirected print statement 19 | with open('file.txt', 'wt') as f: 20 | print('statement 1', file=f) 21 | print('statement 2', file=f) 22 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/rwzip.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Read 4 | import gzip 5 | with gzip.open('somefile.gz', 'rt') as f: 6 | text = f.read() 7 | 8 | import bz2 9 | with bz2.open('somefile.bz2', 'rt') as f: 10 | text = f.read() 11 | 12 | 13 | # Write 14 | import gzip 15 | # compress level default=9 16 | with gzip.open('somefile.gz', 'wt', compresslevel=5) as f: 17 | f.write(text) 18 | 19 | import bz2 20 | with bz2.open('somefile.bz2', 'wt') as f: 21 | f.write(text) 22 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/somefile: -------------------------------------------------------------------------------- 1 | Hello 2 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/stringIO.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import io 4 | 5 | # BytesIO() for binary 6 | s = io.StringIO() 7 | s.write('Hello World\n') 8 | 9 | print('This is a test', file=s) 10 | # Get written data 11 | s.getvalue() 12 | 13 | # Wrap interface 14 | s = io.StringIO('Hello\nWorld\n') 15 | s.read(4) 16 | s.read() 17 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/tofile.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | with open('file.txt', 'wt') as f: 5 | print('Hello World!', file=f) 6 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/wbtobuffer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import os.path 4 | 5 | def read_into_buffer(filename): 6 | # allocate memory for array 7 | buf = bytearray(os.path.getsize(filename)) 8 | with open(filename, 'rb') as f: 9 | # fill data 10 | f.readinto(buf) 11 | return buf 12 | 13 | 14 | # Same Size 15 | record_size = 32 16 | 17 | buf = bytearray(record_size) 18 | with open('somefile', 'rb') as f: 19 | while True: 20 | n = f.readinto(buf) 21 | if n < record_size: 22 | break 23 | -------------------------------------------------------------------------------- /Exercises/Cookbook/fileIO/writenull.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | with open('file2.txt', 'xt') as f: 5 | f.write('Hello\t') 6 | 7 | ## EQUAL 8 | import os 9 | if not os.path.exists('somefile'): 10 | with open('somefile', 'wt') as f: 11 | f.write('Hello\n') 12 | else: 13 | print('File Exists!') 14 | -------------------------------------------------------------------------------- /Exercises/Cookbook/groupby.py: -------------------------------------------------------------------------------- 1 | rows = [ 2 | {'address': '5412 N CLARK', 'date': '07/01/2012'}, 3 | {'address': '5148 N CLARK', 'date': '07/04/2012'}, 4 | {'address': '5800 E 58TH', 'date': '07/02/2012'}, 5 | {'address': '2122 N CLARK', 'date': '07/03/2012'}, 6 | {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'}, 7 | {'address': '1060 W ADDISON', 'date': '07/02/2012'}, 8 | {'address': '4801 N BROADWAY', 'date': '07/01/2012'}, 9 | {'address': '1039 W GRANVILLE', 'date': '07/04/2012'}, 10 | ] 11 | 12 | # use groupby() to get the data by certain keys 13 | from operator import itemgetter 14 | from itertools import groupby 15 | 16 | # Sort by the desired field first 17 | # groupby() returns a data and a grenerator 18 | rows.sort(key=itemgetter('date')) 19 | for date, items in groupby(rows, key=itemgetter('date')): 20 | print date 21 | for i in items: 22 | print ' ', i 23 | -------------------------------------------------------------------------------- /Exercises/Cookbook/headq.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | class PriorityQueue: 4 | def __init__(self): 5 | self._queue = [] 6 | self._index = 0 7 | 8 | def push(self, item, priority): 9 | # priority with minus sign in order to sort the elements from the 10 | # larger one to the smaller one 11 | # with an tuple of the three elements, the instances could be compared 12 | # without any errors turning up 13 | heapq.heappush(self._queue, (-priority, self._index, item)) 14 | self._index += 1 15 | 16 | def pop(self): 17 | return heapq.heappop(self._queue)[-1] 18 | -------------------------------------------------------------------------------- /Exercises/Cookbook/orderdict.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | import json 3 | 4 | def order_dict(): 5 | d = OrderedDict() 6 | d['foo'] = 1 7 | d['bar'] = 2 8 | d['spam'] = 3 9 | d['grok'] = 4 10 | for key in d: 11 | print(key, d[key]) 12 | 13 | if __name__ == '__main__': 14 | order_dict() 15 | 16 | # NOTICE 17 | # a OrderedDict is twice the size of a normal dict, because of a linked 18 | # list served in it. 19 | -------------------------------------------------------------------------------- /Exercises/Cookbook/slice.py: -------------------------------------------------------------------------------- 1 | record = '....................100 .......513.25 ..........' 2 | 3 | SHARES = slice(20, 23) 4 | PRICE = slice(31, 37) 5 | cost = int(record[SHARES]) * float(record[PRICE]) 6 | print cost 7 | 8 | # obj a a.start a.stop a.step 9 | a = slice(5, 50, 2) # 5 50 2 10 | 11 | s = 'HelloWorld' 12 | # indices cut the range to a optimium range 13 | for i in range(*a.indices(len(s))): 14 | print s[i] 15 | -------------------------------------------------------------------------------- /Exercises/Cookbook/zip.py: -------------------------------------------------------------------------------- 1 | prices = { 2 | 'ACME': 45.23, 3 | 'AAPL': 612.78, 4 | 'IBM': 205.55, 5 | 'HPQ': 37.20, 6 | 'FB': 10.75 7 | } 8 | 9 | # sort the dict by the values 10 | min_price = min(zip(prices.values(), prices.keys())) 11 | max_price = max(zip(prices.values(), prices.keys())) 12 | 13 | prices_sorted = sorted(zip(prices.values(), prices.keys())) 14 | 15 | 16 | # NOTICE 17 | # zip() created a generator could be used once 18 | # 19 | # prices_and_names = zip(prices.values(), price.keys()) 20 | # print(min(prices_and_names)) is OK 21 | # print(max(prices_and_names)) will throw a ValueError: max() arg is an empty 22 | # sequence 23 | # 24 | # With zip, keys will dominate when values are the same 25 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/add.py: -------------------------------------------------------------------------------- 1 | def add(x): 2 | def do_add(value): 3 | return x + value 4 | return do_add 5 | 6 | add_5 = add(5) 7 | print add_5(1) 8 | print add_5(2) 9 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/add_from_1_to_79.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | # 记得加上上面这句哦 3 | 4 | bingo = False 5 | a=1 6 | i=2 7 | 8 | while bingo == False: 9 | a = a+i; 10 | i = i+1; 11 | 12 | if i >= 80: 13 | print "The answer is %d." % a 14 | bingo = True 15 | 16 | 17 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/bird.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | 5 | class Bird(object): 6 | 7 | 8 | def __init__(self, nm, a): 9 | self.name = nm 10 | self.age = a 11 | 12 | 13 | def eat(self): 14 | print 'eat' 15 | 16 | 17 | def sing(self): 18 | print 'sing' 19 | 20 | 21 | b = Bird('bird', 423) 22 | 23 | 24 | print b.name 25 | print b.age 26 | b.eat() 27 | b.sing() 28 | 29 | class Lark(Bird): 30 | 31 | 32 | def eat(self): 33 | print 'eat2' 34 | 35 | 36 | l = Lark('lark', 5423) 37 | 38 | 39 | print l.name 40 | print l.age 41 | l.eat() 42 | l.sing() 43 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/class.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Bird(object): 6 | 7 | def __init__(self): 8 | self.hungry = True 9 | 10 | def eat(self): 11 | if self.hungry == True: 12 | print 'Aaaah..' 13 | self.hungry = False 14 | else: 15 | print 'No, thanks.' 16 | 17 | 18 | class SongBird(Bird): 19 | 20 | def __init__(self): 21 | super(SongBird, self).__init__() 22 | self.sound = 'Squawk!' 23 | 24 | def sing(self): 25 | print self.sound 26 | 27 | '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' 28 | 29 | b = Bird() 30 | print 'Hello, Bird b, want something to eat?' 31 | b.eat() 32 | print 'Anymore?' 33 | b.eat() 34 | 35 | print ' ' 36 | 37 | s = SongBird() 38 | print 'Hello, SongBird s, want something to eat?' 39 | s.eat() 40 | print 'Anymore?' 41 | s.eat() 42 | print 'You have eaten so much, sing a song!' 43 | s.sing() 44 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/class2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | class Rectangle(object): 6 | 7 | def __init__(self): 8 | self.width = 0 9 | self.height = 0 10 | 11 | def setSize(self, size): 12 | self.width, self.height = size 13 | 14 | def getSize(self): 15 | return self.width, self.height 16 | 17 | size = property(getSize, setSize) 18 | 19 | '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' 20 | 21 | r = Rectangle() 22 | r.width = 10 23 | r.height = 5 24 | print r.size 25 | r.size = 150, 100 26 | print r.width,r.height 27 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/creditcard/carddata.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/CorePythonExercises/creditcard/carddata.txt -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/creditcard/cardlog.txt: -------------------------------------------------------------------------------- 1 | no txns this month 2 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/deco.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | ''' 6 | decorator to accept any amount of arguments 7 | ''' 8 | 9 | 10 | def decorator(func): 11 | def inner(*args, **kwargs): 12 | print 'Arguments are', args, kwargs 13 | return func(*args, **kwargs) 14 | return inner 15 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/decorator/deco.py: -------------------------------------------------------------------------------- 1 | def decorator(func): 2 | print 'hello' 3 | return func 4 | 5 | 6 | @decorator 7 | def foo(): 8 | pass 9 | 10 | 11 | foo() 12 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/decorator/deco2.py: -------------------------------------------------------------------------------- 1 | def decorator_func_args(func): 2 | # handle with the arguments 3 | def handle_args(*args, **kwargs): 4 | print 'begin' 5 | # invoke the func 6 | func(*args,**kwargs) 7 | print 'end' 8 | return handle_args 9 | 10 | 11 | @decorator_func_args 12 | def foo(a, b = 2): 13 | print a, b 14 | 15 | 16 | foo(1) 17 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/decorator/deco3.py: -------------------------------------------------------------------------------- 1 | def decorator_with_params(arg_of_decorator): # with arguments in decorator 2 | print arg_of_decorator 3 | 4 | # return the function 5 | def newDecorator(func): 6 | print func 7 | return func 8 | return newDecorator 9 | 10 | 11 | @decorator_with_params("deco_args") 12 | def foo(): 13 | pass 14 | 15 | 16 | foo() 17 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/decorator/deco4.py: -------------------------------------------------------------------------------- 1 | def decorator_with_params_and_func_args(arg_of_decorator): 2 | def handle_func(func): 3 | def handle_args(*args, **kwargs): 4 | print 'begin' 5 | func(*args, **kwargs) 6 | print 'end' 7 | print arg_of_decorator, func, args, kwargs 8 | return handle_args 9 | return handle_func 10 | 11 | 12 | @decorator_with_params_and_func_args("123") 13 | def foo(a, b = 2): 14 | print "Content" 15 | 16 | 17 | foo(1, b = 3) 18 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/decorator/property.py: -------------------------------------------------------------------------------- 1 | class B(): 2 | 3 | def __init__(self): 4 | self.__prop = 1 5 | 6 | @property 7 | def prop(self): 8 | print "call get" 9 | return self.__prop 10 | 11 | @prop.setter 12 | def prop(self, value): 13 | print "call set" 14 | self.__prop = value 15 | 16 | @prop.deleter 17 | def prop(self): 18 | print "call del" 19 | del self.__prop 20 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/decorator/staticmethod.py: -------------------------------------------------------------------------------- 1 | ''' 2 | staticmethod change the instance into a static method 3 | classmethod change the instance into a class method 4 | ''' 5 | 6 | 7 | class A(): 8 | @staticmethod 9 | def test_static(): 10 | print "static" 11 | 12 | def test_normal(self): 13 | print "normal" 14 | 15 | @classmethod 16 | def test_class(cls): 17 | print "class", cls 18 | 19 | 20 | a = A() 21 | A.test_static() 22 | a.test_static() 23 | a.test_normal() 24 | a.test_class() 25 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/define.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | def isEqual(num1,num2): 4 | """判断num1和num2是否相等,并返回 5 | True or False""" 6 | if num1 < num2: 7 | print 'too small' 8 | return False 9 | if num1 > num2: 10 | print 'too big' 11 | return False 12 | if num1 == num2: 13 | print 'BINGO' 14 | return True 15 | 16 | 17 | from random import randint 18 | num = randint(1, 100) 19 | 20 | print 'Guess what I think?' 21 | 22 | bingo = False 23 | while bingo == False: 24 | answer = input() 25 | bingo = isEqual(answer, num) 26 | 27 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/eg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | 4 | class Parent(object): 5 | 6 | 7 | def altered(self): 8 | print 'Parent altered():' 9 | 10 | 11 | def override(): 12 | print 'Parent override()' 13 | 14 | 15 | class Child(Parent): 16 | 17 | 18 | def altered(self): 19 | super(Child, self).altered() 20 | 21 | 22 | def override(): 23 | pass 24 | 25 | 26 | dad = Parent() 27 | son = Child() 28 | 29 | 30 | dad.altered() 31 | son.altered() 32 | 33 | 34 | dad.override() 35 | son.override() 36 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/fibonacci.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | ''' 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | Enter a num and a relevant num in Fibonacci Sequence will be returned 6 | by Kasheem Lew 7 | 2015.11.04 8 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 9 | ''' 10 | 11 | 12 | a = 2 13 | n1 = 1 14 | n2 = 1 15 | 16 | 17 | # which one do you want 18 | count = input('>') 19 | 20 | 21 | # print until the one you want is got 22 | while a < count: 23 | n3 = n2 24 | n2 += n1 25 | n1 = n3 26 | a += 1 27 | continue 28 | else: 29 | print n2 30 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/generate_pyc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*- coding: utf-8 -*- 3 | 4 | import sys 5 | import imp 6 | 7 | def generate_pyc(name): 8 | fp, pathname, description = imp.find_module(name) 9 | try: 10 | imp.load_module(name, fp, pathname, description) 11 | finally: 12 | if fp: 13 | fp.close() 14 | 15 | if __name__ == '__main__': 16 | generate_pyc(sys.argv[1]) 17 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/kick_the_ball.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | # kick the ball,the game.py 3 | 4 | from random import choice # make a random choice from the list of the direction below 5 | 6 | 7 | direction = ['左边','右边','中间'] # make a list of dirctions 8 | print "轮到你点球了,准备射向哪边?从下面几个中选择一个吧!" 9 | print "左边,中间,右边" 10 | 11 | 12 | your_choice = raw_input(">") # assign what you choose to your_choice 13 | print "你射向了 %s."%your_choice 14 | 15 | 16 | com = choice(direction) # computer makes the random choice 17 | print "守门员扑向了 %s."%com 18 | 19 | 20 | if your_choice != com: 21 | print "进了!" 22 | else: 23 | print "可惜." # print the consequense 24 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/list&tuple&dict.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | 4 | aList = [1, 2, 3, 4] #to establish a list 5 | 6 | 7 | print aList 8 | print aList[:2] 9 | print aList[2:] 10 | print alist[2] #to print the element you want in the list 11 | 12 | 13 | aList[1] = 5 #to make a little bit change in the list 14 | 15 | 16 | print aList #print the new list 17 | 18 | 19 | aTuple = ('list', 'tuple', 'dict', 'robot') #to form a tuple 20 | 21 | 22 | print aTuple 23 | print aTuple[:2] 24 | print aTuple[2:] 25 | print aTuple[2] #print the tuple.A tuple is unable to be changed 26 | 27 | 28 | aDict = {1:'list', 2:'tuple', 3:'dict'} #form an dict 29 | 30 | 31 | print aDict 32 | 33 | 34 | aDict[4] = keyword #add a factor to the dict 35 | 36 | 37 | print aDict 38 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/ltd.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | 4 | aList = [1, 2, 3, 4] #to establish a list 5 | 6 | 7 | print aList 8 | print aList[:2] 9 | print aList[2:] 10 | print alist[2] #to print the element you want in the list 11 | 12 | 13 | aList[1] = 5 #to make a little bit change in the list 14 | 15 | 16 | print aList #print the new list 17 | 18 | 19 | aTuple = ('list', 'tuple', 'dict', 'robot') #to form a tuple 20 | 21 | 22 | print aTuple 23 | print aTuple[:2] 24 | print aTuple[2:] 25 | print aTuple[2] #print the tuple.A tuple is unable to be changed 26 | 27 | 28 | aDict = {1:'list', 2:'tuple', 3:'dict'} #form an dict 29 | 30 | 31 | print aDict 32 | 33 | 34 | aDict[4] = keyword #add a factor to the dict 35 | 36 | 37 | print aDict 38 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/makeTextFile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | 4 | 'makeTextFile.py -- create text file' 5 | 6 | 7 | import os 8 | ls = os.linesep 9 | 10 | 11 | # get filename 12 | while True: 13 | fname = raw_input('write down a title\n') #create a text 14 | if os.path.exists(fname): 15 | print "ERROR: '%s' already exists"%fname 16 | else: 17 | break 18 | 19 | 20 | # get file content (text) lines 21 | all = [] 22 | print "\nEnter lines ('.' by itself to quit).\n" 23 | 24 | 25 | #loop until user terminates input 26 | while True: 27 | entry = raw_input('>') 28 | if entry == '.': 29 | break 30 | else: 31 | all.append(entry) 32 | 33 | 34 | # write lines to file with proper line-ending 35 | fobj = open(fname, 'w') 36 | fobj.writelines(['%s%s' % (x,ls) for x in all]) 37 | fobj.close() 38 | print ' DONE!' 39 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/maxfactor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | ''' 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | A script to show the num's max factor in the range user provides 6 | by Kasheem Lew 7 | 2015.11.04 8 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 9 | ''' 10 | 11 | 12 | # set a range to find the max factor for 13 | print 'Enter the range you want!' 14 | a = input('Start from:') 15 | b = input('End at:') + 1 16 | 17 | 18 | # start to check at sequence 19 | for num in range( a , b , 1 ): 20 | half = num / 2 21 | 22 | 23 | while half > 1: 24 | 25 | 26 | # aquire the max factor 27 | if num % half == 0: 28 | print 'The max factor of', num, 'is', half, '.' 29 | break 30 | else: 31 | half -= 1 32 | 33 | # no more factors 34 | else: 35 | print num,'is prime.' 36 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/randint.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | num = randint(1,20) 3 | 4 | 5 | print "Guess what do I think?" 6 | bingo = False 7 | 8 | 9 | while bingo == False: 10 | answer = input() 11 | 12 | 13 | if answer > num: 14 | print "Too big." 15 | 16 | if answer < num: 17 | print "Too small." 18 | 19 | if answer == num: 20 | print "BINGO!" 21 | bingo = True 22 | 23 | 24 | print " Bye bye!~" 25 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/readTextFile.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | 4 | ' readTextFile.py -- read and display text file ' 5 | 6 | 7 | #get filename 8 | fname = raw_input('Enter filename: ') 9 | print 10 | 11 | 12 | # attempt to open file for reading 13 | try: 14 | fobj = open(fname, 'r') 15 | except IOError, e: 16 | print "*** file open error:", e 17 | else: 18 | # display contents to the screen 19 | for eachLine in fobj: 20 | print eachLine, 21 | fobj.close() 22 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/stringtemplate.py: -------------------------------------------------------------------------------- 1 | #!usr/bin/env python 2 | 3 | 4 | '''the string template''' 5 | 6 | 7 | from string import Template 8 | 9 | 10 | def main(): 11 | '''the string template.''' 12 | s = Template('There are ${howmany} ${lang} Quotation Symbols') 13 | print s.substitute(lang='Python', howmany=3) 14 | 15 | 16 | if __name__ == '__main__': 17 | main() 18 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/super.py: -------------------------------------------------------------------------------- 1 | class FooParent(object): 2 | def __init__(self): 3 | self.parent = 'I\'m the parent.' 4 | print 'Parent' 5 | 6 | def bar(self, message): 7 | print message, 'from Parent' 8 | 9 | 10 | class FooChild(FooParent): 11 | def __init__(self): 12 | super(FooChild, self).__init__() # FooParent.__init__(self) 13 | print 'Child' 14 | 15 | def bar(self, message): 16 | super(FooChild, self).bar(message) # FooParent.bar(self, message) 17 | print 'Child bar function' 18 | print self.parent 19 | 20 | 21 | if __name__ == '__main__': 22 | fooChild = FooChild() 23 | fooChild.bar('HelloWorld') 24 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import sys 5 | 6 | 7 | print(sys.path) 8 | print(sys.argv[1]) 9 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/tsTserv.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # 模块导入 6 | from socket import * 7 | from time import ctime 8 | 9 | 10 | HOST = '' # 变量为空,表示bind()函数可以绑定在所有有效的地址上 11 | PORT = 21567 # 设置端口号 12 | BUFSIZ = 1024 # 设置缓冲区 13 | ADDR = (HOST, PORT) 14 | 15 | 16 | tcpSerSock = socket(AF_INET, SOCK_STREAM) # 创建TCP/IP套接字 17 | tcpSerSock.bind(ADDR) # 绑定地址到套接字 18 | tcpSerSock.listen(5) # 开始监听,最多允许5个连接同时连入 19 | 20 | 21 | while True: 22 | print 'waiting for connection...' 23 | tcpCliSock, addr = tcpSerSock.accept() #被动接受TCP客户端连接,等待连接的到来 24 | print '...connected from:', addr 25 | 26 | # 有连接时进入对话循环 27 | while True: 28 | data = tcpCliSock.recv(BUFSIZ) # 用户发送数据 29 | # 消息为空表示客户端已经退出 30 | if not data: 31 | break 32 | tcpCliSock.send('[%s] %s' % (ctime(), data)) 33 | 34 | tcpCliSock.close() 35 | 36 | 37 | tcpSerSock.close() 38 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/urlopen.py: -------------------------------------------------------------------------------- 1 | #!usr/bin/env python 2 | 3 | 4 | from urllib import urlopen 5 | 6 | 7 | def main(): 8 | '''the urlopen method.''' 9 | f = urlopen('http://' # protocol 10 | 'localhost' # hostname 11 | ':8000' # port 12 | '/cgi-bin/friend2.py') # file 13 | 14 | 15 | if __name__ == '__main__': 16 | main() 17 | -------------------------------------------------------------------------------- /Exercises/CorePythonExercises/while&if.py: -------------------------------------------------------------------------------- 1 | num = 10 2 | print "Guess what do I think?" 3 | bingo = False 4 | 5 | 6 | while bingo == False: 7 | answer = input(">") 8 | if answer > num: 9 | print "Too big." 10 | 11 | if answer < num: 12 | print "Too small." 13 | 14 | if answer == num: 15 | print "BINGO!" 16 | bingo = True 17 | 18 | 19 | num = 20 20 | print "Guess what do I think?" 21 | answer = input() 22 | 23 | 24 | if answer > num: 25 | print "Too big!" 26 | 27 | if answer < num: 28 | print "Too small!" 29 | 30 | if answer == num: 31 | print "You are so smart!" 32 | 33 | -------------------------------------------------------------------------------- /Exercises/Decorator/cls-dec.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | 4 | class Common(object): 5 | def __init__(self, func): 6 | self.func = func 7 | 8 | def __call__(self, *args, **kwargs): 9 | print 'args: ', args 10 | return self.func(*args, **kwargs) 11 | 12 | 13 | @Common 14 | def test(p): 15 | print p 16 | 17 | 18 | test(10) 19 | -------------------------------------------------------------------------------- /Exercises/Decorator/common.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | def common(func): 4 | def _deco(*args, **kwargs): 5 | print 'args:', args 6 | return func(*args, **kwargs) 7 | return _deco 8 | 9 | @common 10 | def test(p): 11 | print(p) 12 | 13 | test(1) 14 | -------------------------------------------------------------------------------- /Exercises/Decorator/dec-cls.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | 4 | def borg(cls): 5 | cls._state = {} 6 | orig_init = cls.__init__ 7 | def new_init(self, *args, **kwargs): 8 | self.__dict__ = cls._state 9 | orig_init(self, *args, **kwargs) 10 | cls.__init__ = new_init 11 | return cls 12 | 13 | @borg 14 | class A(object): 15 | def common(self): 16 | print hex(id(self)) 17 | -------------------------------------------------------------------------------- /Exercises/Decorator/with-args.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | 4 | def common(*args, **kwargs): 5 | a = args 6 | def _common(func): 7 | def _deco(*args, **kwargs): 8 | print 'args:', args, a 9 | return func(*args, **kwargs) 10 | return _deco 11 | return _common 12 | 13 | @common('c') 14 | def test(p): 15 | print p 16 | 17 | test(10) 18 | -------------------------------------------------------------------------------- /Exercises/Descriptor/des.py: -------------------------------------------------------------------------------- 1 | class Descriptor(object): 2 | def __init__(self, name="default", value="default"): 3 | self.name = name 4 | self.value = value 5 | 6 | def __get__(self, obj, objtype): 7 | print "get from descriptor {}".format(self.name) 8 | return self.value 9 | 10 | def __set__(self, obj, val): 11 | print "set to descriptor {}".format(self.name) 12 | self.value = val 13 | 14 | 15 | class MyClass(object): 16 | descriptor = Descriptor() 17 | 18 | def __repr__(self): 19 | return "" 20 | -------------------------------------------------------------------------------- /Exercises/FrozenTest/app/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from flask import Flask 4 | 5 | 6 | app = Flask(__name__) 7 | app.config['SECRET_KEY'] = 'your secret key is here' 8 | 9 | 10 | from . import views, forms 11 | -------------------------------------------------------------------------------- /Exercises/FrozenTest/app/build/test/index.html: -------------------------------------------------------------------------------- 1 |

just tell you everything is ok!

-------------------------------------------------------------------------------- /Exercises/FrozenTest/app/forms.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from flask_wtf import Form 3 | # from wtforms import 4 | # from wtforms.validators import 5 | 6 | -------------------------------------------------------------------------------- /Exercises/FrozenTest/app/views.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from . import app 3 | from flask import render_template 4 | 5 | 6 | # test views 7 | @app.route('/test/') 8 | def test(): 9 | return "

just tell you everything is ok!

" 10 | 11 | # you can writing your views here 12 | 13 | -------------------------------------------------------------------------------- /Exercises/FrozenTest/freeze.py: -------------------------------------------------------------------------------- 1 | from flask_frozen import Freezer 2 | from app import app 3 | 4 | freezer = Freezer(app) 5 | 6 | if __name__ == '__main__': 7 | freezer.freeze() 8 | -------------------------------------------------------------------------------- /Exercises/FrozenTest/manage.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | manage.py 5 | ~~~~~~~~ 6 | 7 | shell: 8 | python manage.py shell 9 | run server: 10 | python manage.py runserver 11 | -d 开启调试模式 12 | """ 13 | 14 | import sys 15 | from app import app 16 | from flask.ext.script import Manager, Shell 17 | 18 | """编码设置""" 19 | reload(sys) 20 | sys.setdefaultencoding('utf-8') 21 | 22 | 23 | manager = Manager(app) 24 | 25 | 26 | def make_shell_context(): 27 | """自动加载环境""" 28 | return dict( 29 | app=app 30 | ) 31 | 32 | 33 | manager.add_command("shell", Shell(make_context=make_shell_context)) 34 | 35 | 36 | if __name__ == '__main__': 37 | manager.run() 38 | 39 | -------------------------------------------------------------------------------- /Exercises/FrozenTest/requirement.txt: -------------------------------------------------------------------------------- 1 | 2 | Flask==0.10.1 3 | Flask-WTF==0.10.0 4 | 5 | -------------------------------------------------------------------------------- /Exercises/LearnCython/build/temp.macosx-10.11-x86_64-2.7/helloworld.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/LearnCython/build/temp.macosx-10.11-x86_64-2.7/helloworld.o -------------------------------------------------------------------------------- /Exercises/LearnCython/helloworld.pyx: -------------------------------------------------------------------------------- 1 | print "Hello World!" 2 | -------------------------------------------------------------------------------- /Exercises/LearnCython/helloworld.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/LearnCython/helloworld.so -------------------------------------------------------------------------------- /Exercises/LearnCython/setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | from Cython.Build import cythonize 3 | 4 | setup( 5 | ext_modules = cythonize("helloworld.pyx") 6 | ) 7 | -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/LearnDjango/mysite/db.sqlite3 -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/mysite/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/LearnDjango/mysite/mysite/__init__.py -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/mysite/urls.py: -------------------------------------------------------------------------------- 1 | """mysite URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import url 17 | from django.contrib import admin 18 | 19 | urlpatterns = [ 20 | url(r'^admin/', admin.site.urls), 21 | ] 22 | -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/mysite/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for mysite project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/polls/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/LearnDjango/mysite/polls/__init__.py -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/polls/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/polls/apps.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.apps import AppConfig 4 | 5 | 6 | class PollsConfig(AppConfig): 7 | name = 'polls' 8 | -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/polls/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/LearnDjango/mysite/polls/migrations/__init__.py -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/polls/models.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.db import models 4 | 5 | # Create your models here. 6 | -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/polls/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/polls/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from . import views 4 | 5 | urlpatterns = [ 6 | url(r'^$', views.index, name='index'), 7 | ] 8 | -------------------------------------------------------------------------------- /Exercises/LearnDjango/mysite/polls/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | 3 | # Create your views here. 4 | from django.http import HttpResponse 5 | 6 | 7 | def index(request): 8 | return HttpResponse("Hello, world. You're at the polls index.") 9 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | -1 3 | 4 | ENV 5 | migrations 6 | data-dev.sqlite 7 | data-test.sqlite 8 | data-dev.sqlite-journal 9 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/Flask-Web-Development/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/LearnFlask/Flask-Web-Development/__init__.py -------------------------------------------------------------------------------- /Exercises/LearnFlask/Flask-Web-Development/test_basics.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from flask import current_app 3 | from app import create_app, db 4 | 5 | 6 | class BasicsTestCase(unittest.TestCase): 7 | def setUp(self): 8 | self.app = create_app('testing') 9 | self.app_context = self.app.app_context() 10 | self.app_context.push() 11 | db.create_all() 12 | 13 | def tearDown(self): 14 | db.session.remove() 15 | db.drop_all() 16 | self.app_context.pop() 17 | 18 | def test_app_exists(self): 19 | self.assertFalse(current_app is None) 20 | 21 | def test_app_is_testing(self): 22 | self.assertTrue(current_app.config['TESTING']) 23 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/Flask-Web-Development/webtest/app_api.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | # 基于调度方法的视图 3 | 4 | from flask import Flask, jsonify 5 | from flask.views import MethodView 6 | 7 | app = Flask(__name__) 8 | 9 | class UserAPI(MethodView): 10 | 11 | def get(self): 12 | return jsonify({ 13 | 'username': 'fake', 14 | 'avatar': 'http://lorempixel.com/100/100/nature/' 15 | }) 16 | 17 | def post(self): 18 | return 'UNSUPPORTED!' 19 | 20 | app.add_url_rule('/user', view_func=UserAPI.as_view('userview')) 21 | 22 | if __name__ == '__main__': 23 | app.run(host='0.0.0.0', port=9000) 24 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/Flask-Web-Development/webtest/app_response.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, jsonify 2 | from werkzeug.wrappers import Response 3 | app = Flask(__name__) 4 | 5 | 6 | class JSONResponse(Response): 7 | @classmethod 8 | def force_type(cls, rv, environ=None): 9 | if isinstance(rv, dict): 10 | rv = jsonify(rv) 11 | return super(JSONResponse, cls).force_type(rv, environ) 12 | 13 | app.response_class = JSONResponse 14 | 15 | @app.route('/') 16 | def hello_world(): 17 | return {'message': 'Hello World!'} 18 | 19 | @app.route('/custom_headers') 20 | def headers(): 21 | return {'headers': [1, 2, 3]}, 201, [('X-Request-Id', '100')] 22 | 23 | if __name__ == '__main__': 24 | app.run(host='0.0.0.0', port=9000) 25 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/Flask-Web-Development/webtest/app_subdomain.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | from flask import Flask, g 4 | 5 | app = Flask(__name__) 6 | app.config['SERVER_NAME'] = 'example.com:9000' 7 | 8 | @app.url_value_preprocessor 9 | def get_site(endpoint, values): 10 | g.site = values.pop('subdomain') 11 | 12 | @app.route('/', subdomain='') 13 | def index(): 14 | return g.site 15 | 16 | if __name__ == '__main__': 17 | app.run(host='0.0.0.0', port=9000) 18 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/Flask-Web-Development/webtest/hello.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | from flask import Flask 4 | import settings 5 | 6 | app = Flask(__name__) 7 | # 静态文件 8 | # 1. url_for('static', filename='style.css') 9 | # 2. app = Flask(__name__, static_folder='/tmp') 10 | 11 | # 加载配置变量的方式 12 | # 1. 通过配置文件加载 13 | app.config.from_object('settings') 14 | # 2. 通过文件名字加载 15 | app.config.from_pyfile('settings.py', silent=True) 16 | # 3. 通过环境变量加载 17 | # > export YOURAPPLICATION_SETTINGS='settings.py' 18 | app.config.from_envvar('YOURAPPLICATION_SETTINGS') 19 | 20 | # 动态参数 21 | # string: 接受任何没有斜杠的文本(默认) 22 | # path: 与默认相似, 但也接受斜杠 23 | # uuid: 只接受uuid字符串 24 | # any: 可指定多种路径, 但是需要传入参数 25 | @app.route('/item//') 26 | def item(id): 27 | return 'Item: {}'.format(id) 28 | 29 | @app.route('//') 30 | def page(page_name): 31 | return 'Page_Name: {}'.format(page_name) 32 | 33 | # 调试模式 34 | # 1. 35 | app.debug = True 36 | app.run() 37 | # 2. 38 | # app.run(debug=True) 39 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/Flask-Web-Development/webtest/settings.py: -------------------------------------------------------------------------------- 1 | A = 1 2 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/mysql-python/.example1.py.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/LearnFlask/FlaskUploadFiles/mysql-python/.example1.py.swp -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/mysql-python/consts.py: -------------------------------------------------------------------------------- 1 | HOSTNAME = 'localhost' 2 | DATABASE = 'r' 3 | USERNAME = 'web' 4 | PASSWORD = 'web' 5 | DB_URI = 'mysql://{}:{}@{}/{}'.format(USERNAME, PASSWORD, HOSTNAME, DATABASE) 6 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/mysql-python/curd.py: -------------------------------------------------------------------------------- 1 | import MySQLdb 2 | from consts import HOSTNAME, DATABASE, USERNAME, PASSWORD 3 | 4 | con = MySQLdb.connect(HOSTNAME, USERNAME, PASSWORD, DATABASE) 5 | 6 | with con as cur: 7 | cur.execute('drop table if exists users') 8 | cur.execute('create table users(Id INT PRIMARY KEY AUTO_INCREMENT, ' 9 | 'Name VARCHAR(25))') 10 | cur.execute("insert into users(Name) values('kasheemlew')") 11 | cur.execute("insert into users(Name) values('admin')") 12 | cur.execute('select * from users') 13 | 14 | rows = cur.fetchall() 15 | for row in rows: 16 | print row 17 | cur.execute('update users set Name=%s where Id=%s', ('kasheem', 1)) 18 | print 'Number of rows updated:', cur.rowcount 19 | 20 | cur = con.cursor(MySQLdb.cursors.DictCursor) 21 | cur.execute('select * from users') 22 | 23 | rows = cur.fetchall() 24 | for row in rows: 25 | print row['Id'], row['Name'] 26 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/mysql-python/example1.py: -------------------------------------------------------------------------------- 1 | import MySQLdb 2 | from consts import HOSTNAME, DATABASE, USERNAME, PASSWORD 3 | 4 | try: 5 | con = MySQLdb.connect(HOSTNAME, USERNAME, PASSWORD, DATABASE) 6 | cur = con.cursor() 7 | cur.execute("SELECT VERSION()") 8 | ver = cur.fetchone() 9 | print "Database version : %s " % ver 10 | except MySQLdb.Error as e: 11 | print "Error %d: %s" % (e.args[0], e.args[1]) 12 | exit(1) 13 | finally: 14 | if con: 15 | con.close() 16 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/upload-review-demo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/LearnFlask/FlaskUploadFiles/upload-review-demo/__init__.py -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/upload-review-demo/config.py: -------------------------------------------------------------------------------- 1 | SQLALCHEMY_DATABASE_URI = 'mysql://web:web@localhost:3306/r' 2 | UPLOAD_FOLDER = '/tmp/permdir' 3 | SQLALCHEMY_TRACK_MODIFICATIONS = False 4 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/upload-review-demo/databases/schema.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `PasteFile` ( 2 | `id` int(11) NOT NULL AUTO_INCREMENT, 3 | `filename` varchar(5000) NOT NULL, 4 | `filehash` varchar(128) NOT NULL, 5 | `filemd5` varchar(128) NOT NULL, 6 | `uploadtime` datetime NOT NULL, 7 | `mimetype` varchar(256) NOT NULL, 8 | `size` int(11) unsigned NOT NULL, 9 | PRIMARY KEY (`id`), 10 | UNIQUE KEY `filehash` (`filehash`) 11 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 12 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/upload-review-demo/ext.py: -------------------------------------------------------------------------------- 1 | from flask_mako import MakoTemplates, render_template 2 | from flask_sqlalchemy import SQLAlchemy 3 | 4 | mako = MakoTemplates() 5 | db = SQLAlchemy() 6 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/upload-review-demo/mimes.py: -------------------------------------------------------------------------------- 1 | AUDIO_MIMES = [ 2 | 'audio/ogg', 3 | 'audio/mp3', 4 | ] 5 | 6 | IMAGE_MIMES = [ 7 | 'image/jpeg', 8 | 'image/png', 9 | ] 10 | 11 | VIDEO_MIMES = [ 12 | 'video/mp4', 13 | 'video/ogg', 14 | ] 15 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/upload-review-demo/requirements.txt: -------------------------------------------------------------------------------- 1 | flask-sqlalchemy 2 | flask-mako 3 | python-magic 4 | Pillow 5 | cropresize2 6 | short_url 7 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/upload-review-demo/templates/r/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Hello 5 | 6 | 7 |

Hello World

8 | 9 | 10 | -------------------------------------------------------------------------------- /Exercises/LearnFlask/FlaskUploadFiles/upload-review-demo/utils.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | 4 | import os 5 | import hashlib 6 | from functools import partial 7 | 8 | from config import UPLOAD_FOLDER 9 | 10 | HERE = os.path.abspath(os.path.dirname(__file__)) 11 | 12 | 13 | def get_file_md5(f, chunk_size=8192): 14 | h = hashlib.md5() 15 | while True: 16 | chunk = f.read(chunk_size) 17 | if not chunk: 18 | break 19 | h.update(chunk) 20 | return h.hexdigest() 21 | 22 | 23 | def humanize_bytes(bytesize, precision=2): 24 | abbrevs = ( 25 | (1 << 50, 'PB'), 26 | (1 << 40, 'TB'), 27 | (1 << 30, 'GB'), 28 | (1 << 20, 'MB'), 29 | (1 << 10, 'kB'), 30 | (1, 'bytes') 31 | ) 32 | if bytesize == 1: 33 | return '1 byte' 34 | for factor, suffix in abbrevs: 35 | if bytesize >= factor: 36 | break 37 | return '%.*f %s' % (precision, bytesize / factor, suffix) 38 | 39 | 40 | get_file_path = partial(os.path.join, HERE, UPLOAD_FOLDER) 41 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/event.py: -------------------------------------------------------------------------------- 1 | import gevent 2 | from gevent.event import Event 3 | 4 | ''' 5 | Illustrates the use of events 6 | ''' 7 | 8 | evt = Event() 9 | 10 | def setter(): 11 | '''After 3 seconds, wake all threads waiting on the value of evt''' 12 | print('A: Hey wait for me, I have to do something') 13 | gevent.sleep(3) 14 | print("Ok, I'm done") 15 | evt.set() 16 | 17 | def waiter(): 18 | '''After 3 seconds the get call will unblock''' 19 | print("I'll wait for you") 20 | evt.wait() # blocking 21 | print("It's about time") 22 | 23 | def main(): 24 | gevent.joinall([ 25 | gevent.spawn(setter), 26 | gevent.spawn(waiter), 27 | gevent.spawn(waiter), 28 | gevent.spawn(waiter), 29 | gevent.spawn(waiter), 30 | gevent.spawn(waiter) 31 | ]) 32 | 33 | if __name__ == '__main__': main() 34 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/event2.py: -------------------------------------------------------------------------------- 1 | import gevent 2 | from gevent.event import AsyncResult 3 | a = AsyncResult() 4 | 5 | def setter(): 6 | """ 7 | After 3 seconds set the result of a. 8 | """ 9 | gevent.sleep(3) 10 | a.set('Hello!') 11 | 12 | def waiter(): 13 | """ 14 | After 3 seconds the get call will unblock after the setter 15 | puts a value into the AsyncResult. 16 | """ 17 | print(a.get()) 18 | 19 | gevent.joinall([ 20 | gevent.spawn(setter), 21 | gevent.spawn(waiter), 22 | ]) 23 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/group.py: -------------------------------------------------------------------------------- 1 | import gevent 2 | from gevent.pool import Group 3 | 4 | def talk(msg): 5 | for i in xrange(3): 6 | print(msg) 7 | 8 | g1 = gevent.spawn(talk, 'bar') 9 | g2 = gevent.spawn(talk, 'foo') 10 | g3 = gevent.spawn(talk, 'fizz') 11 | 12 | group = Group() 13 | group.add(g1) 14 | group.add(g2) 15 | group.join() 16 | 17 | group.add(g3) 18 | group.join() 19 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/group2.py: -------------------------------------------------------------------------------- 1 | import gevent 2 | from gevent import getcurrent 3 | from gevent.pool import Group 4 | 5 | group = Group() 6 | 7 | def hello_from(n): 8 | print('Size of group %s' % len(group)) 9 | print('Hello from Greenlet %s' % id(getcurrent())) 10 | 11 | group.map(hello_from, xrange(3)) 12 | 13 | def intensive(n): 14 | gevent.sleep(3 - n) 15 | return 'task', n 16 | 17 | print('Ordered') 18 | 19 | ogroup = Group() 20 | for i in ogroup.imap(intensive, xrange(3)): 21 | print(i) 22 | 23 | print('Unordered') 24 | 25 | igroup = Group() 26 | for i in igroup.imap_unordered(intensive, xrange(3)): 27 | print(i) 28 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/monkey.py: -------------------------------------------------------------------------------- 1 | import socket 2 | print(socket.socket) 3 | 4 | print("After monkey patch") 5 | from gevent import monkey 6 | monkey.patch_socket() 7 | print(socket.socket) 8 | 9 | import select 10 | print(select.select) 11 | monkey.patch_select() 12 | print("After monkey patch") 13 | print(select.select) 14 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/queue.py: -------------------------------------------------------------------------------- 1 | import gevent 2 | from gevent.queue import Queue 3 | 4 | tasks = Queue() 5 | 6 | def worker(n): 7 | while not tasks.empty(): 8 | task = tasks.get() 9 | print('Worker %s got task %s' % (n, task)) 10 | gevent.sleep(0) 11 | 12 | print('Quitting time!') 13 | 14 | def boss(): 15 | for i in xrange(1,25): 16 | tasks.put_nowait(i) 17 | 18 | gevent.spawn(boss).join() 19 | 20 | gevent.joinall([ 21 | gevent.spawn(worker, 'steve'), 22 | gevent.spawn(worker, 'john'), 23 | gevent.spawn(worker, 'nancy'), 24 | ]) 25 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/queue2.py: -------------------------------------------------------------------------------- 1 | import gevent 2 | from gevent.queue import Queue, Empty 3 | 4 | tasks = Queue(maxsize=3) 5 | 6 | def worker(n): 7 | try: 8 | while True: 9 | task = tasks.get(timeout=1) # decrements queue size by 1 10 | print('Worker %s got task %s' % (n, task)) 11 | gevent.sleep(0) 12 | except Empty: 13 | print('Quitting time!') 14 | 15 | def boss(): 16 | """ 17 | Boss will wait to hand out work until a individual worker is 18 | free since the maxsize of the task queue is 3. 19 | """ 20 | 21 | for i in xrange(1,10): 22 | tasks.put(i) 23 | print('Assigned all work in iteration 1') 24 | 25 | for i in xrange(10,20): 26 | tasks.put(i) 27 | print('Assigned all work in iteration 2') 28 | 29 | gevent.joinall([ 30 | gevent.spawn(boss), 31 | gevent.spawn(worker, 'steve'), 32 | gevent.spawn(worker, 'john'), 33 | gevent.spawn(worker, 'bob'), 34 | ]) 35 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import gevent 3 | import time 4 | 5 | def foo(): 6 | print 'Running in foo' 7 | gevent.sleep(5) 8 | print 'Explicit context switch to foo again' 9 | 10 | def bar(): 11 | print 'Explicit context to bar' 12 | gevent.sleep(5) 13 | print 'Implicit context switch back to bar' 14 | 15 | gevent.joinall([ 16 | gevent.spawn(foo), 17 | gevent.spawn(bar), 18 | ]) 19 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/test2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import time 3 | import gevent 4 | from gevent import select 5 | 6 | start = time.time() 7 | tic = lambda: 'at %1.1f seconds' % (time.time()-start) 8 | 9 | def gr1(): 10 | # Busy waits for a second, but we don't want to stick around... 11 | print 'Started Polling: %s' % tic() 12 | gr1start = time.time() 13 | select.select([], [], [], 4) 14 | print 'start: %s 1 Ended Polling: %s' % (gr1start, tic()) 15 | 16 | def gr2(): 17 | # Busy waits for a second, but we don't want to stick around... 18 | print 'Started Polling: %s' % tic() 19 | gr2start = time.time() 20 | select.select([], [], [], 3) 21 | print 'start: %s 2 Ended Polling: %s' % (gr2start, tic()) 22 | 23 | def gr3(): 24 | print 'Hey lets do some stuff while the greenlets poll, %s' % tic() 25 | gevent.sleep(1) 26 | 27 | gevent.joinall([ 28 | gevent.spawn(gr1), 29 | gevent.spawn(gr2), 30 | gevent.spawn(gr3), 31 | ]) 32 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/test3.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import gevent 3 | import random 4 | 5 | def task(pid): 6 | """ 7 | Some non-deterministic task 8 | """ 9 | gevent.sleep(1) 10 | print 'Task %s done' % pid 11 | 12 | def synchronous(): 13 | for i in range(1,10): 14 | task(i) 15 | 16 | def asynchronous(): 17 | threads = [gevent.spawn(task, i) for i in xrange(10)] 18 | gevent.joinall(threads) 19 | 20 | print 'Synchronous:' 21 | synchronous() 22 | 23 | print 'Asynchronous:' 24 | asynchronous() 25 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/test4.py: -------------------------------------------------------------------------------- 1 | import gevent.monkey 2 | gevent.monkey.patch_socket() 3 | 4 | import gevent 5 | import urllib2 6 | import simplejson as json 7 | 8 | def fetch(pid): 9 | response = urllib2.urlopen('http://json-time.appspot.com/time.json') 10 | result = response.read() 11 | json_result = json.loads(result) 12 | datetime = json_result['datetime'] 13 | print 'Process %s: %s' % (pid, datetime) 14 | return json_result['datetime'] 15 | 16 | def synchronous(): 17 | for i in range(1, 10): 18 | fetch(i) 19 | 20 | 21 | def asynchronous(): 22 | threads = [] 23 | for i in range(1, 10): 24 | threads.append(gevent.spawn(fetch, i)) 25 | gevent.joinall(threads) 26 | 27 | print 'Sychronous:' 28 | synchronous() 29 | 30 | print 'Asychronous:' 31 | asynchronous() 32 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/test5.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def echo(i): 4 | time.sleep(0.001) 5 | return i 6 | 7 | # Non Deterministic Process Pool 8 | 9 | from multiprocessing.pool import Pool 10 | 11 | p = Pool(10) 12 | run1 = [a for a in p.imap_unordered(echo, xrange(10))] 13 | run2 = [a for a in p.imap_unordered(echo, xrange(10))] 14 | run3 = [a for a in p.imap_unordered(echo, xrange(10))] 15 | run4 = [a for a in p.imap_unordered(echo, xrange(10))] 16 | 17 | print run1 == run2 == run3 == run4 18 | 19 | # Deterministic Gevent Pool 20 | 21 | from gevent.pool import Pool 22 | 23 | p = Pool(10) 24 | run1 = [a for a in p.imap_unordered(echo, xrange(10))] 25 | run2 = [a for a in p.imap_unordered(echo, xrange(10))] 26 | run3 = [a for a in p.imap_unordered(echo, xrange(10))] 27 | run4 = [a for a in p.imap_unordered(echo, xrange(10))] 28 | 29 | print run1 == run2 == run3 == run4 30 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/test6.py: -------------------------------------------------------------------------------- 1 | import gevent 2 | from gevent import Greenlet 3 | 4 | def foo(message, n): 5 | gevent.sleep(n) 6 | print message 7 | 8 | thread1 = Greenlet.spawn(foo, 'Hello', 1) 9 | 10 | thread2 = gevent.spawn(foo, 'I live!', 2) 11 | 12 | thread3 = gevent.spawn(lambda x: (x+1), 2) 13 | 14 | threads = [thread1, thread2, thread3] 15 | 16 | gevent.joinall(threads) 17 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/test7.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import gevent 3 | from gevent import Greenlet 4 | 5 | 6 | class MyGreenlet(Greenlet): 7 | def __init__(self, message, n): 8 | Greenlet.__init__(self) 9 | self.message = message 10 | self.n = n 11 | 12 | def _run(self): 13 | print self.message 14 | gevent.sleep(self.n) 15 | 16 | 17 | g = MyGreenlet('Hi there!', 3) 18 | g.start() 19 | g.join() 20 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/test8.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import gevent 3 | 4 | def win(): 5 | return 'You win!' 6 | 7 | def fail(): 8 | raise Exception('You fail at failing.') 9 | 10 | winner = gevent.spawn(win) 11 | loser = gevent.spawn(fail) 12 | 13 | print winner.started 14 | print loser.started 15 | 16 | try: 17 | gevent.joinall([winner, loser]) 18 | except Exception as e: 19 | print 'This will never be reached' 20 | 21 | print winner.value 22 | print loser.value 23 | 24 | print winner.ready() 25 | print loser.ready() 26 | 27 | print winner.successful() 28 | print loser.successful() 29 | 30 | print loser.exception 31 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/test9.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import gevent 3 | import signal 4 | 5 | def run_forever(): 6 | gevent.sleep(1000) 7 | 8 | if __name__ == '__main__': 9 | gevent.signal(signal.SIGQUIT, gevent.shutdown) 10 | thread = gevent.spawn(run_forever) 11 | thread.join() 12 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/threadtimeout.py: -------------------------------------------------------------------------------- 1 | import gevent 2 | from gevent import Timeout 3 | 4 | def wait(): 5 | gevent.sleep(2) 6 | 7 | timer = Timeout(1).start() 8 | thread1 = gevent.spawn(wait) 9 | 10 | try: 11 | thread1.join(timeout=timer) 12 | except Timeout: 13 | print 'Thread 1 timed out' 14 | 15 | timer = Timeout.start_new(1) 16 | thread2 = gevent.spawn(wait) 17 | 18 | try: 19 | thread2.get(timeout=timer) 20 | except Timeout: 21 | print 'Thread 2 timed out' 22 | 23 | try: 24 | gevent.with_timeout(1, wait) 25 | except: 26 | print 'Thread 3 timed out' 27 | -------------------------------------------------------------------------------- /Exercises/LearnGevent/timeout.py: -------------------------------------------------------------------------------- 1 | import gevent 2 | from gevent import Timeout 3 | 4 | seconds = 10 5 | 6 | timeout = Timeout(seconds) 7 | timeout.start() 8 | 9 | def wait(): 10 | gevent.sleep(10) 11 | 12 | try: 13 | gevent.spawn(wait).join() 14 | except Timeout: 15 | print 'Could not complete' 16 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/Burt/static/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Helvetica, Arial, sans-serif; 3 | width: 600px; 4 | margin: 0 auto; 5 | } 6 | .replaced:hover { color: #00f; } 7 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/Burt/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "main.html" %} 2 | 3 | {% block header %} 4 |

{{ header_text }}

5 | {% end %} 6 | 7 | {% block body %} 8 |
9 |

Welcome to Burt's Books!

10 |

...

11 |
12 | {% end %} 13 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/Burt/templates/main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | {{ page_title }} 4 | 5 | 6 | 7 |
8 |
9 | {% block header %}

Burt's Books

{% end %} 10 |
11 |
12 |
13 | {% block body %}{% end %} 14 |
15 |
16 |
17 | {% block footer %} 18 |

19 | For more information about our selection, hours or events, please email 20 | us at contact@burtsbooks.com. 21 |

22 | {% end %} 23 |
24 |
25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/Burt/templates/modules/book.html: -------------------------------------------------------------------------------- 1 |
2 |

{{ book["title"] }}

3 | {% if book["subtitle"] != "" %} 4 |

{{ book["subtitle"] }}

5 | {% end %} 6 | 7 |
8 |
Released: {{ book["date_released"] }}
9 |
10 | Added: {{ locale.format_date(book["date_added"], relative=False) }} 11 |
12 |
Description:
13 |
{% raw book["description"] %}
14 |
15 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/Burt/templates/recommended.html: -------------------------------------------------------------------------------- 1 | {% extends "main.html" %} 2 | 3 | 4 | {% block body %} 5 |

Recommended Reading

6 | {% for book in books %} 7 | {% module Book(book) %} 8 | {% end %} 9 | {% end %} 10 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/C2/static/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Helvetica,Arial,sans-serif; 3 | width: 600px; 4 | margin: 0 auto; 5 | } 6 | .replaced:hover { color: #00f; } 7 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/C2/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | The Alpha Munger 6 | 7 | 8 |

The Alpha Munger

9 |

Enter two texts below. The replacement text will have its words 10 | replaced by words beginning with the same letter in the source text.

11 |
12 |

Source text
13 |

14 |

Text for replacement
15 |

16 | 17 |
18 | 19 | 20 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/C2/templates/munged.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | The Alpha Munger 6 | 7 | 8 |

Your text

9 |

10 | {% for line in change_lines %} 11 | {% for word in line.split(' ') %} 12 | {% if len(word) > 0 and word[0] in source_map %} 13 | {{ choice(source_map[word[0]]) }} 14 | {% else %} 15 | {{word}} 16 | {% end %} 17 | {% end %} 18 |
19 | {% end %} 20 |

21 | 22 | 23 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/C3/main.py: -------------------------------------------------------------------------------- 1 | import tornado.httpserver 2 | import tornado.ioloop 3 | import tornado.options 4 | import tornado.web 5 | 6 | 7 | from tornado.options import options, define 8 | define("port", default=8000, help="run on the given port", type=int) 9 | 10 | 11 | class MainHandler(tornado.web.RequestHandler): 12 | def get(self): 13 | self.render( 14 | "index.html", 15 | header_text = "Here goes the header", 16 | footer_text = "Here goes the footer" 17 | ) 18 | 19 | 20 | if __name__ == "__main__": 21 | tornado.options.parse_command_line() 22 | app = tornado.web.Application( 23 | headlers=[('/', MainHandler)] 24 | ) 25 | http_server = tornado.httpserver.HTTPServer(app) 26 | http_server.listen(options.port) 27 | tornado.ioloop.IOLoop.instance().start() 28 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/C3/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "main.html" %} 2 | 3 | {% block header %} 4 |

{{ header_text }}

5 | {% end %} 6 | 7 | {% block body %} 8 |

Hello from the child template!

9 | {% end %} 10 | 11 | {% block footer %} 12 |

{{ footer_text }}

13 | {% end %} 14 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/C3/templates/main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | {% block header %}{% end %} 5 |
6 | 7 | {% block body %}{% end %} 8 | 9 |
10 | {% block footer %}{% end %} 11 |
12 | 13 | 14 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/burtbook/static/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Helvetica, Arial, sans-serif; 3 | width: 600px; 4 | margin: 0 auto; 5 | } 6 | .replaced:hover { color: #00f; } 7 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/burtbook/templates/book_edit.html: -------------------------------------------------------------------------------- 1 | {% extends "main.html" %} 2 | {% autoescape None %} 3 | 4 | {% block body %} 5 |
6 | 7 | ISBN
8 | Title
9 | Subtitle
10 | Image
11 | Author
12 | Date released
13 | Description
14 |
15 | 16 |
17 | {% end %} 18 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/burtbook/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "main.html" %} 2 | 3 | {% block header %} 4 |

{{ header_text }}

5 | {% end %} 6 | 7 | {% block body %} 8 |
9 |

Welcome to Burt's Books!

10 |

...

11 |
12 | {% end %} 13 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/burtbook/templates/main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | {{ page_title }} 4 | 5 | 6 | 7 |
8 |
9 | {% block header %}

Burt's Books

{% end %} 10 |
11 |
12 |
13 | {% block body %}{% end %} 14 |
15 |
16 |
17 | {% block footer %} 18 |

19 | For more information about our selection, hours or events, please email 20 | us at contact@burtsbooks.com. 21 |

22 | {% end %} 23 |
24 |
25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/burtbook/templates/modules/book.html: -------------------------------------------------------------------------------- 1 |
2 |

{{ book["title"] }}

3 | {% if book["subtitle"] != "" %} 4 |

{{ book["subtitle"] }}

5 | {% end %} 6 | 7 |
8 |
Released: {{ book["date_released"] }}
9 |
10 | Added: {{ locale.format_date(book["date_added"], relative=False) }} 11 |
12 |
Description:
13 |
{% raw book["description"] %}
14 |
15 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/burtbook/templates/recommended.html: -------------------------------------------------------------------------------- 1 | {% extends "main.html" %} 2 | 3 | 4 | {% block body %} 5 |

Recommended Reading

6 | {% for book in books %} 7 | {% module Book(book) %} 8 | {% end %} 9 | {% end %} 10 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/cookie/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Welcome Back! 4 | 5 | 6 |

Welcome back, {{ user }}

7 | 8 | 9 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/cookie/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Please Log In 4 | 5 | 6 | 7 |
8 | {% raw xsrf_form_html() %} 9 | Username: 10 | 11 |
12 | 13 | 14 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/hello-errors.py: -------------------------------------------------------------------------------- 1 | import tornado.httpserver 2 | import tornado.ioloop 3 | import tornado.options 4 | import tornado.web 5 | 6 | 7 | from tornado.options import define, options 8 | define("port", default=8000, help="run on the given port", type=int) 9 | 10 | 11 | class IndexHandler(tornado.web.RequestHandler): 12 | def get(self): 13 | greeting = self.get_argument('greeting', 'Hello') 14 | self.write(greeting + ', friendly user!') 15 | def write_error(self, status_code, **kwargs): 16 | self.write("Gosh darnit, user! You caused a %d error." % status_code) 17 | 18 | if __name__ == "__main__": 19 | tornado.options.parse_command_line() 20 | app = tornado.web.Application(handlers=[(r"/", IndexHandler)]) 21 | http_server = tornado.httpserver.HTTPServer(app) 22 | http_server.listen(options.port) 23 | tornado.ioloop.IOLoop.instance().start() 24 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/hello.py: -------------------------------------------------------------------------------- 1 | import tornado.httpserver 2 | import tornado.ioloop 3 | import tornado.options 4 | import tornado.web 5 | 6 | 7 | from tornado.options import define, options 8 | define("port", default=8000, help="run on the given port", type=int) 9 | 10 | class IndexHandler(tornado.web.RequestHandler): 11 | def get(self): 12 | greeting = self.get_argument('greeting', 'Hello') 13 | self.write(greeting + ', friendly user!') 14 | 15 | if __name__ == "__main__": 16 | tornado.options.parse_command_line() 17 | app = tornado.web.Application(handlers=[(r"/", IndexHandler)]) 18 | http_server = tornado.httpserver.HTTPServer(app) 19 | http_server.listen(options.port) 20 | tornado.ioloop.IOLoop.instance().start() 21 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/hello_module.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import tornado.web 3 | import tornado.ioloop 4 | import tornado.options 5 | import tornado.httpserver 6 | import os.path 7 | 8 | 9 | from tornado.options import options, define 10 | define("port", default=8000, help="run on the given port", type=int) 11 | 12 | 13 | class HelloHandler(tornado.web.RequestHandler): 14 | def get(self): 15 | self.render('hello.html') 16 | 17 | 18 | class HelloModule(tornado.web.UIModule): 19 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/module/templates/hello.html: -------------------------------------------------------------------------------- 1 | 2 | UI Module Example 3 | 4 | {% module Hello() %} 5 | 6 | 7 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/sslnginx.conf: -------------------------------------------------------------------------------- 1 | server { 2 | listen 443; 3 | ssl on; 4 | ssl_certificate /path/to/cert.pem; 5 | ssl_certificate_key /path/to/cert.key; 6 | 7 | default_type application/octet-stream; 8 | 9 | location /static/ { 10 | root /var/www/static; 11 | if ($query_string) { 12 | expires max; 13 | } 14 | } 15 | 16 | location = /favicon.ico { 17 | rewrite (.*) /static/favicon.ico; 18 | } 19 | 20 | location / { 21 | proxy_pass_header Server; 22 | proxy_set_header Host $http_host; 23 | proxy_redirect off; 24 | proxy_set_header X-Real-IP $remote_addr; 25 | proxy_set_header X-Scheme $scheme; 26 | proxy_pass http://tornados; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Poem Maker Pro 4 | 5 |

Enter terms below.

6 |
7 |

Plural noun

8 |

Singular noun

9 |

Verb (past tense)

10 |

Noun

11 | 12 |
13 | 14 | 15 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/templates/poem.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Poem Maker Pro 4 | 5 |

Your poem

6 |

Two {{ roads }} diverged in a {{ wood }}, and I-
7 | I took the one less travelled by,
8 | And that has {{ made }} all the {{ difference }}.

9 | 10 | 11 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding:utf-8 -*- 3 | 4 | import os 5 | from tornado.httpserver import HTTPServer 6 | from tornado.web import Application, RequestHandler 7 | from tornado.ioloop import IOLoop 8 | 9 | 10 | 11 | class TestHandler(RequestHandler): 12 | def get(self): 13 | import pdb 14 | pdb.set_trace() 15 | self.write("Hello, World!\n") 16 | 17 | 18 | #class TestHandler(RequestHandler): 19 | # def get(self): 20 | # self.write("Hello, World!\n") 21 | 22 | settings = { 23 | "static_path" : os.path.join(os.path.dirname(__file__), "static"), 24 | } 25 | 26 | application = Application([ 27 | (r"/", TestHandler), 28 | ], **settings) 29 | 30 | if __name__ == "__main__": 31 | server = HTTPServer(application) 32 | server.listen(8000) 33 | IOLoop.instance().start() 34 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/tornado.conf: -------------------------------------------------------------------------------- 1 | # 声明一个叫做tornadoes的组以便管理 2 | [group:tornadoes] 3 | programs=tornado-8000,tornado-8001,tornado-8002,tornado-8003 4 | 5 | [program:tornado-8000] 6 | # 希望监听的port参数的tornado应用 7 | command=python /var/www/main.py --port=8000 8 | directory=/var/www 9 | user=www-data 10 | autorestart=true 11 | redirect_stderr=true 12 | stout_logfile=/var/log/tornado.log 13 | loglevel=info 14 | 15 | [program:tornado-8001] 16 | command=python /var/www/main.py --port=8001 17 | directory=/var/www 18 | user=www-data 19 | autorestart=true 20 | redirect_stderr=true 21 | stout_logfile=/var/log/tornado.log 22 | loglevel=info 23 | 24 | [program:tornado-8002] 25 | command=python /var/www/main.py --port=8002 26 | directory=/var/www 27 | user=www-data 28 | autorestart=true 29 | redirect_stderr=true 30 | stout_logfile=/var/log/tornado.log 31 | loglevel=info 32 | 33 | [program:tornado-8003] 34 | command=python /var/www/main.py --port=8003 35 | directory=/var/www 36 | user=www-data 37 | autorestart=true 38 | redirect_stderr=true 39 | stout_logfile=/var/log/tornado.log 40 | loglevel=info 41 | -------------------------------------------------------------------------------- /Exercises/LearnTornado/twitter/templates/logout.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Tornadoes on Twitter 4 | 5 | 6 | 7 |
8 |

You have successfully signed out.

9 | Sign in 10 |
11 | 12 | 13 | -------------------------------------------------------------------------------- /Exercises/MapReduce/parallel.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import os 4 | import time 5 | import multiprocessing # Process based "threading" interface 6 | 7 | 8 | def task(args): 9 | time.sleep(1) 10 | pid = os.getpid() # Return current process 11 | return pid, args 12 | 13 | start = time.time() 14 | # Returns a process pool object, processes is the number of worker processes 15 | # to use. 16 | pool = multiprocessing.Pool(processes=4) 17 | result = pool.map(task, range(10)) 18 | print result 19 | print "Cost: {}".format(time.time() - start) 20 | -------------------------------------------------------------------------------- /Exercises/Marsh/deserialize.py: -------------------------------------------------------------------------------- 1 | from marshmallow import Schema, fields, post_load 2 | from test import User 3 | 4 | class UserSchema(Schema): 5 | name = fields.Str() 6 | email = fields.Email() 7 | created_at = fields.DateTime() 8 | 9 | @post_load 10 | def make_user(self, data): 11 | return User(**data) 12 | 13 | 14 | if __name__ == '__main__': 15 | user_data = { 16 | 'name': 'Kasheem', 17 | 'email': 'kasheem@python.com' 18 | } 19 | shcema = UserSchema() 20 | result = shcema.load(user_data) 21 | print result.data 22 | -------------------------------------------------------------------------------- /Exercises/Marsh/load.py: -------------------------------------------------------------------------------- 1 | from marshmallow import pprint 2 | from test import UserSchema 3 | 4 | user_data = { 5 | 'created_at': '2016-07-07T05:26:03.869245', 6 | 'email': u'kasheem@python.com', 7 | 'name': u'Kasheem' 8 | } 9 | 10 | schema = UserSchema() 11 | result = schema.load(user_data) 12 | pprint(result.data) 13 | -------------------------------------------------------------------------------- /Exercises/Marsh/validator.py: -------------------------------------------------------------------------------- 1 | from marshmallow import fields, Schema, validates, ValidationError 2 | 3 | class ItemSchema(Schema): 4 | quantity = fields.Integer() 5 | 6 | @validates('quantity') 7 | def validate_quantity(self, value): 8 | if value < 0: 9 | raise ValidationError('Quantity must be greater than 0.') 10 | if value > 30: 11 | raise ValidationError('Quantity must not be greater than 30.') 12 | -------------------------------------------------------------------------------- /Exercises/MessageQueue/amqp_producer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import sys 4 | import pika 5 | 6 | parameters = pika.URLParameters('amqp://guest:guest@localhost:5672/%2F') 7 | connection = pika.BlockingConnection(parameters) 8 | channel = connection.channel() 9 | channel.exchange_declare( 10 | exchange='web_develop', 11 | exchange_type='direct', 12 | passive=False, 13 | durable=True, 14 | auto_delete=False 15 | ) 16 | 17 | if len(sys.argv) != 1: 18 | msg = sys.argv[1] 19 | else: 20 | msg = 'hah' 21 | 22 | props = pika.BasicProperties(content_type='text/plain', delivery_mode=2) 23 | 24 | channel.basic_publish('web_develop', 'xxx_routing_key', msg, properties=props) 25 | 26 | connection.close() 27 | -------------------------------------------------------------------------------- /Exercises/MultiThread/_1.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | #!/usr/bin/env python 3 | 4 | import threading 5 | 6 | 7 | def worker(num): 8 | print('Worker: %s' % num) 9 | return 10 | 11 | 12 | threads = [] 13 | for i in range(5): 14 | t = threading.Thread(target=worker, args=(i,)) 15 | threads.append(t) 16 | t.start() 17 | -------------------------------------------------------------------------------- /Exercises/MultiThread/_2.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | #!/usr/bin/env python 3 | 4 | 5 | import threading 6 | import time 7 | 8 | 9 | def worker(): 10 | print threading.currentThread().getName(), 'Starting' 11 | time.sleep(2) 12 | print threading.currentThread().getName(), 'Exiting' 13 | 14 | 15 | def my_service(): 16 | print threading.currentThread().getName(), 'Starting' 17 | time.sleep(3) 18 | print threading.currentThread().getName(), 'Exiting' 19 | 20 | 21 | t = threading.Thread(name='my_service', target=my_service) 22 | w = threading.Thread(name='worker', target=worker) 23 | w2 = threading.Thread(target=worker) # Default name: Thread-1, Thread-2 ... 24 | 25 | w.start() 26 | w2.start() 27 | t.start() 28 | -------------------------------------------------------------------------------- /Exercises/MultiThread/_3.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | #!/usr/bin/env python 3 | 4 | 5 | import logging 6 | import threading 7 | import time 8 | 9 | 10 | logging.basicConfig(level=logging.DEBUG, 11 | format='[%(levelname)s] (%(threadName)-10s) %(message)s', 12 | ) 13 | 14 | 15 | def worker(): 16 | logging.debug('Starting') 17 | time.sleep(2) 18 | logging.debug('Exiting') 19 | 20 | 21 | def my_service(): 22 | logging.debug('Starting') 23 | time.sleep(3) 24 | logging.debug('Exiting') 25 | 26 | 27 | t = threading.Thread(name='my_service', target=my_service) 28 | w = threading.Thread(name='worker', target=worker) 29 | w2 = threading.Thread(target=worker) 30 | 31 | w.start() 32 | w2.start() 33 | t.start() 34 | -------------------------------------------------------------------------------- /Exercises/MultiThread/_4.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | #!/usr/bin/env python 3 | 4 | 5 | import threading 6 | import time 7 | import logging 8 | 9 | 10 | logging.basicConfig(level=logging.DEBUG, 11 | format='(%(threadName)-10s) %(message)s' 12 | ) 13 | 14 | 15 | def daemon(): 16 | logging.debug('Starting') 17 | time.sleep(2) 18 | logging.debug('Exiting') 19 | 20 | 21 | d = threading.Thread(name='daemon', target=daemon) 22 | d.setDaemon(True) # 设置daemon模式,主程序结束,这个子线程依然在 23 | 24 | 25 | def non_daemon(): 26 | logging.debug('Starting') 27 | logging.debug('Exiting') 28 | 29 | 30 | t = threading.Thread(name='non-daemon', target=non_daemon) 31 | 32 | 33 | d.start() 34 | t.start() 35 | -------------------------------------------------------------------------------- /Exercises/MultiThread/_5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*- coding: utf-8 -*- 3 | 4 | import random 5 | import threading 6 | import time 7 | import logging 8 | 9 | 10 | logging.basicConfig(level=logging.DEBUG, 11 | format='(%(threadName)-10s) %(message)s', 12 | ) 13 | 14 | 15 | def worker(): 16 | t = threading.currentThread() 17 | pause = random.randint(1,5) 18 | logging.debug('sleeping %s', pause) 19 | time.sleep(pause) 20 | logging.debug('ending') 21 | return 22 | 23 | 24 | for i in range(3): 25 | t = threading.Thread(target=worker) 26 | t.setDaemon(True) 27 | t.start() 28 | 29 | 30 | main_thread = threading.currentThread() # Get current thread 31 | for t in threading.enumerate(): # enumerate() returns the list of current threads 32 | if t is main_thread: 33 | continue 34 | logging.debug('joining %s', t.getName()) 35 | print(threading.enumerate()) 36 | t.join() 37 | -------------------------------------------------------------------------------- /Exercises/MultiThread/_6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*- coding: utf-8 -*- 3 | 4 | import threading 5 | import logging 6 | 7 | 8 | logging.basicConfig(level=logging.DEBUG, 9 | format='(%(threadName)-10s) %(message)s', 10 | ) 11 | 12 | 13 | class MyThreadWithArgs(threading.Thread): # 继承threading.Thread,实例化,重写run(),调用start()启动 14 | def __init__(self, group=None, target=None, name=None, 15 | args=(), kwargs=None, verbose=None): 16 | threading.Thread.__init__(self, group=group, target=target, name=name, 17 | verbose=verbose) 18 | self.args = args 19 | self.kwargs = kwargs 20 | return 21 | 22 | def run(self): 23 | logging.debug('running with %s and %s', self.args, self.kwargs) 24 | return 25 | 26 | 27 | for i in range(5): 28 | t = MyThreadWithArgs(args=(i,), kwargs={'a': 'A', 'b': 'B'}) 29 | t.start() 30 | -------------------------------------------------------------------------------- /Exercises/MultiThread/_7.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | #!/usr/bin/env python 3 | 4 | import logging 5 | import threading 6 | import time 7 | 8 | 9 | logging.basicConfig(level=logging.DEBUG, 10 | format='(%(threadName)-10s) %(message)s', 11 | ) 12 | 13 | 14 | def delayed(): 15 | logging.debug('worker running') 16 | return 17 | 18 | 19 | t1 = threading.Timer(3, delayed) # Timer主要用计时器来延时 20 | t1.setName('t1') 21 | t2 = threading.Timer(3, delayed) 22 | t2.setName('t2') 23 | 24 | 25 | logging.debug('starting timers') 26 | t1.start() 27 | t2.start() 28 | 29 | 30 | logging.debug('waiting before canceling %s', t2.getName()) 31 | time.sleep(2) 32 | logging.debug('canceling %s', t2.getName()) 33 | t2.cancel() # 取消线程 34 | logging.debug('done') 35 | -------------------------------------------------------------------------------- /Exercises/MultiThread/global.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import threading 4 | global_num = 0 5 | l = threading.Lock() 6 | 7 | 8 | def thread_cal(): 9 | global global_num 10 | for i in xrange(1000): 11 | l.acquire() 12 | global_num += 1 13 | l.release() 14 | 15 | 16 | threads = [] 17 | for i in xrange(10): 18 | threads.append(threading.Thread(target=thread_cal)) 19 | threads[i].start() 20 | 21 | for i in xrange(10): 22 | threads[i].join() 23 | 24 | 25 | print global_num 26 | -------------------------------------------------------------------------------- /Exercises/MultiThread/globaldict.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import threading 4 | global_data = {} 5 | threads = [] 6 | 7 | 8 | def show(): 9 | cur_thread = threading.current_thread() 10 | print cur_thread.getName(), global_data[cur_thread] 11 | 12 | 13 | def thread_cal(): 14 | global global_data 15 | cur_thread = threading.current_thread() 16 | global_data[cur_thread] = 0 17 | for _ in xrange(1000): 18 | global_data[cur_thread] += 1 19 | show() 20 | 21 | for i in range(10): 22 | threads.append(threading.Thread(target=thread_cal)) 23 | threads[i].start() 24 | -------------------------------------------------------------------------------- /Exercises/MultiThread/local.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | import threading 4 | l = threading.Lock() 5 | global_num = 0 6 | 7 | 8 | def thread_cal(): 9 | global global_num 10 | for _ in xrange(1000): 11 | l.acquire() 12 | global_num += 1 13 | l.release() 14 | 15 | 16 | def show(num): 17 | print(threading.current_thread().getName(), num) 18 | 19 | 20 | def thread_cal(): 21 | local_num = 0 22 | for _ in xrange(1000): 23 | local_num += 1 24 | show(local_num) 25 | 26 | 27 | threads = [] 28 | for i in range(10): 29 | threads.append(threading.Thread(target=thread_cal)) 30 | threads[i].start() 31 | -------------------------------------------------------------------------------- /Exercises/MultiThread/threadlocal.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 每个线程可以通过global_data.num获得自己独有的数据,做到线程之间的隔离 3 | 4 | import threading 5 | 6 | 7 | global_data = threading.local() 8 | threads = [] 9 | 10 | 11 | def show(): 12 | print threading.current_thread().getName(), global_data.num 13 | 14 | 15 | def thread_cal(): 16 | global_data.num = 0 17 | for _ in xrange(1000): 18 | global_data.num += 1 19 | show() 20 | 21 | 22 | for i in range(10): 23 | threads.append(threading.Thread(target=thread_cal)) 24 | threads[i].start() 25 | -------------------------------------------------------------------------------- /Exercises/Pickle/stream.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | try: 5 | import cPickle as pickle 6 | except: 7 | import pickle 8 | import pprint 9 | from StringIO import StringIO 10 | 11 | 12 | class SimpleObject(object): 13 | def __init__(self, name): 14 | self.name = name 15 | l = list(name) 16 | l.reverse() 17 | self.name_backwards = ''.join(l) 18 | return 19 | 20 | 21 | data = [] 22 | data.append(SimpleObject('pickle')) 23 | data.append(SimpleObject('cPickle')) 24 | data.append(SimpleObject('last')) 25 | 26 | 27 | # 模拟文件 28 | out_s = StringIO() 29 | 30 | for o in data: 31 | print 'WRITING: %s (%s)' % (o.name, o.name_backwards) 32 | pickle.dump(o, out_s) 33 | # 清除内部缓存区 34 | out_s.flush() 35 | 36 | in_s = StringIO(out_s.getvalue()) 37 | 38 | while True: 39 | try: 40 | o = pickle.load(in_s) 41 | except EOFError: 42 | break 43 | else: 44 | print 'READ: %s (%s)' % (o.name, o.name_backwards) 45 | -------------------------------------------------------------------------------- /Exercises/Pickle/test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | try: 5 | import cPickle as pickle 6 | except: 7 | import pickle 8 | import pprint 9 | 10 | data = [ {'a': 'A', 'b':2, 'c': 3.0} ] 11 | print 'DATA:', 12 | pprint.pprint(data) 13 | 14 | data_string = pickle.dumps(data) 15 | print 'PICKLE:', data_string 16 | -------------------------------------------------------------------------------- /Exercises/Pickle/test2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | try: 5 | import cPickle as pickle 6 | except: 7 | import pickle 8 | import pprint 9 | 10 | 11 | data1 = [ { 'a':'A', 'b':2, 'c':3.0 } ] 12 | print 'BEFORE:', 13 | pprint.pprint(data1) 14 | 15 | data1_string = pickle.dumps(data1) 16 | 17 | data2 = pickle.loads(data1_string) 18 | print 'AFTER:', 19 | pprint.pprint(data2) 20 | 21 | 22 | # 新构造的对象和原对象相同,但并非同一对象 23 | print 'SAME?:', (data1 is data2) 24 | print 'EQUAL?:', (data1 == data2) 25 | -------------------------------------------------------------------------------- /Exercises/PyQueryTest/hello.html: -------------------------------------------------------------------------------- 1 |
2 | 9 |
10 | -------------------------------------------------------------------------------- /Exercises/PyQueryTest/test.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | # Four methods to initialize PyQuery 4 | 5 | # 1. init with string 6 | # from pyquery import PyQuery as pq 7 | # doc = pq('') 8 | 9 | # 2. init with lxml.etree 10 | # from lxml import etree 11 | # doc = pq(etree.fromstring("")) 12 | 13 | # 3. init directly with URL 14 | # from pyquery import PyQuery as pq 15 | # doc = pq('http://www.baidu.com') 16 | 17 | # 4. init with file 18 | # from pyquery import PyQuery as pq 19 | # doc = pq(filename='hello.html') 20 | 21 | from pyquery import PyQuery as pq 22 | 23 | doc = pq(filename='hello.html') 24 | print doc.html() 25 | print '-'*40 26 | print type(doc) 27 | print '-'*40 28 | li = doc('li') 29 | print '-'*40 30 | print type(li) 31 | print '-'*40 32 | print li.text() 33 | 34 | # url for the passage: http://python.jobbole.com/85222/ 35 | -------------------------------------------------------------------------------- /Exercises/PythonHardWay/ex44d.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | 4 | class Parent(object): 5 | 6 | 7 | def override(self): 8 | print 'PARENT override()' 9 | 10 | 11 | def implicit(self): 12 | print 'PARENT implicit()' 13 | 14 | 15 | def altered(self): 16 | print 'PARENT altered()' 17 | 18 | 19 | class Child(Parent): 20 | 21 | 22 | def override(self): 23 | print 'CHILD override()' 24 | 25 | 26 | def altered(self): 27 | print 'CHILD, BEFORE PARENT altered()' 28 | super(Child, self).altered() 29 | print 'CHILD, AFTER PARENT altered()' 30 | 31 | 32 | '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' 33 | 34 | 35 | dad = Parent() 36 | son = Child() 37 | 38 | 39 | dad.implicit() 40 | son.implicit() 41 | 42 | 43 | dad.override() 44 | son.override() 45 | 46 | 47 | dad.altered() 48 | son.altered() 49 | -------------------------------------------------------------------------------- /Exercises/PythonHardWay/exercise10.py: -------------------------------------------------------------------------------- 1 | #Here's some new strange stuff,remember type it exactly. 2 | 3 | 4 | days="Mon Tue Wed Thu Fri Sat Sun" 5 | months="Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" 6 | 7 | 8 | print"Here are the days:",days 9 | print"Here are the months:",months 10 | 11 | 12 | print""" 13 | There's something going on here. 14 | With the three double-quotes. 15 | We'll be able to type as much as we like. 16 | Even 4 lines if we want, or 5, or 6. 17 | """ 18 | -------------------------------------------------------------------------------- /Exercises/PythonHardWay/exercise11.py: -------------------------------------------------------------------------------- 1 | print"I am 6'2\"tall." 2 | print'I am 6\'2"tall.' 3 | 4 | tabby_cat="\tI'm tabbed in." 5 | persian_cat="I'm split\non a line." 6 | backslash_cat="I'm\\a\\cat." 7 | 8 | fat_cat=''' 9 | I'll do a list: 10 | \t* Cat food 11 | \t* Fishies 12 | \t* Catnip\n\t*Grass 13 | ''' 14 | 15 | print tabby_cat 16 | print persian_cat 17 | print backslash_cat 18 | print fat_cat 19 | 20 | print '''she said:"he's a boy"''' 21 | 22 | print"How old are you?", 23 | age=raw_input() 24 | print"How tall are you?", 25 | height=raw_input() 26 | print"How much do you weigh?", 27 | weight=raw_input() 28 | 29 | print"So,you're %s old,%s tall and %s heavy."%(age,height,weight) 30 | -------------------------------------------------------------------------------- /Exercises/PythonHardWay/exercise12.py: -------------------------------------------------------------------------------- 1 | y=raw_input("What's your name") 2 | age=raw_input("How old are you?") 3 | height=raw_input("How tall are you?") 4 | weight=raw_input("How much do you weigh?") 5 | 6 | print"Let's talk about %r.So,you're %s old,%s tall and %s heavy."%(y,age,height,weight) 7 | 8 | -------------------------------------------------------------------------------- /Exercises/PythonHardWay/exercise13.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | 3 | script,first,second,third=argv 4 | 5 | print"The script is called:",script 6 | print"Your first variable is:",first=raw_input() 7 | print"Your second variable is:",second=raw_input() 8 | print"Your third variable is:",third=raw_input() 9 | -------------------------------------------------------------------------------- /Exercises/PythonHardWay/exercise14.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | 3 | script,user_name=argv 4 | prompt='>' 5 | 6 | print "Hi %s,I'm the %s script."%(user_name,script) 7 | print"I'd like to ask you a few questions." 8 | print"Do you like me %s?"%user_name 9 | likes=raw_input(prompt) 10 | 11 | print"Where do you live %s?"%user_name 12 | lives=raw_input(prompt) 13 | 14 | print"What kind of computer do you have?" 15 | computer=raw_input(prompt) 16 | 17 | print""" 18 | Alright, so you said %r about liking me. 19 | You live in %r.Not sure where that is. 20 | And you have a %r computer. Nice. 21 | """%(likes,lives,computer) 22 | 23 | -------------------------------------------------------------------------------- /Exercises/PythonHardWay/exercise15.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | 3 | script,filename=argv 4 | #Line1-3 uses argv to get a filename. 5 | txt=open(filename) 6 | 7 | print"Here's your file %r:"%filename#a little message 8 | print txt.read()#Function on txt named read 9 | 10 | print"Type the filename again:" 11 | file_again=raw_input(">") 12 | 13 | txt_again=open(file_again) 14 | 15 | print txt_again.read() 16 | -------------------------------------------------------------------------------- /Exercises/PythonHardWay/exercise16.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | 3 | script,filename=argv 4 | 5 | print"We're going to erase %r."%filename 6 | print"If you don't want that, hit CTRL-C (^C)." 7 | print"If you do want that, hit RETURN." 8 | 9 | raw_input("?") 10 | 11 | print"Opening the file..." 12 | target=open(filename,'w') 13 | 14 | print"Truncating the file. Goodbye!" 15 | target.truncate() 16 | 17 | print"Now I'm going to ask you for three lines." 18 | 19 | line1=raw_input("line 1: ") 20 | line2=raw_input("line 2: ") 21 | line3=raw_input("line 3: ") 22 | 23 | print "I'm going to write these to the file." 24 | 25 | target.write(line1) 26 | target.write("\n") 27 | target.write(line2) 28 | target.write("\n") 29 | target.write(line3) 30 | target.write("\n") 31 | 32 | print"And finally, we close it." 33 | target.close() 34 | -------------------------------------------------------------------------------- /Exercises/PythonHardWay/exercise7.py: -------------------------------------------------------------------------------- 1 | print"Mary had a little lamb." 2 | print"Its fleece was white as %s."%'snow' 3 | print"And everywhere that Mary went." 4 | print"."*10 #what'd that do 5 | 6 | end1="C" 7 | end2="h" 8 | end3="e" 9 | end4="e" 10 | end5="s" 11 | end6="e" 12 | end7="B" 13 | end8="u" 14 | end9="r" 15 | end10="g" 16 | end11="e" 17 | end12="r" 18 | 19 | #watch that comma at the end.try removing it to see what happens 20 | print end1+end2+end3+end4+end5+end6 21 | print end7+end8+end9+end10+end11+end12 22 | -------------------------------------------------------------------------------- /Exercises/PythonHardWay/exercise8.py: -------------------------------------------------------------------------------- 1 | formatter="%r %r %r %r" 2 | 3 | print formatter%(1,2,3,4) 4 | print formatter%("one","two","three","four") 5 | print formatter%(True,False,False,True) 6 | print formatter%(formatter,formatter,formatter,formatter) 7 | print formatter%( 8 | "I had this thing.", 9 | "That you could type up.", 10 | "But it didn't sing.", 11 | "So I said goodnight." 12 | ) 13 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/cookie.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import urllib2, cookielib 3 | 4 | #声明一个CookieJar对象实例来保存cookie 5 | cookie = cookielib.CookieJar() 6 | #利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器 7 | handler = urllib2.HTTPCookieProcessor(cookie) 8 | #通过handler来构建opener 9 | opener = urllib2.build_opener(handler) 10 | #此处的open方法同urllib2的urlopen方法,也可以传入request 11 | response = opener.open('http://www.baidu.com') 12 | for item in cookie: 13 | print 'Name = ' + item.name 14 | print 'Value = ' + item.value 15 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/cookie.txt: -------------------------------------------------------------------------------- 1 | # Netscape HTTP Cookie File 2 | # http://curl.haxx.se/rfc/cookie_spec.html 3 | # This is a generated file! Do not edit. 4 | 5 | .baidu.com TRUE / FALSE 3604113482 BAIDUID 21BE51AE897BDF43B808F5BCF1BF1F83:FG=1 6 | .baidu.com TRUE / FALSE 3604113482 BIDUPSID 21BE51AE897BDF43B808F5BCF1BF1F83 7 | .baidu.com TRUE / FALSE H_PS_PSSID 1428_18205_17000_17073_15734_12207 8 | .baidu.com TRUE / FALSE 3604113482 PSTM 1456641279 9 | www.baidu.com FALSE / FALSE BDSVRTM 0 10 | www.baidu.com FALSE / FALSE BD_HOME 0 11 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/getdemo.py: -------------------------------------------------------------------------------- 1 | import urllib, urllib2 2 | 3 | values = {} 4 | values['username'] = 'xxx@xxx.com' 5 | values['password'] = 'xxx' 6 | data = urllib.urlencode(values) 7 | url = 'http://xxx.xxx.com' 8 | geturl = url + "?" + data 9 | request = urllib2.Request(geturl) 10 | response = urllib2.urlopen(request) 11 | print response.read() 12 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/getjpg.py: -------------------------------------------------------------------------------- 1 | import urllib, re 2 | 3 | 4 | def getHtml(url): 5 | page = urllib.urlopen(url) 6 | html = page.read() 7 | return html 8 | 9 | def getImg(html): 10 | reg = r'src="(.+?\.jpg)" pic_ext' 11 | imgre = re.compile(reg) 12 | imglist = re.findall(imgre, html) 13 | x = 0 14 | for i in imglist: 15 | urllib.urlretrieve(i, 'picgot/%s.jpg' % x) 16 | x += 1 17 | return "All pictures have been got!" 18 | 19 | html = getHtml("http://tieba.baidu.com/p/2460150866") 20 | 21 | print getImg(html) 22 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/getjpg2.py: -------------------------------------------------------------------------------- 1 | import re 2 | import urllib 3 | 4 | 5 | def getHtml(url): 6 | page = urllib.urlopen(url) 7 | html = page.read() 8 | return html 9 | 10 | def getImg(html): 11 | reg = r'src="(.+?\.jpg)" pic_ext' 12 | imgre = re.compile(reg) 13 | imglist = re.findall(imgre, html) 14 | return imglist 15 | 16 | html = getHtml("http://tieba.baidu.com/p/2460150866") 17 | print getImg(html) 18 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/hasattr.py: -------------------------------------------------------------------------------- 1 | import urllib2 2 | 3 | req = urllib2.Request('http://blog.csdn.net/cqcre') 4 | try: 5 | urllib2.urlopen(req) 6 | except urllib2.URLError, e: 7 | if hasattr(e, "code"): 8 | print e.code 9 | if hasattr(e, "reason"): 10 | print e.reason 11 | else: 12 | print "OK" 13 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/httperror.py: -------------------------------------------------------------------------------- 1 | import urllib2 2 | 3 | req = urllib2.Request('http://blog.csdn.net/cqcre') 4 | try: 5 | urllib2.urlopen(req) 6 | except urllib2.HTTPError, e: 7 | print e.code 8 | print e.reason 9 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/httperror2.py: -------------------------------------------------------------------------------- 1 | import urllib2 2 | 3 | req = urllib2.Request('http://blog.csdn.net/cqcre') 4 | try: 5 | urllib2.urlopen(req) 6 | except urllib2.HTTPError, e: 7 | print e.code 8 | except urllib2.URLError, e: 9 | print e.reason 10 | else: 11 | print "OK" 12 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/postdemo.py: -------------------------------------------------------------------------------- 1 | import urllib,urllib2 2 | 3 | values = {"username":"xxx@xxx.com", "password":"xxx"} 4 | data = urllib.urlencode(values) 5 | url = "http://xxx.xxx.com" 6 | request = urllib2.Request(url,data) 7 | response = urllib2.urlopen(request) 8 | print response.read() 9 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/proxy.py: -------------------------------------------------------------------------------- 1 | import urllib2 2 | 3 | enable_proxy = True 4 | proxy_handler = urllib2.ProxyHandler({"http": 'http://some-proxy.com:8080'}) 5 | null_proxy_handler = urllib2.ProxyHandler({}) 6 | if enable_proxy: 7 | opener = urllib2.build_opener(proxy_handler) 8 | else: 9 | opener = urllib2.build_opener(null_proxy_handler) 10 | urllib2.install_opener(opener) 11 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/readcookie.py: -------------------------------------------------------------------------------- 1 | import cookielib, urllib2 2 | 3 | cookie = cookielib.MozillaCookieJar() 4 | cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True) 5 | req = urllib2.Request("http://www.baidu.com") 6 | opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) 7 | response = opener.open(req) 8 | print response.read() 9 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/savecookie.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import cookielib, urllib2 3 | 4 | #设置保存cookie的文件,同级目录下的cookie.txt 5 | filename = 'cookie.txt' 6 | #声明一个MozillaCookieJar对象实例来保存cookie,之后写入文件 7 | cookie = cookielib.MozillaCookieJar(filename) 8 | #利用urllib2库中的HTTPCookieProcessor对象来创建cookie处理器 9 | handler = urllib2.HTTPCookieProcessor(cookie) 10 | #通过handler来创建opener 11 | opener = urllib2.build_opener(handler) 12 | #创建一个请求,原理同urllib2的urlopen 13 | response = opener.open("http://www.baidu.com") 14 | #保存cookie到文件 15 | cookie.save(ignore_discard=True, ignore_expires=True) 16 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/urlerror.py: -------------------------------------------------------------------------------- 1 | import urllib2 2 | 3 | request = urllib2.Request('http://www.xxxx.com') 4 | try: 5 | urllib2.urlopen(request) 6 | except urllib2.URLError, e: 7 | print e.reason 8 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/withheader: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Exercises/PythonRobot/withheader.py: -------------------------------------------------------------------------------- 1 | import urllib, urllib2 2 | 3 | url = 'http://www.server.com/login' 4 | user_agent = 'Mozilla/5.0i (Windows NT 6.3; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0' 5 | values = {'username': 'xxx', 'password': 'xxx'} 6 | headers = {'User-Agent': user_agent, 'Referer':'http://www.zhihu.com/article'} 7 | data = urllib.urlencode(values) 8 | request = urllib2.Request(url, data, headers) 9 | response = urllib2.urlopen(request) 10 | page = response.read() 11 | -------------------------------------------------------------------------------- /Exercises/QiniuPythonDemo/test.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_qiniustorage import Qiniu 3 | 4 | QINIU_ACCESS_KEY = '' 5 | QINIU_SECRET_KEY = '' 6 | QINIU_BUCKET_NAME = '' 7 | QINIU_BUCKET_DOMAIN = '' 8 | 9 | app = Flask(__name__) 10 | app.config.from_object(__name__) 11 | qiniu_store = Qiniu(app) 12 | # 或者 13 | # qiniu_store = Qiniu() 14 | # qiniu_store.init_app(app) 15 | 16 | # 保存文件到七牛 17 | @app.route('/save') 18 | def save(): 19 | data = 'data to save' 20 | filename = 'filename' 21 | ret, info = qiniu_store.save(data, filename) 22 | return str(ret) 23 | 24 | # 删除七牛空间中的文件 25 | @app.route('/delete') 26 | def delete(): 27 | filename = 'filename' 28 | ret, info = qiniu_store.delete(filename) 29 | return str(ret) 30 | 31 | # 根据文件名获取对应的公开URL 32 | @app.route('/url') 33 | def url(): 34 | filename = 'filename' 35 | return qiniu_store.url(filename) 36 | -------------------------------------------------------------------------------- /Exercises/Recursion/solve.py: -------------------------------------------------------------------------------- 1 | def register(cls): 2 | cls.another_method = Mixin.another_method 3 | return cls 4 | -------------------------------------------------------------------------------- /Exercises/Recursion/test.py: -------------------------------------------------------------------------------- 1 | class View(object): 2 | def method(self): 3 | pass 4 | 5 | class ChildView(View): 6 | def method(self): 7 | super(ChildView, self).method() 8 | 9 | class Mixin(object): 10 | pass 11 | 12 | def register(cls): 13 | return type( 14 | 'DecoratedView', 15 | (Mixin, cls), 16 | {} 17 | ) 18 | -------------------------------------------------------------------------------- /Exercises/Recursion/test2.py: -------------------------------------------------------------------------------- 1 | class Mixin(object): 2 | pass 3 | 4 | def register(cls): 5 | return type( 6 | cls.__name__, 7 | (Mixin, cls), 8 | {} 9 | ) 10 | 11 | class View(object): 12 | def method(self): 13 | print "method() from View()" 14 | 15 | @register 16 | class ChildView(View): 17 | def method(self): 18 | super(ChildView, self).method() 19 | -------------------------------------------------------------------------------- /Exercises/RedirectBackWithWTF/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | from redirect import RedirectForm 3 | from wtforms import TextField, HiddenField 4 | 5 | app = Flask(__name__) 6 | app.config['SECRET_KEY'] = 'hard to guess string' 7 | 8 | 9 | class LoginForm(RedirectForm): 10 | username = TextField('Username') 11 | password = TextField('Password') 12 | 13 | @app.route('/login', methods=['GET', 'POST']) 14 | def login(): 15 | form = LoginForm() 16 | if form.validate_on_submit(): 17 | return form.redirect('index') 18 | return render_template('login.html', form=form) 19 | 20 | if __name__ == '__main__': 21 | app.run(debug=True) 22 | -------------------------------------------------------------------------------- /Exercises/RedirectBackWithWTF/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Test -- Index 4 | 5 | 6 | -------------------------------------------------------------------------------- /Exercises/RedirectBackWithWTF/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | {{ form.username }} 5 | {{ form.password }} 6 | 7 |
8 | 9 | 10 | -------------------------------------------------------------------------------- /Exercises/RedirectDemo/app.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from flask import Flask, request, render_template, url_for 3 | from redirect_urls import is_safe_url, get_redirect_target, redirect_back 4 | 5 | app = Flask(__name__) 6 | 7 | @app.route('/') 8 | def index(): 9 | return 'this is index' 10 | 11 | @app.route('/login', methods=['GET', 'POST']) 12 | def login(): 13 | next = get_redirect_target() 14 | if request.method == 'POST': 15 | # login code here 16 | return redirect_back(url_for("index")) 17 | return render_template('index.html', next=next) 18 | 19 | if __name__ == '__main__': 20 | app.run(debug=True) 21 | -------------------------------------------------------------------------------- /Exercises/RedirectDemo/redirect_urls.py: -------------------------------------------------------------------------------- 1 | from urlparse import urlparse, urljoin 2 | from flask import request, url_for, redirect 3 | 4 | def is_safe_url(target): 5 | ref_url = urlparse(request.host_url) 6 | test_url = urlparse(urljoin(request.host_url, target)) 7 | return test_url.scheme in ('http', 'https') and \ 8 | ref_url.netloc == test_url.netloc 9 | 10 | def get_redirect_target(): 11 | for target in request.values.get('next'), request.referrer: 12 | if not target: 13 | continue 14 | if is_safe_url(target): 15 | return target 16 | 17 | def redirect_back(endpoint, **values): 18 | target = request.form['next'] 19 | if not target or not is_safe_url(target): 20 | target = url_for(endpoint, **values) 21 | return redirect(target) 22 | -------------------------------------------------------------------------------- /Exercises/RedirectDemo/templates/index.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |
Username: 4 |
5 |
Password: 6 |
7 |
8 |

9 | 10 | 11 |

12 | -------------------------------------------------------------------------------- /Exercises/Request/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*- coding: utf-8 -*- 3 | 4 | import requests 5 | 6 | # Get a webpage, eg: GitHub's public timeline 7 | # The Response object `r` 8 | r = requests.get('https://api.github.com/events') 9 | 10 | # Make an HTTP POST request 11 | r = requests.post('http://httpbin.org/test', data = {'key': 'value'}) 12 | 13 | # HTTP PUT 14 | r = requests.put('http://httpbin.org/put', data = {'key': 'value'}) 15 | 16 | # HTTP DELETE 17 | r = requests.delete('http://httpbin.org/delete') 18 | 19 | # HTTP HEAD 20 | # get only the head of a webpage 21 | r = requests.head('http://httpbin.org/get') 22 | 23 | # HTTP OPTIONS 24 | # get the methods surppoted by the server 25 | r = requests.options('http://httpbin.org/get') 26 | 27 | 28 | # Passing Parameters In URLS 29 | payload = {'key1': 'value1', 'key2': 'value2'} 30 | r = requests.get('http://httpbin.org/get', params=payload) 31 | -------------------------------------------------------------------------------- /Exercises/ScrapyDemo/pic/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/ScrapyDemo/pic/1.png -------------------------------------------------------------------------------- /Exercises/ScrapyDemo/pic/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/ScrapyDemo/pic/2.png -------------------------------------------------------------------------------- /Exercises/ScrapyDemo/pic/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/ScrapyDemo/pic/3.png -------------------------------------------------------------------------------- /Exercises/ScrapyDemo/scrapy.cfg: -------------------------------------------------------------------------------- 1 | # Automatically created by: scrapy startproject 2 | # 3 | # For more information about the [deploy] section see: 4 | # https://scrapyd.readthedocs.org/en/latest/deploy.html 5 | 6 | [settings] 7 | default = scrial.settings 8 | 9 | [deploy] 10 | #url = http://localhost:6800/ 11 | project = scrial 12 | -------------------------------------------------------------------------------- /Exercises/ScrapyDemo/scrial/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/ScrapyDemo/scrial/__init__.py -------------------------------------------------------------------------------- /Exercises/ScrapyDemo/scrial/items.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Define here the models for your scraped items 4 | # 5 | # See documentation in: 6 | # http://doc.scrapy.org/en/latest/topics/items.html 7 | 8 | import scrapy 9 | 10 | 11 | class ScrialItem(scrapy.Item): 12 | # define the fields for your item here like: 13 | # name = scrapy.Field() 14 | pass 15 | 16 | 17 | class DmozItem(scrapy.Item): 18 | title = scrapy.Field() 19 | link = scrapy.Field() 20 | desc = scrapy.Field() 21 | -------------------------------------------------------------------------------- /Exercises/ScrapyDemo/scrial/pipelines.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Define your item pipelines here 4 | # 5 | # Don't forget to add your pipeline to the ITEM_PIPELINES setting 6 | # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html 7 | 8 | 9 | class ScrialPipeline(object): 10 | def process_item(self, item, spider): 11 | return item 12 | -------------------------------------------------------------------------------- /Exercises/ScrapyDemo/scrial/spiders/__init__.py: -------------------------------------------------------------------------------- 1 | # This package will contain the spiders of your Scrapy project 2 | # 3 | # Please refer to the documentation for information on how to create and manage 4 | # your spiders. 5 | -------------------------------------------------------------------------------- /Exercises/ScrapyDemo/scrial/spiders/dmoz_spider.py: -------------------------------------------------------------------------------- 1 | import scrapy 2 | 3 | 4 | class DmozSpider(scrapy.spiders.Spider): 5 | name = 'dmoz' 6 | allowed_domains = ["dmoz.org"] 7 | start_urls = [ 8 | "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", 9 | "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" 10 | ] 11 | 12 | def parse(self, response): 13 | for sel in response.xpath('//ul/li'): 14 | title = sel.xpath('a/text()').extract() 15 | link = sel.xpath('a/@href').extract() 16 | desc = sel.xpath('text()').extract() 17 | print title, link, desc 18 | -------------------------------------------------------------------------------- /Exercises/Shell/array.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | array1=(1 2 3 4 5) 4 | array2=( 5 | 1 6 | 2 7 | 3 8 | 4 9 | 5 10 | ) 11 | echo ${array1[0]} 12 | echo 'array2' 13 | # @ to get all elements 14 | echo ${array2[@]} 15 | # length of the array 16 | echo ${#array2[@]} 17 | echo ${#array2[*]} 18 | # length of an element 19 | echo ${#array2[0]} 20 | -------------------------------------------------------------------------------- /Exercises/Shell/cal.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | val=`expr 2 + 2` # must with space between numbers and + 4 | echo "sum: $val" 5 | 6 | val=`expr 2 \* 2` # \ before * 7 | echo "multiply: $val" 8 | 9 | a=10 10 | b=20 11 | # if...then...fi 12 | if [ $a == $b ] 13 | then 14 | echo "a is equal to b" 15 | fi 16 | 17 | # and(&&) 18 | if [ $a -gt $b -a $a -lt $b ] 19 | then 20 | echo "somthing..." 21 | fi 22 | 23 | # or(||) 24 | if [ $a -le $b -o $a -ne $b ] 25 | then 26 | echo "something..." 27 | else 28 | echo "something else" 29 | fi 30 | 31 | # Sentence 32 | # [ $a = $b ]: sentence a is equal to sentence b 33 | # [ $a != $b ]: sentence a is not equal to sentence b 34 | # [ -z $a ]: length is 0 35 | # [ -n $a ]: length is not 0 36 | # [ $a ]: sentence is None 37 | -------------------------------------------------------------------------------- /Exercises/Shell/para.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | your_name="kasheemlew" 4 | echo $your_name 5 | # brace is optional 6 | echo ${your_name} 7 | 8 | for i in `ls /etc`; do 9 | echo " ${i}" 10 | done 11 | 12 | # reassign would cast an error 13 | readonly your_name 14 | # your_name="k" 15 | 16 | # delete an parameter 17 | unset your_name 18 | 19 | str='this \n is a \n string' 20 | echo $str 21 | str="this \n is a \n string" 22 | echo $str 23 | 24 | string="abcd" 25 | # get the length of the string 26 | echo ${#string} 27 | string="hello world!" 28 | # get from index 1 to index 4 29 | echo ${string:1:4} 30 | # find index world 31 | echo `expr index "$string" world` 32 | -------------------------------------------------------------------------------- /Exercises/Shell/para2.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | echo "Shell parameters:"; 4 | echo "para1: $0"; 5 | echo "para2: $1"; 6 | echo "number of the arguments: $#"; 7 | echo "display arguments as the first string: $*"; 8 | echo "current process id: $$"; 9 | echo "last process id in the backend: $!"; 10 | -------------------------------------------------------------------------------- /Exercises/Shell/stable-shell.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Some advice for writing stable shell script 4 | # URL: https://segmentfault.com/a/1190000006900083 5 | 6 | # print the commands been executed 7 | set -x 8 | # end the program when crash an error 9 | set -e 10 | 11 | # shellcheck helps 12 | # Github: https://github.com/koalaman/shellcheck 13 | 14 | # Deal with Parameter 15 | # https://segmentfault.com/a/1190000002539169 16 | 17 | # parameters are global in default 18 | # define local parameter: 19 | local hello="world" 20 | # echo ${hello}; would cause an error 21 | 22 | # invoke Function sighandler when received SIGINT 23 | trap sighandler INT 24 | 25 | echo "Hello world!"; 26 | 27 | # allow invoke functions when script ends 28 | trap func EXIT 29 | 30 | # allow invoke functions when errors come up 31 | trap func ERR 32 | -------------------------------------------------------------------------------- /Exercises/Shell/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # This is an annotation 4 | # Two ways to execute the script 5 | # 1. chmod +x ./test.sh 6 | # ./test.sh 7 | # 2. /bin/sh test.sh (the information of interpreter in the first line is 8 | # useless 9 | 10 | echo "Hello World!" 11 | -------------------------------------------------------------------------------- /Exercises/Singleton/decorator.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | # 定义了一个装饰器 singleton,它返回了一个内部函数 getinstance,该函数会判断某 3 | # 个类是否在字典 instances 中,如果不存在,则会将 cls 作为 key,cls(*args, **kw) 4 | # 作为 value 存到 instances 中,否则,直接返回 instances[cls]。 5 | 6 | from functools import wraps 7 | 8 | def singleton(cls): 9 | instances = {} 10 | @wraps(cls) 11 | def getinstance(*args, **kw): 12 | if cls not in instances: 13 | instances[cls] = cls(*args, **kw) 14 | return instances[cls] 15 | return getinstance 16 | 17 | @singleton 18 | class MyClass(object): 19 | a = 1 20 | -------------------------------------------------------------------------------- /Exercises/Singleton/metaclass.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | # 元类(metaclass)可以控制类的创建过程,它拦截类的创建, 修改类的定义, 返回修改后的类 3 | 4 | class Singleton(type): 5 | _instances = {} 6 | def __call__(cls, *args, **kwargs): 7 | if cls not in cls._instances: 8 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 9 | return cls._instances[cls] 10 | 11 | # Python2 12 | class MyClass(object): 13 | __metaclass__ = Singleton 14 | 15 | # Python3 16 | class MyClass(metaclass=Singleton): 17 | pass 18 | -------------------------------------------------------------------------------- /Exercises/Singleton/module.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | # 模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。 3 | 4 | class My_Singleton(object): 5 | def foo(self): 6 | pass 7 | 8 | my_singleton = My_Singleton() 9 | -------------------------------------------------------------------------------- /Exercises/Singleton/new.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | # 将类的实例和一个类变量 _instance 关联起来,如果 cls._instance 为 None 则创建实 3 | # 例,否则直接返回 cls._instance。 4 | 5 | class Singleton(object): 6 | _instance = None 7 | def __new__(cls, *args, **kw): 8 | if not cls._instance: 9 | cls._instance = super(Singleton, cls).__new__(cls, *args, **kw) 10 | return cls._instance 11 | 12 | class MyClass(Singleton): 13 | a = 1 14 | -------------------------------------------------------------------------------- /Exercises/Socket/chatroom/server-demo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*- coding: utf-8 -*- 3 | 4 | 5 | CONNECTION_LIST = [] 6 | 7 | read_sockets, write_sockets, error_sockets = select.select(CONNECTION_LIST, [], []) 8 | 9 | def broadcast_data(sock, message): 10 | # Do not send the message to master socket and the client who has send us 11 | # the message 12 | for socket in CONNECTION_LIST: 13 | if socket != server_socket and socket != sock: 14 | try: 15 | socket.send(message) 16 | except: 17 | # Broken socket connection 18 | socket.close() 19 | CONNECTION_LIST.remove(socket) 20 | -------------------------------------------------------------------------------- /Exercises/Socket/chatroom/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*- coding: utf-8 -*- 3 | 4 | 5 | import socket 6 | import select 7 | 8 | 9 | sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 10 | sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 | 12 | 13 | sock1.connect(('192.168.1.1', 25)) 14 | sock2.connect(('192.168.1.1', 25)) 15 | 16 | 17 | while True: 18 | # select的三个参数都是list类型, 分别代表读事件, 写事件, 错误事件, 19 | # 返回满足的事件 20 | rlist, wlist, elist = select.select([sock1, sock2], [], [], 5) 21 | if [rlist, wlist, elist] == [[], [], []]: 22 | print('Five seconds elapsed.\n') 23 | else: 24 | for sock in rlist: 25 | print(sock.recv(100)) 26 | -------------------------------------------------------------------------------- /Exercises/Socket/keep-alive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*- coding: utf-8 -*- 3 | 4 | import socket 5 | import sys 6 | 7 | HOST = '' 8 | PORT = 5000 9 | 10 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 11 | print('Socket created') 12 | 13 | try: 14 | s.bind((HOST, PORT)) 15 | except socket.error, msg: 16 | print('Bind failed. Error Code: {m1} Message {m2}'.format(m1=str(msg[0]), m2=msg[1])) 17 | sys.exit() 18 | print('Socket bind completed') 19 | 20 | s.listen(10) 21 | print('Socket now listening') 22 | 23 | while 1: 24 | conn, addr = s.accept() 25 | print('Connected with {a1} : {a2}'.format(a1=addr[0], a2=str(addr[1]))) 26 | data = conn.recv(1024) 27 | reply = 'OK...' + data 28 | if not data: 29 | break 30 | conn.sendall(reply) 31 | 32 | conn.close() 33 | s.close() 34 | -------------------------------------------------------------------------------- /Exercises/Socket/server.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #-*- coding: utf-8 -*- 3 | 4 | 5 | import socket 6 | import sys 7 | 8 | 9 | # 绑定socket 10 | HOST = '' # 所有可用接口 11 | PORT = 8888 # 任意端口 12 | 13 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 14 | print('Socket created') 15 | 16 | try: 17 | s.bind((HOST, PORT)) 18 | except socket.error, msg: 19 | print('Bind failed. Error Code: {m1} Message: {m2}'.format(m1=str(msg[0]), m2=msg[1])) 20 | sys.exit() 21 | print('Socket bind complete') 22 | 23 | 24 | # 监听连接 25 | s.listen(10) # 参数(backlog)控制连接个数 26 | print('Socket now listening') 27 | 28 | 29 | # 接收连接 30 | conn, addr = s.accept() 31 | print('Connected with {a}: {ad}'.format(a=addr[0], ad=str(addr[1]))) 32 | 33 | 34 | data = conn.recv(1024) 35 | conn.sendall(data) 36 | 37 | conn.close() 38 | s.close() 39 | -------------------------------------------------------------------------------- /Exercises/SortAlgorithm/bubble.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | # 冒泡排序(bubble sort) 4 | # 原理: 5 | # 1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。 6 | # 2. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。 7 | # 3. 针对所有的元素重复以上的步骤,除了最后一个。 8 | # 4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。 9 | 10 | # 时间复杂度: 11 | # 最差: O(n^2) 12 | # 最优: O(n) 13 | 14 | 15 | def bubble_sort(alist): 16 | length = len(alist) 17 | for index in range(length-1): 18 | for i in range(0, length-index-1): 19 | if alist[i] > alist[i+1]: 20 | alist[i+1], alist[i] = alist[i], alist[i+1] 21 | return alist 22 | 23 | 24 | # 优化: 添加标记,在排序完成时停止排序 25 | 26 | def bubble_sort_flag(alist): 27 | length = len(alist) 28 | for index in range(length): 29 | flag = True 30 | for i in range(0, length-index-1): 31 | if alist[i] > alist[i+1]: 32 | alist[i+1], alist[i] = alist[i], alist[i+1] 33 | flag = False 34 | if flag: 35 | return alist 36 | return alist 37 | -------------------------------------------------------------------------------- /Exercises/SortAlgorithm/comb_sort.py: -------------------------------------------------------------------------------- 1 | def comb_sort(alist): 2 | shrink = 1.3 3 | gap = len(alist) 4 | 5 | while True: 6 | gap = int(gap / shrink) 7 | i = 0 8 | if gap < 1: 9 | break 10 | else: 11 | while i + gap < length: 12 | if alist[i] > alist[i+gap]: 13 | alist[i], alist[i+gap] = alist[i+gap], alist[i] 14 | i += 1 15 | return alist 16 | -------------------------------------------------------------------------------- /Exercises/SortAlgorithm/insertion.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | # 插入排序(insertion sort) 4 | # 原理: 5 | # 1. 从第一个元素开始,该元素可以认为已经被排序 6 | # 2. 取出下一个元素,在已经排序的元素序列中从后向前扫描 7 | # 3. 如果该元素(已排序)大于新元素,将该元素移到下一位置 8 | # 4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置 9 | # 5. 将新元素插入到该位置后 10 | # 6. 重复步骤2~5 11 | 12 | # 时间复杂度: 13 | # 最差: O(n^2) 14 | # 最优: O(n) 15 | 16 | 17 | def insertion_sort(alist): 18 | length = len(alist) 19 | if length == 1: 20 | return alist 21 | b = insertion_sort(alist[1:]) 22 | lengthb = len(b) 23 | for index in range(lengthb): 24 | if alist[0] <= b[index]: 25 | return b[:index] + [alist[0]] + b[index:] 26 | return b + [alist[0]] 27 | -------------------------------------------------------------------------------- /Exercises/SortAlgorithm/readme.md: -------------------------------------------------------------------------------- 1 | # Sort Algorithms 2 | 3 | Collection of Common Sort Alogrithms in Python 4 | 5 | - [x] Insertion Sort 6 | - [x] Quick Sort 7 | - [x] Selection Sort 8 | - [x] Heap Sort 9 | - [x] Merge Sort 10 | - [x] Bubble Sort 11 | - [x] Shell Sort 12 | - [ ] Bucket Sort 13 | - [ ] Radix Sort 14 | -------------------------------------------------------------------------------- /Exercises/SortAlgorithm/selection.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | # 选择排序(selection sort) 4 | # 原理: 5 | # 1. 在未排序序列中找到最小(大)元素,存放到排序序列的起始位置, 6 | # 2. 再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。 7 | # 3. 重复第二步,直到所有元素均排序完毕。 8 | 9 | 10 | # 时间复杂度: 11 | # 最差: O(n^2) 12 | # 最优: O(n^2) 13 | 14 | 15 | def selection_sort(alist): 16 | length = len(alist) 17 | for index in range(length): 18 | m = index 19 | for i in range(index, length): 20 | if alist[i] < alist[m]: 21 | m = i 22 | alist[m], alist[index] = alist[index], alist[m] 23 | return alist 24 | -------------------------------------------------------------------------------- /Exercises/SortAlgorithm/shell.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | # 希尔排序/递减增量排序算法 4 | # 原理: 5 | # 基于插入排序的性质: 6 | # * 插入排序在对几乎已经排好序的数据操作时,效率高,即可以达到线性排序的效率 7 | # * 但插入排序一般来说是低效的,因为插入排序每次只能将数据移动一位。 8 | # 9 | # *希尔排序* 通过将比较的全部元素分为几个区域来提升插入排序的性能。这样可以让一 10 | # 个元素可以一次性地朝最终位置前进一大步(每次以一定步长以一定步长进行排序,直至 11 | # 步长为1)。然后算法再取越来越小的步长进行排序,算法的最后一步就是普通的插入排序 12 | # 13 | # 步长选择: 14 | # 只要最终步长为1都可以正常工作,Donald Shell最初建议步长选择为n/2并且对步长取 15 | # 半直到步长达到1。另外步长还可以使用Sedgewick提出的(1, 5, 19, 41, 109,…)。 16 | # 也可以使用斐波那契数列除去0和1将剩余的数以黄金分区比的两倍的幂进行运算得到的数列。 17 | 18 | # 时间复杂度: 19 | # 最差: O(nlog(2)n) 20 | # 最优: O(n) 21 | 22 | 23 | def shell_sort(alist): 24 | length = len(alist) 25 | gap = length / 2 26 | while gap > 0: 27 | for i in range(gap, length): 28 | temp = alist[i] 29 | j = i 30 | # 插入排序 31 | while j >= gap and alist[j-gap] > temp: 32 | alist[j] = alist[j-gap] 33 | j -= gap 34 | alist[j] = temp 35 | gap = gap / 2 36 | return alist 37 | -------------------------------------------------------------------------------- /Exercises/Thread/c1.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def countdown(n): 4 | while n > 0: 5 | print('T-minus', n) 6 | n -= 1 7 | time.sleep(1) 8 | 9 | from threading import Thread 10 | 11 | t = Thread(target=countdown, args=(10,)) 12 | t.start() 13 | if not t.is_alive(): 14 | print('Completed') 15 | -------------------------------------------------------------------------------- /Exercises/Thread/c2.py: -------------------------------------------------------------------------------- 1 | import time 2 | from threading import Thread 3 | 4 | class CountdownTask: 5 | def __init__(self): 6 | self._running = True 7 | 8 | def terminate(self): 9 | self._running = False 10 | 11 | def run(self, n): 12 | while self._running and n > 0: 13 | print('T-minus', n) 14 | n -= 1 15 | time.sleep(1) 16 | 17 | 18 | c = CountdownTask() 19 | t = Thread(target=c.run, args=(10,)) 20 | t.start() 21 | -------------------------------------------------------------------------------- /Exercises/Thread/c3.py: -------------------------------------------------------------------------------- 1 | from threading import Thread 2 | import time 3 | 4 | class CountdownThread(Thread): 5 | def __init__(self, n): 6 | super().__init__() 7 | self.n = n 8 | 9 | def run(self): 10 | while self.n > 0: 11 | print('T-minus', self.n) 12 | self.n -= 1 13 | time.sleep(1) 14 | 15 | c = CountdownThread(5) 16 | c.start() 17 | -------------------------------------------------------------------------------- /Exercises/Thread/c4.py: -------------------------------------------------------------------------------- 1 | from threading import Thread, Event 2 | import time 3 | 4 | def countdown(n, started_evt): 5 | print('countdown starting') 6 | started_evt.set() 7 | while n > 0: 8 | print('T-minus', n) 9 | n -= 1 10 | time.sleep(1) 11 | 12 | started_evt = Event() 13 | 14 | print('Launching countdown') 15 | t = Thread(target=countdown, args=(10, started_evt)) 16 | t.start() 17 | 18 | started_evt.wait() 19 | print('countdown is running') 20 | -------------------------------------------------------------------------------- /Exercises/Thread/c5.py: -------------------------------------------------------------------------------- 1 | import time 2 | from threading import Thread, Event 3 | 4 | def func1(n, evt): 5 | count = n 6 | while count > 0: 7 | if count == 5: 8 | evt.set() 9 | print('func1', count) 10 | count -= 1 11 | time.sleep(1) 12 | 13 | def func2(n, evt): 14 | evt.wait() 15 | count = n 16 | while count > 0: 17 | print('func2', count) 18 | count -= 1 19 | time.sleep(1) 20 | 21 | evt = Event() 22 | t1 = Thread(target=func1, args=(10, evt)) 23 | t2 = Thread(target=func2, args=(10, evt)) 24 | t1.start() 25 | t2.start() 26 | -------------------------------------------------------------------------------- /Exercises/Thread/c6.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import time 3 | 4 | class PeriodicTimer: 5 | def __init__(self, interval): 6 | self._interval = interval 7 | self._flag = 0 8 | self._cv = threading.Condition() 9 | 10 | def start(self): 11 | t = threading.Thread(target=self.run) 12 | t.daemon = True 13 | t.start() 14 | 15 | def run(self): 16 | while True: 17 | time.sleep(self._interval) 18 | with self._cv: 19 | self._flag ^= 1 20 | self._cv.notify_all() 21 | 22 | def wait_for_tick(self): 23 | with self._cv: 24 | last_flag = self._flag 25 | while last_flag == self._flag: 26 | self._cv.wait() 27 | -------------------------------------------------------------------------------- /Exercises/Thread/threading_multi1.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | counter = 0 4 | 5 | def worker(): 6 | global counter 7 | counter += 1 8 | print("The Count is %d" % counter) 9 | print("----------------") 10 | 11 | print("Starting up") 12 | for i in range(10): 13 | threading.Thread(target=worker).start() 14 | print("Finishing up") 15 | -------------------------------------------------------------------------------- /Exercises/Thread/threading_multi3.py: -------------------------------------------------------------------------------- 1 | import threading, time, random 2 | 3 | counter_lock = threading.Lock() 4 | printer_lock = threading.Lock() 5 | 6 | counter = 0 7 | 8 | def worker(): 9 | global counter 10 | with counter_lock: 11 | counter += 1 12 | with printer_lock: 13 | print('The count is %d' % counter) 14 | print('----------------') 15 | 16 | with printer_lock: 17 | print('Starting up') 18 | 19 | worker_threads = [] 20 | for i in range(10): 21 | t = threading.Thread(target=worker) 22 | worker_threads.append(t) 23 | t.start() 24 | 25 | for t in worker_threads: 26 | t.join() 27 | 28 | with printer_lock: 29 | print('Finishing up') 30 | -------------------------------------------------------------------------------- /Exercises/TwoDimensioBarCode/TwoDimensionalBarCode.py: -------------------------------------------------------------------------------- 1 | import qrcode 2 | 3 | img = qrcode.make('http://www.baidu.com') 4 | -------------------------------------------------------------------------------- /Exercises/TwoDimensioBarCode/app/__init__.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | from flask import Flask 4 | 5 | 6 | app = Flask(__name__) 7 | app.config['SECRET_KEY'] = 'your secret key is here' 8 | 9 | 10 | from . import views, forms 11 | -------------------------------------------------------------------------------- /Exercises/TwoDimensioBarCode/app/forms.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from flask_wtf import Form 3 | # from wtforms import 4 | # from wtforms.validators import 5 | 6 | -------------------------------------------------------------------------------- /Exercises/TwoDimensioBarCode/app/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 2 Dimensioon Bar Code Test 4 | 5 |
{{ img }}
6 | 7 | 8 | -------------------------------------------------------------------------------- /Exercises/TwoDimensioBarCode/app/views.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | from . import app 3 | from flask import render_template 4 | from qrcode import make 5 | 6 | 7 | # test views 8 | @app.route('/test/') 9 | def test(): 10 | return "

just tell you everything is ok!

" 11 | 12 | # you can writing your views here 13 | @app.route('/') 14 | def index(): 15 | img = make('http://www.baidu.com') 16 | return render_template('index.html', img=img) 17 | -------------------------------------------------------------------------------- /Exercises/TwoDimensioBarCode/manage.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | """ 4 | manage.py 5 | ~~~~~~~~ 6 | 7 | shell: 8 | python manage.py shell 9 | run server: 10 | python manage.py runserver 11 | -d 开启调试模式 12 | """ 13 | 14 | import sys 15 | from app import app 16 | from flask.ext.script import Manager, Shell 17 | 18 | """编码设置""" 19 | reload(sys) 20 | sys.setdefaultencoding('utf-8') 21 | 22 | 23 | manager = Manager(app) 24 | 25 | 26 | def make_shell_context(): 27 | """自动加载环境""" 28 | return dict( 29 | app=app 30 | ) 31 | 32 | 33 | manager.add_command("shell", Shell(make_context=make_shell_context)) 34 | 35 | 36 | if __name__ == '__main__': 37 | manager.run() 38 | 39 | -------------------------------------------------------------------------------- /Exercises/TwoDimensioBarCode/requirement.txt: -------------------------------------------------------------------------------- 1 | 2 | Flask==0.10.1 3 | Flask-WTF==0.10.0 4 | 5 | -------------------------------------------------------------------------------- /Exercises/UnitTest/client.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import requests 3 | 4 | 5 | def api_request(url): 6 | r = requests.get(url) 7 | return r.json() 8 | 9 | def get_review_author(url): 10 | rs = api_request(url) 11 | return rs['review']['author'] 12 | -------------------------------------------------------------------------------- /Exercises/UnitTest/test_mock.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import unittest 4 | 5 | import mock 6 | import client 7 | 8 | 9 | class TestClient(unittest.TestCase): 10 | def setUp(self): 11 | self.result = {'review': {'author': 'dongwm'}} 12 | 13 | def test_response(self): 14 | api_result = mock.Mock(return_value=self.result) 15 | client.api_request = api_result 16 | self.assertEqual(client.get_review_author( 17 | 'http://api.dongwm.com/review/123'), 'dongwm') 18 | 19 | def test_patch_request(self): 20 | api_result = mock.Mock(return_value=self.result) 21 | with mock.patch('client.api_requst', api_result): 22 | self.assertEqual(client.get_review_author( 23 | 'http://api.dongwm.com/review/123'), 'dongwm') 24 | -------------------------------------------------------------------------------- /Exercises/UnitTest/ut_case.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import unittest 3 | 4 | from collections import Counter 5 | 6 | class TestCounter(unittest.TestCase): 7 | def setUp(self): 8 | self.c = Counter('abcdaba') 9 | print 'setUp starting ...' 10 | 11 | # test function should start with test_ 12 | def test_basics(self): 13 | c = self.c 14 | self.assertEqual(c, Counter(a=3, b=2, c=1, d=1)) 15 | self.assertIsInstance(c, dict) 16 | self.assertEqual(len(c), 4) 17 | self.assertIn('a', c) 18 | self.assertNotIn('f', c) 19 | self.assertRaises(TypeError, hash, c) 20 | 21 | def test_update(self): 22 | c = self.c 23 | c.update(f=1) 24 | self.assertEqual(c, Counter(a=3, b=2, c=1, d=1, f=1)) 25 | c.update(a=10) 26 | self.assertEqual(c, Counter(a=13, b=2, c=1, d=1, f=1)) 27 | 28 | def tearDown(self): 29 | print 'tearDown starting...' 30 | 31 | if __name__ == '__main__': 32 | unittest.main() 33 | -------------------------------------------------------------------------------- /Exercises/UnitTest/ut_suite.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import unittest 4 | 5 | from collections import Counter 6 | 7 | class TestCounter(unittest.TestCase): 8 | def setUp(self): 9 | self.c = Counter('abcdaba') 10 | print('setUp starting ...') 11 | 12 | def runTest(self): 13 | c = self.c 14 | self.assertEqual(c, Counter(a=3, b=2, c=1, d=1)) 15 | 16 | def tearDown(self): 17 | print('tearDown starting ...') 18 | 19 | if __name__ == '__main__': 20 | suite = unittest.TestSuite() 21 | suite.addTest(TestCounter()) 22 | runner = unittest.TextTestRunner() 23 | runner.run(suite) 24 | -------------------------------------------------------------------------------- /Exercises/UnitTest/ut_suite_with_case.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import unittest 4 | from ut_case import TestCounter 5 | 6 | 7 | if __name__ == '__main__': 8 | suite = unittest.TestSuite() 9 | suite.addTest(TestCounter('test_basics')) 10 | suite.addTest(TestCounter('test_update')) 11 | runner = unittest.TextTestRunner() 12 | runner.run(suite) 13 | -------------------------------------------------------------------------------- /Exercises/WSGI/hello.py: -------------------------------------------------------------------------------- 1 | def application(environ, start_response): 2 | start_response('200 OK', [('Content-Type', 'text/html')]) 3 | return '

Hello %s!

' % (environ['PATH_INFO'][1:] or 'World') 4 | -------------------------------------------------------------------------------- /Exercises/WSGI/server.py: -------------------------------------------------------------------------------- 1 | from wsgiref.simple_server import make_server 2 | from hello import application 3 | 4 | httpd = make_server('', 8000, application) 5 | print "Serving HTTP on port 8000..." 6 | 7 | httpd.serve_forever() 8 | -------------------------------------------------------------------------------- /Exercises/aiohttp/client.py: -------------------------------------------------------------------------------- 1 | import aiohttp 2 | import asyncio 3 | import async_timeout 4 | 5 | async def fetch(session, url): 6 | with async_timeout.timeout(10): 7 | async with session.get(url) as response: 8 | return await response.text() 9 | 10 | async def main(loop): 11 | async with aiohttp.ClientSession(loop=loop) as session: 12 | html = await fetch(session, 'https://www.python.org') 13 | print(html) 14 | 15 | loop = asyncio.get_event_loop() 16 | loop.run_until_complete(main(loop)) 17 | -------------------------------------------------------------------------------- /Exercises/aiohttp/server.py: -------------------------------------------------------------------------------- 1 | from aiohttp import web 2 | 3 | async def handle(request): 4 | name = request.match_info.get('name', "Anomymous") 5 | text = "Hello, " + name 6 | return web.Response(text=text) 7 | 8 | app = web.Application() 9 | app.router.add_get('/', handle) 10 | app.router.add_get('/{name}', handle) 11 | 12 | web.run_app(app) 13 | -------------------------------------------------------------------------------- /Exercises/changePermission.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | with open('ex.txt') as f: 4 | stat = os.stat(f.fileno()) 5 | os.chmod(f.fileno(), 0o640) 6 | -------------------------------------------------------------------------------- /Exercises/fork.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | f = open("ex.txt", mode="rb", buffering=0) 4 | pid = os.fork() 5 | print("getpid {:>5}, fork {:>5}, fd {}: {}".format(os.getpid(), pid, f.fileno(), f.read(6))) 6 | f.close() 7 | -------------------------------------------------------------------------------- /Exercises/forkp.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | def child(): 4 | print "We are in the child process with PID= %d"%os.getpid() 5 | 6 | def parent(): 7 | print "We are in the parent process with PID= %d"%os.getpid() 8 | newRef=os.fork() 9 | if newRef==0: 10 | child() 11 | else: 12 | print "We are in the parent process and our child process has PID= %d"%newRef 13 | 14 | parent() 15 | -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/app/README: -------------------------------------------------------------------------------- 1 | Your application code should be placed in this directory. 2 | 3 | The native code will be looking for a apptest/__main__.py file as the entry point. -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/app_packages/README: -------------------------------------------------------------------------------- 1 | This directory exists so that 3rd party packages can be installed here. 2 | -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/app_packages/rubicon/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | try: 3 | # If we're on iOS, we won't have pkg-resources; but then, 4 | # we won't need to register the namespace package, either. 5 | # Ignore the error if it occurs. 6 | __import__("pkg_resources").declare_namespace(__name__) 7 | except ImportError: 8 | print('Rubicon namespace package not registered!') 9 | -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/app_packages/rubicon/objc/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function, absolute_import, division, unicode_literals 2 | 3 | __version__ = '0.1.3' 4 | 5 | from .objc import ( 6 | objc, send_message, send_super, 7 | get_selector, 8 | ObjCClass, ObjCInstance, NSObject, 9 | objc_ivar, objc_rawmethod, objc_method, objc_classmethod 10 | ) 11 | 12 | from .core_foundation import at, to_str, to_number, to_value, to_set, to_list 13 | 14 | from .types import ( 15 | text, 16 | NSInteger, NSUInteger, 17 | CGFloat, 18 | NSPointEncoding, NSSizeEncoding, NSRectEncoding, NSRangeEncoding, 19 | CGPoint, NSPoint, 20 | CGSize, NSSize, 21 | CGRect, NSRect, 22 | CGSizeMake, NSMakeSize, 23 | CGRectMake, NSMakeRect, 24 | CGPointMake, NSMakePoint, 25 | NSTimeInterval, 26 | CFIndex, UniChar, unichar, CGGlyph, 27 | CFRange, NSRange, 28 | NSZeroPoint 29 | ) 30 | -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest.xcodeproj/project.xcworkspace/xcuserdata/fujun.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest.xcodeproj/project.xcworkspace/xcuserdata/fujun.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest.xcodeproj/xcuserdata/fujun.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest.xcodeproj/xcuserdata/fujun.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | apptest.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 60796EE119190F4100A9926B 16 | 17 | primary 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-120.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-120.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-152.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-167.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-167.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-180.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-180.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-29.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-29.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-40.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-40.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-58.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-58.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-76.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-76.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-80.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-80.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-87.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/AppIcon.appiconset/icon-87.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-1024x768.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-1024x768.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-1536x2048.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-1536x2048.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-2048x1536.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-2048x1536.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-640x1136.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-640x1136.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-640x960.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-640x960.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-768x1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsonglew/learn-python/edbf0b5d24bf0e2d9ad7aa5811c7d3aa0a66b57c/Exercises/iOSDemoWithPython/apptest/Images.xcassets/LaunchImage.launchimage/launch-768x1024.png -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/apptest-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header 3 | // 4 | // The contents of this file are implicitly included at the beginning of every source file. 5 | // 6 | 7 | #import 8 | 9 | #ifndef __IPHONE_3_0 10 | #warning "This project uses features only available in iOS SDK 3.0 and later." 11 | #endif 12 | 13 | #ifdef __OBJC__ 14 | #import 15 | #import 16 | #endif 17 | -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/apptest/en.lproj/InfoPlist.strings: -------------------------------------------------------------------------------- 1 | /* Localized versions of Info.plist keys */ 2 | 3 | -------------------------------------------------------------------------------- /Exercises/iOSDemoWithPython/untitled.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: utf-8 -*- 3 | 4 | from ctypes import cdll 5 | from ctypes import util 6 | from rubicon.objc import ObjCClass, objc_method 7 | # 载入Foundation框架 8 | cdll.LoadLibrary(util.find_library('Foundation')) 9 | # 获取NSArray类 10 | NSArray = ObjCClass("NSArray") 11 | # 等同于 12 | # NSArray *myArray = [NSArray arrayWithObjects:@"ok", @"ok1", @"ok2", nil] 13 | myArray = NSArray.arrayWithObjects_("ok", "ok1", "ok2", None) 14 | 15 | print myArray.count 16 | print myArray.indexOfObject_("ok2") 17 | 18 | -------------------------------------------------------------------------------- /Exercises/iterator_and_generator/countdown.py: -------------------------------------------------------------------------------- 1 | class countdown(object): 2 | """class iterator countdown""" 3 | def __init__(self, count): 4 | self.count = count 5 | 6 | def __iter__(self): 7 | return self 8 | 9 | def next(self): 10 | if self.count <= 0: 11 | raise StopIteration 12 | t = self.count 13 | self.count -= 1 14 | return t 15 | 16 | 17 | def countdown2(n): 18 | while n > 0: 19 | yield n 20 | n -= 1 21 | 22 | 23 | def countdown3(n): 24 | print "Executing countdown ..." 25 | while n > 0: 26 | yield n 27 | n -= 1 28 | -------------------------------------------------------------------------------- /Exercises/iterator_and_generator/generator_read_file.py: -------------------------------------------------------------------------------- 1 | # Note: At no point in our generator solution did we ever create large 2 | # temporary lists 3 | # it was based on the concept of pipelining data between different components 4 | wwwlog = open("big-access-log") 5 | bytecolumn = (line.rsplit(None,1)[1] for line in wwwlog) 6 | bytes = (int(x) for x in bytecolumn if x != '-') 7 | print "Total", sum(bytes) 8 | -------------------------------------------------------------------------------- /Exercises/iterator_and_generator/iteration.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | def get_a_index(string): 4 | for index, word in enumerate(string): 5 | if word == 'a': 6 | yield index 7 | 8 | string = "this is a string" 9 | indexs = get_a_index(string) 10 | 11 | for i in indexs: 12 | print i 13 | 14 | # indexs has iterated for one turn, next(indexs) this would trigger a 15 | # StopIteration Error 16 | # define a iterable object could solve this problem 17 | 18 | class LoopIter(object): 19 | def __init__(self, data): 20 | self.data = data 21 | 22 | def __iter__(self): 23 | for index, word in enumerate(self.data): 24 | if word == 'a': 25 | yield index 26 | 27 | indexs = LoopIter(string) 28 | 29 | for i in indexs: 30 | print i 31 | for i in indexs: 32 | print i 33 | -------------------------------------------------------------------------------- /Exercises/iterator_and_generator/recv_count.py: -------------------------------------------------------------------------------- 1 | # recv_count.py 2 | # Think of this function as receiving values rather than generating them 3 | 4 | def recv_count(): 5 | try: 6 | while True: 7 | n = (yield) 8 | print "T-minus", n 9 | except GeneratorExit: 10 | print "Kaboom!" 11 | 12 | r = recv_count() 13 | r.next() # r.send(None) 14 | -------------------------------------------------------------------------------- /Exercises/sieveEratosthenes.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | 3 | 4 | def sieve(n): 5 | before_sieve = [1] * (n+1) 6 | before_sieve[0] = 0 7 | before_sieve[1] = 0 8 | for i in range(2, (n+1)/2): 9 | j = 2 10 | while(j*i < n+1): 11 | before_sieve[j*i] = 0 12 | j += 1 13 | return before_sieve 14 | 15 | def main(n): 16 | after_sieve = sieve(n) 17 | for i in range(n+1): 18 | if after_sieve[i] == 1: 19 | print '%d ' % i, 20 | 21 | main(100) 22 | -------------------------------------------------------------------------------- /Exercises/stack.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | class Stack(): 4 | """模拟栈""" 5 | def __init__(self): 6 | self.items = [] 7 | 8 | def isEmpty(self): 9 | return len(self.items)==0 10 | 11 | def push(self, item): 12 | self.items.append(item) 13 | 14 | def pop(self): 15 | return self.items.pop() 16 | 17 | def peek(self): 18 | if not self.isEmpty(): 19 | return self.items[len(self.items)-1] 20 | 21 | def size(self): 22 | return len(self.items) 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### The Zen of Python 2 | 3 | Beautiful is better than ugly. 4 | 5 | Explicit is better than implicit. 6 | 7 | Simple is better than complex. 8 | 9 | Complex is better than complicated. 10 | 11 | Flat is better than nested. 12 | 13 | Sparse is better than dense. 14 | 15 | Readability counts. 16 | 17 | Special cases aren't special enough to break the rules. 18 | 19 | Although practicality beats purity. 20 | 21 | Errors should never pass silently. 22 | 23 | Unless explicitly silenced. 24 | 25 | In the face of ambiguity, refuse the temptation to guess. 26 | 27 | There should be one-- and preferably only one --obvious way to do it. 28 | 29 | Although that way may not be obvious at first unless you're Dutch. 30 | 31 | Now is better than never. 32 | 33 | Although never is often better than *right* now. 34 | 35 | If the implementation is hard to explain, it's a bad idea. 36 | 37 | If the implementation is easy to explain, it may be a good idea. 38 | 39 | Namespaces are one honking great idea -- let's do more of those! 40 | --------------------------------------------------------------------------------