├── .gitignore
├── Others
├── Algorithm
│ ├── __init__.py
│ └── sort
│ │ ├── __init__.py
│ │ └── insertion_sort.py
├── Application
│ ├── .DS_Store
│ ├── Appium
│ │ ├── __init__.py
│ │ ├── android_contacts.py
│ │ ├── android_weixin.py
│ │ ├── ios_complex.py
│ │ ├── ios_sauce.py
│ │ ├── ios_sauce_webview.py
│ │ ├── ios_simple.py
│ │ └── ios_webview.py
│ ├── AtxSample
│ │ ├── __init__.py
│ │ └── control_calc.py
│ ├── MTS
│ │ ├── Request.py
│ │ ├── Scheduler.py
│ │ ├── SimpleDB.py
│ │ ├── __init__.py
│ │ ├── settings.py
│ │ ├── static
│ │ │ ├── css
│ │ │ │ ├── bootstrap-theme.css
│ │ │ │ ├── bootstrap-theme.css.map
│ │ │ │ ├── bootstrap-theme.min.css
│ │ │ │ ├── bootstrap.css
│ │ │ │ ├── bootstrap.css.map
│ │ │ │ ├── bootstrap.min.css
│ │ │ │ ├── dashboard.css
│ │ │ │ ├── jumbotron-narrow.css
│ │ │ │ └── signin.css
│ │ │ ├── fonts
│ │ │ │ ├── glyphicons-halflings-regular.eot
│ │ │ │ ├── glyphicons-halflings-regular.svg
│ │ │ │ ├── glyphicons-halflings-regular.ttf
│ │ │ │ ├── glyphicons-halflings-regular.woff
│ │ │ │ └── glyphicons-halflings-regular.woff2
│ │ │ ├── images
│ │ │ │ ├── dfyz.gif
│ │ │ │ ├── lanqiu.jpg
│ │ │ │ ├── logo.jpg
│ │ │ │ ├── paiqiu.jpg
│ │ │ │ └── yumaoqiu.jpg
│ │ │ └── js
│ │ │ │ ├── bootstrap.js
│ │ │ │ ├── bootstrap.min.js
│ │ │ │ ├── holder.js
│ │ │ │ ├── jquery.min.js
│ │ │ │ └── npm.js
│ │ ├── task_scheduler.py
│ │ ├── templates
│ │ │ ├── about.html
│ │ │ ├── auth_create.html
│ │ │ ├── auth_login.html
│ │ │ ├── dashboard.html
│ │ │ ├── detail.html
│ │ │ ├── index.html
│ │ │ ├── main_user.html
│ │ │ ├── main_visitor.html
│ │ │ ├── modules
│ │ │ │ └── testcase.html
│ │ │ ├── task_submit.html
│ │ │ ├── task_view.html
│ │ │ ├── temp.html
│ │ │ ├── test_add.html
│ │ │ ├── test_run.html
│ │ │ ├── test_upload.html
│ │ │ └── test_view.html
│ │ ├── test
│ │ │ ├── __init__.py
│ │ │ ├── gets.py
│ │ │ ├── hello.py
│ │ │ ├── helloworld.py
│ │ │ ├── poemmaker.py
│ │ │ ├── string_service.py
│ │ │ └── string_test.py
│ │ ├── uploads
│ │ │ ├── 060836ab-c6ff-49a6-bed5-d589d6bc95c0.tc
│ │ │ ├── 08fd628f-d4a0-4379-afa6-11bfb1ba6bc6.tc
│ │ │ ├── 0e579558-2567-4be0-a4b2-ab852090b6c3.tc
│ │ │ ├── 0eb10481-140b-4e99-a3e5-e6ab362301fe.tc
│ │ │ ├── 18cb0406-0cd7-4c14-b821-971f2dadac9f.tc
│ │ │ ├── 58564db8-757d-4faa-93cd-a895ddda69c4.tc
│ │ │ ├── a7d8e5fd-b7fa-4177-854a-3499abf90743.tc
│ │ │ ├── b35c69b6-3c78-4835-9296-9254dd18dd39.tc
│ │ │ ├── ba3209d8-77ba-4b11-9951-96999858956f.tc
│ │ │ ├── e8434d50-62bc-4aa2-9ecc-463c46c159f5.tc
│ │ │ └── e8822765-8ec3-455b-82fb-da4b51cc6ec1.tc
│ │ └── web_server.py
│ ├── __init__.py
│ ├── microblog
│ │ ├── __init__.py
│ │ ├── app.db
│ │ ├── app
│ │ │ ├── __init__.py
│ │ │ ├── forms.py
│ │ │ ├── models.py
│ │ │ ├── run.py
│ │ │ ├── templates
│ │ │ │ ├── base.html
│ │ │ │ ├── index.html
│ │ │ │ └── login.html
│ │ │ └── views.py
│ │ ├── config.py
│ │ ├── db_create.py
│ │ ├── db_downgrade.py
│ │ ├── db_migrate.py
│ │ ├── db_repository
│ │ │ ├── README
│ │ │ ├── __init__.py
│ │ │ ├── manage.py
│ │ │ ├── migrate.cfg
│ │ │ └── versions
│ │ │ │ ├── 001_migration.py
│ │ │ │ └── __init__.py
│ │ └── db_upgrade.py
│ ├── name_stat
│ │ ├── __init__.py
│ │ ├── film_name_stat.py
│ │ ├── name.txt
│ │ └── named_stat.py
│ ├── parallel_doing
│ │ ├── __init__.py
│ │ ├── main.py
│ │ └── setting_parallel.py
│ ├── project_analysis
│ │ ├── Library_analysis.py
│ │ ├── __init__.py
│ │ ├── function_analysis.py
│ │ ├── keyword_analysis.py
│ │ ├── log_lines_length.py
│ │ └── short_log_query.py
│ ├── selenium
│ │ ├── __init__.py
│ │ └── test_baidu.py
│ └── understand_python
│ │ ├── __init__.py
│ │ ├── defaultdict_sample.py
│ │ ├── json
│ │ ├── dump_load.py
│ │ └── dumps_loads.py
│ │ ├── subprocess1.py
│ │ ├── system_sample.py
│ │ └── system_test.py
├── Builtin
│ ├── __init__.py
│ ├── basestring_sample.py
│ ├── bytearray_sample.py
│ ├── call_sample.py
│ ├── callable_sample.py
│ ├── cmp_sample.py
│ ├── compile_sample.py
│ ├── complex_sample.py
│ ├── delattr_sample.py
│ ├── divmod_sample.py
│ ├── eval_sample.py
│ ├── generator
│ │ ├── __init__.py
│ │ └── zrange.py
│ ├── id_sample.py
│ ├── iterator
│ │ ├── __init__.py
│ │ ├── __iter__iterator.py
│ │ ├── myrange.py
│ │ └── zrange.py
│ └── meta_class
│ │ ├── __init__.py
│ │ └── upper_meta_class.py
├── Classes
│ ├── __init__.py
│ ├── all_are_class.py
│ ├── all_function.py
│ ├── class_method.py
│ ├── get_set_attr.py
│ ├── getattribute.py
│ ├── new_function.py
│ ├── property1.py
│ ├── property2.py
│ ├── return_class.py
│ ├── static_method.py
│ ├── str_and_repr.py
│ ├── super
│ │ ├── __init__.py
│ │ ├── super_init1.py
│ │ ├── super_init2.py
│ │ ├── super_method.py
│ │ └── super_mro.py
│ ├── vars_of_class_instance1.py
│ ├── vars_of_class_instance2.py
│ └── vars_of_class_instance3.py
├── Concurrency
│ ├── __init__.py
│ ├── fork.py
│ ├── gevent
│ │ ├── __init__.py
│ │ ├── gevent1.py
│ │ ├── gevent2.py
│ │ └── gevent3.py
│ ├── multiprocessing
│ │ ├── __init__.py
│ │ ├── multi_processing.py
│ │ ├── pool_example.py
│ │ └── process_communication.py
│ ├── subprocess_call.py
│ ├── threading
│ │ ├── ThreadLocal.py
│ │ ├── __init__.py
│ │ ├── threading_sample.py
│ │ ├── threading_timer_cancel.py
│ │ └── threading_timer_start.py
│ └── threadpool
│ │ ├── __init__.py
│ │ └── threadpool_sample.py
├── DesignPatterns
│ ├── __init__.py
│ ├── abstract_factory.py
│ ├── borg.py
│ ├── builder.py
│ ├── const
│ │ ├── __init__.py
│ │ ├── const.py
│ │ ├── const_sample.py
│ │ └── constant.py
│ ├── observer.py
│ └── publish_subscribe.py
├── Dicts
│ ├── __init__.py
│ └── hashlib_sample.py
├── Function
│ ├── __init__.py
│ ├── asterisk_param
│ │ ├── __init__.py
│ │ ├── asterisk_param_base.py
│ │ ├── asterisk_param_one.py
│ │ ├── asterisk_param_order.py
│ │ └── asterisk_param_two.py
│ └── recursion
│ │ ├── README.md
│ │ ├── __init__.py
│ │ ├── normal_recursion.py
│ │ ├── tail_call_optimize.py
│ │ └── tail_recursion.py
├── InterviewQuestions
│ ├── Offer
│ │ ├── 65_plus_with_bit_operation.py
│ │ ├── README.md
│ │ └── __init__.py
│ └── __init__.py
├── Lambda
│ ├── __init__.py
│ ├── list_sort_1.py
│ └── list_sort_2.py
├── Lists
│ ├── __init__.py
│ ├── check_list_empty.py
│ ├── connect_list.py
│ ├── reverse_word.py
│ ├── sort_sorted.py
│ ├── update_list.py
│ ├── zip_sample1.py
│ └── zip_sample2.py
├── ML
│ ├── __init__.py
│ └── linear_module.py
├── Modules
│ ├── BDD
│ │ ├── __init__.py
│ │ ├── behave
│ │ │ ├── __init__.py
│ │ │ └── features
│ │ │ │ ├── __init__.py
│ │ │ │ └── fib
│ │ │ │ ├── __init__.py
│ │ │ │ ├── fib.feature
│ │ │ │ └── steps
│ │ │ │ ├── __init__.py
│ │ │ │ └── fib.py
│ │ └── lettuce
│ │ │ ├── __init__.py
│ │ │ └── tests
│ │ │ ├── __init__.py
│ │ │ └── features
│ │ │ ├── __init__.py
│ │ │ ├── steps.py
│ │ │ └── zero.feature
│ ├── Celery
│ │ ├── README.md
│ │ ├── __init__.py
│ │ └── tasks.py
│ ├── HTMLParser
│ │ ├── README.md
│ │ ├── __init__.py
│ │ ├── htmlparser1.py
│ │ └── htmlparser2.py
│ ├── __init__.py
│ ├── avro
│ │ ├── __init__.py
│ │ ├── avro_access.py
│ │ ├── user.avsc
│ │ └── users.avro
│ ├── base64
│ │ ├── __init__.py
│ │ ├── base64_padding.py
│ │ └── base64_sample.py
│ ├── code
│ │ ├── __init__.py
│ │ └── md5
│ │ │ ├── __init__.py
│ │ │ ├── hashlib_md5_string.py
│ │ │ └── md5_string.py
│ ├── collections
│ │ ├── __init__.py
│ │ └── deque_example.py
│ ├── commands
│ │ ├── __init__.py
│ │ └── commands_sample.py
│ ├── cookie
│ │ ├── __init__.py
│ │ ├── cookie.txt
│ │ ├── cookie_from_txt.py
│ │ ├── cookie_items.py
│ │ ├── cookie_login.py
│ │ └── cookie_save.py
│ ├── ctypes
│ │ ├── __init__.py
│ │ ├── a.c
│ │ └── call_so.py
│ ├── database
│ │ ├── __init__.py
│ │ ├── pymongo
│ │ │ ├── __init__.py
│ │ │ └── mongo_sample.py
│ │ └── redis
│ │ │ ├── __init__.py
│ │ │ └── redis_sample.py
│ ├── decimal
│ │ ├── __init__.py
│ │ └── decimal_sample.py
│ ├── envelopes
│ │ ├── __init__.py
│ │ └── envelopes1.py
│ ├── etcd
│ │ ├── __init__.py
│ │ ├── etcd_read.py
│ │ └── etcd_write.py
│ ├── fake.py
│ ├── file
│ │ ├── __init__.py
│ │ ├── new_file.txt
│ │ ├── only_nonexist_write1.py
│ │ ├── only_nonexist_write2.py
│ │ ├── path.py
│ │ └── with.py
│ ├── help_doc_print.py
│ ├── itertools
│ │ ├── README.md
│ │ ├── __init__.py
│ │ └── itertools_sample.py
│ ├── jieba
│ │ └── jieba_cut.py
│ ├── json
│ │ ├── 2501
│ │ │ ├── json2xml
│ │ │ │ ├── expected.xml
│ │ │ │ ├── input.json
│ │ │ │ ├── node.ini
│ │ │ │ ├── temp.xml
│ │ │ │ └── trans.xml
│ │ │ └── xml2json
│ │ │ │ ├── expected.json
│ │ │ │ ├── input.xml
│ │ │ │ ├── node.ini
│ │ │ │ └── trans.xml
│ │ ├── backup
│ │ │ ├── json_diff.py
│ │ │ ├── json_expected.json
│ │ │ ├── keys.ini
│ │ │ ├── output.xml
│ │ │ ├── xml2json.py
│ │ │ ├── xml_input.xml
│ │ │ └── xpath_test.py
│ │ └── xml_json_checker.py
│ ├── kafka
│ │ ├── __init__.py
│ │ └── access_kafka.py
│ ├── math
│ │ ├── gcd_sample.py
│ │ └── inf_nan.py
│ ├── networking
│ │ ├── BaseHTTPServer
│ │ │ ├── HTTPServerDemo.py
│ │ │ ├── README.md
│ │ │ └── __init__.py
│ │ ├── SimpleHTTPServer
│ │ │ ├── README.md
│ │ │ ├── __init__.py
│ │ │ ├── simple_http_server.py
│ │ │ └── simple_http_server_local_only.py
│ │ ├── __init__.py
│ │ ├── beautiful_soup
│ │ │ ├── __init__.py
│ │ │ └── html_content.py
│ │ ├── dpkt
│ │ │ ├── README.md
│ │ │ ├── __init__.py
│ │ │ ├── data
│ │ │ │ └── http.pcap
│ │ │ ├── print_http_requests.py
│ │ │ └── print_udp_requests.py
│ │ ├── email
│ │ │ ├── README.md
│ │ │ ├── __init__.py
│ │ │ ├── send_attached_mail.py
│ │ │ ├── send_html_mail.py
│ │ │ ├── send_image_mail.py
│ │ │ ├── send_mixed_mail.py
│ │ │ ├── send_plain_mail.py
│ │ │ └── send_to_many.py
│ │ ├── ftplib
│ │ │ ├── __init__.py
│ │ │ ├── ftplib-2.py
│ │ │ └── ftplib_1.py
│ │ ├── paramiko
│ │ │ ├── README.md
│ │ │ ├── __init__.py
│ │ │ ├── paramiko_download_file.py
│ │ │ ├── paramiko_remote_exec.py
│ │ │ └── paramiko_upload_file.py
│ │ ├── pcap
│ │ │ ├── README.md
│ │ │ ├── __init__.py
│ │ │ └── livecap.py
│ │ ├── pyftplib
│ │ │ ├── __init__.py
│ │ │ └── ftp_server.py
│ │ ├── requests
│ │ │ ├── __init__.py
│ │ │ ├── download_sample.py
│ │ │ └── requests_sample.py
│ │ ├── scapy
│ │ │ ├── __init__.py
│ │ │ └── scapy_sample.py
│ │ └── urllib
│ │ │ ├── __init__.py
│ │ │ └── urllib_test.py
│ ├── numpy
│ │ ├── __init__.py
│ │ ├── array_math.py
│ │ ├── bool_array_index.py
│ │ ├── broadcasting1.py
│ │ ├── broadcasting2.py
│ │ ├── create.py
│ │ ├── data_type.py
│ │ ├── index_slicing.py
│ │ ├── int_index.py
│ │ ├── int_index_element.py
│ │ ├── matrix_multi.py
│ │ ├── shape.py
│ │ ├── slicing.py
│ │ ├── sum.py
│ │ └── transposing.py
│ ├── openpyxl
│ │ ├── 1234.xlsx
│ │ ├── __init__.py
│ │ ├── openpyxl_read.py
│ │ └── openpyxl_write.py
│ ├── optparse
│ │ ├── __init__.py
│ │ └── optparse_sample.py
│ ├── pandas
│ │ ├── __init__.py
│ │ ├── bool_index.py
│ │ ├── column.py
│ │ ├── csv_read_1.py
│ │ ├── date_range.py
│ │ ├── describe.py
│ │ ├── head_tail.py
│ │ ├── index_columns_values.py
│ │ ├── init_with_dict.py
│ │ ├── loc.py
│ │ ├── series.py
│ │ ├── slice.py
│ │ ├── sort_index.py
│ │ ├── sort_value.py
│ │ ├── t.py
│ │ └── tips.csv
│ ├── re
│ │ ├── __init__.py
│ │ └── re_search.py
│ ├── sh
│ │ ├── __init__.py
│ │ └── sh_sample1.py
│ ├── sklearn
│ │ ├── __init__.py
│ │ └── plot_ols.py
│ ├── socket
│ │ ├── __init__.py
│ │ ├── socket_client.py
│ │ ├── socket_server.py
│ │ ├── udp_client.py
│ │ └── udp_server.py
│ ├── struct
│ │ ├── __init__.py
│ │ └── struct_sample.py
│ ├── sysconfig_sample.py
│ ├── tarfile
│ │ ├── __init__.py
│ │ └── tar_file.py
│ ├── time
│ │ ├── __init__.py
│ │ ├── date
│ │ │ ├── __init__.py
│ │ │ ├── date_string.py
│ │ │ ├── last_friday.py
│ │ │ └── yesterday_tomorrow.py
│ │ └── time
│ │ │ ├── __init__.py
│ │ │ └── time_precision.py
│ ├── unittest
│ │ ├── __init__.py
│ │ └── unittest_sample.py
│ ├── xml
│ │ ├── 22601.xml
│ │ ├── 22602.xml
│ │ ├── Manager.xml
│ │ ├── __init__.py
│ │ ├── create_xml.py
│ │ └── etree_sample.py
│ ├── yaml
│ │ ├── __init__.py
│ │ ├── dsql-config.yml
│ │ └── read_yaml.py
│ └── zipfile
│ │ ├── __init__.py
│ │ └── zip_file.py
├── Questions
│ ├── 3bit_number.py
│ ├── __init__.py
│ ├── codeforce_1a.py
│ ├── multiply_table.py
│ └── reduce_number.py
├── Shells
│ ├── start_ftp_server.sh
│ └── start_http_server.sh
├── Strings
│ ├── __init__.py
│ ├── capwords.py
│ ├── find_in_index.py
│ ├── input_and_raw_input.py
│ ├── is_a_digital.py
│ ├── is_a_string.py
│ ├── ord_chr.py
│ ├── string_format.py
│ ├── string_template.py
│ ├── stringio_and_cstringio.py
│ └── ys_string.py
├── Tuple
│ ├── __init__.py
│ └── tuple_test.py
├── __init__.py
├── bkm
│ ├── __init__.py
│ ├── file
│ │ ├── __init__.py
│ │ ├── file.txt
│ │ ├── get_line_1.py
│ │ ├── get_line_2.py
│ │ ├── get_line_count_1.py
│ │ └── get_line_count_2.py
│ ├── get_host_name.py
│ ├── global_var.py
│ ├── io
│ │ ├── __init__.py
│ │ └── printf_in_python.py
│ ├── is_digit.py
│ ├── skill
│ │ ├── __doc__sample.py
│ │ ├── __init__.py
│ │ ├── filter_sample.py
│ │ └── use_all_for_import.py
│ └── split_list_to_chunk.py
├── block_chain
│ └── pow.py
├── collection
│ ├── 2d_array_exchange.py
│ ├── __init__.py
│ ├── counter
│ │ ├── __init__.py
│ │ ├── counter_access_count.py
│ │ └── counter_init.py
│ ├── defaultdict
│ │ └── __init__.py
│ ├── dict
│ │ ├── __init__.py
│ │ ├── dict_viewitems.py
│ │ └── sort_dict.py
│ ├── heapq
│ │ ├── __init__.py
│ │ └── min_max.py
│ ├── return_elem_for_index.py
│ ├── shuffle_list.py
│ └── test.py
├── count_file.py
├── decorator
│ ├── __init__.py
│ ├── decorator_sample.py
│ ├── log_it.py
│ ├── singleton_sample.py
│ ├── time_this.py
│ ├── understand_decorator1.py
│ └── understand_decorator2.py
├── hidden_features_of_python
│ ├── __init__.py
│ ├── chaining_comparison.py
│ └── enumerate.py
├── mock.py
├── puzzle
│ ├── __init__.py
│ ├── class_static_var.py
│ ├── default_list_param.py
│ └── defaultdict_tree.py
├── standard
│ ├── __init__.py
│ ├── copy
│ │ ├── __init__.py
│ │ ├── copy_1.py
│ │ └── copy_2.py
│ ├── difflib_data.py
│ ├── file
│ │ ├── __init__.py
│ │ ├── dir_copy.py
│ │ ├── dir_delete.py
│ │ ├── file_archive.py
│ │ ├── file_copy.py
│ │ ├── file_rename.py
│ │ ├── infile_replace.py
│ │ └── infile_replace.txt
│ ├── io
│ │ ├── __init__.py
│ │ └── pprint_data.py
│ ├── multiprocessing
│ │ ├── __init__.py
│ │ └── thread_pool.py
│ ├── random_sample.py
│ ├── sys
│ │ ├── __init__.py
│ │ ├── platform_sample.py
│ │ └── sys_args.py
│ ├── time
│ │ ├── __init__.py
│ │ ├── clock_time.py
│ │ ├── date_data.py
│ │ ├── time_data.py
│ │ └── time_instance.py
│ └── turtule_sample.py
└── syntax
│ ├── __init__.py
│ ├── builtin
│ ├── __init__.py
│ ├── dir_function.py
│ └── eq_function.py
│ ├── class
│ ├── __init__.py
│ ├── inner_class.py
│ └── static_var_of_class.py
│ ├── collection
│ ├── __init__.py
│ ├── merge_lists.py
│ ├── named_slice.py
│ ├── set_duplicate_intersection_difference.py
│ └── zip_reverse_dict.py
│ ├── except
│ ├── __init__.py
│ ├── user_defined_exception.py
│ └── user_named_exception_class.py
│ ├── func
│ ├── __init__.py
│ ├── apply_func.py
│ ├── func_return_func.py
│ ├── func_return_lambda.py
│ ├── higher_order_function.py
│ └── pass_func_as_param2.py
│ ├── loop
│ ├── __init__.py
│ └── break_out_of_nested_loops.py
│ ├── other
│ ├── __init__.py
│ ├── dict_get.py
│ ├── dynamic_class.py
│ ├── exec_eval.py
│ ├── for_else.py
│ ├── generator_sample.py
│ ├── if_else.py
│ ├── kwargs_param.py
│ ├── list_and_generator.py
│ ├── list_copy.py
│ ├── list_dict_set_comprehension.py
│ ├── list_in_class.py
│ ├── multi_exception_in_one_line.py
│ ├── range_vs_xrange.py
│ ├── reduce_sample.py
│ ├── repr_sample.py
│ ├── swap_variables.py
│ └── underscore.py
│ └── var_scope
│ ├── __init__.py
│ ├── var_chain.py
│ ├── var_of_block.py
│ └── var_of_local.py
├── README.md
├── bandit_result.html
├── docs
├── Python实践1-Python自动化测试常用库整理.md
├── Python实践10-doctest简介.md
├── Python实践11-装饰器本质.md
├── Python实践12-带参数的装饰器和多层装饰.md
├── Python实践13-正则表达式.md
├── Python实践14-filter()函数.md
├── Python实践15-map()函数.md
├── Python实践16-reduce()函数.md
├── Python实践17-进程池.md
├── Python实践18-可迭代对象和迭代器.md
├── Python实践19-生成器.md
├── Python实践2-用Paramiko实现互信主机间的文件传输.md
├── Python实践20-闭包简介.md
├── Python实践21-PEP 8代码规范整理.md
├── Python实践22-classmethod和staticmethod.md
├── Python实践23-__call__()和callable().md
├── Python实践24-偏函数.md
├── Python实践25-sorted()函数.md
├── Python实践26-使用sorted()函数对字典进行排序.md
├── Python实践27-locals()和globals().md
├── Python实践28-eval()和名称空间.md
├── Python实践29-__future__模块.md
├── Python实践3-用Tenacity提高自动化测试工具的健壮性.md
├── Python实践30-合并字典.md
├── Python实践31-用virtualenv构建Python2和Python3的运行环境.md
├── Python实践32-PyCharm里使用pipenv创建的环境.md
├── Python实践33-为什么要用namedtuple.md
├── Python实践34-读写yaml文件.md
├── Python实践35-引用计数 del 垃圾回收和循环引用.md
├── Python实践36-用setdefault和defaultdict实现项目出现次数的统计.md
├── Python实践37-统计序列中元素的个数.md
├── Python实践38-魔术方法repr.md
├── Python实践39-魔法方法bool.md
├── Python实践4-守护线程.md
├── Python实践40-for和while语句里面的else.md
├── Python实践41-过时的threadpool.md
├── Python实践42-元类快速入门.md
├── Python实践43-sklearn环境安装.md
├── Python实践44-如何实现switch-case.md
├── Python实践45-threadpool任务的多参数和结果收集.md
├── Python实践46-用requests-html获取城区名.md
├── Python实践47-选择Python2还是Python3.md
├── Python实践48-使用records库操作MySQL数据库.md
├── Python实践49-用untangle将xml解析成Python对象.md
├── Python实践5-Python的特点.md
├── Python实践50-用xmltodict将xml转换成字典.md
├── Python实践51-特殊方法__getattr__和__getattribute__.md
├── Python实践52-JSON序列化.md
├── Python实践53-内置json模块和simplejson.md
├── Python实践54-又一个json第三方库demjson.md
├── Python实践55-pickle序列化.md
├── Python实践56-使用装饰器为你的函数计时.md
├── Python实践57-用timeit模块计时.md
├── Python实践58-性能调优之cProfile.md
├── Python实践59-性能调优之代码里面调用cProfile.md
├── Python实践6-模块结构和布局.md
├── Python实践60-性能调优之pstats模块.md
├── Python实践61-configparser模块简介.md
├── Python实践62-列表切片知识点1.md
├── Python实践63-为什么不建议切片时同时指定start, end和stride.md
├── Python实践64-设计并开发链家网爬虫1.md
├── Python实践65-同时支持Python2和Python3.md
├── Python实践66-设计并开发链家网爬虫2.md
├── Python实践67-设计并开发链家网爬虫3.md
├── Python实践68-用xlrd读取Excel文件.md
├── Python实践69-用xlwt写Excel文件.md
├── Python实践7-布尔值False.md
├── Python实践70-用xlutils操作Excel.md
├── Python实践71-解决名称冲突的两种方法.md
├── Python实践72-用StringIO在内存中读写字符串.md
├── Python实践73-匿名函数和lambda.md
├── Python实践74-标准异常类.md
├── Python实践75-使用@property.md
├── Python实践76-多重继承和MRO.md
├── Python实践77-requests库使用代理.md
├── Python实践78-测试框架unittest-1.md
├── Python实践79-测试框架unittest-2.md
├── Python实践8-Python的那些命令行选项.md
├── Python实践80-自定义异常.md
├── Python实践81-使用pprint打印数据.md
├── Python实践82-把Json打得好看点.md
├── Python实践83-assert语句.md
├── Python实践84-pass语句.md
├── Python实践85-测试框架unittest-3.md
├── Python实践86-allpairs模块.md
├── Python实践87-内置函数all和any.md
├── Python实践88-django安装和基本命令.md
├── Python实践89-用yagmail发送邮件.md
├── Python实践9-检查文件是否存在.md
├── Python实践90-三引号.md
├── Python实践91-Python3的print.md
├── Python实践92-可变对象作为函数默认参数.md
├── Python实践93-Python3的pathlib.md
├── Python实践94-标准库weakref.md
└── Python实践95-url转二维码.md
└── practice
├── __init__.py
├── ai
├── datasets
│ ├── 50_Startups.csv
│ ├── movielens
│ │ ├── README.html
│ │ ├── ml-100k
│ │ │ └── u.data
│ │ ├── movies.dat
│ │ └── users.dat
│ └── studentscores.csv
├── distance
│ ├── cos_distance.py
│ ├── e_distance.py
│ ├── hm_distance.py
│ └── m_distance.py
├── fr
│ └── face_recognition_sample.py
├── normal_dist.py
├── pic
│ └── simular
│ │ ├── 1.png
│ │ ├── 2.png
│ │ ├── cosin_sample.py
│ │ ├── pil_sample1.py
│ │ ├── pil_sample2.py
│ │ ├── ssim_sample.py
│ │ └── 我们不一样.png
├── sklearn
│ ├── cf.py
│ ├── dts.py
│ ├── knn.py
│ ├── linear_regression1.py
│ ├── linear_regression2.py
│ ├── logistic_regression.py
│ ├── std_norm.py
│ └── wine_data.csv
└── string_entropy.py
├── application
└── blockchain
│ └── simple_block_chain.py
├── bokeh_sample.py
├── class
├── 20180122
│ └── class_static_method.py
├── 20180123
│ ├── file_sha1.py
│ ├── filehash.py
│ └── some_file.txt
├── 20180205
│ ├── magic_bool.py
│ └── str_repr.py
├── 20180313
│ ├── getattr_order.py
│ └── getattr_sample.py
├── 20180414
│ ├── mro_sample.py
│ └── user_property.py
├── abc_sample.py
└── slot
│ ├── noslot_memory.py
│ ├── slot_memory.py
│ └── slot_sample.py
├── closure
└── 20180121
│ └── closure_vs_class.py
├── collection
├── dict
│ ├── 20180129
│ │ └── dict_merge.py
│ ├── 20180203
│ │ ├── defaultdict_sample.py
│ │ └── setdefault_sample.py
│ └── 20180204
│ │ ├── count_sample.py
│ │ └── counter_sample.py
├── list
│ └── 20180325
│ │ ├── slice1.py
│ │ └── stride.py
├── set
│ ├── set_add_tuple.py
│ └── set_sample.py
└── tuple
│ └── 20180130
│ └── namedtuple_sample.py
├── concurrency
├── asyncio_sample.py
├── coroutines_aiohttp.py
├── coroutines_sample1.py
├── coroutines_sample2.py
├── coroutines_sample3.py
├── coroutines_sample4.py
├── process_pool.py
├── thread_sample.py
├── threading_daemon.py
├── threadpool_executor.py
├── threadpool_params_callback.py
├── threadpool_sample.py
└── tomorrow_sample.py
├── decorator
├── 20180114
│ ├── delay_param.py
│ ├── delay_wrapper.py
│ └── multi_deco.py
├── 20180118
│ └── singleton.py
└── class_decorator.py
├── func
├── default_param_1.py
├── filter_sample.py
├── map_sample.py
├── partial_func.py
├── reduce_sample.py
├── sort_dict.py
└── sorted_sample.py
├── generator
└── 20180117
│ └── prime_generator.py
├── iterator
└── 20180115
│ └── adult_iterator.py
├── lib
├── bisect_sample.py
├── builtin
│ ├── all_any.py
│ ├── pathlib_sample.py
│ ├── print_sample.py
│ └── weakref_sample.py
├── configparser
│ ├── config_parser.py
│ └── db_config.ini
├── copy
│ └── shallow_deep_copy.py
├── csv
│ └── 20180307
│ │ ├── csv_lib.csv
│ │ ├── csv_sample.py
│ │ ├── file_lib.csv
│ │ └── stock.csv
├── difflib
│ └── difflib_sample.py
├── file
│ └── 20180221
│ │ └── file_dir_exists.py
├── future
│ └── 20180128
│ │ ├── p2_division.py
│ │ ├── p2_unicode.py
│ │ ├── p3_division.py
│ │ └── p3_unicode.py
├── glob
│ └── glob_sample.py
├── io
│ └── string_io.py
├── itertools
│ ├── itertools1.py
│ └── itertools2.py
├── json
│ ├── demjson_sample.py
│ ├── dump_load.py
│ ├── dumps_loads.py
│ ├── print_json.py
│ └── user.json
├── mail
│ └── yagmail_sample.py
├── marshal
│ ├── marshal.out
│ ├── marshal_sample.py
│ └── out.bin
├── paramiko_with_key.py
├── pickle
│ ├── pickle_sample.py
│ └── user.pkl
├── plotly_sample.py
├── pprint_sample.py
├── pytesseract
│ ├── tesseract-ocr.py
│ └── zen.png
├── qrcode
│ └── qrcode_url.py
├── records
│ └── 20180311
│ │ └── records_mysql.py
├── request_cache
│ ├── cache.sqlite
│ └── request_cache_sample.py
├── request_html
│ └── lianjia_city_district.py
├── requests
│ └── proxy_sample.py
├── tenacity_sample
│ ├── retry_decorator.py
│ └── try_with_exception.py
├── test
│ ├── 20180223
│ │ └── doctest_sample.py
│ └── allpairs_sample.py
├── unittest
│ ├── test_api.py
│ ├── test_calculator.py
│ ├── unittest_sample1.py
│ ├── unittest_sample_fixture.py
│ └── unittest_suite.py
├── untangle
│ └── untangle_xml.py
├── warnings
│ ├── warnings_sample1.py
│ └── warnings_sample2.py
├── xls
│ ├── copy.xls
│ ├── copy_xls.py
│ ├── new.xls
│ ├── origin.xls
│ ├── read_xls.py
│ └── write_xls.py
├── xmltodict
│ ├── file.xml
│ ├── out.xml
│ └── xmltodict_sample.py
└── yaml
│ └── 20180131
│ ├── PyYAML.yml
│ ├── father.yml
│ ├── ruamel.yml
│ ├── ruamel_yaml_sample.py
│ └── yaml_sample.py
├── module
├── 20180127
│ └── locals_globals.py
└── 20180128
│ ├── eval_globals_locals.py
│ └── eval_str.py
├── profile
├── cProfile
│ ├── bar.py
│ ├── foo.py
│ ├── foobar.py
│ ├── result.out
│ ├── state.py
│ └── stats.py
├── decorator
│ └── fn_timer.py
├── line_profile
│ └── foo.py
├── other
│ ├── domath.py
│ └── multi_process_profiling.py
├── pypy
│ └── pypy_sample.py
├── timeit
│ └── func_timeit.py
└── yappi
│ ├── __init__.py
│ ├── funcs.py
│ └── yappi_sample.py
├── regex
└── 20180114
│ ├── re_module_func.py
│ └── re_object_func.py
├── replace_stdout.py
├── runtime
├── 20180131
│ └── ref_loop.py
├── 20180204
│ ├── hello.py
│ └── read_pyc.py
├── 20180228
│ ├── user_class.py
│ ├── user_metaclass.py
│ └── user_type.py
├── code_block.py
├── compileall_sample.py
├── dis
│ ├── dis_foo.py
│ └── dis_pass.py
├── frame_object.py
├── helloworld.py
└── type
│ └── class_type.py
├── spider
├── 20180117
│ └── bilibili_kichiku.py
└── 20180121
│ ├── create_tag_cloud.py
│ ├── get_novel.py
│ ├── get_tag.py
│ ├── keyword_tag_cloud4.png
│ ├── novel.txt
│ └── rsa.txt
├── syntax
├── assert
│ └── assert_sample.py
├── exception
│ └── user_exception.py
├── loop
│ └── 20180205
│ │ ├── for_else.py
│ │ └── while_else.py
├── nonlocal
│ └── nolocal_sample.py
└── switch_case
│ └── 20180308
│ ├── dict_function.py
│ ├── if_else.py
│ └── switch_with_lambda.py
├── tool
├── import_search.py
└── time_split.py
├── type
└── 20180204
│ ├── false_object.py
│ └── false_value.py
└── unicode
└── 20180115
├── ide_encoding.py
├── text.txt
└── text1.txt
/Others/Algorithm/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Algorithm/sort/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Application/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/.DS_Store
--------------------------------------------------------------------------------
/Others/Application/Appium/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Application/AtxSample/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Application/AtxSample/control_calc.py:
--------------------------------------------------------------------------------
1 | import atx
2 |
3 |
--------------------------------------------------------------------------------
/Others/Application/MTS/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Application/MTS/settings.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # author = ZengYueTian
3 | # date = 2015-04-15
4 |
5 |
6 | __UPLOADS__ = "uploads/"
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Others/Application/MTS/static/fonts/glyphicons-halflings-regular.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/MTS/static/fonts/glyphicons-halflings-regular.eot
--------------------------------------------------------------------------------
/Others/Application/MTS/static/fonts/glyphicons-halflings-regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/MTS/static/fonts/glyphicons-halflings-regular.ttf
--------------------------------------------------------------------------------
/Others/Application/MTS/static/fonts/glyphicons-halflings-regular.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/MTS/static/fonts/glyphicons-halflings-regular.woff
--------------------------------------------------------------------------------
/Others/Application/MTS/static/fonts/glyphicons-halflings-regular.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/MTS/static/fonts/glyphicons-halflings-regular.woff2
--------------------------------------------------------------------------------
/Others/Application/MTS/static/images/dfyz.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/MTS/static/images/dfyz.gif
--------------------------------------------------------------------------------
/Others/Application/MTS/static/images/lanqiu.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/MTS/static/images/lanqiu.jpg
--------------------------------------------------------------------------------
/Others/Application/MTS/static/images/logo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/MTS/static/images/logo.jpg
--------------------------------------------------------------------------------
/Others/Application/MTS/static/images/paiqiu.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/MTS/static/images/paiqiu.jpg
--------------------------------------------------------------------------------
/Others/Application/MTS/static/images/yumaoqiu.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/MTS/static/images/yumaoqiu.jpg
--------------------------------------------------------------------------------
/Others/Application/MTS/static/js/npm.js:
--------------------------------------------------------------------------------
1 | // This file is autogenerated via the `commonjs` Grunt task. You can require() this file in a CommonJS environment.
2 | require('../../js/transition.js')
3 | require('../../js/alert.js')
4 | require('../../js/button.js')
5 | require('../../js/carousel.js')
6 | require('../../js/collapse.js')
7 | require('../../js/dropdown.js')
8 | require('../../js/modal.js')
9 | require('../../js/tooltip.js')
10 | require('../../js/popover.js')
11 | require('../../js/scrollspy.js')
12 | require('../../js/tab.js')
13 | require('../../js/affix.js')
--------------------------------------------------------------------------------
/Others/Application/MTS/templates/about.html:
--------------------------------------------------------------------------------
1 | {% extends "main_visitor.html" %}
2 |
3 |
4 | {% block title %}
5 | 关于我们
6 | {% end %}
7 |
8 |
9 | {% block body %}
10 |
13 |
14 |

15 |
16 |
17 |
云指针比特是国内一流的移动测试服务提供商。
18 |
地址:北京东直门外大街48号,东方银座D座6C。
19 |
20 |
21 | {% end %}
22 |
23 |
--------------------------------------------------------------------------------
/Others/Application/MTS/templates/dashboard.html:
--------------------------------------------------------------------------------
1 | {% extends "main_user.html" %}
2 |
3 |
4 | {% block body %}
5 |
6 |
7 | "hello "
8 |
9 |
10 | {% end %}
--------------------------------------------------------------------------------
/Others/Application/MTS/templates/detail.html:
--------------------------------------------------------------------------------
1 | {% extends "main_visitor.html" %}
2 |
3 |
4 | {% block title %}
5 | 场馆信息
6 | {% end %}
7 |
8 |
9 | {% block body %}
10 |
13 |
14 |
15 |
16 |
17 | {% end %}
18 |
19 |
--------------------------------------------------------------------------------
/Others/Application/MTS/templates/index.html:
--------------------------------------------------------------------------------
1 | {% extends "main_visitor.html" %}
2 |
3 |
4 | {% block title %}
5 | 比特云测试机器人
6 | {% end %}
7 |
8 |
9 | {% block body %}
10 |
13 |
14 |

15 |
16 |
17 | {% end %}
18 |
19 |
--------------------------------------------------------------------------------
/Others/Application/MTS/templates/modules/testcase.html:
--------------------------------------------------------------------------------
1 |
2 |
{{ site["title"] }}
3 |
4 |

5 |
6 |
7 |
联系方式: {{ site["phone"]}}
8 |
9 | 场馆地址: {{ site["address"]}}
10 |
11 |
详细信息:
12 |
{% raw site["description"] %}
13 |
14 |
--------------------------------------------------------------------------------
/Others/Application/MTS/templates/task_submit.html:
--------------------------------------------------------------------------------
1 | {% extends "main_user.html" %}
2 |
3 |
4 | {% block title %}
5 | 提交完成
6 | {% end %}
7 |
8 |
9 | {% block body %}
10 |
13 |
14 |
15 |
16 |
17 |
测试用例: {{testcase}}
18 |
测试设备: {{device}}
19 |
20 |
21 |
22 |
23 | {% end %}
24 |
25 |
--------------------------------------------------------------------------------
/Others/Application/MTS/templates/task_view.html:
--------------------------------------------------------------------------------
1 | {% extends "main_user.html" %}
2 |
3 |
4 |
5 | {% block body %}
6 |
9 |
23 | {% end %}
24 |
25 |
--------------------------------------------------------------------------------
/Others/Application/MTS/templates/test_upload.html:
--------------------------------------------------------------------------------
1 | {% extends "main_user.html" %}
2 |
3 |
4 |
5 |
6 | {% block body %}
7 |
10 |
11 |
12 |
13 |
14 | 测试用例已经保存为文件:{{file}}
15 |
16 |
17 |
18 |
19 | {% end %}
20 |
21 |
--------------------------------------------------------------------------------
/Others/Application/MTS/templates/test_view.html:
--------------------------------------------------------------------------------
1 | {% extends "main_user.html" %}
2 |
3 |
4 |
5 | {% block body %}
6 |
9 |
23 | {% end %}
24 |
25 |
--------------------------------------------------------------------------------
/Others/Application/MTS/test/__init__.py:
--------------------------------------------------------------------------------
1 | __author__ = 'zengyuetian'
2 |
--------------------------------------------------------------------------------
/Others/Application/MTS/test/helloworld.py:
--------------------------------------------------------------------------------
1 | __author__ = 'zengyuetian'
2 |
3 | import tornado.ioloop
4 | import tornado.web
5 |
6 | class MainHandler(tornado.web.RequestHandler):
7 | def get(self):
8 | self.write("Hello world")
9 |
10 |
11 | application = tornado.web.Application([
12 | (r"/", MainHandler),
13 | ])
14 |
15 | if __name__ == "__main__":
16 | application.listen(8888)
17 | tornado.ioloop.IOLoop.instance().start()
18 |
19 |
--------------------------------------------------------------------------------
/Others/Application/MTS/test/poemmaker.py:
--------------------------------------------------------------------------------
1 | __author__ = 'zengyuetian'
2 |
3 | import os.path
4 |
5 | import tornado.httpserver
6 |
--------------------------------------------------------------------------------
/Others/Application/MTS/test/string_test.py:
--------------------------------------------------------------------------------
1 | __author__ = 'zengyuetian'
2 |
3 |
4 | tom = "world"
5 | john = "good"
6 | kitty = "morning"
7 | string = "Hello %s %s %s" %(tom, john, kitty)
8 | print string
9 |
--------------------------------------------------------------------------------
/Others/Application/MTS/uploads/060836ab-c6ff-49a6-bed5-d589d6bc95c0.tc:
--------------------------------------------------------------------------------
1 | tap contacts
2 | tap fengyu
3 | tap message
4 | tap ui_emoji
5 | tap emoji_laugh
6 | tap emoji_laugh
7 | tap emoji_laugh
8 | tap send
9 | wait 5
10 | tap wechat
11 |
--------------------------------------------------------------------------------
/Others/Application/MTS/uploads/08fd628f-d4a0-4379-afa6-11bfb1ba6bc6.tc:
--------------------------------------------------------------------------------
1 | tap contacts
2 | tap fengyu
3 | tap message
4 | tap ui_emoji
5 | tap emoji_laugh
6 | tap emoji_laugh
7 | tap emoji_laugh
8 | tap send
9 | wait 5
10 | tap wechat
11 |
--------------------------------------------------------------------------------
/Others/Application/MTS/uploads/0e579558-2567-4be0-a4b2-ab852090b6c3.tc:
--------------------------------------------------------------------------------
1 | tap contacts
2 | tap fengyu
3 | tap message
4 | tap ui_emoji
5 | tap emoji_laugh
6 | tap emoji_laugh
7 | tap emoji_laugh
8 | tap send
9 | wait 5
10 | tap wechat
11 |
--------------------------------------------------------------------------------
/Others/Application/MTS/uploads/0eb10481-140b-4e99-a3e5-e6ab362301fe.tc:
--------------------------------------------------------------------------------
1 | tap contacts
2 | tap fengyu
3 | tap message
4 | tap ui_emoji
5 | tap emoji_laugh
6 | tap emoji_laugh
7 | tap emoji_laugh
8 | tap send
9 | wait 5
10 | tap wechat
11 |
--------------------------------------------------------------------------------
/Others/Application/MTS/uploads/18cb0406-0cd7-4c14-b821-971f2dadac9f.tc:
--------------------------------------------------------------------------------
1 | tap contacts
2 | tap fengyu
3 | tap message
4 | tap ui_emoji
5 | tap emoji_laugh
6 | tap emoji_laugh
7 | tap emoji_laugh
8 | tap send
9 | wait 5
10 | tap wechat
11 |
--------------------------------------------------------------------------------
/Others/Application/MTS/uploads/58564db8-757d-4faa-93cd-a895ddda69c4.tc:
--------------------------------------------------------------------------------
1 | tap contacts
2 | tap fengyu
3 | tap message
4 | tap ui_emoji
5 | tap emoji_laugh
6 | tap emoji_laugh
7 | tap emoji_laugh
8 | tap send
9 | wait 5
10 | tap wechat
11 |
--------------------------------------------------------------------------------
/Others/Application/MTS/uploads/a7d8e5fd-b7fa-4177-854a-3499abf90743.tc:
--------------------------------------------------------------------------------
1 | tap contacts
2 | tap fengyu
3 | tap message
4 | tap ui_emoji
5 | tap emoji_laugh
6 | tap emoji_laugh
7 | tap emoji_laugh
8 | tap send
9 | wait 5
10 | tap wechat
11 |
--------------------------------------------------------------------------------
/Others/Application/MTS/uploads/b35c69b6-3c78-4835-9296-9254dd18dd39.tc:
--------------------------------------------------------------------------------
1 | tap contacts
2 | tap fengyu
3 | tap message
4 | tap ui_emoji
5 | tap emoji_laugh
6 | tap emoji_laugh
7 | tap emoji_laugh
8 | tap send
9 | wait 5
10 | tap wechat
11 |
--------------------------------------------------------------------------------
/Others/Application/MTS/uploads/ba3209d8-77ba-4b11-9951-96999858956f.tc:
--------------------------------------------------------------------------------
1 | tap contacts
2 | tap fengyu
3 | tap message
4 | tap ui_emoji
5 | tap emoji_laugh
6 | tap emoji_laugh
7 | tap emoji_laugh
8 | tap send
9 | wait 5
10 | tap wechat
11 |
--------------------------------------------------------------------------------
/Others/Application/MTS/uploads/e8434d50-62bc-4aa2-9ecc-463c46c159f5.tc:
--------------------------------------------------------------------------------
1 | tap contacts
2 | tap fengyu
3 | tap message
4 | tap ui_emoji
5 | tap emoji_laugh
6 | tap emoji_laugh
7 | tap emoji_laugh
8 | tap send
9 | wait 5
10 | tap wechat
11 |
--------------------------------------------------------------------------------
/Others/Application/MTS/uploads/e8822765-8ec3-455b-82fb-da4b51cc6ec1.tc:
--------------------------------------------------------------------------------
1 | tap contacts
2 | tap fengyu
3 | tap message
4 | tap ui_emoji
5 | tap emoji_laugh
6 | tap emoji_laugh
7 | tap emoji_laugh
8 | tap send
9 | wait 5
10 | tap wechat
11 |
--------------------------------------------------------------------------------
/Others/Application/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Application/microblog/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Application/microblog/app.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/microblog/app.db
--------------------------------------------------------------------------------
/Others/Application/microblog/app/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | from flask import Flask
4 | from flask_sqlalchemy import SQLAlchemy
5 |
6 | app = Flask(__name__)
7 | app.config.from_object('config')
8 | db = SQLAlchemy(app)
9 |
10 | from app import views, models
11 |
12 |
--------------------------------------------------------------------------------
/Others/Application/microblog/app/forms.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | from flask_wtf import FlaskForm
4 | # from flask.ext.wtf import FlaskForm
5 | from wtforms import StringField, BooleanField
6 | from wtforms.validators import DataRequired
7 |
8 |
9 | class LoginForm(FlaskForm):
10 | openid = StringField('openid', validators=[DataRequired()])
11 | remember_me = BooleanField('remember_me', default=False)
12 |
13 |
--------------------------------------------------------------------------------
/Others/Application/microblog/app/run.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | from app import app
4 | app.run(debug=True)
--------------------------------------------------------------------------------
/Others/Application/microblog/app/templates/index.html:
--------------------------------------------------------------------------------
1 | {% extends "base.html" %}
2 | {% block content %}
3 | Hi, {{user.nickname}}!
4 | {% for post in posts %}
5 | {{post.author.nickname}} says: {{post.body}}
6 | {% endfor %}
7 | {% endblock %}
--------------------------------------------------------------------------------
/Others/Application/microblog/db_create.py:
--------------------------------------------------------------------------------
1 | #!flask/bin/python
2 | from migrate.versioning import api
3 | from config import SQLALCHEMY_DATABASE_URI
4 | from config import SQLALCHEMY_MIGRATE_REPO
5 | from app import db
6 | import os.path
7 | db.create_all()
8 | if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
9 | api.create(SQLALCHEMY_MIGRATE_REPO, 'database repository')
10 | api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
11 | else:
12 | api.version_control(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, api.version(SQLALCHEMY_MIGRATE_REPO))
--------------------------------------------------------------------------------
/Others/Application/microblog/db_downgrade.py:
--------------------------------------------------------------------------------
1 | #!flask/bin/python
2 | from migrate.versioning import api
3 | from config import SQLALCHEMY_DATABASE_URI
4 | from config import SQLALCHEMY_MIGRATE_REPO
5 | v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
6 | api.downgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, v - 1)
7 | print 'Current database version: ' + str(api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO))
--------------------------------------------------------------------------------
/Others/Application/microblog/db_repository/README:
--------------------------------------------------------------------------------
1 | This is a database migration repository.
2 |
3 | More information at
4 | http://code.google.com/p/sqlalchemy-migrate/
5 |
--------------------------------------------------------------------------------
/Others/Application/microblog/db_repository/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/microblog/db_repository/__init__.py
--------------------------------------------------------------------------------
/Others/Application/microblog/db_repository/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | from migrate.versioning.shell import main
3 |
4 | if __name__ == '__main__':
5 | main()
6 |
--------------------------------------------------------------------------------
/Others/Application/microblog/db_repository/versions/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Application/microblog/db_repository/versions/__init__.py
--------------------------------------------------------------------------------
/Others/Application/microblog/db_upgrade.py:
--------------------------------------------------------------------------------
1 | #!flask/bin/python
2 | from migrate.versioning import api
3 | from config import SQLALCHEMY_DATABASE_URI
4 | from config import SQLALCHEMY_MIGRATE_REPO
5 | api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
6 | print 'Current database version: ' + str(api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO))
--------------------------------------------------------------------------------
/Others/Application/name_stat/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Application/parallel_doing/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Application/parallel_doing/main.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import threading
4 | from setting_parallel import *
5 |
6 |
7 | if __name__ == '__main__':
8 | t = Timer(1, handle_list)
9 | t.start()
10 | index = 1000
11 |
12 | t = threading.Thread(target=wait_to_end)
13 | t.start()
14 |
15 | main_thread = threading.currentThread()
16 | for t in threading.enumerate():
17 | if t is not main_thread:
18 | t.join()
19 |
20 | print "end"
21 |
--------------------------------------------------------------------------------
/Others/Application/parallel_doing/setting_parallel.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | from threading import Timer
4 | import time
5 |
6 | num = 0
7 | datas = range(100)
8 |
9 |
10 | def handle_list():
11 | global num
12 | print "-------", datas[num]
13 | t = Timer(1, handle_list)
14 | t.start()
15 | num += 1
16 |
17 |
18 | def wait_to_end():
19 | i = 0
20 | while i < 10000:
21 | print i
22 | i += 1
23 | time.sleep(0.1)
--------------------------------------------------------------------------------
/Others/Application/project_analysis/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Application/project_analysis/log_lines_length.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding:utf-8 -*-
3 |
4 | # 获得log文件行数, 以及最长的行的长度
5 |
6 | # http://stackoverflow.com/questions/2659952/maximum-length-of-http-get-request
7 | # Most web servers have a limit of 8192 bytes (8KB)
8 |
9 | if __name__ == "__main__":
10 | i = 0
11 | length = 0
12 |
13 | for line in open("query.shop.log"):
14 | i += 1
15 | if len(line) > length:
16 | length = len(line)
17 |
18 | print 'total lines ', i
19 | print 'max len is : ', length
20 |
--------------------------------------------------------------------------------
/Others/Application/project_analysis/short_log_query.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding:utf-8 -*-
3 |
4 | # 将日志中行超过特定长度的行去除,用剩下的行生成一个新文件
5 |
6 | length = 500
7 |
8 | if __name__ == "__main__":
9 | i = 0
10 |
11 | new_file = open("query.log.new", "w+")
12 |
13 | for line in open("/query.shop.log"):
14 | if len(line) > length:
15 | i += 1
16 | if i % 100 == 0:
17 | print 'line goes ', i
18 | else:
19 | new_file.writelines(line)
20 | pass
21 | print 'total lines ', i
22 |
--------------------------------------------------------------------------------
/Others/Application/selenium/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Application/selenium/test_baidu.py:
--------------------------------------------------------------------------------
1 | #!/user/bin/env python
2 | # -*-coding:utf-8-*-
3 | # @time : 16/11/8 12:09
4 | # @Author : Zhangxy
5 | # @File : 001baiduSearch.py
6 | # @Software : PyCharm
7 |
8 | from selenium import webdriver
9 |
10 | driver = webdriver.Chrome()
11 |
12 | driver.get("http://www.baidu.com")
13 | driver.find_element_by_link_text(u"登录").click()
14 | # driver.find_element_by_xpath('//*[@id="u1"]/a[8]').click()
15 | # driver.find_element_by_link_text('搜索设置').click()
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Others/Application/understand_python/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Application/understand_python/json/dump_load.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import json
4 |
5 | fname = "json.log"
6 |
7 | list1 = ['selenium', 'appium', 'android', 'ios', 'uiautomator']
8 |
9 | # 把list1先序列化,再写入到一个文件中
10 | print json.dump(list1, open(fname, 'w'))
11 | print u'文件内容为:'
12 | r = open(fname, 'r+')
13 | print r.read()
14 |
15 | # 先读取文件内容,再进行反序列化
16 | res = json.load(open(fname, 'r+'))
17 | print res, u'数据类型:', type(res)
18 |
--------------------------------------------------------------------------------
/Others/Application/understand_python/json/dumps_loads.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import json
4 |
5 | dict1 = {'name': 'wuya', 'age': 22, 'address': 'xian'}
6 |
7 | print u'未序列化前的数据类型为:', type(dict1)
8 | print u'未序列化前的数据:', dict1
9 |
10 | # 对dict1进行序列化的处理
11 | str1 = json.dumps(dict1)
12 | print u'序列化后的数据类型为:', type(str1)
13 | print u'序列化后的数据为:', str1
14 |
15 | # 对str1进行反序列化
16 | dict2 = json.loads(str1)
17 | print u'反序列化后的数据类型:', type(dict2)
18 | print u'反序列化后的数据:', dict2
19 |
--------------------------------------------------------------------------------
/Others/Application/understand_python/subprocess1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # author: Zeng YueTian
3 |
4 | import subprocess
5 |
6 | # Popen启动进程
7 | proc = subprocess.Popen(['echo', 'hello from the child'], stdout=subprocess.PIPE)
8 |
9 | # communicate 用于读取子进程的输出
10 | out, err = proc.communicate()
11 |
12 | print(out.decode('utf-8'))
13 |
14 |
--------------------------------------------------------------------------------
/Others/Application/understand_python/system_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # author: Zeng YueTian
3 |
4 |
5 | import os
6 |
7 | # os.system("python system_test.py")
8 |
9 | os.system("nohup python system_test.py > /dev/null 2>&1 &")
10 | print "done"
--------------------------------------------------------------------------------
/Others/Application/understand_python/system_test.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # author: Zeng YueTian
3 |
4 | import time
5 | for i in range(100):
6 | print i
7 | time.sleep(1)
8 |
--------------------------------------------------------------------------------
/Others/Builtin/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Builtin/basestring_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | basestring是str和unicode的超类(父类),也是抽象类,因此不能被调用和实例化,
4 | 但可以被用来判断一个对象是否为str或者unicode的实例,isinstance(obj, basestring)等价于isinstance(obj, (str, unicode));
5 | 版本:python2.3版本以后引入该函数,兼容python2.3以后python2各版本。注意:python3中舍弃了该函数,所以该函数不能在python3中使用。
6 | """
7 |
8 | print isinstance("Hello world", str)
9 | # True
10 |
11 | print isinstance("Hello world", basestring)
12 | # True
13 |
14 | print isinstance(u"你好", unicode)
15 | # True
16 |
17 | print isinstance(u"你好", basestring)
18 | # True
19 |
--------------------------------------------------------------------------------
/Others/Builtin/call_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | 在Python中,函数也是一种对象。实际上,任何一个有__call__()特殊方法的对象都被当作是函数。
4 | """
5 |
6 |
7 | class SampleMore(object):
8 | def __call__(self, a):
9 | return a+10
10 |
11 |
12 | add = SampleMore()
13 | print(add(2))
14 | print map(add, [2, 4, 6])
15 |
--------------------------------------------------------------------------------
/Others/Builtin/cmp_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # run via python2.7
3 |
4 | """
5 | 它的返回值只有三个,正数,0,负数,下面来看一下:
6 | cmp(x, y)
7 | 中文说明:比较两个对象x和y,如果x < y ,返回负数;x == y, 返回0;x > y,返回正数。
8 | 版本:该函数只有在python2中可用,而且在python2所有版本中都可用。但是在python3中该函数已经被删减掉,这点要特别注意。
9 | """
10 |
11 |
12 | # -1, 0, 1
13 |
14 | print(cmp(1, 2))
15 | print(cmp(1, 1))
16 | print(cmp(5, 2))
17 |
18 | # #注意:这时候它会先比较第一个字符,然后比较第二个字符,逐个比较知道能判断出大小为止。
19 | print(cmp('abcd', 'a'))
20 |
--------------------------------------------------------------------------------
/Others/Builtin/compile_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | __author__ = 'zengyuetian'
3 |
4 | """
5 | 将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。
6 | 参数source:字符串或者AST(Abstract Syntax Trees)对象。
7 | 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。
8 | 参数model:指定编译代码的种类。可以指定为 ‘exec’,’eval’,’single’。
9 | 参数flag和dont_inherit:这两个参数暂不介绍,可选参数。
10 |
11 | 版本:在python2.3、2.6、2.7、3.2中均有不同,使用时要引起注意,兼容python3
12 | """
13 |
14 | code = "for i in range(0, 10): print i"
15 | cmpcode = compile(code, '', 'exec')
16 | exec cmpcode
17 |
18 |
19 | str = "3*4 + 5"
20 | a = compile(str, '', 'eval')
21 | print eval(a)
22 |
--------------------------------------------------------------------------------
/Others/Builtin/complex_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | __author__ = 'zengyuetian'
3 |
4 | """
5 | 创建一个值为real + imag * j的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。
6 | 参数real: int, long, float或字符串;
7 | 参数imag: int, long, float。
8 | """
9 |
10 |
11 | print complex(1, 2)
12 |
13 | print complex(1)
14 |
15 | print complex("1")
16 |
17 | print complex("1+2j")
18 |
19 |
--------------------------------------------------------------------------------
/Others/Builtin/delattr_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | __author__ = 'zengyuetian'
3 |
4 | """
5 | 删除object对象名为name的属性。这个函数的命名真是简单易懂啊,和jquery里面差不多,但是功能不一样哦,注意一下。
6 | 参数object:对象。
7 | 参数name:属性名称字符串。
8 | 版本:各版本中都支持该函数,python3中仍可用。
9 | """
10 |
11 |
12 | class Person(object):
13 | def __init__(self, name, age):
14 | self.name = name
15 | self.age = age
16 |
17 |
18 | tom = Person("Tom", 35)
19 | print dir(tom)
20 |
21 | delattr(tom, 'name')
22 | print dir(tom)
23 |
--------------------------------------------------------------------------------
/Others/Builtin/divmod_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | __author__ = 'zengyuetian'
3 |
4 | """
5 | divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数
6 | 返回结果类型为tuple
7 | 参数:
8 | a,b可以为数字(包括复数)
9 | 版本:
10 | 在python2.3版本之前不允许处理复数,这个大家要注意一下
11 | """
12 |
13 | print divmod(9, 2)
14 | print divmod(11, 3)
15 | print divmod(1+2j, 1+0.5j)
16 |
17 |
--------------------------------------------------------------------------------
/Others/Builtin/eval_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
4 |
5 | b = eval(a)
6 | print b
7 | print type(b)
8 |
9 | a = "{1: 'a', 2: 'b'}"
10 | b = eval(a)
11 | print b
12 | print type(b)
13 |
14 | a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
15 | b = eval(a)
16 | print b
17 | print type(b)
18 |
--------------------------------------------------------------------------------
/Others/Builtin/generator/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Builtin/iterator/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Builtin/iterator/__iter__iterator.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | __iter__ 方法会返回一个迭代器iterator
4 | 迭代器是拥有next(__next__)方法的对象,调用next时会返回下一个值
5 | """
6 |
7 |
8 | class Fibs(object):
9 | def __init__(self):
10 | self.a = 0
11 | self.b = 1
12 |
13 | def next(self):
14 | self.a, self.b = self.b, self.a + self.b
15 | return self.a
16 |
17 | def __iter__(self):
18 | return self
19 |
20 | fibs = Fibs()
21 | for f in fibs:
22 | if f > 1000:
23 | print f
24 | break
--------------------------------------------------------------------------------
/Others/Builtin/meta_class/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Classes/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Classes/all_function.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import copy
4 |
5 | print [n for n in dir(copy) if not n.startswith('_')]
6 |
7 | # __all__表示 从模块导入所有名字代表什么含义 from copy import *
8 | # __all__会将没有指定的变量,类和函数过滤出去
9 | # 如果没有定义__all__, import *会默认导入所有不以下划线开头的全局名称
10 | print copy.__all__
--------------------------------------------------------------------------------
/Others/Classes/class_method.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | 类方法是将类本身作为对象进行操作的方法。类方法使用@classmethod装饰器定义,
4 | 其第一个参数是类,约定写为cls。类对象和实例都可以调用类方法
5 | """
6 |
7 |
8 | class MyClass(object):
9 | @classmethod
10 | def get_max_value(cls):
11 | return 100
12 |
13 | print MyClass.get_max_value()
14 | cl = MyClass()
15 | print cl.get_max_value()
16 |
17 |
--------------------------------------------------------------------------------
/Others/Classes/getattribute.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | __getattribute__, 当特性被访问时自动调用(只能在新式类中使用)
4 |
5 |
6 | """
7 |
8 |
9 | class Rectangle(object):
10 | def __init__(self):
11 | self.width = 0
12 | self.height = 0
13 |
14 | def __getattribute__(self, item):
15 | print "visit item: {0}".format(item)
16 | return object.__getattribute__(self, item)
17 |
18 |
19 | rect = Rectangle()
20 | print rect.width
21 |
22 |
--------------------------------------------------------------------------------
/Others/Classes/property2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | property函数创建了一个属性,其中的访问器函数被当做参数(先取值,后赋值)
4 |
5 |
6 | """
7 |
8 |
9 | class Rectangle(object):
10 | def __init__(self):
11 | self.width = 0
12 | self.height = 0
13 |
14 | def get_size(self):
15 | return self.width, self.height
16 |
17 | def set_size(self, size):
18 | self.width, self.height = size
19 |
20 | # property函数创建了一个属性,其中的访问器函数被当做参数(先取值,后赋值)
21 | size = property(get_size, set_size)
22 |
23 | r = Rectangle()
24 | r.size = (10, 20)
25 | print r.size
26 |
--------------------------------------------------------------------------------
/Others/Classes/return_class.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 |
4 | def choose_class(name):
5 | if name == 'foo':
6 | class Foo(object):
7 | pass
8 | return Foo
9 | else:
10 | class Bar(object):
11 | pass
12 | return Bar
13 |
14 | MyClass = choose_class('foo')
15 | print MyClass
16 |
--------------------------------------------------------------------------------
/Others/Classes/static_method.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | 静态方法是一种普通函数,就位于类定义的命名空间中,它不会对任何实例类型进行操作。
4 | 使用装饰器@staticmethod定义静态方法。
5 | 类对象和实例都可以调用静态方法
6 | """
7 |
8 |
9 | class MyClass(object):
10 | @staticmethod
11 | def get_max_value():
12 | return 100
13 |
14 | print MyClass.get_max_value()
15 |
--------------------------------------------------------------------------------
/Others/Classes/super/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Classes/super/super_init1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 子类(派生类)并不会自动调用父类(基类)的init方法
4 | # 需要子类主动调用父类的init
5 |
6 | # 方法1
7 |
8 |
9 | class Foo(object):
10 | def __init__(self):
11 | self.val = 1
12 |
13 |
14 | class Foo2(Foo):
15 | def __init__(self):
16 | Foo.__init__(self)
17 | print self.val
18 |
19 |
20 | if __name__ == '__main__':
21 | foo2 = Foo2()
22 |
--------------------------------------------------------------------------------
/Others/Classes/super/super_init2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 子类(派生类)并不会自动调用父类(基类)的init方法
4 | # 需要子类主动调用父类的init
5 |
6 | # 方法2
7 |
8 |
9 | class Foo(object):
10 | def __init__(self):
11 | self.val = 1
12 |
13 |
14 | class Foo2(Foo):
15 | def __init__(self):
16 | super(Foo2, self).__init__()
17 | print self.val
18 |
19 |
20 | if __name__ == '__main__':
21 | foo2 = Foo2()
--------------------------------------------------------------------------------
/Others/Classes/super/super_method.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # super用来执行父类中的函数
3 |
4 |
5 | class Foo(object):
6 | def hi(self):
7 | print 'hi,Foo'
8 |
9 |
10 | class Foo2(Foo):
11 | def hi(self):
12 | super(Foo2, self).hi()
13 |
14 |
15 | if __name__ == '__main__':
16 | foo2 = Foo2()
17 | foo2.hi()
18 |
--------------------------------------------------------------------------------
/Others/Classes/vars_of_class_instance1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 类变量定义在类的定义之后,
4 | # 实例变量则是以为self.开头
5 |
6 |
7 | class Foo(object):
8 | val = 0
9 |
10 | def __init__(self):
11 | self.val = 1
12 |
13 |
14 | if __name__ == '__main__':
15 | foo = Foo()
16 | print foo.val # 1
17 | print Foo.val # 0
18 |
19 |
--------------------------------------------------------------------------------
/Others/Classes/vars_of_class_instance2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 实例也能够访问类变量,如下:
4 | # 复制代码
5 |
6 |
7 | class Foo(object):
8 |
9 | val = 0
10 |
11 | def __init__(self):
12 | pass
13 |
14 | if __name__ == '__main__':
15 | foo = Foo()
16 | print foo.val # 0
17 | print Foo.val # 0
18 |
--------------------------------------------------------------------------------
/Others/Classes/vars_of_class_instance3.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 可以通过以下方式访问类变量
4 |
5 |
6 | class Foo(object):
7 |
8 | val = 3
9 |
10 | def __init__(self):
11 | print self.__class__.val
12 |
13 |
14 | if __name__ == '__main__':
15 | foo = Foo()
--------------------------------------------------------------------------------
/Others/Concurrency/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Concurrency/fork.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import os
4 |
5 | print 'Process (%s) start...' % os.getpid()
6 |
7 | pid = os.fork()
8 | if pid == 0:
9 | print "I am child process (%s) and my parent is %s" % (os.getpid(), os.getppid())
10 |
11 | else:
12 | print "I (%s) just create a child process (%s)" % (os.getpid(), pid)
13 |
--------------------------------------------------------------------------------
/Others/Concurrency/gevent/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Concurrency/gevent/gevent2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | """
4 | 要让greenlet交替运行,可以通过gevent.sleep()交出控制权:
5 | """
6 |
7 | from gevent import monkey
8 | monkey.patch_socket()
9 | import gevent
10 |
11 | def f(n):
12 | for i in range(n):
13 | print gevent.getcurrent(), i
14 | gevent.sleep(0)
15 |
16 | g1 = gevent.spawn(f, 5)
17 | g2 = gevent.spawn(f, 5)
18 | g3 = gevent.spawn(f, 5)
19 | g1.join()
20 | g2.join()
21 | g3.join()
22 |
--------------------------------------------------------------------------------
/Others/Concurrency/multiprocessing/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Concurrency/multiprocessing/multi_processing.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | from multiprocessing import Process
3 | import os
4 |
5 |
6 | def run_proc(name):
7 | print "Run child process %s (%s)" %(name, os.getpid())
8 |
9 | if __name__ == "__main__":
10 | print "Parent process %s." %os.getpid()
11 |
12 | p = Process(target=run_proc, args=('test', ))
13 | print 'Process will start'
14 |
15 | p.start()
16 | p.join()
17 | print "Process end."
18 |
--------------------------------------------------------------------------------
/Others/Concurrency/subprocess_call.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import subprocess
4 |
5 | # 不转义
6 | subprocess.call(['echo', 'l'])
7 |
8 | # 转义
9 | subprocess.call('echo %PATH%', shell=True)
10 |
11 | # 获取输出
12 | result = subprocess.check_output('echo %PATH%', shell=True)
13 | print result
14 |
--------------------------------------------------------------------------------
/Others/Concurrency/threading/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Concurrency/threading/threading_timer_cancel.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Timers通过调用它们的start()方法作为线程启动。
3 | # timer可以通过调用cancel()方法(在它的动作开始之前)停止。
4 | # timer在执行它的动作之前等待的时间间隔可能与用户指定的时间间隔不完全相同。
5 |
6 | from threading import Timer
7 |
8 | def fun():
9 | print "hello, world"
10 |
11 | if __name__=='__main__':
12 | t = Timer(5.0, fun)
13 | t.start() # 开始执行线程,但是不会打印"hello, world"
14 | t.cancel() # 因为cancel取消了线程的执行,所以fun()函数不会被执行
--------------------------------------------------------------------------------
/Others/Concurrency/threading/threading_timer_start.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 这个类表示一个动作应该在一个特定的时间之后运行 — 也就是一个计时器。
3 | # Timer是Thread的子类, 因此也可以使用函数创建自定义线程。
4 | from threading import Timer
5 |
6 |
7 | def fun():
8 | print "hello, world"
9 |
10 | if __name__ == '__main__':
11 | t = Timer(5.0, fun)
12 | t.start() # 5秒后, "hello, world"将被打印
--------------------------------------------------------------------------------
/Others/Concurrency/threadpool/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/DesignPatterns/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/DesignPatterns/const/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/DesignPatterns/const/const_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | const test code
4 |
5 | """
6 |
7 | from constant import const
8 | print const.HOST_IP
9 | const.HOST_IP = "127.0.0.1"
10 |
--------------------------------------------------------------------------------
/Others/DesignPatterns/const/constant.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | host constant
4 |
5 | """
6 |
7 | import const
8 | const.HOST_IP = "192.168.1.1"
9 | const.HOST_NAME = "localhost"
10 |
11 |
--------------------------------------------------------------------------------
/Others/Dicts/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Function/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Function/asterisk_param/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Function/asterisk_param/asterisk_param_one.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 函数调用时,参数使用星号
3 |
4 | # 星号作用于tuple/list/str前,意思是解包(unpack)tuple/list/str,
5 | # 解包后的tuple/list/str将不再是一个参数,而是每个元素都是一个函数参数,依次传递给函数
6 |
7 |
8 | def print_student_info(age, score):
9 | print("age:", age)
10 | print("score:", score)
11 |
12 |
13 | info_list = [18, 100]
14 | print_student_info(*info_list)
15 |
16 | # 如果此时星号被作用于一个dict前,那么只有dict的key会被解包,然后作为参数传递
17 | info_dict = {"age": 20, "score": 99}
18 | print_student_info(*info_dict)
19 |
--------------------------------------------------------------------------------
/Others/Function/asterisk_param/asterisk_param_order.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # run via python3
3 | """
4 | 如果我们要在一个函数中包含多种参数的组合,必须遵守这样的顺序:
5 | 位置参数(必选参数),默认参数,单星号参数或星号分隔符,关键字参数,双星号参数
6 | """
7 |
8 |
9 | # --------
10 | def mix(a, b=0, *c, x, **y):
11 | """位置参数与关键字参数混合"""
12 | return a, b, c, x, y
13 |
14 |
15 | print(mix(1, 2, 3, 4, 5, x=6, y=7, z=8))
16 |
17 | # 程序输出
18 | # (1, 2, (3, 4, 5), 6, {'y': 7, 'z': 8})
19 |
--------------------------------------------------------------------------------
/Others/Function/asterisk_param/asterisk_param_two.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 函数定义和调用时用两个星号
3 |
4 |
5 | def print_student_info1(**info):
6 | print("age:", info.get("age", None))
7 | print("score:", info.get("score", None))
8 |
9 |
10 | def print_student_info2(age, score):
11 | print("age:", age)
12 | print("score:", score)
13 |
14 |
15 | # 两个星号将会把字典完全unpack
16 | info_dict = {"age": 20, "score": 99}
17 | print_student_info1(**info_dict)
18 | print_student_info2(**info_dict)
19 |
--------------------------------------------------------------------------------
/Others/Function/recursion/README.md:
--------------------------------------------------------------------------------
1 | 虽然尾递归优化很好, 但python 不支持尾递归,递归深度超过1000时会报错
2 |
3 | RuntimeError: maximum recursion depth exceeded
4 |
--------------------------------------------------------------------------------
/Others/Function/recursion/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Function/recursion/normal_recursion.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 可以看到, 一般递归, 每一级递归都需要调用函数, 会创建新的栈,
4 | # 随着递归深度的增加, 创建的栈越来越多, 造成爆栈
5 |
6 |
7 | def normal_recursion(n):
8 | if n == 1:
9 | return 1
10 | else:
11 | return n + normal_recursion(n-1)
12 |
13 | print(normal_recursion(900))
--------------------------------------------------------------------------------
/Others/Function/recursion/tail_recursion.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 尾递归基于函数的尾调用, 每一级调用直接返回函数的返回值更新调用栈,
4 | # 而不用创建新的调用栈, 类似迭代的实现, 时间和空间上均优化了一般递归!
5 |
6 |
7 | def tail_recursion(n, total=0):
8 | if n == 0:
9 | return total
10 | else:
11 | return tail_recursion(n-1, total+n)
12 |
13 | print(tail_recursion(900))
--------------------------------------------------------------------------------
/Others/InterviewQuestions/Offer/65_plus_with_bit_operation.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 题目,写一个函数,求两个整数之和,要求在函数体内,不得使用+,-,*,/四则运算符号
3 |
4 |
5 | def add(num1, num2):
6 | while num2 != 0:
7 | num = num1 ^ num2
8 | carry = (num1 & num2) << 1
9 | num1 = num
10 | num2 = carry
11 | return num1
12 |
13 | if __name__ == "__main__":
14 | assert add(123, 798) == 921
15 | assert add(111, 666) == 777
16 |
17 |
--------------------------------------------------------------------------------
/Others/InterviewQuestions/Offer/README.md:
--------------------------------------------------------------------------------
1 | # 剑指Offer中文版(第2版)
2 |
3 |
--------------------------------------------------------------------------------
/Others/InterviewQuestions/Offer/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/InterviewQuestions/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Lambda/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Lambda/list_sort_1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | if __name__ == "__main__":
4 | items = [{'name': 'Homer', 'age': 39},
5 | {'name': 'Bart', 'age': 10},
6 | {"name": 'cater', 'age': 20}]
7 |
8 | items.sort(key=lambda x: x.get("age"))
9 | print(items)
10 |
11 | items.sort(key=lambda x: x.get("age"), reverse=True)
12 | print(items)
13 |
14 |
--------------------------------------------------------------------------------
/Others/Lambda/list_sort_2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | if __name__ == "__main__":
4 | items = [{'name': 'Homer', 'age': 39},
5 | {'name': 'Bart', 'age': 10},
6 | {"name": 'cater', 'age': 20}]
7 |
8 | new_items = sorted(items, key=lambda x: x.get('age'))
9 | print(new_items)
10 |
11 | new_items = sorted(items, key=lambda x: x.get('age'), reverse=True)
12 | print(new_items)
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Others/Lists/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Lists/check_list_empty.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 检查列表是否为空的最好方法
3 |
4 | a = []
5 | if not a:
6 | print("list is empty")
--------------------------------------------------------------------------------
/Others/Lists/connect_list.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | nfc = ["name", "age", "city"]
4 | num = [1, 2, 3]
5 |
6 | print nfc + num
7 |
8 |
--------------------------------------------------------------------------------
/Others/Lists/reverse_word.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 将字符串逐字或者逐词翻转
3 |
4 | # 方案一 步长负一 实现翻转 最好的方法
5 | my_str = '123'
6 | print my_str
7 | print my_str[::-1]
8 |
9 |
10 | # 方案二 序列 翻转 需要有分割符
11 | my_str = '1 2 3'
12 | strs = my_str.split(' ')
13 | strs.reverse()
14 | print ' '.join(strs)
15 |
16 |
17 | # 方案三 序列 翻转 API 需要配合join
18 | my_str = '123'
19 | print ''.join(reversed(my_str)) # reversed返回迭代器
20 |
21 |
22 | # 方案四 list的pop方法 来自penn201500
23 | # python3
24 | my_str = '123'
25 | for i in range(1, len(my_str)+1):
26 | print(list(my_str).pop())
27 |
--------------------------------------------------------------------------------
/Others/Lists/sort_sorted.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # sorted是内建函数(BIF)
4 | list1 = [5, 4, 6, 9]
5 | list2 = sorted(list1)
6 | print "list1", list1
7 | print "list2", list2
8 | print sorted('Hello world')
9 |
10 | # sort()是列表类型的内建函数list.sort()
11 | # L.sort(cmp=None, key=None, reverse=False)
12 | list1.sort()
13 | print "list1", list1
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Others/Lists/update_list.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | name_list = ['python', 'perl', 'java']
4 |
5 | # 删除尾部元素
6 | print name_list.pop()
7 | print name_list
8 |
9 | # 增加元素,append方法
10 | name_list.append('test append')
11 | print name_list
12 |
13 | # 增加元素,在指定位置插入, insert方法
14 | name_list.insert(1, 100)
15 | print name_list
16 |
17 | # 删除元素,删除指定位置的元素
18 | print name_list.pop(0)
19 | print name_list
20 |
21 | # 删除元素,删除指定值的元素
22 | name_list.remove(100)
23 | print name_list
24 |
25 | # list里面的元素的数据类型也可以不同
26 | L = ['Apple', 123, True]
27 |
--------------------------------------------------------------------------------
/Others/Lists/zip_sample2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | nfc = ["name", "age", "city"]
4 | num = ["tian", "12", "sh"]
5 |
6 | for n1, n2 in zip(nfc, num):
7 | print n1 + " is " + n2
8 |
--------------------------------------------------------------------------------
/Others/ML/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/ML/linear_module.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | from sklearn import linear_model
4 | clf = linear_model.LinearRegression()
5 | clf.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2])
6 | LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
7 | print clf.coef_
8 | # array([ 0.5, 0.5])
--------------------------------------------------------------------------------
/Others/Modules/BDD/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Modules/BDD/behave/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/BDD/behave/features/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/BDD/behave/features/fib/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/BDD/behave/features/fib/fib.feature:
--------------------------------------------------------------------------------
1 | Feature:Calc Fib
2 | In order to introduce Behave
3 | We calc fib as example
4 | Scenario Outline: Calc fib number
5 | Given we have the number
6 | when we calc the fib
7 | then we get the fib number
8 | Examples: Some Numbers
9 | | number | fib_number |
10 | | 1 | 1 |
11 | | 2 | 2 |
12 | | 10 | 55 |
--------------------------------------------------------------------------------
/Others/Modules/BDD/behave/features/fib/steps/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/BDD/lettuce/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Modules/BDD/lettuce/tests/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Modules/BDD/lettuce/tests/features/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Modules/Celery/README.md:
--------------------------------------------------------------------------------
1 | celery -A tasks worker --loglevel=info
--------------------------------------------------------------------------------
/Others/Modules/Celery/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/Celery/tasks.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | from celery import Celery
4 |
5 | broker = 'redis://127.0.0.1:6379/5'
6 | backend = 'redis://127.0.0.1:6379/6'
7 |
8 | app = Celery('tasks', broker=broker, backend=backend)
9 |
10 |
11 | @app.task
12 | def add(x, y):
13 | return x+y
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Others/Modules/HTMLParser/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Modules/avro/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/avro/user.avsc:
--------------------------------------------------------------------------------
1 | {"namespace": "example.avro",
2 | "type": "record",
3 | "name": "User",
4 | "fields": [
5 | {"name": "name", "type": "string"},
6 | {"name": "favorite_number", "type": ["int", "null"]},
7 | {"name": "favorite_color", "type": ["string", "null"]}
8 | ]
9 | }
--------------------------------------------------------------------------------
/Others/Modules/avro/users.avro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Modules/avro/users.avro
--------------------------------------------------------------------------------
/Others/Modules/base64/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/code/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/code/md5/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/code/md5/hashlib_md5_string.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | import hashlib
3 | src = 'http://flv.srs.cloutropy.com/wasu/time1.flv'
4 | m2 = hashlib.md5()
5 | m2.update(src)
6 | hashlib_md5_string = m2.hexdigest()
7 | print(hashlib_md5_string.upper())
8 |
--------------------------------------------------------------------------------
/Others/Modules/code/md5/md5_string.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import md5
4 |
5 | src = 'http://flv.srs.cloutropy.com/wasu/time1.flv'
6 | m1 = md5.new()
7 | m1.update(src)
8 | md5_string = m1.hexdigest()
9 | print(md5_string.upper())
10 |
--------------------------------------------------------------------------------
/Others/Modules/collections/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/collections/deque_example.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 | # deque provides you with a double ended queue
3 | # which means that you can append and delete elements from either side of the queue
4 |
5 | q = deque(range(5))
6 | print q # deque([0, 1, 2, 3, 4])
7 |
8 | q.append(5)
9 | q.appendleft(6)
10 |
11 | print q # deque([6, 0, 1, 2, 3, 4, 5])
12 |
13 | print q.pop()
14 | print q # deque([6, 0, 1, 2, 3, 4])
15 |
16 | q.rotate(3)
17 | print q # deque([2, 3, 4, 6, 0, 1])
18 |
19 | q.rotate(-1)
20 | print q # deque([3, 4, 6, 0, 1, 2])
21 |
--------------------------------------------------------------------------------
/Others/Modules/commands/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/cookie/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/cookie/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 3640516628 BAIDUID 9F33FD1FF495DF74A072582E85BCC3AC:FG=1
6 | .baidu.com TRUE / FALSE 3640516628 BIDUPSID 9F33FD1FF495DF74A072582E85BCC3AC
7 | .baidu.com TRUE / FALSE H_PS_PSSID 1423_21111_17001_20929
8 | .baidu.com TRUE / FALSE 3640516628 PSTM 1493032971
9 | www.baidu.com FALSE / FALSE BDSVRTM 0
10 | www.baidu.com FALSE / FALSE BD_HOME 0
11 |
--------------------------------------------------------------------------------
/Others/Modules/cookie/cookie_from_txt.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | import cookielib
3 | import urllib2
4 |
5 | cookie = cookielib.MozillaCookieJar()
6 | cookie.load('cookie.txt', ignore_expires=True, ignore_discard=True)
7 | req = urllib2.Request('http://www.baidu.com')
8 | opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
9 | response = opener.open(req)
10 | print response.read()
--------------------------------------------------------------------------------
/Others/Modules/cookie/cookie_items.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | import urllib2
3 | import cookielib
4 |
5 | # declare cookiejar object to save cookie
6 | cookie = cookielib.CookieJar()
7 | # use urllib2's HTTPCookieProcess object to create cookie handler
8 | handler = urllib2.HTTPCookieProcessor(cookie)
9 | #create opener via handler
10 | opener = urllib2.build_opener(handler)
11 |
12 | response = opener.open('http://www.baidu.com')
13 | for item in cookie:
14 | print 'Name = ' + item.name
15 | print 'Value = ' + item.value
--------------------------------------------------------------------------------
/Others/Modules/cookie/cookie_save.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | import cookielib
3 | import urllib2
4 |
5 | filename = 'cookie.txt'
6 | cookie = cookielib.MozillaCookieJar(filename)
7 | handler = urllib2.HTTPCookieProcessor(cookie)
8 | opener = urllib2.build_opener(handler)
9 | response = opener.open('http://www.baidu.com')
10 | cookie.save(ignore_discard=True, ignore_expires=True)
11 |
--------------------------------------------------------------------------------
/Others/Modules/ctypes/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/ctypes/a.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | void show() {
4 | printf("this is a test\n");
5 | }
6 |
7 | int add(int a, int b) {
8 | return a + b;
9 | }
--------------------------------------------------------------------------------
/Others/Modules/ctypes/call_so.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # call .so function within python
3 |
4 | from ctypes import cdll
5 |
6 | cur = cdll.LoadLibrary('./a.so')
7 | cur.show()
8 | print cur.add(1, 2)
9 |
--------------------------------------------------------------------------------
/Others/Modules/database/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/database/pymongo/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/database/redis/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/decimal/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/decimal/decimal_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | 十进制数学计算
4 | """
5 |
6 | from decimal import Decimal as D
7 | from decimal import getcontext
8 | print getcontext()
9 |
10 | getcontext().prec = 20
11 | print D(1)/D(3)
12 | print 1.00/3.00
13 |
14 |
--------------------------------------------------------------------------------
/Others/Modules/envelopes/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/etcd/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/fake.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | __module__ = fake
4 | """
5 |
6 |
7 | def func1():
8 | """
9 | This is fake doc test
10 | :return: None
11 | """
12 | pass
--------------------------------------------------------------------------------
/Others/Modules/file/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/file/new_file.txt:
--------------------------------------------------------------------------------
1 | hello
--------------------------------------------------------------------------------
/Others/Modules/file/only_nonexist_write1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import os
4 |
5 | if not os.path.exists("new_file.txt"):
6 | with open("new_file.txt", "wt") as fil:
7 | fil.write("hello")
8 | else:
9 | print("file already exists")
10 |
--------------------------------------------------------------------------------
/Others/Modules/file/only_nonexist_write2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # "xt" only works for python3
3 |
4 | try:
5 | with open("new_file.txt", "xt") as fil:
6 | fil.write("hello2")
7 | except Exception as e:
8 | print("file already exists")
--------------------------------------------------------------------------------
/Others/Modules/file/path.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | import inspect
3 | import os
4 | import sys
5 |
6 |
7 | def get_root_path():
8 | file_path = os.path.abspath(inspect.getfile(sys.modules[__name__]))
9 | print(file_path)
10 | parent_path = os.path.dirname(file_path)
11 | parent_path = os.path.dirname(parent_path)
12 | parent_path = os.path.dirname(parent_path)
13 | print(parent_path)
14 | return parent_path
15 |
16 |
17 | if __name__ == "__main__":
18 | get_root_path()
19 |
--------------------------------------------------------------------------------
/Others/Modules/file/with.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | with open("with.py") as f:
4 | for line in f:
5 | print line
6 |
--------------------------------------------------------------------------------
/Others/Modules/help_doc_print.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 |
4 | import fake
5 |
6 | print help(fake.func1)
7 |
8 | print "----------------------"
9 |
10 | print fake.func1.__doc__
11 | print "----------------------"
12 |
13 | print fake.__doc__
14 |
--------------------------------------------------------------------------------
/Others/Modules/itertools/README.md:
--------------------------------------------------------------------------------
1 | review done
--------------------------------------------------------------------------------
/Others/Modules/itertools/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/jieba/jieba_cut.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import jieba
6 | import pkuseg
7 |
8 | if __name__ == '__main__':
9 | text = "绿子在电话的另一头久久默然不语,如同全世界的细雨落在全世界所有的草坪上一般的沉默在持续。"
10 | seg_list = jieba.cut(text, cut_all=False, HMM=True)
11 | print("Cut result is: " + "/".join(seg_list))
12 |
13 | seg = pkuseg.pkuseg() # 以默认配置加载模型
14 | text = seg.cut(text) # 进行分词
15 | print("Cut result is: " + "/".join(text))
--------------------------------------------------------------------------------
/Others/Modules/json/2501/json2xml/expected.xml:
--------------------------------------------------------------------------------
1 |
2 | 10213
3 |
4 | male
5 |
6 |
7 | math
8 | 90
9 |
10 |
11 | english
12 | 881
13 |
14 |
--------------------------------------------------------------------------------
/Others/Modules/json/2501/json2xml/input.json:
--------------------------------------------------------------------------------
1 | { "student": {
2 | "stid": "10213",
3 | "info": {
4 | "name": "name",
5 | "mail":"xxx@xxx.com",
6 | "sex": "male"
7 | },
8 | "course": [
9 | {
10 | "name": "math",
11 | "score": "90"
12 | },
13 | {
14 | "name": "english",
15 | "score": "881"
16 | }
17 | ]
18 | }
19 | }
--------------------------------------------------------------------------------
/Others/Modules/json/2501/json2xml/node.ini:
--------------------------------------------------------------------------------
1 | info/name
2 | info/mail
--------------------------------------------------------------------------------
/Others/Modules/json/2501/json2xml/temp.xml:
--------------------------------------------------------------------------------
1 | 10213namexxx@xxx.commalemath90english881
--------------------------------------------------------------------------------
/Others/Modules/json/2501/json2xml/trans.xml:
--------------------------------------------------------------------------------
1 | 10213malemath90english881
--------------------------------------------------------------------------------
/Others/Modules/json/2501/xml2json/expected.json:
--------------------------------------------------------------------------------
1 | { "student": {
2 | "stid": "10213",
3 | "info": {
4 | "sex": "male"
5 | },
6 | "course": [
7 | {
8 | "name": "math",
9 | "score": "90"
10 | },
11 | {
12 | "name": "english",
13 | "score": "881"
14 | }
15 | ]
16 | }
17 | }
--------------------------------------------------------------------------------
/Others/Modules/json/2501/xml2json/input.xml:
--------------------------------------------------------------------------------
1 |
2 | 10213
3 |
4 | zyt
5 | xxx@xxx.com
6 | male
7 |
8 |
9 | math
10 | 90
11 |
12 |
13 | english
14 | 881
15 |
16 |
--------------------------------------------------------------------------------
/Others/Modules/json/2501/xml2json/node.ini:
--------------------------------------------------------------------------------
1 | info/name
2 | info/mail
--------------------------------------------------------------------------------
/Others/Modules/json/2501/xml2json/trans.xml:
--------------------------------------------------------------------------------
1 |
2 | 10213
3 |
4 | zyt
5 | male
6 |
7 |
8 | math
9 | 90
10 |
11 |
12 | english
13 | 881
14 |
15 |
--------------------------------------------------------------------------------
/Others/Modules/json/backup/json_diff.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import json_tools
6 |
7 | if __name__ == '__main__':
8 | a = {'left':1, "right":{"a": [1, 2, {"b":"x", "a":1}]}}
9 | b = {'right':{"a":[1, 2, {"a":1, "b":'x'}]}, "left":1}
10 |
11 | result = json_tools.diff(a, b)
12 | print(result)
--------------------------------------------------------------------------------
/Others/Modules/json/backup/json_expected.json:
--------------------------------------------------------------------------------
1 | { "student": {
2 | "stid": "10213",
3 | "info": {
4 | "name": "name",
5 | "mail": "xxx@xxx.com",
6 | "sex": "male"
7 | },
8 | "course": [
9 | {
10 | "name": "math",
11 | "score": "90"
12 | },
13 | {
14 | "name": "english",
15 | "score": "881"
16 | }
17 | ]
18 | }
19 | }
--------------------------------------------------------------------------------
/Others/Modules/json/backup/keys.ini:
--------------------------------------------------------------------------------
1 | info/name
2 | info/mail
--------------------------------------------------------------------------------
/Others/Modules/json/backup/output.xml:
--------------------------------------------------------------------------------
1 |
2 | 10213
3 |
4 | male
5 |
6 |
7 | math
8 | 90
9 |
10 |
11 | english
12 | 881
13 |
14 |
--------------------------------------------------------------------------------
/Others/Modules/json/backup/xml_input.xml:
--------------------------------------------------------------------------------
1 |
2 | 10213
3 |
4 | zyt
5 | xxx@xxx.com
6 | male
7 |
8 |
9 | math
10 | 90
11 |
12 |
13 | english
14 | 881
15 |
16 |
--------------------------------------------------------------------------------
/Others/Modules/kafka/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/math/gcd_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 | # 求多个数的最大公约数
5 | # math 模块有个求两个数最大公约数的函数gcd
6 | # reduce在Python2是内置函数,Python3中迁移到functools模块中
7 |
8 | import math
9 | import functools
10 |
11 | if __name__ == '__main__':
12 | num_list = [30, 40, 60, 15]
13 |
14 | gcd_result = functools.reduce(math.gcd, num_list)
15 | print(gcd_result)
16 |
--------------------------------------------------------------------------------
/Others/Modules/networking/BaseHTTPServer/README.md:
--------------------------------------------------------------------------------
1 | 说明:
2 |
3 | 1、get测试:http://steven-pc:8000/?test=data
4 |
5 | 2、通过curl来测试post数据:
6 |
7 | curl -d "data=postdata" http://steven-pc:8000?test=post
8 | data:postdata
9 | test:post
10 |
11 | 3、支持中文:必须在头部加:#encoding=utf-8
12 |
13 | 三、CGIHTTPServer: 包含处理POST请求和执行CGIHTTPRequestHandler类。
14 |
15 | 参考 CGI介绍及使用Python来开发CGI应用示例
--------------------------------------------------------------------------------
/Others/Modules/networking/BaseHTTPServer/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/networking/SimpleHTTPServer/README.md:
--------------------------------------------------------------------------------
1 | review done
--------------------------------------------------------------------------------
/Others/Modules/networking/SimpleHTTPServer/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/networking/SimpleHTTPServer/simple_http_server.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 一个简单的HTTP服务器 - 其他机器可以访问
3 |
4 | import SimpleHTTPServer
5 | import SocketServer
6 |
7 | PORT = 8000
8 |
9 | Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
10 |
11 | httpd = SocketServer.TCPServer(("", PORT), Handler)
12 |
13 | print "serving at port", PORT
14 | httpd.serve_forever()
15 |
--------------------------------------------------------------------------------
/Others/Modules/networking/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Modules/networking/beautiful_soup/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/networking/dpkt/README.md:
--------------------------------------------------------------------------------
1 | pip install dpkt
2 |
3 | 解析数据包(拆包)
4 |
5 | 创建数据包(封包)
6 |
--------------------------------------------------------------------------------
/Others/Modules/networking/dpkt/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Modules/networking/dpkt/data/http.pcap:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Modules/networking/dpkt/data/http.pcap
--------------------------------------------------------------------------------
/Others/Modules/networking/email/README.md:
--------------------------------------------------------------------------------
1 | Email related sample code
--------------------------------------------------------------------------------
/Others/Modules/networking/email/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/networking/email/send_plain_mail.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import smtplib
4 | from email.mime.text import MIMEText
5 | from email.header import Header
6 |
7 | sender = '***'
8 | receiver = '***'
9 | subject = 'python email test'
10 | smtp_server = 'smtp.163.com'
11 | username = '***'
12 | password = '***'
13 |
14 | msg = MIMEText(u'你好', 'plain', 'utf-8') # 中文需参数‘utf-8',单字节字符不需要
15 | msg['Subject'] = Header(subject, 'utf-8')
16 |
17 | smtp = smtplib.SMTP()
18 | smtp.connect(smtp_server)
19 | smtp.login(username, password)
20 | smtp.sendmail(sender, receiver, msg.as_string())
21 | smtp.quit()
22 |
--------------------------------------------------------------------------------
/Others/Modules/networking/email/send_to_many.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | import smtplib
3 | from email.mime.text import MIMEText
4 |
5 | sender = '***'
6 | receiver = ['***', '***', '...', '***']
7 | subject = 'python email test'
8 | smtp_server = 'smtp.163.com'
9 | username = '***'
10 | password = '***'
11 |
12 | msg = MIMEText('你好', 'plain', 'utf-8')
13 |
14 | msg['Subject'] = subject
15 |
16 | smtp = smtplib.SMTP()
17 | smtp.connect(smtp_server)
18 | smtp.login(username, password)
19 | smtp.sendmail(sender, receiver, msg.as_string())
20 | smtp.quit()
--------------------------------------------------------------------------------
/Others/Modules/networking/ftplib/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/networking/ftplib/ftplib-2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import ftplib
4 | import sys
5 |
6 | def get_text(ftp, filename, outfile=None):
7 | # fetch a text file
8 | if outfile is None:
9 | outfile = sys.stdout
10 | # use a lambda to add newlines to the lines read from the server
11 | ftp.retrlines("RETR" + filename, lambda s, w=outfile.write: w(s+"\n"))
12 |
13 |
--------------------------------------------------------------------------------
/Others/Modules/networking/ftplib/ftplib_1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import ftplib
4 |
5 | ftp = ftplib.FTP("www.python.org")
6 | ftp.login("anonymous", "ftplib-example-1")
7 |
8 | print ftp.dir()
9 | ftp.quit()
10 |
--------------------------------------------------------------------------------
/Others/Modules/networking/paramiko/README.md:
--------------------------------------------------------------------------------
1 | 已经整理
--------------------------------------------------------------------------------
/Others/Modules/networking/paramiko/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/networking/paramiko/paramiko_download_file.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 从远程下载文件
3 |
4 | import paramiko
5 |
6 | t = paramiko.Transport(("192.168.1.211", 22))
7 | t.connect(username="admin", password="123456")
8 | sftp = paramiko.SFTPClient.from_transport(t)
9 | remotepath = '/tmp/test.txt'
10 | localpath = 'E:/test.txt'
11 | sftp.get(remotepath, localpath)
12 | t.close()
13 |
--------------------------------------------------------------------------------
/Others/Modules/networking/paramiko/paramiko_remote_exec.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 执行远程命令
3 |
4 | import paramiko
5 |
6 | ssh = paramiko.SSHClient()
7 | ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
8 | ssh.connect("192.168.1.64", 22, "admin", "123456")
9 | stdin, stdout, stderr = ssh.exec_command("ls /")
10 | print stdout.readlines()
11 | ssh.close()
12 |
13 |
--------------------------------------------------------------------------------
/Others/Modules/networking/paramiko/paramiko_upload_file.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 上传文件到远程
3 |
4 | import paramiko
5 |
6 | t = paramiko.Transport(("192.168.1.211", 22))
7 | t.connect(username="admin", password="123456")
8 | sftp = paramiko.SFTPClient.from_transport(t)
9 | remotepath = '/tmp/test.txt'
10 | localpath = 'D:/test.txt'
11 | sftp.put(localpath,remotepath)
12 | t.close()
13 |
--------------------------------------------------------------------------------
/Others/Modules/networking/pcap/README.md:
--------------------------------------------------------------------------------
1 | pypcap进行实时的数据包捕获
--------------------------------------------------------------------------------
/Others/Modules/networking/pcap/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/networking/pcap/livecap.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import pcap
4 | import dpkt
5 |
6 | pc = pcap.pcap('en0') # 注,参数可为网卡名,如eth0
7 |
8 | pc.setfilter('tcp port 80') # 2.设置监听过滤器
9 |
10 | for ts, pkt in pc:
11 | eth = dpkt.ethernet.Ethernet(pkt)
12 | ip = eth.data
13 | print ts
14 | # udp = ip.data
15 | # dns = dpkt.dns.DNS(udp.data)
--------------------------------------------------------------------------------
/Others/Modules/networking/pyftplib/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/networking/requests/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/networking/requests/download_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | 下载文件并保存
4 | """
5 |
6 | import requests
7 |
8 | def download_file(url, filename):
9 | # local_filename = url.split('/')[-1]
10 | r = requests.get(url, stream=True)
11 | with open(filename, 'wb') as fd:
12 | for chunk in r.iter_content(chunk_size=1024):
13 | if chunk: # filter out keep-alive new chunks
14 | fd.write(chunk)
--------------------------------------------------------------------------------
/Others/Modules/networking/scapy/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/networking/scapy/scapy_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import sys
4 | import struct
5 | from scapy.all import *
6 |
7 | data = struct.pack('=BHI', 0x12, 20, 1000)
8 | pkt = IP(src='192.168.1.81', dst='192.168.1.10')/UDP(sport=12345,dport=5555)/data
9 | send(pkt, inter=1, count=5)
--------------------------------------------------------------------------------
/Others/Modules/networking/urllib/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/networking/urllib/urllib_test.py:
--------------------------------------------------------------------------------
1 | from urllib import urlopen
2 |
3 | webpage = urlopen('http://www.cnblogs.com/IProgramming/')
4 | txt = webpage.readline(45)
5 | print txt
6 |
--------------------------------------------------------------------------------
/Others/Modules/numpy/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/numpy/broadcasting2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import numpy as np
5 |
6 | # We will add the vector v to each row of the matrix x,
7 | # storing the result in the matrix y
8 | x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
9 | v = np.array([1, 0, 1])
10 | y = x + v # Add v to each row of x using broadcasting
11 | print(y) # Prints "[[ 2 2 4]
12 | # [ 5 5 7]
13 | # [ 8 8 10]
14 | # [11 11 13]]"
--------------------------------------------------------------------------------
/Others/Modules/numpy/matrix_multi.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import numpy as np
5 |
6 | x = np.array([[1,2],[3,4]])
7 | y = np.array([[5,6],[7,8]])
8 |
9 | v = np.array([9,10])
10 | w = np.array([11, 12])
11 |
12 | # Inner product of vectors; both produce 219
13 | print(v.dot(w))
14 | print(np.dot(v, w))
15 |
16 | # Matrix / vector product; both produce the rank 1 array [29 67]
17 | print(x.dot(v))
18 | print(np.dot(x, v))
19 |
20 | # Matrix / matrix product; both produce the rank 2 array
21 | # [[19 22]
22 | # [43 50]]
23 | print(x.dot(y))
24 | print(np.dot(x, y))
--------------------------------------------------------------------------------
/Others/Modules/numpy/shape.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import numpy as np
5 |
6 | a = np.array([1, 2, 3]) # Create a rank 1 array
7 | print type(a) # Prints ""
8 | print a.shape # Prints "(3,)"
9 | print a[0], a[1], a[2] # Prints "1 2 3"
10 | a[0] = 5 # Change an element of the array
11 | print a # Prints "[5, 2, 3]"
12 |
13 | b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array
14 | print b.shape # Prints "(2, 3)"
15 | print b[0, 0], b[0, 1], b[1, 0] # Prints "1 2 4"
--------------------------------------------------------------------------------
/Others/Modules/numpy/sum.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import numpy as np
5 |
6 | x = np.array([[1,2],[3,4]])
7 |
8 | print(np.sum(x)) # Compute sum of all elements; prints "10"
9 | print(np.sum(x, axis=0)) # Compute sum of each column; prints "[4 6]"
10 | print(np.sum(x, axis=1)) # Compute sum of each row; prints "[3 7]"
--------------------------------------------------------------------------------
/Others/Modules/numpy/transposing.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import numpy as np
5 |
6 | x = np.array([[1,2], [3,4]])
7 | print(x) # Prints "[[1 2]
8 | # [3 4]]"
9 | print(x.T) # Prints "[[1 3]
10 | # [2 4]]"
11 |
12 | # Note that taking the transpose of a rank 1 array does nothing:
13 | v = np.array([1,2,3])
14 | print(v) # Prints "[1 2 3]"
15 | print(v.T) # Prints "[1 2 3]"
--------------------------------------------------------------------------------
/Others/Modules/openpyxl/1234.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/Others/Modules/openpyxl/1234.xlsx
--------------------------------------------------------------------------------
/Others/Modules/openpyxl/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/openpyxl/openpyxl_read.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | 读取excel文件内容
4 | """
5 | from openpyxl import load_workbook
6 |
7 | wb2 = load_workbook("1234.xlsx")
8 | print wb2.get_sheet_names()
9 | ws_wb2 = wb2["python"]
10 | for row in ws_wb2.rows:
11 | for cell in row:
12 | print cell.value
13 |
--------------------------------------------------------------------------------
/Others/Modules/optparse/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/pandas/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/pandas/bool_index.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import pandas as pd
5 | import numpy as np
6 |
7 | dates = pd.date_range('20170101', periods=6)
8 | df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
9 | print(df)
10 | print(df[df.A > 0])
11 | print(df[df > 0])
12 |
13 |
14 | df2 = df.copy()
15 | df2['E'] = ['one', 'one','two','three','four','three']
16 |
17 | print(df2)
18 |
19 | print("============= start to filter =============== ")
20 |
21 | print(df2[df2['E'].isin(['two','four'])])
--------------------------------------------------------------------------------
/Others/Modules/pandas/column.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import pandas as pd
5 | import numpy as np
6 |
7 | dates = pd.date_range('20170101', periods=6)
8 | df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
9 | print(df)
10 | print(df['A'])
--------------------------------------------------------------------------------
/Others/Modules/pandas/csv_read_1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # read local csv file
3 |
4 | import pandas as pd
5 |
6 | df = pd.read_csv('tips.csv')
7 | # df = pd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv" )
8 |
9 | print df
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Others/Modules/pandas/date_range.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 通过传递numpy数组,使用datetime索引和标记列来创建DataFrame
4 |
5 | import pandas as pd
6 | import numpy as np
7 |
8 | dates = pd.date_range('20170101', periods=7)
9 | print(dates)
10 |
11 | print("--"*16)
12 | df = pd.DataFrame(np.random.randn(7,4), index=dates, columns=list('ABCD'))
13 | print(df)
14 |
--------------------------------------------------------------------------------
/Others/Modules/pandas/describe.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 描述显示数据的快速统计摘要
4 |
5 |
6 | import pandas as pd
7 | import numpy as np
8 |
9 | dates = pd.date_range('20170101', periods=7)
10 | df = pd.DataFrame(np.random.randn(7,4), index=dates, columns=list('ABCD'))
11 | print(df)
12 | print(df.describe())
13 |
--------------------------------------------------------------------------------
/Others/Modules/pandas/head_tail.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import pandas as pd
5 | import numpy as np
6 |
7 | dates = pd.date_range('20170101', periods=7)
8 | df = pd.DataFrame(np.random.randn(7,4), index=dates, columns=list('ABCD'))
9 | print(df.head())
10 | print("--------------" * 10)
11 | print(df.tail(3))
--------------------------------------------------------------------------------
/Others/Modules/pandas/index_columns_values.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import pandas as pd
5 | import numpy as np
6 |
7 | dates = pd.date_range('20170101', periods=7)
8 | df = pd.DataFrame(np.random.randn(7,4), index=dates, columns=list('ABCD'))
9 | print(df)
10 |
11 | print("index is :" )
12 | print(df.index)
13 | print("columns is :" )
14 | print(df.columns)
15 | print("values is :" )
16 | print(df.values)
17 |
--------------------------------------------------------------------------------
/Others/Modules/pandas/init_with_dict.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | # 通过传递可以转换为类似系列的对象的字典来创建DataFrame
5 |
6 | import pandas as pd
7 | import numpy as np
8 |
9 | df2 = pd.DataFrame({ 'A' : 1.,
10 | 'B' : pd.Timestamp('20170102'),
11 | 'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
12 | 'D' : np.array([3] * 4,dtype='int32'),
13 | 'E' : pd.Categorical(["test","train","test","train"]),
14 | 'F' : 'foo' })
15 |
16 | print(df2)
--------------------------------------------------------------------------------
/Others/Modules/pandas/series.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 通过传递值列表来创建一个系列,让Pandas创建一个默认的整数索引
4 | import pandas as pd
5 | import numpy as np
6 |
7 | s = pd.Series([1,3,5,np.nan,6,8])
8 |
9 | print(s)
--------------------------------------------------------------------------------
/Others/Modules/pandas/slice.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import pandas as pd
5 | import numpy as np
6 |
7 | dates = pd.date_range('20170101', periods=6)
8 | df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
9 |
10 | print(df[0:3])
11 |
12 | print("========= 指定选择日期 ========")
13 |
14 | print(df['20170102':'20170103'])
--------------------------------------------------------------------------------
/Others/Modules/pandas/sort_index.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 通过轴排序
4 | import pandas as pd
5 | import numpy as np
6 |
7 | dates = pd.date_range('20170101', periods=6)
8 | df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
9 |
10 | print(df)
11 | print(df.sort_index(axis=1, ascending=False))
--------------------------------------------------------------------------------
/Others/Modules/pandas/sort_value.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import pandas as pd
5 | import numpy as np
6 |
7 | dates = pd.date_range('20170101', periods=6)
8 | df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
9 | print(df)
10 | print(df.sort_values(by='B'))
--------------------------------------------------------------------------------
/Others/Modules/pandas/t.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import pandas as pd
5 | import numpy as np
6 |
7 | dates = pd.date_range('20170101', periods=6)
8 | df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
9 | print(df)
10 | print(df.T)
--------------------------------------------------------------------------------
/Others/Modules/re/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/re/re_search.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import re
4 |
5 | if __name__ == "__main__":
6 |
7 | text = " 42 46 300"
8 | pattern = "[0-9]+"
9 | match = re.search(pattern, text, flags=0)
10 | print match.group()
11 |
--------------------------------------------------------------------------------
/Others/Modules/sh/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/sh/sh_sample1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import sh as pbs
4 |
5 | print(sh.ls("/"))
6 |
7 | # print(sh.Command("zsh"))
8 |
9 | # p=sh.sleep(3, _bg=True)
10 | # print "print directly"
11 | # p.wait()
12 | # print "3 sec later"
13 |
--------------------------------------------------------------------------------
/Others/Modules/sklearn/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/socket/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/socket/socket_client.py:
--------------------------------------------------------------------------------
1 | import socket
2 |
3 | s = socket.socket()
4 | host = socket.gethostname()
5 | port = 8088
6 |
7 | s.connect((host, port))
8 | print s.recv(1024)
--------------------------------------------------------------------------------
/Others/Modules/socket/socket_server.py:
--------------------------------------------------------------------------------
1 | import socket
2 | s = socket.socket()
3 | host = socket.gethostname()
4 | port = 8088
5 | s.bind((host, port))
6 |
7 | s.listen(5)
8 |
9 | while True:
10 | c, address = s.accept()
11 | print 'Got connection from ', address
12 | c.send('Thanks for your connection')
13 | c.close()
--------------------------------------------------------------------------------
/Others/Modules/socket/udp_client.py:
--------------------------------------------------------------------------------
1 | from socket import *
2 |
3 | HOST = 'localhost'
4 | PORT = 20123
5 | BUFSIZ = 128
6 | ADDR = (HOST, PORT)
7 |
8 | udpClient = socket(AF_INET, SOCK_DGRAM)
9 |
10 | while True:
11 | data = raw_input('>')
12 | if not data:
13 | break
14 |
15 | udpClient.sendto(data, ADDR)
16 |
17 | data, ADDR = udpClient.recvfrom(BUFSIZ)
18 | print data
19 | if not data:
20 | break
21 |
22 | udpClient.close()
--------------------------------------------------------------------------------
/Others/Modules/socket/udp_server.py:
--------------------------------------------------------------------------------
1 | from socket import *
2 | from time import ctime
3 |
4 | HOST = ''
5 | PORT = 20123
6 | BUFSIZ = 128
7 | ADDR = (HOST, PORT)
8 |
9 | udpServer = socket(AF_INET, SOCK_DGRAM)
10 | udpServer.bind(ADDR)
11 |
12 |
13 | while True:
14 | print 'waiting for message ... '
15 | data, addr = udpServer.recvfrom(BUFSIZ)
16 | udpServer.sendto('[%s] %s' %(ctime(), data), addr)
17 | print '... received from and returned to: ', addr
18 |
19 | udpServer.close()
20 |
--------------------------------------------------------------------------------
/Others/Modules/struct/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/struct/struct_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import struct
4 |
5 | # struct的pack函数把任意数据类型变成字符串
6 | # >表示字节顺序是big-endian,也就是网络序,I表示4字节无符号整数
7 | print struct.pack('>I', 10240099)
8 |
9 | # unpack把str变成相应的数据类型
10 | # 根据>IH的说明,后面的str依次变为I:4字节无符号整数和H:2字节无符号整数
11 | print struct.unpack('>IH', '\xf0\xf0\xf0\xf0\x80\x80')
12 |
--------------------------------------------------------------------------------
/Others/Modules/tarfile/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/tarfile/tar_file.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | """
3 | 压缩和解压*.tar.gz文件
4 |
5 | """
6 |
7 | import tarfile
8 | import os
9 |
10 | def untar(filename, dir):
11 | t = tarfile.open(filename)
12 | t.extractall(path = dir)
13 |
14 |
15 |
16 | def tar(filename):
17 | t = tarfile.open(filename + ".tar.gz", "w:gz")
18 | for root, dir, files in os.walk(filename):
19 | print root, dir, files
20 | for file in files:
21 | full_path = os.path.join(root, file)
22 | t.add(full_path)
23 | t.close()
24 |
--------------------------------------------------------------------------------
/Others/Modules/time/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/time/date/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/time/date/date_string.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 日期字符串
3 |
4 | import time
5 |
6 | ISOTIMEFORMAT='%Y-%m-%d %X'
7 |
8 | # 1970/1/1 00:00:00
9 | print time.time()
10 |
11 | # 当前时区
12 | current = time.localtime()
13 | # strfmtime格式化
14 | print time.strftime("%Y%m%d%H%M%S", current)
15 |
16 | # 0 时区 UTC时区
17 | current = time.gmtime()
18 | print time.strftime(ISOTIMEFORMAT, current)
19 |
20 | # 查看时区 -28800=8*3600
21 | print time.timezone
22 |
23 | # 将一个时间戳(默认当前时间)转换成时间字符串
24 | time_str = time.time()
25 | print time.ctime(time_str)
26 | print time.ctime()
--------------------------------------------------------------------------------
/Others/Modules/time/date/last_friday.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 寻找上一个星期五
3 |
4 | import datetime, calendar
5 | lastFriday = datetime.date.today()
6 | while lastFriday.weekday() != calendar.FRIDAY:
7 | lastFriday -= datetime.date.resolution
8 | print lastFriday.strftime('%d-%b-%Y')
9 |
10 | # 另一种方法
11 | lastFriday = datetime.date.today()
12 | oneday = datetime.timedelta(days=1)
13 | while lastFriday.weekday() != calendar.FRIDAY:
14 | lastFriday -= oneday
15 | print lastFriday.strftime('%d-%b-%Y')
--------------------------------------------------------------------------------
/Others/Modules/time/date/yesterday_tomorrow.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 计算昨天和明天的日期
3 |
4 | import datetime
5 | today = datetime.date.today()
6 | yesterday = today - datetime.timedelta(days=1)
7 | tomorrow = today + datetime.timedelta(days=1)
8 | print(yesterday, today, tomorrow)
--------------------------------------------------------------------------------
/Others/Modules/time/time/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/time/time/time_precision.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Second, Millisecond(毫秒), Microsecond(微秒)
3 |
4 | import time
5 | import datetime
6 |
7 | print(time.time()) # 返回当前时间的时间戳(1970纪元后经过的浮点秒数)。
8 | # 1493019531.63
9 |
10 | print(datetime.datetime.now().microsecond) # 获取当前时间的微秒数
11 | # 630000
--------------------------------------------------------------------------------
/Others/Modules/unittest/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/xml/22602.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Everyday Italian
4 | Giada De Laurentiis
5 | 2005
6 | 30.00
7 |
8 |
9 | Learning XML
10 | Erik T. Ray
11 | 2003
12 | 39.95
13 |
14 |
--------------------------------------------------------------------------------
/Others/Modules/xml/Manager.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | joy
5 | 27
6 | 女
7 |
8 |
9 | tom
10 | 30
11 | 男
12 |
13 |
14 | ruby
15 | 29
16 | 女
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Others/Modules/xml/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/yaml/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Modules/yaml/dsql-config.yml:
--------------------------------------------------------------------------------
1 | # config file of dsql
2 | DSQL:
3 | HOME: /usr/localdsql
4 | Hadoop:
5 | HOME: /usr/localnhadoop
6 | Server: 10.60.1.140
7 | Client:
8 | - 10.60.1.141
9 | - 10.60.1.142
10 | - 10.60.1.143
11 |
--------------------------------------------------------------------------------
/Others/Modules/yaml/read_yaml.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | import yaml
3 |
4 | config = yaml.load(file("dsql-config.yml"))
5 | print config["DSQL"]["Hadoop"]["Client"][2]
6 |
7 |
--------------------------------------------------------------------------------
/Others/Modules/zipfile/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Questions/3bit_number.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
4 |
5 | cnt = 0 # count the sum of result
6 | for i in range(1, 5):
7 | for j in range(1, 5):
8 | for k in range(1, 5):
9 | if i != j and i != k and j != k:
10 | print i * 100 + j * 10 + k
11 | cnt += 1
12 | print "count is " + str(cnt)
13 |
--------------------------------------------------------------------------------
/Others/Questions/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/Questions/codeforce_1a.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | """
4 | 题意:给一个n*m的矩形,和a*a的正方形。要用a*a的正方形去覆盖n*m的矩形,
5 | 要求a*a的正方形不能切割开,但是两个a*a的正方形可以重叠,问最小需要几个这样的正方形
6 | """
7 |
8 | my_list = raw_input().split()
9 | n = int(my_list[0])
10 | m = int(my_list[1])
11 | a = int(my_list[2])
12 |
13 | print (n / a + (n % a > 0)) * (m / a + (m % a > 0))
14 |
--------------------------------------------------------------------------------
/Others/Questions/multiply_table.py:
--------------------------------------------------------------------------------
1 | for i in range(1, 10):
2 | for j in range(1, i + 1):
3 | print i, '*', j, '=', i * j, ",",
4 | print ''
5 |
--------------------------------------------------------------------------------
/Others/Shells/start_ftp_server.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 |
4 | python -m pyftpdlib -p 21
--------------------------------------------------------------------------------
/Others/Shells/start_http_server.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | # start a simple http server with port
3 | # then you can curl or wget file with http://ip:9999
4 |
5 | python -m SimpleHTTPServer 9999
6 |
7 | # for python 3
8 | # python3 -m http.server
--------------------------------------------------------------------------------
/Others/Strings/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Strings/capwords.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | import string
4 |
5 | s = 'this quick brown fox jumped over the lazy dog'
6 | print s
7 | print string.capwords(s)
8 | # This Quick Brown Fox Jumped Over The Lazy Dog
9 | # capwords是先split(),然后capitalize(),最后join()而成。
10 | # string.capwords(s[, sep])
11 | # 该方法也可以将多个空格压缩成一个空格,并且删掉尾部的空格
12 | s1 = 'test several whitespace, and trailing whitespace '
13 | print s1
14 | print string.capwords(s1)
15 | #Test Several Whitespace, And Trailing Whitespace
16 |
--------------------------------------------------------------------------------
/Others/Strings/find_in_index.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # coding=utf-8
3 | # 在字符串中查找字串
4 |
5 | if 'hello world,hello'.find('world') != -1:
6 | print('find')
7 |
8 | if 'world' in 'hello world,hello':
9 | print('find')
10 |
11 | if 'hello world,hello'.index('world'):
12 | print('find')
13 |
14 | try:
15 | if 'hello world, hello'.index('world') >= 0:
16 | print('find')
17 | except:
18 | pass
19 |
--------------------------------------------------------------------------------
/Others/Strings/input_and_raw_input.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 在python2中,input()会把输入当做表达式进行运算,raw_input()把输入当做string返回
4 | # 在python3中,raw_input()被删除,python3中的input()和python2中的raw_input()效果等同
5 | # eval(input())和python2中的raw_input()效果等同
6 |
7 | # 注,以下为方法示例,不能正常执行
8 | # 必须有引号
9 | name = input("what is your name")
10 | print "hello ", name
11 |
12 | # 不需要引号
13 | name = raw_input("what is your name again")
14 | print "hello ", name
15 |
--------------------------------------------------------------------------------
/Others/Strings/is_a_digital.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | text = "6665s78"
4 | print text.isdigit() # False, s
5 |
6 |
7 | text = "6665.78"
8 | print text.isdigit() # False, .
9 |
10 | text = "66658"
11 | print text.isdigit() # True
12 |
--------------------------------------------------------------------------------
/Others/Strings/is_a_string.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 判断一个值是否是字符串
3 |
4 |
5 | def is_a_string(obj):
6 | return isinstance(obj, basestring)
7 |
8 | print is_a_string(123456) # False
9 | print is_a_string(True) # False
10 | print is_a_string([1, 2, 3]) # False
11 |
12 | print is_a_string("Hello Python") # True
13 |
--------------------------------------------------------------------------------
/Others/Strings/ord_chr.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 返回字符的ascii码值
4 | print ord('a')
5 |
6 | # 返回整数对应的ASCII字符,与ord()作用相反
7 | print chr(97)
8 |
9 |
--------------------------------------------------------------------------------
/Others/Strings/string_template.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 格式化字符串
3 |
4 | """
5 | Template无疑是一个好东西,可以将字符串的格式固定下来,重复利用。
6 | 同时Template也可以让开发人员可以分别考虑字符串的格式和其内容了,无形中减轻了开发人员的压力。
7 | Template属于string中的一个类,所以要使用的话可以用以下方式调用
8 | from string import Template
9 | Template有个特殊标示符$,它具有以下的规则:
10 | 它的主要实现方式为$xxx,其中xxx是满足python命名规则的字符串,即不能以数字开头,不能为关键字等
11 | 如果$xxx需要和其他字符串接触时,可用{}将xxx包裹起来
12 | """
13 |
14 | import string
15 |
16 | values = {'name': 'jumper', 'age': 30}
17 |
18 | t = string.Template("""
19 | name : $name
20 | age : ${age} years
21 | Escape : $$
22 | """)
23 |
24 | print 'TEMPLATE:', t.substitute(values)
--------------------------------------------------------------------------------
/Others/Strings/ys_string.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 原始字符串,用r开头,但是最后一个字符不能是\,除非被转义
3 |
4 | text = r'\\hello\\world'
5 | print text
6 |
--------------------------------------------------------------------------------
/Others/Tuple/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/Tuple/tuple_test.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | t = (1)
4 | print t
5 |
6 | t = (1, )
7 | print t
--------------------------------------------------------------------------------
/Others/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/bkm/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/bkm/file/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/bkm/file/file.txt:
--------------------------------------------------------------------------------
1 | line1
2 | line2
3 | line3
4 | line4
5 | line5
--------------------------------------------------------------------------------
/Others/bkm/file/get_line_1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 根据指定的行号,从文本文件中读取一行数据
3 |
4 | # linecache读取并缓存你指定名字的文件中的所有文本
5 | # 所以对于大文件慎重使用
6 |
7 | import linecache
8 | thefilepath = "file.txt"
9 | desired_line_number = 5
10 | theline = linecache.getline(thefilepath, desired_line_number)
11 | print theline
12 |
--------------------------------------------------------------------------------
/Others/bkm/file/get_line_2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 根据指定的行号,从文本文件中读取一行数据
3 |
4 | def getline(thefilepath, desired_line_number):
5 | if desired_line_number < 1:
6 | return ''
7 | for current_line_number, line in enumerate(open(thefilepath, 'rU')):
8 | if current_line_number == desired_line_number-1:
9 | return line
10 | return ''
11 |
12 | thefilepath = "file.txt"
13 | desired_line_number = 5
14 | theline = getline(thefilepath, desired_line_number)
15 | print theline
--------------------------------------------------------------------------------
/Others/bkm/file/get_line_count_1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 计算文件行数
3 |
4 | thefilepath = "file.txt"
5 | count = len(open(thefilepath, 'rU').readlines())
6 | print count
7 |
--------------------------------------------------------------------------------
/Others/bkm/file/get_line_count_2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 计算文件行数
3 |
4 | thefilepath = "file.txt"
5 | # count = -1
6 | for count, line in enumerate(open(thefilepath, 'rU')):
7 | pass
8 | count += 1
9 | print count
10 |
--------------------------------------------------------------------------------
/Others/bkm/get_host_name.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 获得hostname
3 |
4 | import os
5 |
6 | def hostname():
7 | sys = os.name
8 |
9 | if sys == 'nt':
10 | hostname = os.getenv('computername')
11 | return hostname
12 |
13 | elif sys == 'posix':
14 | host = os.popen('echo $HOSTNAME')
15 | try:
16 | hostname = host.read()
17 | return hostname
18 | finally:
19 | host.close()
20 | else:
21 | return 'Unkwon hostname'
22 |
23 |
24 | hostname = hostname()
25 | print hostname
26 |
--------------------------------------------------------------------------------
/Others/bkm/global_var.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 在函数中使用全局变量
3 |
4 | globvar = 0
5 |
6 |
7 | def set_globvar_to_one():
8 | global globvar # 需要用global修饰一下
9 | globvar = 1
10 |
11 |
12 | def print_globvar():
13 | print globvar # 如果只是读的话,不用global修饰
14 |
15 |
16 | set_globvar_to_one()
17 | print_globvar()
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/Others/bkm/io/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/bkm/io/printf_in_python.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 在Python中使用printf
3 |
4 | import sys
5 |
6 |
7 | def printf(fmt, *args):
8 | sys.stdout.write(fmt % args)
9 |
10 | printf("%d %s", 10*100, "python")
--------------------------------------------------------------------------------
/Others/bkm/is_digit.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 检查字符串是不是数字
3 |
4 | a = "038403"
5 | print a.isdigit()
6 |
7 | b = "9badc"
8 | print b.isdigit()
--------------------------------------------------------------------------------
/Others/bkm/skill/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/bkm/skill/filter_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # filter的用法
3 |
4 | lst = [1, 2, 3, 4, 5, 6]
5 |
6 | # 所有奇数都会返回True, 偶数会返回False被过滤掉
7 | print filter(lambda x: x % 2 != 0, lst)
8 | # [1, 3, 5]
9 |
10 |
11 | def not_empty(s):
12 | return s and s.strip()
13 |
14 | print filter(not_empty, ['A', '', 'B', None, 'C', ' '])
--------------------------------------------------------------------------------
/Others/bkm/split_list_to_chunk.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 把列表分隔成同样大小的块
3 |
4 | import pprint
5 | # xrange 用法与 range 完全相同,所不同的是生成的不是一个list对象,而是一个生成器。
6 |
7 |
8 | def chunks(l, n):
9 | for i in xrange(0, len(l), n):
10 | yield l[i: i+n]
11 |
12 |
13 | pprint.pprint(list(chunks(range(10, 75), 10)))
14 |
15 | # 一句话
16 | l = range(10, 75)
17 | n = 10
18 | print tuple(l[i: i+n] for i in xrange(0, len(l), n))
--------------------------------------------------------------------------------
/Others/block_chain/pow.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 | import time
5 | from itertools import count
6 | from hashlib import md5
7 |
8 |
9 | if __name__ == "__main__":
10 | start = time.time()
11 | msg = 'randomstring'
12 | for i in count():
13 | hashid = md5(msg + str(i)).hexdigest()
14 | if hashid.startswith('0000000'):
15 | print i, hashid
16 | break
17 | print('Time: {0}'.format(time.time() - start))
--------------------------------------------------------------------------------
/Others/collection/2d_array_exchange.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 二维阵列变换
3 |
4 | arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
5 |
6 | print map(list, zip(*arr))
--------------------------------------------------------------------------------
/Others/collection/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/collection/counter/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/collection/counter/counter_access_count.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 访问集合中元素的个数
3 |
4 | import collections
5 |
6 | c = collections.Counter('abcdaab')
7 |
8 | for letter in 'abcde':
9 | print '%s : %d' % (letter, c[letter])
10 |
--------------------------------------------------------------------------------
/Others/collection/counter/counter_init.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 初始化Counter对象
3 |
4 | import collections
5 |
6 | print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
7 | print collections.Counter({'a':2, 'b':3, 'c':1})
8 | print collections.Counter(a=2, b=3, c=1)
9 |
10 | c = collections.Counter()
11 | print 'Initial :', c
12 |
13 | c.update('abcdaab') # Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})
14 | print 'Sequence:', c
15 |
16 | c.update({'a':1, 'd':5}) # 增加
17 | print 'Dict :', c # Counter({'d': 6, 'a': 4, 'b': 2, 'c': 1})
--------------------------------------------------------------------------------
/Others/collection/defaultdict/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/collection/dict/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/collection/dict/dict_viewitems.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 求字典的交并差集合
3 |
4 | d1 = dict(a=1, b=2)
5 | d2 = dict(b=2, c=3)
6 |
7 | v1 = d1.viewitems()
8 | v2 = d2.viewitems()
9 |
10 |
11 | set1 = v1 & v2 # 交集
12 | print set1
13 |
14 | dict3 = dict(set1) # 可以转化为字典
15 | print dict3
16 |
17 | set1 = v1 | v2 # 并集
18 | print set1
19 |
20 | set1 = v1 - v2 # 差集(仅v1有,v2没有的)
21 | print set1
22 |
23 | set1 = v1 ^ v2 # 对称差集 (不会同时出现在 v1 和 v2 中)
24 | print set1
25 |
26 |
--------------------------------------------------------------------------------
/Others/collection/dict/sort_dict.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 对字典进行排序
3 |
4 | import operator
5 | x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
6 | # sorted_x是一个元组列表,用每个元组的第1个元素排序
7 | sorted_x = sorted(x.items(), key=operator.itemgetter(0))
8 | print(sorted_x)
9 | assert sorted_x == [(0, 0), (1, 2), (2, 1), (3, 4), (4, 3)]
10 |
11 | # 下面是另一种方法
12 | # sorted_x是一个元组列表,用每个元组的第2个元素排序
13 | sorted_x = sorted(x.items(), key=lambda x: x[1])
14 | print(sorted_x)
15 | assert sorted_x == [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
--------------------------------------------------------------------------------
/Others/collection/heapq/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/collection/heapq/min_max.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 求最大最小元素
3 |
4 | import random
5 | import heapq
6 |
7 | a = [random.randint(0, 100) for __ in xrange(100)]
8 | print heapq.nsmallest(5, a)
9 |
10 | print heapq.nlargest(5, a)
11 |
--------------------------------------------------------------------------------
/Others/collection/return_elem_for_index.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 如果列表中存在指定索引,就返回该索引的元素
3 |
4 | def list_get(L, i, default_value=None):
5 | if -len(L) <= i < len(L):
6 | return L[i]
7 | else:
8 | return default_value
--------------------------------------------------------------------------------
/Others/collection/shuffle_list.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 用随机顺序处理列表中的元素
3 |
4 | import random
5 |
6 | def process(elem):
7 | pass
8 |
9 | def process_all_in_random_order(data, process):
10 | data = list(data)
11 |
12 | random.shuffle(data)
13 | for element in data:
14 | process(element)
--------------------------------------------------------------------------------
/Others/count_file.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # count how many python file in this dir
3 |
4 | import os
5 |
6 | python_file_num = 0
7 | for root, dirs, files in os.walk("."):
8 | for fi in files:
9 | # exclude init files
10 | if fi.find('.py') > -1 and fi.find('__init__.py') < 0:
11 | python_file_num += 1
12 | print(fi)
13 |
14 | print("\nTotal python file number is {0}.".format(python_file_num))
15 |
--------------------------------------------------------------------------------
/Others/decorator/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/decorator/singleton_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 单例模式
3 |
4 |
5 | def singleton(cls):
6 | instances = dict()
7 |
8 | def _singleton(*args, **kwargs):
9 | if cls not in instances:
10 | instances[cls] = cls(*args, **kwargs)
11 | return instances[cls]
12 |
13 | return _singleton
14 |
15 |
16 | @singleton
17 | class MyClass(object):
18 | pass
19 |
20 |
21 | if __name__ == "__main__":
22 | t1 = MyClass()
23 | t2 = MyClass()
24 | print id(t1)
25 | print id(t2)
26 |
--------------------------------------------------------------------------------
/Others/decorator/understand_decorator1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 |
4 | def connect_db():
5 | print 'connect db'
6 |
7 |
8 | def close_db():
9 | print 'close db'
10 |
11 |
12 | def query_user():
13 | print 'query some user'
14 |
15 |
16 | def query_data(query):
17 | """ 定义装饰器,返回一个函数,对query进行wrapper包装 """
18 | def wrapper():
19 | connect_db()
20 | query()
21 | close_db()
22 | return wrapper
23 |
24 | # 这里调用query_data进行实际装饰(注意装饰是动词)
25 | query_user = query_data(query_user)
26 |
27 | # 调用被装饰后的函数query_user
28 | query_user()
29 |
--------------------------------------------------------------------------------
/Others/decorator/understand_decorator2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 可以使用 python的装饰器语法糖@
3 |
4 |
5 | def connect_db():
6 | print 'connect db'
7 |
8 |
9 | def close_db():
10 | print 'close db'
11 |
12 |
13 | def query_user():
14 | print 'query some user'
15 |
16 |
17 | def query_data(query):
18 | """ 定义装饰器,返回一个函数,对query进行wrapper包装 """
19 | def wrapper():
20 | connect_db()
21 | query()
22 | close_db()
23 | return wrapper
24 |
25 |
26 | # 使用 @ 调用装饰器进行装饰
27 | @query_data
28 | def query_user():
29 | print 'query some user'
30 |
31 | query_user()
32 |
--------------------------------------------------------------------------------
/Others/hidden_features_of_python/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/hidden_features_of_python/chaining_comparison.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # python support chaining comparison operators
3 | # 链式比较
4 |
5 | x = 5
6 | print(1 < x < 10)
7 | print(x < 10 < x*10 < 100)
8 | print(5 == x > 4)
9 |
--------------------------------------------------------------------------------
/Others/hidden_features_of_python/enumerate.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 循环访问序列中的元素和索引
3 | # 用enumerate包装一个可迭代对象,可以同时使用迭代项和索引,在迭代的同时获取迭代项所在位置时非常方便。
4 |
5 | # enumerate 还可以接收一个可选参数start,默认start等于0。
6 | # enumerate(list, start=1),这样index的起始值就是1
7 |
8 | a = ['a', 'b', 'c', 'd', 'e']
9 | for index, item in enumerate(a):
10 | print(index, item)
11 |
12 | print("--------")
13 |
14 | a = ['a', 'b', 'c', 'd', 'e']
15 | for index, item in enumerate(a, 1):
16 | print(index, item)
--------------------------------------------------------------------------------
/Others/mock.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | from flask import Flask
5 | app = Flask(__name__)
6 |
7 |
8 | def make_func(i):
9 | def func():
10 | return 'this is {0}'.format(i)
11 | return func
12 |
13 |
14 | if __name__ == '__main__':
15 | funcs = map(make_func, range(2))
16 | print(funcs)
17 | for i in range(2):
18 | app.add_url_rule('/test{0}'.format(i), endpoint='{0}'.format(i), view_func=funcs[i])
19 |
20 | app.run(host='0.0.0.0', port=8080)
21 |
--------------------------------------------------------------------------------
/Others/puzzle/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/puzzle/class_static_var.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 类的静态变量
3 |
4 | # Variables declared inside the class definition, but not inside a method are class or static variables
5 |
6 | class MyClass:
7 | i = 3
8 |
9 | # this creates a class-level "i" variable, but this is distinct from any instance-level "i" variable, so you could have
10 |
11 | cl = MyClass()
12 |
13 | cl.i = 4
14 | print cl.i
15 | print MyClass.i
--------------------------------------------------------------------------------
/Others/puzzle/default_list_param.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 变化的函数默认参数
3 |
4 | """
5 | python中的函数是最高等级的对象,而不仅仅是一小段代码
6 | 一个函数是一个被它自己定义而执行的对象,默认数据是一种成员数据,
7 | 所以它们的状态和其他对象一样,会随着每一次调用而改变
8 | """
9 |
10 |
11 | def foo(a=[]):
12 | a.append(5)
13 | return a
14 |
15 |
16 | print foo()
17 | print foo()
18 | print foo()
19 |
20 |
--------------------------------------------------------------------------------
/Others/standard/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/standard/copy/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/standard/copy/copy_1.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 返回具有同样内容和属性的对象的拷贝
3 |
4 |
5 | import copy
6 | existing_list = [1, 2, 3]
7 | new_list = copy.copy(existing_list)
8 | print new_list
9 |
--------------------------------------------------------------------------------
/Others/standard/copy/copy_2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 深度拷贝,对象中的属性和内容被分别和递归地拷贝
3 |
4 | import copy
5 | existing_list_of_dicts = [{"name": "hello"}, {"name": "python"}]
6 | new_list_of_dicts = copy.deepcopy(existing_list_of_dicts)
7 | print existing_list_of_dicts
8 |
--------------------------------------------------------------------------------
/Others/standard/file/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/standard/file/dir_copy.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 复制文件夹
3 | import shutil
4 | import os
5 |
6 | shutil.copytree("test_dir/", "test_dir_copy/")
7 |
8 | "test_dir_copy" in os.listdir(os.curdir)
--------------------------------------------------------------------------------
/Others/standard/file/dir_delete.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 删除文件夹
3 |
4 | import shutil
5 | import os
6 |
7 | # os.removedirs 不能删除非空文件夹
8 | try:
9 | os.removedirs("test_dir")
10 | except Exception as msg:
11 | print msg
12 |
13 | # 使用 shutil.rmtree 来删除非空文件夹
14 | shutil.rmtree("test_dir")
--------------------------------------------------------------------------------
/Others/standard/file/file_archive.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 压缩文件
3 |
4 | import shutil
5 |
6 | print shutil.get_archive_formats()
7 |
8 | # 产生压缩文件
9 | # shutil.make_archive(basename, format, root_dir)
10 | shutil.make_archive("test_archive", "zip", "test_dir/")
--------------------------------------------------------------------------------
/Others/standard/file/file_copy.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 复制文件
3 |
4 | import shutil
5 | import os
6 |
7 | shutil.copy("file_copy.py", "file_copy.py.bak")
8 | print "file_copy.py" in os.listdir(os.curdir)
9 | print "file_copy.py.bak" in os.listdir(os.curdir)
10 |
--------------------------------------------------------------------------------
/Others/standard/file/file_rename.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 移动文件
3 |
4 | import shutil
5 | import os
6 |
7 | os.renames("file_copy.py", "../file_copy.py")
8 | os.renames("../file_copy.py", "file_copy.py")
9 |
--------------------------------------------------------------------------------
/Others/standard/file/infile_replace.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 文本文件中替换字符串
3 |
4 | import fileinput
5 |
6 | # inplace=1:标准输出会被重定向到打开文件;backup='.bak'
7 | # 替换文件内容之前备份后缀以_bak结尾;
8 | for line in fileinput.input("infile_replace.txt", backup='.bak', inplace=1):
9 | print line.replace('abcd', 'OK')
10 | fileinput.close()
11 |
--------------------------------------------------------------------------------
/Others/standard/file/infile_replace.txt:
--------------------------------------------------------------------------------
1 | abcd efg
2 |
3 | abc
4 |
5 | zxy aaabcdeofld
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/Others/standard/io/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/standard/io/pprint_data.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # pprint 是 pretty printer 的缩写,用来打印 Python 数据结构,与 print 相比,它打印出来的结构更加整齐,便于阅读。
3 |
4 | import pprint
5 | data = (
6 | "this is a string",
7 | [1, 2, 3, 4],
8 | ("more tuples", 1.0, 2.3, 4.5),
9 | "this is yet another string"
10 | )
11 |
12 | print data
13 |
14 | pprint.pprint(data)
--------------------------------------------------------------------------------
/Others/standard/multiprocessing/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/standard/multiprocessing/thread_pool.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 一行代码实现多线程/多进程
3 |
4 | import urllib2
5 | from multiprocessing.dummy import Pool as ThreadPool
6 |
7 | urls = [
8 | 'http://www.163.com',
9 | 'http://www.baidu.com',
10 | 'http://www.sina.com.cn'
11 | ]
12 |
13 | pool = ThreadPool(4)
14 | results = pool.map(urllib2.urlopen, urls)
15 | pool.close()
16 | pool.join()
17 |
--------------------------------------------------------------------------------
/Others/standard/random_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 随机函数
3 |
4 | import random
5 | # 0-1
6 | print random.random()
7 |
8 | # 随机浮点数
9 | print random.uniform(1, 10)
10 |
11 | # randint
12 | print random.randint(10, 20)
13 |
14 |
15 | print random.randrange(10, 100, 2)
16 |
17 |
18 | print random.choice("learn python")
19 | print random.choice(['hello', 'world', 'yes'])
20 | print random.choice(('hello', 'world', 'yes'))
21 |
22 | print random.choice('abcdefg!@#$%^&*')
23 |
24 | lst = range(100)
25 | random.shuffle(lst)
26 | print lst
27 |
28 | lst = range(100)
29 | print random.sample(lst, 5)
--------------------------------------------------------------------------------
/Others/standard/sys/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/standard/time/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/standard/time/clock_time.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 计算CPU用时和间隔时间
3 |
4 | import time
5 |
6 |
7 | def procedure():
8 | time.sleep(2.5)
9 |
10 | # Return the CPU time or real time since the start of the process or since
11 | # the first call to clock()
12 |
13 | # measure process time
14 | t0 = time.clock()
15 | procedure()
16 | print time.clock() - t0, "seconds process time"
17 |
18 | # measure wall time
19 | t0 = time.time()
20 | procedure()
21 | print time.time() - t0, "seconds wall time"
--------------------------------------------------------------------------------
/Others/standard/time/date_data.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 日期数据
3 |
4 | import datetime
5 |
6 | today = datetime.date.today()
7 | print today
8 | print 'ctime:', today.ctime()
9 | print 'tuple:', today.timetuple() #返回日期对应的time.struct_time对象;
10 | print 'ordinal:', today.toordinal() # 返回日期对应的Gregorian Calendar日期;罗马教皇格利高里的
11 | print 'Year:', today.year
12 | print 'Mon :', today.month
13 | print 'Day :', today.day
14 |
--------------------------------------------------------------------------------
/Others/standard/time/time_data.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 初始化时间数据
3 |
4 | import datetime
5 |
6 | t = datetime.time(1, 2, 3)
7 | print t
8 | print 'hour :', t.hour
9 | print 'minute:', t.minute
10 | print 'second:', t.second
11 | print 'microsecond:', t.microsecond
12 | print 'tzinfo:', t.tzinfo
13 |
--------------------------------------------------------------------------------
/Others/standard/time/time_instance.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 时间实例的相关数据
3 |
4 | import datetime
5 |
6 | print 'Earliest :', datetime.time.min
7 | print 'Latest :', datetime.time.max
8 | print 'Resolution:', datetime.time.resolution
--------------------------------------------------------------------------------
/Others/standard/turtule_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | #
3 | from turtle import Turtle
4 | t = Turtle()
5 | t.setpos(-200, 0)
6 | for i in range(36):
7 | t.forward(400)
8 | t.right(170)
--------------------------------------------------------------------------------
/Others/syntax/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/syntax/builtin/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/syntax/builtin/eq_function.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # __eq__()用于判断对象内容是否相等
3 |
4 | # is 当比较的是相同的对象实例时总是返回True
5 | # == 取决于 __eq__()方法的实现
6 |
7 |
8 | class A(object):
9 | def __init__(self, name):
10 | self.name = name
11 |
12 | def __eq__(self, obj):
13 | return self.name == obj.name
14 |
15 |
16 | if __name__ == '__main__':
17 | a = A("Leon")
18 | b = A("Leon")
19 | print a == b # True
20 | print a is b # False
21 |
22 |
23 |
--------------------------------------------------------------------------------
/Others/syntax/class/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/syntax/class/static_var_of_class.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 类的静态变量
3 |
4 |
5 | class MyClass(object):
6 | i = 3
7 |
8 |
9 | m = MyClass()
10 | m.i = 4
11 |
12 | print(MyClass.i) # 3
13 | print(m.i) # 4
14 |
15 | # 上面的i变量是类级别的,它和所有的实体对象的i不一样
16 |
--------------------------------------------------------------------------------
/Others/syntax/collection/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/syntax/collection/merge_lists.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 合并列表
3 |
4 | a = [1, 3, 5, 7, 9]
5 | b = [2, 3, 4, 5, 6]
6 | c = [5, 6, 7, 8, 0]
7 | print list(set().union(a, b, c))
--------------------------------------------------------------------------------
/Others/syntax/collection/named_slice.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 命名切片
3 |
4 | a = [0, 1, 2, 3, 4, 5]
5 |
6 | # slice(start, end, step)
7 | LASTTHREE = slice(-3, None)
8 | print LASTTHREE
9 | print a[LASTTHREE]
--------------------------------------------------------------------------------
/Others/syntax/collection/set_duplicate_intersection_difference.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 查找列表中重复的元素,两个集合求交,两个集合求异
3 |
4 | # duplicate
5 | some_list = ['a', 'b', 'c', 'm', 'n', 'c']
6 | duplicates = set([x for x in some_list if some_list.count(x) > 1])
7 | print duplicates
8 |
9 | # intersection
10 | valid = set(['yellow', 'red', 'blue', 'green', 'black'])
11 | input_set = set(['red', 'brown'])
12 | print(input_set.intersection(valid))
13 |
14 | # difference
15 | print(input_set.difference(valid))
16 |
17 |
18 |
--------------------------------------------------------------------------------
/Others/syntax/collection/zip_reverse_dict.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 使用zip反转字典
3 |
4 | m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
5 | print m
6 |
7 | print m.items()
8 | # [('a', 1), ('c', 3), ('b', 2), ('d', 4)]
9 |
10 | print zip(m.values(), m.keys())
11 | # [(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
12 |
13 | mi = dict(zip(m.values(), m.keys()))
14 | print mi
15 | # {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
--------------------------------------------------------------------------------
/Others/syntax/except/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/syntax/except/user_named_exception_class.py:
--------------------------------------------------------------------------------
1 | # coding=utf
2 | # 用户自定义的异常类
3 |
4 | #Exceptions should typically be derived from the Exception class, either directly or
5 | #indirectly. For example:
6 |
7 | class MyError(Exception):
8 | def __init__(self, value):
9 | self.value = value
10 | def __str__(self):
11 | return repr(self.value)
12 |
13 | try:
14 | raise MyError(2*2)
15 | except MyError, e:
16 | print 'My exception occurred, value:', e.value
17 |
--------------------------------------------------------------------------------
/Others/syntax/func/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/syntax/func/apply_func.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 展示如何使用apply函数
3 |
4 | def func(x, y, z):
5 | return x + y + z
6 |
7 | print apply(func, (2, 3, 4))
8 |
9 | f = lambda x, y, z: x + y + z
10 | print apply(f, (2, 3, 4))
--------------------------------------------------------------------------------
/Others/syntax/func/func_return_func.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 函数返回另一个函数
3 |
4 |
5 | def knights():
6 | title = 'sir'
7 | action = (lambda x: title + " " + x)
8 | return action
9 |
10 | act = knights()
11 | print act('robin')
12 |
--------------------------------------------------------------------------------
/Others/syntax/func/func_return_lambda.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 返回一个lambda函数的函数
3 |
4 | def action(x):
5 | return (lambda y: x + y)
6 |
7 | act = action(2)
8 |
9 | print act
10 |
11 | print act(98)
--------------------------------------------------------------------------------
/Others/syntax/func/higher_order_function.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 高阶函数
3 |
4 | # 既然变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
5 |
6 |
7 | def add(x, y, f):
8 | return f(x) + f(y)
9 |
10 | a = add(-10, 5, abs)
11 | print a
12 | assert a == 15
13 |
14 |
--------------------------------------------------------------------------------
/Others/syntax/func/pass_func_as_param2.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 将函数作为参数传入
3 |
4 | def minmax(test, *args):
5 | res = args[0]
6 | for arg in args[1:]:
7 | if test(arg, res):
8 | res = arg
9 | return res
10 |
11 | def lessthan(x, y): return x < y
12 | def grtrthan(x, y): return x > y
13 |
14 | print minmax(lessthan, 4, 2, 1, 5, 6, 3)
15 | print minmax(grtrthan, 4, 2, 1, 5, 6, 3)
--------------------------------------------------------------------------------
/Others/syntax/loop/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/syntax/loop/break_out_of_nested_loops.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 从多重循环中退出
3 |
4 | for x in xrange(10):
5 | for y in xrange(10):
6 | for z in xrange(10):
7 | print x, y, z
8 | if x*y*z == 30:
9 | break
10 | else:
11 | continue
12 | break
13 | else:
14 | continue
15 | break
16 |
17 |
--------------------------------------------------------------------------------
/Others/syntax/other/__init__.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
--------------------------------------------------------------------------------
/Others/syntax/other/dict_get.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 访问字典中键值的两种方法
3 |
4 | #对于一个字典(dict) d,除了可以用d['key']访问元素,也可以用d.get('key')。
5 | # 当字典不包含某键值时,前一种方法会报异常,而后一种则会返回一个默认值,缺省的默认值是None。
6 | # 下面代码展示这种用法:
7 |
8 |
9 | info = {"name": "Python"}
10 |
11 | print info.get("age", 32)
12 | print info['age']
13 |
--------------------------------------------------------------------------------
/Others/syntax/other/dynamic_class.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 根据参数动态生成类
3 |
4 | def do_task(task_name):
5 | task = eval(task_name)()
6 | task.step1()
7 |
8 |
9 |
10 | class Task1(object):
11 | def step1(self):
12 | print "task1"
13 |
14 | class Task2(object):
15 | def step1(self):
16 | print "task2"
17 |
18 | if __name__ == "__main__":
19 | do_task("Task1")
20 | do_task("Task2")
21 |
22 |
23 |
--------------------------------------------------------------------------------
/Others/syntax/other/exec_eval.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # exec语句用来执行储存在字符串或文件中的Python语句。
4 | exec 'print "Hello World"'
5 |
6 | # eval语句用来计算存储在字符串中的有效Python表达式
7 | print eval('2*3')
--------------------------------------------------------------------------------
/Others/syntax/other/for_else.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 使用for else语句查找素数
3 |
4 | for n in range(2, 10000):
5 | for i in range(2, n):
6 | if n % i == 0:
7 | break
8 | else:
9 | # loop through without finding
10 | print(n, "is a prime number")
11 |
--------------------------------------------------------------------------------
/Others/syntax/other/generator_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 |
4 | def create_generator():
5 | mylist = range(10)
6 | for i in mylist:
7 | yield i*i
8 |
9 | my_generator = create_generator()
10 | print my_generator
11 | for i in my_generator:
12 | print i
13 |
--------------------------------------------------------------------------------
/Others/syntax/other/if_else.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 把if else写在同一行
3 |
4 | def max_of_two(x, y):
5 | return x if x > y else y
6 |
7 | print max_of_two(3, 5)
8 |
--------------------------------------------------------------------------------
/Others/syntax/other/kwargs_param.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 在使用kwargs参数中如果获得键值对
3 |
4 | def greet_me(**kwargs):
5 | for key, value in kwargs.items():
6 | print("{0} == {1}".format(key, value))
7 |
8 | greet_me(name="yasoob", age=30)
9 |
10 |
--------------------------------------------------------------------------------
/Others/syntax/other/list_and_generator.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 用range生成list和generator
3 |
4 | L = [x*x for x in range(10)]
5 | print type(L)
6 | print L
7 |
8 | # 创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator。
9 |
10 | g = (x*x for x in range(10))
11 | print type(g)
12 | print g
13 | print g.next()
14 | print g.next()
15 | print g.next()
16 |
17 | # 不断调用next()方法实在是太变态了,正确的方法是使用for循环,因为generator也是可迭代对象
18 | g = (x*x for x in range(10))
19 | for i in g:
20 | print i
21 |
--------------------------------------------------------------------------------
/Others/syntax/other/list_copy.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 列表的内容复制
3 |
4 | a = [1, 2, 3]
5 | b = a[:]
6 | assert b == a and b is not a
7 |
--------------------------------------------------------------------------------
/Others/syntax/other/list_dict_set_comprehension.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 列表推导,字典推导,集合推导
3 |
4 | # list comprehension
5 | a = [1, 2, 3, 4, 5, 6]
6 | even_squares = [x**2 for x in a if x % 2 == 0]
7 | print even_squares
8 |
9 | # dict comprehension
10 | student_ranks = {"fang": 88, "liu": 77, "tian": 99}
11 | rank_dict = {rank: name for name, rank in student_ranks.items()}
12 | print rank_dict
13 |
14 | # set comprehension
15 | name_len_set = {len(name) for name in student_ranks.keys()}
16 | print name_len_set
17 |
--------------------------------------------------------------------------------
/Others/syntax/other/list_in_class.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 类中的列表成员变量是所有对象共享的,因为列表是引用
3 |
4 | class Student(object):
5 | age = 0
6 | friends = []
7 |
8 | def meet_new_friend(self, name):
9 | self.friends.append(name)
10 |
11 | if __name__ == "__main__":
12 | a = Student()
13 | a.age = 10
14 | a.meet_new_friend("friend1")
15 | b = Student()
16 | b.age = 12
17 | b.meet_new_friend("friend2")
18 |
19 | print b.friends # ['friend1', 'friend2']
20 |
21 |
--------------------------------------------------------------------------------
/Others/syntax/other/multi_exception_in_one_line.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 一行里捕捉多个异常
3 |
4 | try:
5 | # 可能出错的代码
6 | pass
7 | except (ValueError, ZeroDivisionError) as e:
8 | pass
9 |
10 |
--------------------------------------------------------------------------------
/Others/syntax/other/range_vs_xrange.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # range和xrange
3 |
4 | # xrange 和 range 这两个基本上都是在循环的时候用
5 | for i in range(0, 100):
6 | print i
7 |
8 | for i in xrange(0, 100):
9 | print i
10 |
11 | # range会直接生成一个list对象
12 | # 而xrange则不会直接生成一个list,而是每次调用返回其中的一个值:
13 | # xrange 用法与 range 完全相同,所不同的是生成的不是一个list对象,而是一个生成器。
14 | # 要生成很大的数字序列的时候,用xrange会比range性能优很多,因为不需要一上来就开辟一块很大的内存空间。
15 |
16 | a = xrange(0,100)
17 | print type(a)
18 | print a
19 | print a[0], a[99]
--------------------------------------------------------------------------------
/Others/syntax/other/reduce_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 用reduce求和
3 |
4 | def add(x, y):
5 | return x + y
6 |
7 |
8 | sum = reduce(add, range(101))
9 | print sum
10 |
11 |
12 | def fn(x, y):
13 | return x * 10 + y
14 |
15 |
16 | def char2num(s):
17 | return {'0': 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}[s]
18 |
19 |
20 | print reduce(fn, map(char2num, "123456"))
21 |
--------------------------------------------------------------------------------
/Others/syntax/other/repr_sample.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # repr函数用来取得对象的规范字符串表示
3 |
4 | # 反引号(也称转换符)可以完成相同的功能。
5 | # 在大多数时候有eval(repr(object)) == object
6 |
7 |
8 | i = []
9 | i.append('item')
10 |
11 | print `i` # "['item']"
12 |
13 | print repr(i) # "['item']"
14 |
--------------------------------------------------------------------------------
/Others/syntax/other/swap_variables.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # easy way to switch variables
3 | # 快速交换两个变量
4 |
5 | a, b = 5, 10
6 | a, b = b, a
7 | print a, b # 10, 5
8 |
--------------------------------------------------------------------------------
/Others/syntax/other/underscore.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 使用下划线忽略不关心的变量
3 |
4 | data = ['ACME', 50, 91.1, (2012, 12,21)]
5 | _, shares, price, _ = data
6 | print shares
7 |
--------------------------------------------------------------------------------
/Others/syntax/var_scope/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 |
7 | if __name__ == "__main__":
8 | pass
--------------------------------------------------------------------------------
/Others/syntax/var_scope/var_chain.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 作用域链
4 | # Python中有作用域链,变量会由内到外找,先去自己作用域去找,自己没有再去上级去找,直到找不到报错
5 |
6 | name = "lzl"
7 |
8 |
9 | def f1():
10 | name = "Eric"
11 |
12 | def f2():
13 | name = "Snor"
14 | print(name)
15 |
16 | f2()
17 |
18 |
19 | f1()
20 |
--------------------------------------------------------------------------------
/Others/syntax/var_scope/var_of_block.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 块级作用域
4 |
5 | # 代码执行成功,没有问题;在Java/C#中,执行上面的代码会提示name,age没有定义,
6 | # 而在Python中可以执行成功,这是因为在Python中是没有块级作用域的,
7 | # 代码块里的变量,外部可以调用,所以可运行成功;
8 |
9 | if 1 == 1:
10 | name = "lzl"
11 |
12 | print(name)
13 |
14 |
15 | for i in range(10):
16 | age = i
17 |
18 | print(age)
19 |
--------------------------------------------------------------------------------
/Others/syntax/var_scope/var_of_local.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | # 局部作用域
4 | # name的作用域也只是在函数内部,外部依然无法进行调用
5 |
6 |
7 | def func():
8 | name = "lzl"
9 |
10 |
11 | func() # 执行函数
12 | print(name)
13 |
--------------------------------------------------------------------------------
/docs/Python实践14-filter()函数.md:
--------------------------------------------------------------------------------
1 | ### 作用
2 | - Python中filter()函数能够通过函数过滤序列
3 | - 最终返回一个新的列表
4 |
5 | ### 形式
6 | - filter()函数接受两个参数,形如filter(func, seq)
7 | - 第一个参数func是一个函数
8 | - 第二个参数seq是一个序列
9 | - filter()将函数func调用,一一映射到序列seq的每一个元素上
10 | - 如果func对某元素的返回值为真,则将该元素加入到新列表中
11 | - 最终返回这个新列表
12 |
13 |
14 | ### 例子
15 | 下面的例子演示了如何过滤成人年龄
16 | ```
17 | adult_ages = filter(lambda x: x >= 18, range(1, 100))
18 | print(adult_ages)
19 | ```
20 |
21 | ### 代码下载
22 | 本文地址已经归档到github,您可以访问下面的链接获得。
23 | [代码地址](https://github.com/jumper2014/Asgard/tree/master/practice/func/20180118)
24 |
25 | 如果觉得本文对您有帮助,敬请点赞。
--------------------------------------------------------------------------------
/docs/Python实践47-选择Python2还是Python3.md:
--------------------------------------------------------------------------------
1 | ### 现状
2 | - 貌似现在大部分部署在生产环境的应用使用的还是Python2.7
3 | - 但是Python3已经完全做好起用于部署在生产环境的准备了
4 | - Python2.7在现在到2020年之间仅仅进行必要的安全更新
5 | - Python3作为新的最佳实践,会继续存在。Python2在两年之后就会退休。到那时只会Python2的话,会显得你很落伍。
6 |
7 |
8 | ### 建议
9 | - 高度建议从现在开始新的应用都用Python3来开发
10 | - 如果是刚刚开始学习Python的话,学习Python2.7是有用的,但是学习Python3更有用
11 | - 很多公司已有的应用还是2.7的,如果要使用和维护它们,还是得了解2.7
12 | - 如果你在开发开源库,最好能够支持Python2和Python3,这样会使你拥有更多用户。
13 |
14 |
15 | ### 哪些情况应该使用Python2
16 | - 项目中的某些重要依赖只有Python2的实现
17 | - 如果部署环境默认Python版本是2,并且升级到3导致工作量巨大
18 | - 已有项目移植到Python3风险和成本过大
--------------------------------------------------------------------------------
/docs/Python实践5-Python的特点.md:
--------------------------------------------------------------------------------
1 | ### Python起源
2 | - 1989年Guido始创了Python, 1991年发布了第一个公开发行版
3 |
4 | ### Python的特点
5 | - 解释执行,动态语言
6 | - 是面向对象的高级语言,容易对现实世界进行建模
7 | - 在数据分析和人工智能方面使用广泛
8 | - 内置和第三方的库众多,开箱即用,新人容易上手
9 | - 社区活跃,资源丰富
10 |
11 |
12 | ### 个人感受
13 | - 简便易用的各种库,特别适合做自动化相关工作
14 | - 有一定的跨平台性,不过windows上总体对Python的支持不好,所以开发和测试尽量避免使用windows作为平台。
15 | - 如果是新手开发,还是用强类型的静态语言开发比较好,写出来的东西更容易维护。
16 | - 适合做原型开发工具,效率高。如果用来做复杂的多人协作项目,对开发者要求比较高。
17 | - 由于各种库比较多,语法灵活,还有两个主要版本,相对来说知识点要比其他语言要多些。
--------------------------------------------------------------------------------
/docs/Python实践6-模块结构和布局.md:
--------------------------------------------------------------------------------
1 | ### 模块经典的结构和布局
2 | 1. 起始行 #!/usr/bin/env python
3 | 2. 模块文档(文档字符串)
4 | 3. 模块导入
5 | 4. (全局)变量定义
6 | 5. 类定义(如果有的话)
7 | 6. 函数定义(如果有的话)
8 | 7. 主程序
9 |
10 |
11 | ### 主程序
12 | 我们常常看到的主程序形如
13 | ```
14 | if __name__ == "__main__":
15 | pass
16 | ```
17 | 那么它的作用是什么呢?
18 | - `__name__` 系统变量用来表示该模块是被导入的还是被直接执行
19 | - 如果模块是被导入的,`__name__`的值为模块的名字
20 | - 如果模块是被直接执行,`__name__`的值就为`'__main__'`
21 | - 所以这个主程序就只有在被直接执行的时候会运行,而在被导入的时候避免被执行
22 |
23 | 如果觉得本文对您有帮助,敬请点赞。
--------------------------------------------------------------------------------
/docs/Python实践63-为什么不建议切片时同时指定start, end和stride.md:
--------------------------------------------------------------------------------
1 | ### 步进切片
2 | - python允许实现步进切片,形式是mylist[start, end, stride]
3 | - 含义是从start开始到end(不包含end位置)的元素里面,每隔步进stride取一个元素
4 | - 例如a= [1, 2, 3, 4], a[::2]的结果就是[1, 3]
5 | - 其中的步进stride可以是负数,一个常用方法就是b = a[::-1]来获得a的倒序列表
6 |
7 | ### 不建议切片时同时指定start, end和stride
8 | - 三个参数同时指定,会导致代码难以理解,因为三个条件同时满足的结果可能和你指定的参数并不完全相关
9 | - 最好不要使用负数的步进,因为不宜理解
10 | - 如果非要执行范围切割和步进切割,最好拆成两条赋值语句。一个进行范围切割,一个做步进切割。
--------------------------------------------------------------------------------
/docs/Python实践73-匿名函数和lambda.md:
--------------------------------------------------------------------------------
1 | ### 匿名函数和lambda表达式
2 | - 匿名函数是指不用def形式声明的函数
3 | - Python允许用lambda关键字创建匿名函数
4 | - lambda表达式的返回是一个可调用的函数对象
5 | - lambda表达式的形式为:lambda [arg1 [, arg2, ...]]: expression
6 |
7 | ### lambda表达式的特点
8 | - 只能由一条表达式组成
9 | - 一般在高阶函数中使用lambda表达式作为参数
10 | - 精简的函数定义方式可以减少代码行数
11 | - 调用处即定义有时可以提高代码可读性
12 | - 可以用来实现闭包
13 |
14 | ### 简单例子
15 | ```
16 | squares = map(lambda x: x**2, range(10))
17 | print(squares)
18 | ```
--------------------------------------------------------------------------------
/docs/Python实践83-assert语句.md:
--------------------------------------------------------------------------------
1 | ### assert简介
2 | - 形式:assert condition, your message
3 | - condition为True时,程序继续运行,下一个语句会被执行
4 | - condition为False时将会抛出AssertionError异常,该异常的信息为your message
5 | - assert常常用来调试和测试
6 |
7 | ### 简单的例子
8 | ```
9 | def divide(num1, num2):
10 | assert num2 != 0, "Divisor cannot be zero"
11 | return num1 / num2
12 |
13 |
14 | if __name__ == '__main__':
15 | try:
16 | a2 = divide(12, 0)
17 | except AssertionError as e:
18 | print(e)
19 | # Divisor cannot be zero
20 |
21 | ```
--------------------------------------------------------------------------------
/docs/Python实践84-pass语句.md:
--------------------------------------------------------------------------------
1 | ### pass简介
2 | - Python里的pass一般用作占位符,让未实现的功能部分语法正确
3 | - pass表示什么也不做
4 |
5 |
6 | ### pass和注释
7 | - 虽然pass和注释的行为很相似,都是什么都不做,但是他们是完全不同的
8 | - 注释会被Python解释器忽略
9 | - pass不会被Python解释器忽略,只是告诉执行器什么都不要做而已
10 |
11 | ### 例子
12 | - 占位符,为了程序通过编译和接下来的扩展
13 | ```
14 | class C:
15 | pass
16 | ```
17 | - 什么都不做,但是显式表示程序逻辑
18 | ```
19 | for num in [20, 11, 9, 66, 4, 89, 44]:
20 | if num%2 == 0:
21 | pass
22 | else:
23 | print(num)
24 | ```
--------------------------------------------------------------------------------
/docs/Python实践92-可变对象作为函数默认参数.md:
--------------------------------------------------------------------------------
1 | ### 函数默认值
2 | - 函数的默认值只被赋值一次。这使得当默认值是可变对象时会有所不同,比如列表、字典或者大多数类的实例。
3 | - 例如,下面的函数在后续调用过程中会累积(前面)传给它的参数:
4 | ```
5 | def f(a, L=[]):
6 | L.append(a)
7 | return L
8 |
9 | print(f(1))
10 | print(f(2))
11 | print(f(3))
12 | ```
13 | 这将输出:
14 | ```
15 | [1]
16 | [1, 2]
17 | [1, 2, 3]
18 | ```
19 | - 如果你不想让默认值在后续调用中累积,你可以像下面一样定义函数:
20 | ```
21 | def f(a, L=None):
22 | if L is None:
23 | L = []
24 | L.append(a)
25 | return L
26 | ```
--------------------------------------------------------------------------------
/practice/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/__init__.py
--------------------------------------------------------------------------------
/practice/ai/datasets/movielens/movies.dat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/ai/datasets/movielens/movies.dat
--------------------------------------------------------------------------------
/practice/ai/datasets/studentscores.csv:
--------------------------------------------------------------------------------
1 | Hours,Scores
2 | 2.5,21
3 | 5.1,47
4 | 3.2,27
5 | 8.5,75
6 | 3.5,30
7 | 1.5,20
8 | 9.2,88
9 | 5.5,60
10 | 8.3,81
11 | 2.7,25
12 | 7.7,85
13 | 5.9,62
14 | 4.5,41
15 | 3.3,42
16 | 1.1,17
17 | 8.9,95
18 | 2.5,30
19 | 1.9,24
20 | 6.1,67
21 | 7.4,69
22 | 2.7,30
23 | 4.8,54
24 | 3.8,35
25 | 6.9,76
26 | 7.8,86
27 |
--------------------------------------------------------------------------------
/practice/ai/distance/cos_distance.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import numpy as np
6 |
7 | if __name__ == '__main__':
8 | x = np.random.random(10)
9 | y = np.random.random(10)
10 | print(x)
11 | print(y)
12 |
13 | # 根据公式求解
14 | # np.dot 点积
15 | # np.linalog.norm 向量的2范数, 即向量的每个元素的平方和再开平方根,
16 | d1 = np.dot(x, y) / (np.linalg.norm(x) * np.linalg.norm(y))
17 | print(d1)
--------------------------------------------------------------------------------
/practice/ai/distance/e_distance.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 | # 欧氏距离
5 |
6 | import numpy as np
7 |
8 | if __name__ == '__main__':
9 | x = np.random.random(10)
10 | y = np.random.random(10)
11 | print(x)
12 | print(y)
13 |
14 | # 根据公式求解欧氏距离
15 | d1 = np.sqrt(np.sum(np.square(x - y)))
16 | print(d1)
17 |
--------------------------------------------------------------------------------
/practice/ai/distance/m_distance.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 | # 曼哈顿距离
5 |
6 | import numpy as np
7 |
8 | if __name__ == '__main__':
9 | x = np.random.random(10)
10 | y = np.random.random(10)
11 | print(x)
12 | print(y)
13 |
14 | # 根据公式求解曼哈顿距离
15 | d1 = np.sum(np.abs(x - y))
16 | print(d1)
--------------------------------------------------------------------------------
/practice/ai/fr/face_recognition_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | import face_recognition
7 |
8 | if __name__ == '__main__':
9 | pass
--------------------------------------------------------------------------------
/practice/ai/pic/simular/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/ai/pic/simular/1.png
--------------------------------------------------------------------------------
/practice/ai/pic/simular/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/ai/pic/simular/2.png
--------------------------------------------------------------------------------
/practice/ai/pic/simular/我们不一样.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/ai/pic/simular/我们不一样.png
--------------------------------------------------------------------------------
/practice/bokeh_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | from bokeh.plotting import figure, output_file, show
7 | # 创建图表
8 | p = figure(plot_width=300, plot_height=300, tools="pan,reset,save")
9 | # 图表中添加圆
10 | p.circle([1, 2.5, 3, 2], [2, 3, 1, 1.5], radius=0.3, alpha=0.5)
11 | # 定义输出形式
12 | output_file("foo.html")
13 | # 展示图表
14 | show(p)
15 |
16 |
--------------------------------------------------------------------------------
/practice/class/20180123/file_sha1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | from filehash import sha1
5 |
6 | if __name__ == "__main__":
7 | print sha1('some_file.txt')
--------------------------------------------------------------------------------
/practice/class/20180123/some_file.txt:
--------------------------------------------------------------------------------
1 | hello python
--------------------------------------------------------------------------------
/practice/class/20180205/magic_bool.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # __bool__优先级比 __len__ 高
4 | # 需要Python 3
5 |
6 |
7 | class MyClass(object):
8 | def __init__(self):
9 | pass
10 |
11 | def __bool__(self):
12 | return False
13 |
14 | def __len__(self):
15 | return 1
16 |
17 |
18 | def print_boolean_value(value):
19 | if value:
20 | print('True')
21 | else:
22 | print('False')
23 |
24 |
25 | if __name__ == "__main__":
26 | obj = MyClass()
27 | # output: False
28 | print_boolean_value(obj)
29 |
30 |
--------------------------------------------------------------------------------
/practice/class/slot/slot_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | class Student(object):
7 | __slots__ = ['name', 'age']
8 |
9 | def __init__(self, name, age):
10 | self.name = name
11 | self.age = age
12 | self.grade = 0
13 |
14 |
15 | if __name__ == '__main__':
16 | try:
17 | s = Student('Li', 20)
18 | except Exception as e:
19 | print(e)
20 | # 'Student' object has no attribute 'grade'
21 |
--------------------------------------------------------------------------------
/practice/collection/dict/20180203/defaultdict_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | # collections.defaultdict可以接受一个函数作为参数来初始化。
5 | # 什么意思呢,我们想要frequencies[word]初始化为0,
6 | # 这时就可以用一个int()函数作为参数出给defaultdict,我们不带参数调用int(),int()就会返回一个0值
7 |
8 | from collections import defaultdict
9 |
10 | if __name__ == "__main__":
11 | # 将句子里面的单词抽取成元组
12 | txt = 'I like python and i use python'
13 | words = txt.split(' ')
14 | print(words)
15 |
16 | # 开始统计单词出现次数
17 | counts = defaultdict(int)
18 | for word in words:
19 | counts[word] += 1
20 | print(counts)
21 |
22 |
--------------------------------------------------------------------------------
/practice/collection/dict/20180203/setdefault_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | if __name__ == '__main__':
5 | # 将句子里面的单词抽取成元组
6 | txt = 'I like python and i use python'
7 | words = txt.split(' ')
8 | print(words)
9 |
10 | # 开始统计单词出现次数
11 | counts = dict()
12 | for word in words:
13 | counts[word] = counts.setdefault(word, 0) + 1
14 | print(counts)
15 |
--------------------------------------------------------------------------------
/practice/collection/dict/20180204/count_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | if __name__ == "__main__":
5 | # 将句子里面的单词抽取成元组
6 | txt = 'I like python and i use python'
7 | words = txt.split(' ')
8 | print(words)
9 |
10 | words_set = set(words)
11 | counts = dict()
12 | for word in words_set:
13 | counts[word] = words.count(word)
14 | print(counts)
--------------------------------------------------------------------------------
/practice/collection/dict/20180204/counter_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 |
5 | from collections import Counter
6 |
7 | if __name__ == "__main__":
8 | # 将句子里面的单词抽取成元组
9 | txt = 'I like python and i use python'
10 | words = txt.split(' ')
11 | print(words)
12 |
13 | # 一行代码搞定
14 | counter = Counter(words)
15 | print(dict(counter))
--------------------------------------------------------------------------------
/practice/collection/list/20180325/stride.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | if __name__ == '__main__':
7 | a = [1, 2, 3, 4]
8 | print(a[::2])
9 | print(a[::-1])
--------------------------------------------------------------------------------
/practice/collection/set/set_add_tuple.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | if __name__ == '__main__':
7 | myset = set()
8 | myset.add(("1", "2", "3"))
9 | myset.add(("1", "2", "1"))
10 | myset.add(("1", "2", "3"))
11 |
12 | print(myset)
--------------------------------------------------------------------------------
/practice/collection/set/set_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | if __name__ == '__main__':
7 | nums = {1, 2, 3}
8 | nums.add(4)
9 | squares = {x*x for x in nums}
10 | print(nums)
11 | print(squares)
12 | # {1, 2, 3, 4}
13 | # {16, 1, 4, 9}
--------------------------------------------------------------------------------
/practice/collection/tuple/20180130/namedtuple_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | from collections import namedtuple
5 |
6 | if __name__ == '__main__':
7 | # 定义一个namedtuple类型User,并包含name,sex和age属性。
8 | User = namedtuple('User', ['name', 'sex', 'age'])
9 |
10 | # 创建一个User对象
11 | user = User(name='Li', sex='male', age=21)
12 |
13 | # 使用索引访问元素,output: Li
14 | print(user[0])
15 |
16 | # 使用属性访问元素,output: 21
17 | print(user.age)
18 |
19 | # 修改对象属性,注意要使用"_replace"方法
20 | user = user._replace(age=22)
21 | # output: 22
22 | print(user.age)
23 |
--------------------------------------------------------------------------------
/practice/concurrency/coroutines_aiohttp.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import aiohttp
6 | import asyncio
7 |
8 |
9 | async def main(url):
10 | async with aiohttp.ClientSession() as session:
11 | async with session.get(url) as resp:
12 | print(resp.status)
13 | print(await resp.text())
14 |
15 | url = 'https://zhuanlan.zhihu.com/python2018'
16 | loop = asyncio.get_event_loop()
17 | loop.run_until_complete(main(url))
--------------------------------------------------------------------------------
/practice/concurrency/coroutines_sample1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import asyncio
6 |
7 |
8 | async def main():
9 | print('hello')
10 | await asyncio.sleep(1)
11 | print('world')
12 |
13 | loop = asyncio.get_event_loop()
14 | loop.run_until_complete(main())
15 | loop.close()
--------------------------------------------------------------------------------
/practice/concurrency/coroutines_sample2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import asyncio
6 |
7 |
8 | async def main():
9 | print('hello')
10 | await asyncio.sleep(1)
11 | print('world')
12 |
13 | loop = asyncio.get_event_loop()
14 | task = loop.create_task(main())
15 | print(task) # pending状态的Task
16 | loop.run_until_complete(task)
17 | print(task) # finished状态的Task
18 | print(isinstance(task, asyncio.Future)) # True
19 | loop.close()
--------------------------------------------------------------------------------
/practice/concurrency/coroutines_sample3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import asyncio
6 |
7 |
8 | async def main():
9 | print('hello')
10 | await asyncio.sleep(1)
11 | print('world')
12 | return 'hello world'
13 |
14 | loop = asyncio.get_event_loop()
15 | # 定义一个future
16 | task = asyncio.ensure_future(main())
17 | loop.run_until_complete(task)
18 | # 获得协程的执行结果
19 | print('Task return: {}'.format(task.result()))
20 | loop.close()
21 | """
22 | hello
23 | world
24 | Task return: hello world
25 | """
--------------------------------------------------------------------------------
/practice/decorator/20180114/delay_param.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 让装饰器带参数,
4 | # 和不带参数的示例相比在外层多了一层包装。
5 |
6 | import time
7 |
8 |
9 | def delay(sec):
10 | def wrapper(func):
11 | def _wrapper(*args, **kwargs):
12 | time.sleep(sec)
13 | ret = func(*args, **kwargs)
14 | print("delay %d seconds to call %s" % (sec, func.__name__))
15 | return ret
16 | return _wrapper
17 | return wrapper
18 |
19 |
20 | @delay(2)
21 | def add(a, b):
22 | return a + b
23 |
24 |
25 | if __name__ == "__main__":
26 | add(1, 2)
27 |
--------------------------------------------------------------------------------
/practice/decorator/20180114/delay_wrapper.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import time
5 |
6 |
7 | def delay(func):
8 | def wrapper(*args, **kwargs):
9 | time.sleep(1)
10 | ret = func(*args, **kwargs)
11 | print("delay 1 second to call %s" % func.__name__)
12 | return ret
13 | return wrapper
14 |
15 |
16 | @delay
17 | def add(a, b):
18 | return a + b
19 |
20 |
21 | if __name__ == "__main__":
22 | add(1, 2)
23 |
--------------------------------------------------------------------------------
/practice/decorator/20180118/singleton.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 |
5 | def singleton(cls):
6 | instances = dict()
7 |
8 | def _singleton(*args, **kwargs):
9 | if cls not in instances:
10 | instances[cls] = cls(*args, **kwargs)
11 | return instances[cls]
12 | return _singleton
13 |
14 |
15 |
16 | if __name__ == "__main__":
17 | pass
--------------------------------------------------------------------------------
/practice/func/default_param_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | def f1(a, L=[]):
7 | L.append(a)
8 | return L
9 |
10 |
11 | print(f1(1))
12 | print(f1(2))
13 | print(f1(3))
14 |
15 |
16 | def f2(a, L=None):
17 | if L is None:
18 | L = []
19 | L.append(a)
20 | return L
21 |
22 |
23 | print(f2(1))
24 | print(f2(2))
25 | print(f2(3))
26 |
--------------------------------------------------------------------------------
/practice/func/filter_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 |
5 | if __name__ == "__main__":
6 | adult_ages = filter(lambda x: x >= 18, range(1, 100))
7 | print(adult_ages)
--------------------------------------------------------------------------------
/practice/func/map_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 |
5 | if __name__ == "__main__":
6 | # 单个序列输入
7 | squares = map(lambda x: x**2, range(10))
8 | print(squares)
9 |
10 | # 多个序列输入
11 | full_names = map(lambda x, y: "{0} {1}".format(x, y), ["Zhang", "Li"], ["Yan", "Gang"])
12 | print(full_names)
13 |
--------------------------------------------------------------------------------
/practice/func/partial_func.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # partial()函数的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。
4 |
5 |
6 | from functools import partial
7 |
8 | if __name__ == "__main__":
9 | standard = "User N"
10 |
11 | # 用偏函数构造一个新的函数
12 | usern = partial(standard.replace, "N")
13 |
14 | # output: User 1
15 | print(usern("1"))
16 |
17 | # output: User 9527
18 | print(usern("9527"))
19 |
--------------------------------------------------------------------------------
/practice/func/reduce_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 使用reduce计算序列和与积
4 |
5 |
6 | if __name__ == "__main__":
7 | # 计算和
8 | sum_result = reduce(lambda x, y: x+y, range(1, 10))
9 | assert(sum_result == 45)
10 | print(sum_result)
11 |
12 | # 计算阶乘
13 | factorial_result = reduce(lambda x, y: x * y, range(1, 10))
14 | assert(factorial_result == 362880)
15 | print(factorial_result)
--------------------------------------------------------------------------------
/practice/func/sort_dict.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 字典排序 根据“键”或“键值”进行不同顺序的排序
3 | """
4 | 函数原型:sorted(iterable, cmp=None, key=None, reverse=False)
5 | 解释:iterable 可迭代类型
6 | cmp为比较函数,
7 | key为排序的对象(这里指键或键值),是迭代集合中的一项
8 | reverse:注明升序还是降序,True--降序,False--升序(默认)
9 | """
10 |
11 | word_counts = {'love': 5, 'she': 9, 'he': 4}
12 |
13 | # items(),返回字典键值对list
14 | sorted_count = sorted(word_counts.items(), key=lambda item: item[1], reverse=False)
15 | print(sorted_count)
16 |
--------------------------------------------------------------------------------
/practice/lib/builtin/all_any.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | if __name__ == "__main__":
6 | elements = [False, False, True]
7 | print(all(elements)) # False
8 | print(any(elements)) # True
9 |
10 | elements = []
11 | print(all(elements)) # True
12 | print(any(elements)) # False
13 |
--------------------------------------------------------------------------------
/practice/lib/builtin/print_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | if __name__ == '__main__':
7 | # 把平方计算结果打印在同一行
8 | for i in range(10):
9 | print("{0}*{0}".format(i), i*i, sep="=", end="\t")
--------------------------------------------------------------------------------
/practice/lib/configparser/db_config.ini:
--------------------------------------------------------------------------------
1 | [baseconf]
2 | host = 127.0.0.1
3 | port = 3306
4 | user = root
5 | db_name = api
6 |
7 | [concurrent]
8 | processor = 4
9 |
10 |
--------------------------------------------------------------------------------
/practice/lib/csv/20180307/stock.csv:
--------------------------------------------------------------------------------
1 | GOOG,"Google, Inc.",505.24,0.47,0.09
2 | YHOO,Yahoo! Inc.,27.38,0.33,1.22
3 | CNET,"CNET Networks, Inc.",8.62,-0.13,-1.49
4 |
--------------------------------------------------------------------------------
/practice/lib/future/20180128/p2_division.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | # output: 3,地板除
5 | print(10/3)
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/practice/lib/future/20180128/p2_unicode.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | # False
5 | print '\'xxx\' is unicode?', isinstance('xxx', unicode)
6 | # True
7 | print 'u\'xxx\' is unicode?', isinstance(u'xxx', unicode)
8 | # True
9 | print '\'xxx\' is str?', isinstance('xxx', str)
10 | # True
11 | print 'b\'xxx\' is str?', isinstance(b'xxx', str)
--------------------------------------------------------------------------------
/practice/lib/future/20180128/p3_division.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | from __future__ import division
4 |
5 | # output: 3.333333333
6 | print(10/3)
7 |
8 | # output: 3,地板除
9 | print(10//3)
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/practice/lib/future/20180128/p3_unicode.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | from __future__ import unicode_literals
5 |
6 | # True
7 | print '\'xxx\' is unicode?', isinstance('xxx', unicode)
8 | # True
9 | print 'u\'xxx\' is unicode?', isinstance(u'xxx', unicode)
10 | # False
11 | print '\'xxx\' is str?', isinstance('xxx', str)
12 | # True
13 | print 'b\'xxx\' is str?', isinstance(b'xxx', str)
--------------------------------------------------------------------------------
/practice/lib/glob/glob_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import glob
6 |
7 | if __name__ == '__main__':
8 | files = glob.glob(pathname='../../../*.py', recursive=True)
9 | print(files)
--------------------------------------------------------------------------------
/practice/lib/itertools/itertools1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import itertools
6 |
7 | if __name__ == '__main__':
8 | x = itertools.chain(range(3), range(4), [3, 2, 1])
9 | print(list(x))
10 | # [0, 1, 2, 0, 1, 2, 3, 3, 2, 1]
11 |
12 |
13 | x = itertools.accumulate(range(10))
14 | print(list(x))
15 | # [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
16 |
17 |
--------------------------------------------------------------------------------
/practice/lib/itertools/itertools2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import itertools
6 |
7 | if __name__ == '__main__':
8 | x = itertools.compress(range(5), (True, False, True, True, False))
9 | print(list(x))
10 | # [0, 2, 3]
11 |
12 | x = itertools.combinations_with_replacement('ABC', 2)
13 | print(list(x))
14 | # [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]
15 |
16 | x = itertools.combinations(range(4), 3)
17 | print(list(x))
18 | # [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]
--------------------------------------------------------------------------------
/practice/lib/json/dump_load.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import json
6 | if __name__ == '__main__':
7 | user = {'id': 1, 'name': 'python', 'age': 30}
8 | print(type(user)) # < type 'dict' >
9 | print(user) # {'age': 30, 'id': 1, 'name': 'python'}
10 |
11 | json.dump(user, open('user.json', 'w'))
12 |
13 | fp = open('user.json', 'r')
14 | user2 = json.load(fp)
15 | print(type(user2)) #
16 | print(user2) # {u'age': 30, u'id': 1, u'name': u'python'}
--------------------------------------------------------------------------------
/practice/lib/json/user.json:
--------------------------------------------------------------------------------
1 | {"age": 30, "id": 1, "name": "python"}
--------------------------------------------------------------------------------
/practice/lib/mail/yagmail_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import yagmail
6 |
7 | if __name__ == '__main__':
8 | yag = yagmail.SMTP(user="user1@163.com", password="user1password", host='smtp.163.com')
9 |
10 | contents = ['This is the body, and here is just text https://zhuanlan.zhihu.com/python2018',
11 | 'You can find an file attached.', '/tmp/sample.png']
12 |
13 | yag.send(to='user2@hotmail.com',
14 | subject='yagmail sample',
15 | contents=contents)
16 |
--------------------------------------------------------------------------------
/practice/lib/marshal/marshal.out:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/lib/marshal/marshal.out
--------------------------------------------------------------------------------
/practice/lib/marshal/out.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/lib/marshal/out.bin
--------------------------------------------------------------------------------
/practice/lib/pickle/pickle_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import pickle
6 |
7 |
8 | class User:
9 | def __init__(self, name, age):
10 | self.name = name
11 | self.age = age
12 |
13 | def show(self):
14 | print(self.name + "_" + str(self.age))
15 |
16 |
17 | # 序列化到文件
18 | user = User("Python", 20)
19 | user.show()
20 | f = open('user.pkl', 'wb')
21 | pickle.dump(user, f)
22 | f.close()
23 |
24 | # 反序列化到内存
25 | f = open('user.pkl', 'rb')
26 | user1 = pickle.load(f)
27 | f.close()
28 | user1.show()
29 |
--------------------------------------------------------------------------------
/practice/lib/pickle/user.pkl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/lib/pickle/user.pkl
--------------------------------------------------------------------------------
/practice/lib/plotly_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import plotly.express as px
6 | if __name__ == '__main__':
7 | iris = px.data.iris()
8 | fig = px.scatter(iris, x='sepal_width', y='sepal_length')
9 | fig.show()
--------------------------------------------------------------------------------
/practice/lib/pprint_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | if __name__ == '__main__':
7 | import pprint
8 |
9 | data = (
10 | "this is a string",
11 | [1, 2, 3, 4, {"name": "python", "age": 30}],
12 | ("more tuples", 1.0, 2.3, 4.5),
13 | "this is yet another string"
14 | )
15 |
16 | pprint.pprint(data, indent=4, width=20, depth=2)
--------------------------------------------------------------------------------
/practice/lib/pytesseract/tesseract-ocr.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import pytesseract
6 | from PIL import Image
7 |
8 | if __name__ == '__main__':
9 | print(pytesseract.image_to_string(Image.open('zen.png')))
--------------------------------------------------------------------------------
/practice/lib/pytesseract/zen.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/lib/pytesseract/zen.png
--------------------------------------------------------------------------------
/practice/lib/qrcode/qrcode_url.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 |
3 | import qrcode
4 |
5 | if __name__ == "__main__":
6 | url = "https://zhuanlan.zhihu.com/python2018"
7 | print(url)
8 | qr = qrcode.QRCode(
9 | version=1,
10 | error_correction=qrcode.constants.ERROR_CORRECT_L,
11 | box_size=10,
12 | border=4,
13 | )
14 |
15 | qr.add_data(url)
16 | qr.make(fit=True)
17 |
18 | img = qr.make_image()
19 | img.show()
20 |
21 |
--------------------------------------------------------------------------------
/practice/lib/request_cache/cache.sqlite:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/lib/request_cache/cache.sqlite
--------------------------------------------------------------------------------
/practice/lib/request_cache/request_cache_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import requests
6 | import requests_cache
7 | import time
8 |
9 | if __name__ == '__main__':
10 | requests_cache.install_cache(expire_after=300)
11 | start = time.time()
12 | for i in range(10):
13 | response = requests.get('http://httpbin.org/delay/1')
14 | print(response.content)
15 | print("cost time: {}".format(time.time()-start))
--------------------------------------------------------------------------------
/practice/lib/requests/proxy_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import requests
6 |
7 | if __name__ == '__main__':
8 | # 不使用代理
9 | resp = requests.get('http://httpbin.org/ip')
10 | print(resp.text)
11 | # {"origin": "114.93.163.248"}
12 |
13 | proxies = {
14 | 'http': 'http://139.227.252.141:8118',
15 | 'https': 'https://139.227.252.141:8118'
16 | }
17 |
18 | # 使用代理
19 | resp = requests.get('http://httpbin.org/ip', proxies=proxies)
20 | print(resp.text)
21 | # {"origin": "139.227.252.141"}
22 |
--------------------------------------------------------------------------------
/practice/lib/tenacity_sample/retry_decorator.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | import random
4 | from tenacity import retry
5 |
6 |
7 | @retry
8 | def do_something_unreliable():
9 | if random.randint(0, 10) > 1:
10 | raise IOError("Unstable status, try again")
11 | else:
12 | print("Get stable result")
13 | return
14 |
15 |
16 | if __name__ == "__main__":
17 | do_something_unreliable()
--------------------------------------------------------------------------------
/practice/lib/tenacity_sample/try_with_exception.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | import random
4 |
5 |
6 | def do_something_unreliable(retry=10):
7 | for i in range(retry):
8 | try:
9 | if random.randint(0, 10) > 1:
10 | raise IOError("Unstable status, try again")
11 | else:
12 | print("Get stable result")
13 | return
14 | except Exception as e:
15 | print(e.message)
16 |
17 |
18 | if __name__ == "__main__":
19 | do_something_unreliable(3)
--------------------------------------------------------------------------------
/practice/lib/test/20180223/doctest_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 |
5 | def add(x, y):
6 | """ add two number or string
7 | >>> add(1, 2)
8 | 3
9 |
10 | >>> add("hello", " world")
11 | 'hello world'
12 |
13 | >>> add(1, 2.0)
14 | 3
15 |
16 | >>> add("hello", " python") # doctest: +ELLIPSIS
17 | 'hello ...'
18 |
19 | """
20 | return x+y
21 |
22 |
23 | if __name__ == '__main__':
24 | import doctest
25 | doctest.testmod()
--------------------------------------------------------------------------------
/practice/lib/unittest/test_calculator.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import unittest
6 | import time
7 | from unittest import TestCase
8 | from unittest.mock import patch
9 |
10 |
11 | def sum(a, b):
12 | time.sleep(100) # long running process
13 | return a + b
14 |
15 |
16 | class TestCalculator(TestCase):
17 | @patch('__main__.sum', return_value=5)
18 | def test_sum(self, sum):
19 | self.assertEqual(sum(2, 3), 5)
20 |
21 |
22 | if __name__ == '__main__':
23 | unittest.main()
24 |
--------------------------------------------------------------------------------
/practice/lib/warnings/warnings_sample1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import warnings
6 | if __name__ == '__main__':
7 |
8 | # 凡是UserWarning都转换为的异常
9 | warnings.simplefilter(action='error', category=UserWarning)
10 |
11 | print('Before the warning')
12 | warnings.warn('This is a warning message')
13 | print('After the warning')
--------------------------------------------------------------------------------
/practice/lib/warnings/warnings_sample2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import warnings
6 |
7 |
8 | def function_with_warning():
9 | warnings.warn('This is a warning!')
10 |
11 |
12 | if __name__ == '__main__':
13 | function_with_warning()
14 | function_with_warning()
15 | function_with_warning()
--------------------------------------------------------------------------------
/practice/lib/xls/copy.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/lib/xls/copy.xls
--------------------------------------------------------------------------------
/practice/lib/xls/new.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/lib/xls/new.xls
--------------------------------------------------------------------------------
/practice/lib/xls/origin.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/lib/xls/origin.xls
--------------------------------------------------------------------------------
/practice/lib/xmltodict/file.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | elements
4 | more elements
5 |
6 |
7 | element as well
8 |
9 |
--------------------------------------------------------------------------------
/practice/lib/xmltodict/out.xml:
--------------------------------------------------------------------------------
1 |
2 | This is a test
--------------------------------------------------------------------------------
/practice/lib/yaml/20180131/PyYAML.yml:
--------------------------------------------------------------------------------
1 | age: 38
2 | children:
3 | - {age: 15, name: Jimmy Smith}
4 | - {age: 12, name: Jenny Smith}
5 | name: John Smith
6 | spouse: {age: 25, name: Jane Smith}
7 |
--------------------------------------------------------------------------------
/practice/lib/yaml/20180131/father.yml:
--------------------------------------------------------------------------------
1 | name: John Smith
2 | age: 37
3 | spouse:
4 | name: Jane Smith
5 | age: 25
6 | children:
7 | - name: Jimmy Smith
8 | age: 15
9 | - name: Jenny Smith
10 | age: 12
--------------------------------------------------------------------------------
/practice/lib/yaml/20180131/ruamel.yml:
--------------------------------------------------------------------------------
1 | name: John Smith
2 | age: 38
3 | spouse:
4 | name: Jane Smith
5 | age: 25
6 | children:
7 | - name: Jimmy Smith
8 | age: 15
9 | - name: Jenny Smith
10 | age: 12
11 |
--------------------------------------------------------------------------------
/practice/lib/yaml/20180131/ruamel_yaml_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | from ruamel import yaml
5 |
6 | if __name__ == "__main__":
7 | with open('father.yml') as f:
8 | content = yaml.load(f, Loader=yaml.RoundTripLoader)
9 |
10 | # output:
11 | print(type(content))
12 | print(content)
13 |
14 | content.update({'age': 38})
15 | print(content)
16 |
17 | with open('ruamel.yml', 'w') as nf:
18 | yaml.dump(content, nf, Dumper=yaml.RoundTripDumper)
--------------------------------------------------------------------------------
/practice/lib/yaml/20180131/yaml_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import yaml
5 |
6 | if __name__ == "__main__":
7 | with open('father.yml') as f:
8 | content = yaml.load(f)
9 |
10 | # output:
11 | print(type(content))
12 | print(content)
13 |
14 | content.update({'age': 38})
15 | print(content)
16 |
17 | with open('PyYAML.yml', 'w') as nf:
18 | yaml.dump(content, nf)
--------------------------------------------------------------------------------
/practice/module/20180127/locals_globals.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 展示全局名称空间和局部名称空间
4 |
5 |
6 | def foo():
7 | num = 10
8 | # 在局部名称空间中访问全局名称空间的变量
9 | # output: ('foo globals-num', 5)
10 | print("foo globals-num", globals()['num'])
11 |
12 | # output: ('foo locals-num', 10)
13 | print("foo locals-num", locals()['num'])
14 |
15 |
16 | num = 5
17 | foo()
18 |
19 | # 在全局名称空间下,globals()和locals()返回相同的字典。
20 | print("globals", globals())
21 | print("locals", globals())
22 |
--------------------------------------------------------------------------------
/practice/profile/cProfile/bar.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | def bar():
7 | result = 0
8 | for i in range(1000000):
9 | result += i
10 | return result
11 |
--------------------------------------------------------------------------------
/practice/profile/cProfile/foo.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | from bar import bar
6 |
7 |
8 | def foo():
9 | result = 0
10 | for i in range(100000):
11 | result += i
12 | for i in range(5):
13 | bar()
14 | return result
15 |
16 |
17 | if __name__ == '__main__':
18 | foo()
19 |
--------------------------------------------------------------------------------
/practice/profile/cProfile/result.out:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/profile/cProfile/result.out
--------------------------------------------------------------------------------
/practice/profile/cProfile/state.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import pstats
6 |
7 | if __name__ == '__main__':
8 | # 创建Stats对象
9 | p = pstats.Stats("foo.out")
10 |
11 | # 这一行的效果和直接运行cProfile.run("foo()")的显示效果是一样的
12 | p.strip_dirs().sort_stats(-1).print_stats()
--------------------------------------------------------------------------------
/practice/profile/line_profile/foo.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | @profile
6 | def foo():
7 | result = 0
8 | for i in range(100000):
9 | result += i
10 | return result
11 |
12 |
13 | if __name__ == '__main__':
14 | foo()
--------------------------------------------------------------------------------
/practice/profile/other/domath.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | print(math.factorial(1024))
4 | print(math.sin(1024))
--------------------------------------------------------------------------------
/practice/profile/pypy/pypy_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import time
3 |
4 | t = time.time()
5 |
6 | for i in range(10**8):
7 | continue
8 |
9 | print time.time()-t
--------------------------------------------------------------------------------
/practice/profile/yappi/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/profile/yappi/__init__.py
--------------------------------------------------------------------------------
/practice/profile/yappi/funcs.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import random
3 | import time
4 |
5 | def consumer_time():
6 | duration = random.randint(0, 200)
7 | for i in range(duration):
8 | time.sleep(0.01)
9 | for j in range(duration):
10 | x = 100.94 * 238.487*random.randint(0, 10)
11 |
12 |
13 | if __name__ == "__main__":
14 | consumer_time()
--------------------------------------------------------------------------------
/practice/regex/20180114/re_module_func.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 演示正则对象的用法
4 | # 预编译正则表达式可以提升执行性能
5 |
6 | import re
7 |
8 |
9 | # match是从字符串开头开始匹配
10 | m = re.match('.*com', 'www.baidu.com')
11 | print(m)
12 | result = m.group()
13 | print(result)
14 | # 输出www.baidu.com
15 |
16 | # search是搜索第一次出现的位置
17 | m = re.search('com', 'www.baidu.com')
18 | print(m.group())
19 | # 输出com
20 |
21 |
22 |
--------------------------------------------------------------------------------
/practice/regex/20180114/re_object_func.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 演示正则对象的用法
4 | # 预编译正则表达式可以提升执行性能
5 |
6 | import re
7 |
8 | p = re.compile('.*com')
9 | print(p)
10 | # match是从字符串开头开始匹配
11 | m = p.match('www.baidu.com')
12 | result = m.group()
13 | print(m)
14 | print(result)
15 | # 输出www.baidu.com
16 |
17 | # search是搜索第一次出现的位置
18 | p = re.compile('com')
19 | m = p.search('www.baidu.com')
20 | print(m.group())
21 | # 输出com
--------------------------------------------------------------------------------
/practice/replace_stdout.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | import sys
3 |
4 | # 重定向stdout到一个文件
5 | sys.stdout = open("stdout.log", "w")
6 | print("hello world")
7 |
8 | # 重置stdout
9 | reload(sys)
10 | print("hello again")
--------------------------------------------------------------------------------
/practice/runtime/20180131/ref_loop.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 演示循环引用
4 |
5 | import objgraph # 可以用来检测内存泄漏
6 |
7 | if __name__ == '__main__':
8 | a = list()
9 | b = list()
10 | # 查看list类型对象的数量
11 | # output: n
12 | print(objgraph.count('list'))
13 | a.append(b)
14 | # b.append(a) # 循环引用
15 |
16 | print(a)
17 | print(b)
18 | del a
19 | del b
20 | # 再次查看list类型对象的数量
21 | # output: n
22 | print(objgraph.count('list'))
23 |
--------------------------------------------------------------------------------
/practice/runtime/20180204/hello.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | if __name__ == '__main__':
5 | print('hello world!')
--------------------------------------------------------------------------------
/practice/runtime/20180204/read_pyc.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | import dis, marshal
5 |
6 | if __name__ == '__main__':
7 | with open('hello.pyc', 'rb') as f:
8 | f.seek(8)
9 | dis.dis(marshal.load(f))
--------------------------------------------------------------------------------
/practice/runtime/20180228/user_class.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 |
5 | class User(object):
6 | register = True
7 |
8 |
9 | if __name__ == '__main__':
10 | user = User()
11 | print(user.register)
--------------------------------------------------------------------------------
/practice/runtime/20180228/user_metaclass.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 |
5 | class UserMetaclass(type):
6 | def __new__(cls, name, bases, attrs):
7 | attrs['register'] = True
8 | return type.__new__(cls, name, bases, attrs)
9 |
10 |
11 | class User(object):
12 | __metaclass__ = UserMetaclass
13 |
14 |
15 | if __name__ == '__main__':
16 | user = User()
17 | print(user.register)
--------------------------------------------------------------------------------
/practice/runtime/20180228/user_type.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | if __name__ == '__main__':
5 | User = type('User', (object,), dict(register=True)) # 创建User class
6 | user = User()
7 | print(user.register)
--------------------------------------------------------------------------------
/practice/runtime/compileall_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | if __name__ == '__main__':
7 | import compileall
8 | compileall.compile_dir('.', force=True)
--------------------------------------------------------------------------------
/practice/runtime/dis/dis_foo.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 | import dis
6 |
7 |
8 | def foo():
9 | print('foo')
10 |
11 |
12 | if __name__ == '__main__':
13 | print(dis.dis(foo))
14 |
--------------------------------------------------------------------------------
/practice/runtime/dis/dis_pass.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | import dis
7 |
8 |
9 | def foo():
10 | pass
11 |
12 |
13 | if __name__ == '__main__':
14 | print(dis.dis(foo))
--------------------------------------------------------------------------------
/practice/runtime/helloworld.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | if __name__ == '__main__':
5 | print('hello world!')
--------------------------------------------------------------------------------
/practice/spider/20180117/bilibili_kichiku.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 |
--------------------------------------------------------------------------------
/practice/spider/20180121/keyword_tag_cloud4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/spider/20180121/keyword_tag_cloud4.png
--------------------------------------------------------------------------------
/practice/syntax/assert/assert_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | def divide(num1, num2):
7 | assert num2 != 0, "Divisor cannot be zero"
8 | return num1 / num2
9 |
10 |
11 | if __name__ == '__main__':
12 | try:
13 | a2 = divide(12, 0)
14 | except AssertionError as e:
15 | print(e)
16 | # Divisor cannot be zero
17 |
--------------------------------------------------------------------------------
/practice/syntax/exception/user_exception.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | class VerifyException(Exception):
7 | def __init__(self, message):
8 | super().__init__(self)
9 | self.message = message
10 |
11 | def __str__(self):
12 | return self.message
13 |
14 |
15 | if __name__ == '__main__':
16 | user_age = -1
17 | try:
18 | if user_age < 0:
19 | raise VerifyException('User age is negative')
20 | except Exception as e:
21 | print(e.message)
22 |
--------------------------------------------------------------------------------
/practice/syntax/loop/20180205/for_else.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | if __name__ == '__main__':
5 | # 没有遇到break, else就会被执行
6 | for i in range(2):
7 | print(i)
8 | else:
9 | print('loop done')
10 |
11 | # 遇到break, else不执行
12 | for i in range(2):
13 | if i == 1:
14 | break
15 | print(i)
16 | else:
17 | print('loop done')
18 |
19 | # 如果循环要迭代的序列是空的,else依然会被执行
20 | for i in []:
21 | print(i)
22 | else:
23 | print('loo done for empty list')
--------------------------------------------------------------------------------
/practice/syntax/loop/20180205/while_else.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | if __name__ == '__main__':
5 | # 没有遇到break, else就会被执行
6 | i = 0
7 | while i < 2:
8 | print(i)
9 | i += 1
10 | else:
11 | print('loop done')
12 |
13 | # 遇到break, else不执行
14 | i = 0
15 | while i < 2:
16 | if i == 1:
17 | break
18 | print(i)
19 | i += 1
20 | else:
21 | print('loop done')
22 |
--------------------------------------------------------------------------------
/practice/syntax/nonlocal/nolocal_sample.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # author: zengyuetian
4 |
5 |
6 | def count_down(n):
7 | def decrement():
8 | nonlocal n
9 | n -= 1
10 |
11 | while n > 0:
12 | print(n)
13 | decrement()
14 |
15 |
16 | if __name__ == '__main__':
17 | count_down(3)
18 |
--------------------------------------------------------------------------------
/practice/syntax/switch_case/20180308/dict_function.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 | # 用字典和函数代替switch case语法结构
4 |
5 |
6 | def start_app():
7 | print("start app")
8 |
9 |
10 | def stop_app():
11 | print("stop app")
12 |
13 |
14 | def restart_app():
15 | print("restart app")
16 |
17 |
18 | switch = {
19 | "start": start_app,
20 | "stop": stop_app,
21 | "restart": restart_app
22 | }
23 |
24 | if __name__ == '__main__':
25 | option = raw_input("input:")
26 | switch[option]()
27 |
--------------------------------------------------------------------------------
/practice/syntax/switch_case/20180308/if_else.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # coding=utf-8
3 |
4 | if __name__ == '__main__':
5 | option = raw_input("input:")
6 | if option == "start":
7 | print("start app")
8 | elif option == "stop":
9 | print("stop app")
10 | elif option == "restart":
11 | print("restart app")
--------------------------------------------------------------------------------
/practice/syntax/switch_case/20180308/switch_with_lambda.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # 使用lambda模拟switch
3 |
4 | # Python has no switch keyword
5 | # Here we simulate switch with lambda
6 |
7 | def a(s):
8 | print s
9 |
10 |
11 | def switch(ch):
12 | try:
13 | {
14 | '1': lambda: a("one"),
15 | '2': lambda: a("two"),
16 | '3': lambda: a("three")
17 |
18 | }[ch]()
19 | except KeyError:
20 | a("key not found")
21 |
22 |
23 | switch("1")
24 | switch("a")
25 |
--------------------------------------------------------------------------------
/practice/unicode/20180115/text.txt:
--------------------------------------------------------------------------------
1 | 实践
--------------------------------------------------------------------------------
/practice/unicode/20180115/text1.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jumper2014/PyCodeComplete/4ef7d2c3aec6d28a53eed0e649cdeb74df3d783b/practice/unicode/20180115/text1.txt
--------------------------------------------------------------------------------