code
stringlengths 20
13.2k
| label
stringlengths 21
6.26k
|
---|---|
1 import torch
2
3
4 def determine_device(gpu_flag_enabled):
5 """Determine device given gpu flag and the availability of cuda"""
6 return torch.device(
7 "cuda" if torch.cuda.is_available() and gpu_flag_enabled else "cpu"
8 )
| Clean Code: No Issues Detected
|
1 # coding=utf8
2 """
3 jinja2的过滤器
4 """
5 import markdown
6
7
8 def md2html(md):
9 """
10 @param {unicode} md
11 @return {unicode html}
12 """
13 return markdown.markdown(md, ['extra', 'codehilite', 'toc', 'nl2br'], safe_mode="escape")
14
15
16 JINJA2_FILTERS = {
17 'md2html': md2html,
18 }
| Clean Code: No Issues Detected
|
1 #coding=utf8
2
3 import datetime
4 from flask import Blueprint, request, jsonify, render_template, redirect
5 import flask_login
6 import weibo as sinaweibo
7
8 from models.base import create_session, User
9 from utils import user_cache
10 from configs import settings
11
12
13 bp_base = Blueprint('base', __name__, url_prefix='/base')
14
15
16 @bp_base.route('/weibo/login/')
17 def weibo_login():
18 api = sinaweibo.Client(settings.API_KEY,settings.API_SECRET,settings.REDIRECT_URI)
19 code = request.args.get('code')
20 try:
21 api.set_code(code)
22 except Exception, e:
23 return redirect('/blog/')
24
25 sinainfo = api.token
26 user = user_cache.get_user(sinainfo.get('uid'), format='object')
27 if user:
28 flask_login.login_user(user, remember=True)
29 else:
30 user = User()
31 user.open_id = sinainfo.get('uid')
32 user.token = sinainfo.get('access_token')
33 userinfo = api.get('users/show', uid=sinainfo.get('uid'))
34 user.name = userinfo.get('name')
35 user.address = userinfo.get('location')
36 user.create_time = datetime.datetime.now()
37 session = create_session()
38 session.add(user)
39 session.commit()
40 flask_login.login_user(user, remember=True)
41 session.close()
42 return redirect('/blog/')
43
44
45 @bp_base.route('/logout/')
46 def logout():
47 flask_login.logout_user()
48 return redirect('/blog/') | 22 - error: syntax-error
|
1 #!/usr/bin/python
2 #coding=utf8
3
4 import datetime
5 from sqlalchemy import (
6 MetaData, Table, Column, Integer, BigInteger, Float, String, Text, DateTime,
7 ForeignKey, Date, UniqueConstraint)
8 from sqlalchemy.orm import relationship
9 from sqlalchemy.ext.declarative import declarative_base
10
11 from models import sae_engine
12 from models import create_session
13
14 Base = declarative_base()
15 metadata = MetaData()
16
17
18 class BlogArticle(Base):
19
20 """
21 发布历史日志
22 """
23
24 __tablename__ = 'blog_article'
25 __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
26
27 id = Column(Integer, primary_key=True)
28 title = Column(String(50))
29 markdown = Column(Text)
30 html = Column(Text)
31 create_by = Column(Integer, index=True, nullable=False)
32 create_time = Column(DateTime, nullable=False)
33 update_time = Column(DateTime, index=True, nullable=False,)
34 is_active = Column(Integer, nullable=False, default=1)
35
36 if __name__ == '__main__':
37 Base.metadata.create_all(bind=sae_engine)
| 18 - refactor: too-few-public-methods
4 - warning: unused-import
5 - warning: unused-import
5 - warning: unused-import
5 - warning: unused-import
5 - warning: unused-import
5 - warning: unused-import
5 - warning: unused-import
8 - warning: unused-import
12 - warning: unused-import
|
1 # coding=utf8
2 """
3 学web安全用到的一些页面
4 """
5 from flask import Blueprint, render_template
6 from sae.storage import Bucket
7
8 from configs import settings
9
10
11 bp_security = Blueprint('security', __name__, url_prefix='/security')
12 bucket = Bucket(settings.STORAGE_BUCKET_DOMAIN_NAME)
13 bucket.put()
14
15
16 @bp_security.route('/wanbo/video/')
17 def wanbo_video():
18 return render_template('security/wanbo_video.html') | Clean Code: No Issues Detected
|
1 #!/usr/bin/python
2 # coding=utf8
3
4
5 from flask import Flask, render_template, g
6 import flask_login
7
8 from configs import settings
9 from utils.filters import JINJA2_FILTERS
10 from utils import user_cache
11 from views import blog, base, security
12
13
14 def create_app(debug=settings.DEBUG):
15 app = Flask(__name__)
16 app.register_blueprint(blog.bp_blog)
17 app.register_blueprint(base.bp_base)
18 app.register_blueprint(security.bp_security)
19 app.jinja_env.filters.update(JINJA2_FILTERS)
20 app.debug = debug
21 app.secret_key = "gausszh"
22
23 @app.route('/')
24 def index():
25 return render_template('index.html')
26
27 @app.before_request
28 def check_user():
29 g.user = flask_login.current_user
30
31 login_manager = flask_login.LoginManager()
32 login_manager.setup_app(app)
33
34 @login_manager.user_loader
35 def load_user(userid):
36 user = user_cache.get_user(userid, format='object')
37 return user
38
39 login_manager.unauthorized = blog.list
40 # login_manager.anonymous_user = AnonymousUserMixin
41
42 return app
43
44 app = create_app(settings.DEBUG)
45
46
47 if __name__ == '__main__':
48 host = settings.APP_HOST
49 port = settings.APP_PORT
50 app.run(host=host, port=port)
| 15 - warning: redefined-outer-name
|
1 # coding=utf8
2
3 try:
4 import simplejson as json
5 except Exception:
6 import json
7 import datetime
8 from sqlalchemy.sql import or_
9
10 from models.base import create_session, User
11 from models.blog import BlogArticle
12 from configs import settings
13 from utils import redis_connection
14 # import sae.kvdb
15
16 APP = "base"
17
18
19 def get_user(uid, format="json"):
20 _cache = redis_connection()
21 key = str("%s:user:%s" % (APP, uid))
22 userinfo = _cache.get(key)
23 new = False
24 if not userinfo:
25 session = create_session()
26 userinfo = session.query(User).filter(or_(User.id == uid,
27 User.open_id == uid)).first()
28 userinfo = orm2json(userinfo)
29 _cache.set(key, json.dumps(userinfo), settings.CACHE_TIMEOUT)
30 new = True
31 session.close()
32 if not new:
33 userinfo = json.loads(userinfo)
34
35 if format == 'object' and userinfo:
36 user = User()
37 for k in userinfo:
38 setattr(user, k, userinfo.get(k))
39 userinfo = user
40 return userinfo or None
41
42
43 def delete_user(uid):
44 _cache = redis_connection()
45 key = str("%s:user:%s" % (APP, uid))
46 _cache.delete(key)
47
48
49 def get_anonymous_count():
50 _cache = redis_connection()
51 key = "%s:anonymous:count" % APP
52 count = _cache.get(key)
53 if not count:
54 session = create_session()
55 count = session.query(User).filter(
56 User.open_id.startswith("anonymous")).count()
57 _cache.set(key, count, settings.CACHE_TIMEOUT)
58 session.close()
59 return int(count)
60
61
62 def incr_anonymous_count():
63 _cache = redis_connection()
64 key = "%s:anonymous:count" % APP
65 count = get_anonymous_count()
66 _cache.set(key, count + 1, settings.CACHE_TIMEOUT)
67
68
69 def get_blog(blog_id):
70 """
71 获取博客的数据
72 """
73 _cache = redis_connection()
74 key = str("%s:blog:%s" % (APP, blog_id))
75 bloginfo = _cache.get(key)
76 new = False
77 if not bloginfo:
78 session = create_session()
79 bloginfo = session.query(BlogArticle).filter_by(id=blog_id).first()
80 bloginfo = orm2json(bloginfo)
81 _cache.set(key, json.dumps(bloginfo), settings.CACHE_TIMEOUT)
82 new = True
83 session.close()
84 if not new:
85 bloginfo = json.loads(bloginfo)
86 return bloginfo
87
88
89 def delete_blog(blog_id):
90 _cache = redis_connection()
91 key = str("%s:blog:%s" % (APP, blog_id))
92 _cache.delete(key)
93
94
95 def orm2json(orm):
96 """
97 将sqlalchemy返回的对象转换为可序列话json类型的对象
98 """
99 def single2py(instance):
100 d = {}
101 if instance:
102 keys = instance.__dict__.keys()
103 for key in keys:
104 if key.startswith('_'):
105 continue
106 value = getattr(instance, key)
107 d[key] = isinstance(value, datetime.datetime) and \
108 value.strftime('%Y-%m-%d %H:%M:%S') or value
109 return d
110 if isinstance(orm, list):
111 return [single2py(ins) for ins in orm]
112 return single2py(orm)
| 5 - warning: broad-exception-caught
19 - warning: redefined-builtin
|
1 # coding=utf8
2
3 import datetime
4 import urllib
5 from flask import Blueprint, request, jsonify, render_template, g
6 import flask_login
7 from sae.storage import Bucket
8
9 from models.blog import create_session, BlogArticle
10 from utils.blog_cache import set_draft_blog
11 from configs import settings
12
13
14 bp_blog = Blueprint('blog', __name__, url_prefix='/blog')
15 bucket = Bucket(settings.STORAGE_BUCKET_DOMAIN_NAME)
16 bucket.put()
17
18
19 @bp_blog.route('/')
20 @bp_blog.route('/list/')
21 def list():
22 session = create_session()
23 blogs = session.query(BlogArticle).order_by(BlogArticle.update_time.desc())\
24 .all()
25 session.close()
26 return render_template('blog/blog_list.html', blogs=blogs)
27
28
29 @bp_blog.route('/delete/<int:blog_id>/', methods=['POST'])
30 @flask_login.login_required
31 def delete(blog_id):
32 session = create_session()
33 blog = session.query(BlogArticle).filter_by(id=blog_id).first()
34 if blog.create_by == g.user.id:
35 blog.is_active = 0
36 session.commit()
37 session.close()
38 return jsonify(ok=True, data={'blog_id': blog_id})
39 session.close()
40 return jsonify(ok=False, reason=u'数据错误')
41
42
43 @bp_blog.route('/draft/', methods=['POST'])
44 @flask_login.login_required
45 def draft():
46 """
47 保存未上传的文章为草稿
48 """
49 form = request.form
50 markdown = form.get('markdown', '')
51 set_draft_blog(flask_login.current_user.id, markdown)
52 return jsonify(ok=True)
53
54
55 @bp_blog.route('/edit/<int:blog_id>/', methods=['GET', 'POST'])
56 @bp_blog.route('/edit/', methods=['GET', 'POST'])
57 @flask_login.login_required
58 def edit(blog_id=0):
59 if request.method == 'GET':
60 if blog_id == 0:
61 blog = None
62 else:
63 session = create_session()
64 blog = session.query(BlogArticle).filter_by(id=blog_id).first()
65 session.close()
66 return render_template('blog/blog_edit.html', blog=blog)
67
68 if request.method == 'POST':
69 form = request.form
70 markdown = form.get('markdown')
71 title = form.get('title')
72 blog_id = form.get('blog_id')
73 if markdown and title and (len(markdown.strip()) *
74 len(title.strip()) > 0):
75
76 session = create_session()
77 now = datetime.datetime.now()
78 # blog_id belong to this user
79 if blog_id:
80 blog = session.query(BlogArticle).filter_by(id=blog_id).first()
81 if not blog_id or not blog:
82 blog = BlogArticle()
83 blog.create_by = flask_login.current_user.id
84 blog.create_time = now
85 blog.is_active = 1
86 blog.update_time = now
87 blog.title = title
88 blog.markdown = markdown
89 session.add(blog)
90 session.commit()
91 blog_id = blog.id
92 session.close()
93 return jsonify(ok=True, data={'blog_id': blog_id})
94 return jsonify(ok=False, reason=u'数据错误')
95
96
97 @bp_blog.route('/view/<int:blog_id>/')
98 def view_blog(blog_id):
99 session = create_session()
100 query = session.query(BlogArticle).filter_by(id=blog_id)
101 if not flask_login.current_user.is_active():
102 query = query.filter_by(is_active=1)
103 blog = query.first()
104 session.close()
105 return render_template('blog/blog_view.html', blog=blog)
106
107
108 @bp_blog.route('/files/', methods=['POST'])
109 @flask_login.login_required
110 def save_file():
111 """
112 存储上传的图片
113 """
114 files_name = request.files.keys()
115 ret = []
116 for fn in files_name:
117 # 暂未做安全校验 PIL
118 img_file = request.files.get(fn)
119 bucket.put_object(fn, img_file)
120 link = bucket.generate_url(fn)
121 ret.append({'name': fn, 'link': link})
122 http_files_link = request.form.keys()
123 for fn in http_files_link:
124 http_link = request.form.get(fn)
125 img_file = urllib.urlopen(http_link)
126 bucket.put_object(fn, img_file)
127 link = bucket.generate_url(fn)
128 ret.append({'name': fn, 'link': link})
129 return jsonify(ok=True, data=ret)
130
131
| 21 - warning: redefined-builtin
40 - warning: redundant-u-string-prefix
94 - warning: redundant-u-string-prefix
58 - refactor: inconsistent-return-statements
125 - error: no-member
|
1 #coding=utf8
2
3 import datetime
4 import redis
5
6 import flask_login
7
8 from models.base import User, create_session
9 from utils import user_cache
10 from configs import settings
11
12
13 def AnonymousUserMixin():
14 '''
15 This is the default object for representing an anonymous user.
16 '''
17 session = create_session()
18 user = User()
19 count = user_cache.get_anonymous_count()
20 anonymouser_id = 1000 + count
21 user.open_id = 'anonymous%s' % anonymouser_id
22 user.name = u'游客%s' % anonymouser_id
23 user.token = ''
24 user.create_time = datetime.datetime.now()
25 session.add(user)
26 session.commit()
27 user_cache.incr_anonymous_count()
28 flask_login.login_user(user, remember=True)
29 session.close()
30 return user
31
32 redis_pool = redis.ConnectionPool(host=settings.REDIS_IP,
33 port=settings.REDIS_PORT,
34 db=settings.REDIS_DB)
35
36
37 def redis_connection():
38 return redis.Redis(connection_pool=redis_pool)
| 22 - warning: redundant-u-string-prefix
|
1 #coding=utf8
2 """
3 基础类--用户信息
4 """
5
6 from sqlalchemy import (
7 MetaData, Table, Column, Integer, BigInteger, Float, String, Text, DateTime,
8 ForeignKey, Date, UniqueConstraint)
9 from sqlalchemy.orm import relationship
10 from sqlalchemy.ext.declarative import declarative_base
11
12 from models import sae_engine
13 from models import create_session
14
15 Base = declarative_base()
16 metadata = MetaData()
17
18
19 class User(Base):
20
21 """
22 发布历史日志
23 """
24
25 __tablename__ = 'user'
26 __table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
27
28 id = Column(Integer, primary_key=True)
29 open_id = Column(String(45), nullable=False, index=True)
30 token = Column(String(64), nullable=False, index=True)
31 name = Column(String(45))
32 email = Column(String(60))
33 address = Column(String(150))
34 tel = Column(String(15))
35 school = Column(String(45))
36 create_time = Column(DateTime)
37
38 def is_authenticated(self):
39 return True
40
41 def is_active(self):
42 return True
43
44 def is_anonymous(self):
45 return False
46
47 def get_id(self):
48 return unicode(self.id)
49
50 def __repr__(self):
51 return '<User %r>' % (self.name)
52
53
54 if __name__ == '__main__':
55 Base.metadata.create_all(bind=sae_engine)
| 48 - error: undefined-variable
6 - warning: unused-import
6 - warning: unused-import
6 - warning: unused-import
6 - warning: unused-import
6 - warning: unused-import
6 - warning: unused-import
6 - warning: unused-import
9 - warning: unused-import
13 - warning: unused-import
|
1 #coding=utf-8
2
3
4 from sqlalchemy import create_engine
5 from sqlalchemy.orm import sessionmaker
6 from sqlalchemy.ext.declarative import declarative_base
7
8 from configs import settings
9 sae_engine = create_engine(settings.DB_SAE_URI+'?charset=utf8', encoding='utf-8',
10 convert_unicode=True, pool_recycle=settings.DB_POOL_RECYCLE_TIMEOUT,
11 echo=settings.DB_ECHO)
12
13 create_session = sessionmaker(autocommit=False, autoflush=False,
14 bind=sae_engine)
15
16
17 Base = declarative_base() | Clean Code: No Issues Detected
|
1 #coding=utf8
2 import os
3
4 # system setting
5 DEBUG = True
6 APP_HOST = '127.0.0.1'
7 APP_PORT = 7020
8 STORAGE_BUCKET_DOMAIN_NAME = 'blogimg'
9
10 # database
11
12 if os.environ.get('SERVER_SOFTWARE'):#线上
13 import sae
14 DB_SAE_URI = 'mysql://%s:%s@%s:%s/database_name' % (sae.const.MYSQL_USER,
15 sae.const.MYSQL_PASS, sae.const.MYSQL_HOST, sae.const.MYSQL_PORT)
16 DB_POOL_RECYCLE_TIMEOUT = 10
17 DB_ECHO = True
18 else:
19 DB_SAE_URI = 'mysql://user:pass@127.0.0.1:3306/database_name'
20 # DB_SAE_URI = 'sqlite:////database.db'
21 DB_POOL_RECYCLE_TIMEOUT = 10
22 DB_ECHO = True
23
24 # cache
25 REDIS_HOST = "127.0.0.1"
26 REDIS_PORT = 6379
27 REDIS_DB = 1
28 CACHE_TIMEOUT = 3
29
30 # app
31 API_KEY = '***'
32 API_SECRET = '****'
33 REDIRECT_URI = 'http://****'
| 13 - warning: bad-indentation
14 - warning: bad-indentation
16 - warning: bad-indentation
17 - warning: bad-indentation
19 - warning: bad-indentation
21 - warning: bad-indentation
22 - warning: bad-indentation
|
1 # coding=utf8
2 from configs import settings
3 from utils import redis_connection
4
5
6 APP = "blog"
7
8
9 def set_draft_blog(uid, markdown):
10 _cache = redis_connection()
11 key = str("%s:draft:blog:%s" % (APP, uid))
12 _cache.set(key, markdown, settings.DRAFT_BLOG_TIMEOUT)
| Clean Code: No Issues Detected
|
1 # MAARTech technical test submission.
2 # Author: Connor Goddard
3 # First Published: 2021-05-20
4
5 # Submission notes:
6 # - For this task, I've made a two key assumptions: 1) we only need to support CSV file types; and 2) that it's a requirement to have the ORIGINAL/RAW data AS CONTAINED IN THE DATA FILES imported into the database tables.
7 #
8 # - I've made the decision NOT to transform the data and build new feature columns (e.g. combine the 'lat' and 'long' columns into a single GIS 'POINT' column) because in my experience,
9 # you would typically want to make sure the RAW data is imported 'as-is', and then apply such transformations across the 'raw' tables
10 # to curate new 'analytics' tables once the data is available in the database. This same reasoning led me to choose to NOT convert
11 # the hexadecimal representation of OSM tag values into plaintext. Again, this could be done as part of a downstream process, with the original data preserved.
12 #
13 # - I recognise that the data contained in the input files appears to be OpenStreetMap data, so it is possible that instead of connecting to and querying the database directly from Python,
14 # we could potentially make use of the official 'osm2pgsql' tool (https://osm2pgsql.org/) which could automate much of the table schema creation and unpacking. (This could even be called dynamically via a Python script.)
15 #
16 # - In terms of database credentials, in a production envrionment, we'd want to load the credentials in from a secure location at runtime (i.e. ideally from a secrets manager,
17 # but at the very least from a 'secure' configuration file - excluded from version control).
18 #
19 # - I could have used SQLAlchemy to provide the connection to the database (SQLAlchemy is a popular and well-established library for working with RDBMS databases in Python), however,
20 # because I wanted to take particular advantage of the 'COPY FROM' syntax supported by PostgresSQL, using SQL Alchemy would have been in some ways redundant, because I would have needed to
21 # access the underlying engine (psycopg2) in order to use the 'copy_expert()' function (i.e. it was more efficient just to import and use the psycopg2 library directly in this case).
22 #
23 # - I felt that building Python classes/objects in this situation was a little bit overkill, so kept everything contained inside a single script file with core functionality split out to dedicated functions.
24 # Obviously if the scope of the application was to grow (e.g. to parse and import different data file types), then abstracting certain logic (e.g. to load/parse these different file types) to dedicated
25 # class files would be a reasonable option.
26 #
27 # - In terms of evolving this application, I would like to add the ability to define the table schema directly from CSV header structure.
28
29
30 import click
31 from psycopg2 import connect, sql
32 from pathlib import Path
33 import yaml
34 import logging
35
36 # I'm a fan of using decorators for readabililty.
37 @click.command()
38 @click.option('--config', default='./config.yml', help='The path to the config file.')
39 def run(config):
40 """Imports data from CSV files into a series of PostgresSQL tables (one table per file)."""
41
42 logging.info('Application started.')
43
44 db_conn = None
45
46 # Personally, I prefer YAML format in defining configuration files vs. the standard 'INI' format provided by Python. I find it cleaner.
47 config = read_yaml_config(config)
48
49 files = list_files(config['target_path'])
50
51 try:
52 # Use the '**' syntax to flatten the dictionary into key-value pairs that can be passed into as parameters into psycopg2.connect().
53 db_conn = connect(**config['db'])
54
55 for file in files:
56 import_file_to_database(file, db_conn)
57
58 logging.info('Import complete.')
59
60 except Exception:
61 logging.error('An error occurred whilst importing data files into the database', exc_info=1)
62
63 finally:
64 if db_conn is not None:
65 db_conn.close()
66
67 def read_yaml_config(config_path):
68
69 try:
70 with open(config_path) as file:
71 # We use safe_load() here to help prevent execution of any arbitary code embedded in the YAML file.
72 yaml_file = yaml.safe_load(file)
73 return yaml_file
74 except Exception:
75 logging.error('Failed to load YAML config file.', exc_info=1)
76
77 def list_files(search_folder:str):
78
79 pattern = "*.csv"
80
81 directory = Path(search_folder)
82
83 # Return a list of all files that match the pattern in the search folder.
84 return [csvFile for csvFile in directory.glob(pattern)]
85
86 def import_file_to_database(file_path:str, conn):
87
88 file_name = Path(file_path).stem
89
90 try:
91
92 logging.info('Importing file {} into database table {}.'.format(file_path, file_name))
93
94 with conn.cursor() as cur:
95
96 # First, attempt to create the table if it doesn't already exist.
97 query = sql.SQL("""
98
99 CREATE TABLE IF NOT EXISTS {table_name} (
100
101 osm_id INTEGER PRIMARY KEY,
102 area NUMERIC NOT NULL,
103 lon NUMERIC NOT NULL,
104 lat NUMERIC NOT NULL,
105 tags JSONB,
106 osm_type VARCHAR(25) NOT NULL,
107 p_tag_value TEXT,
108 city TEXT,
109 postcode TEXT,
110 address TEXT,
111 street TEXT,
112 has_way BOOLEAN NOT NULL,
113 shop_type TEXT,
114 derived_shared_area NUMERIC,
115 derived_way_area NUMERIC,
116 parent_way INTEGER,
117 shared_divisor INTEGER,
118 area_sq_foot NUMERIC NOT NULL
119 )
120
121 """).format(table_name = file_name)
122
123 cur.execute(query)
124 cur.commit()
125
126 with open(file_path, 'r') as f:
127
128 # Second, use the PgSQL 'COPY' feature to efficiently copy the contects of the CSV file into the table. (This can scale to millions of rows.) - https://www.postgresql.org/docs/current/sql-copy.html
129 query = sql.SQL("""
130 COPY {table_name} FROM stdin WITH CSV HEADER
131 DELIMITER as ','
132 """).format(table_name = file_name)
133
134 cur.copy_expert(sql=query, file=f)
135
136 except Exception:
137 logging.error('Failed to import file {} into database table {}'.format(file_path, file_name), exc_info=1)
138
139 finally:
140 if cur is not None:
141 cur.close()
142
143 if __name__ == '__main__':
144 run() | 60 - warning: broad-exception-caught
74 - warning: broad-exception-caught
70 - warning: unspecified-encoding
67 - refactor: inconsistent-return-statements
84 - refactor: unnecessary-comprehension
136 - warning: broad-exception-caught
92 - warning: logging-format-interpolation
126 - warning: unspecified-encoding
137 - warning: logging-format-interpolation
144 - error: no-value-for-parameter
|
1 """
2 import.py
3 ~~~~~~~~~
4
5 Run this script to convert social security popular baby names dataset to SQLite.
6 """
7 import glob
8 import io
9 import os
10 import sqlite3
11 import sys
12
13
14 SCHEMA = """
15 CREATE TABLE IF NOT EXISTS names (
16 year integer,
17 name text,
18 sex text,
19 occurrences integer
20 );
21
22 CREATE INDEX IF NOT EXISTS names_year_idx ON names (year);
23 CREATE INDEX IF NOT EXISTS names_name_idx ON names (name);
24 CREATE INDEX IF NOT EXISTS names_sex_idx ON names (sex);
25 CREATE INDEX IF NOT EXISTS names_occurrences_idx ON names (occurrences);
26 """
27
28
29 INSERT = """
30 INSERT OR IGNORE INTO names (
31 year,
32 name,
33 sex,
34 occurrences
35 ) VALUES (
36 :year,
37 :name,
38 :sex,
39 :occurrences
40 );
41 """
42
43
44 def data_generator():
45 """Generator function that yields dicts for each line in each data file"""
46 for path in glob.glob('data/*.txt'):
47 with io.open(path, 'r') as f:
48 print('Processing file {}'.format(path))
49 year = os.path.splitext(os.path.basename(path))[0].strip('yob')
50 for line in f:
51 line = line.strip()
52 name, sex, occurrences = line.split(',')
53 yield {
54 'year': int(year.lower()),
55 'name': name.lower(),
56 'sex': sex.lower(),
57 'occurrences': int(occurrences)
58 }
59
60
61 def create_db(name):
62 """Create Sqlite DB using SCHEMA"""
63 db = sqlite3.connect(name, check_same_thread=False, detect_types=sqlite3.PARSE_COLNAMES)
64 db.executescript(SCHEMA)
65 return db
66
67
68 def main(argv):
69 """Convert directory of text files to SQLite database"""
70 db = create_db(argv[0])
71 db.executemany(INSERT, data_generator())
72 db.commit()
73 db.close()
74
75
76 if __name__ == '__main__':
77 sys.exit(main(sys.argv[1:]))
| 47 - warning: unspecified-encoding
|
1 import mido
2
3 # Volca Beats has ridiculous note mappings
4 # 36 - C2 - Kick
5 # 38 - D2 - Snare
6 # 43 - G2 - Lo Tom
7 # 50 - D3 - Hi Tom
8 # 42 - F#2 - Closed Hat
9 # 46 - A#2 - Open Hat
10 # 39 - D#2 - Clap
11 # 75 - D#5 - Claves
12 # 67 - G4 - Agogo
13 # 49 - C#3 - Crash
14
15
16 note_mapping = {
17 48 : 36,
18 49 : 38,
19 50 : 43,
20 51 : 50,
21 52 : 42,
22 53 : 46,
23 54 : 39,
24 55 : 75,
25 56 : 67,
26 57 : 49
27 }
28
29
30 mido.set_backend('mido.backends.rtmidi')
31
32 inport = mido.open_input('RemapInput', virtual=True)
33
34 outputs = mido.get_output_names()
35 um_one = next(x for x in outputs if 'UM-ONE' in x)
36
37 outport = mido.open_output(um_one, virtual=False)
38
39 for msg in inport:
40 if msg.type in ['note_on','note_off']:
41 # mido starts MIDI channels at 0
42 if msg.channel == 1:
43 if msg.note in note_mapping:
44 new_note = note_mapping[msg.note]
45 msg.note = new_note
46 outport.send(msg)
| Clean Code: No Issues Detected
|
1 from django.apps import AppConfig
2
3
4 class ListsssConfig(AppConfig):
5 name = 'listsss'
| 4 - refactor: too-few-public-methods
|
1 # -*- coding: utf-8 -*-
2 # @Time : 2018/6/28 17:06
3 # @Author : Mat
4 # @Email : mat_wu@163.com
5 # @File : __init__.py.py
6 # @Software: PyCharm
7
8
9 '''
10
11 functional_tests,中的文件需要已tests开头系统命令才能读取到测试用例并执行测试
12
13 测试执行命令python manage.py test functional_tests,来完成功能测试
14
15 如果执行 python manage.py test 那么django 将会执行 功能测试和单元测试
16
17 如果想只运行单元测试则需要执行固定的app ,python manage.py test listsss
18
19 ''' | Clean Code: No Issues Detected
|
1 from django.test import TestCase
2 from django.urls import resolve
3 from django.http import HttpRequest
4 from django.template.loader import render_to_string
5 from django.utils.html import escape
6 from listsss.models import Item, List
7 from listsss.views import home_page
8 import unittest
9
10
11 # Create your tests here.
12 class HomePageTest(TestCase):
13 def test_root_url_resolves_to_home_page_view(self):
14 print("第x个测试通过了")
15 found = resolve('/')
16 self.assertEqual(found.func, home_page)
17
18 def test_home_page_return_correct_html(self):
19 request = HttpRequest()
20 resp = home_page(request)
21
22 # 使用render_to_string ,django自带函数 生成string字符串,和渲染获取到的字符串对比
23 #### 注释:这个没有办法解决,两次生成得tocken值是不相同的,所以先注释掉这个字段对应的断言
24 expected_html = render_to_string('listsss/home.html', request=request)
25
26 # .decode()将字符串转换成unicode
27 # self.assertEqual(resp.content.decode(), expected_html)
28
29 # self.assertTrue(resp.content.startswith(b'<html>'))
30 self.assertIn(b"<title>To-Do lists</title>", resp.content)
31 self.assertTrue(resp.content.endswith(b'</html>'))
32
33 # def test_home_page_only_saves_items_when_necessary(self):
34 # request = HttpRequest()
35 # home_page(request)
36 # self.assertEqual(Item.objects.count(), 0)
37
38 # 中途这个用例不要了
39 # def test_home_page_displays_all_list_items(self):
40 # Item.objects.create(text='itemey 1')
41 # Item.objects.create(text='itemey 2')
42 #
43 # req = HttpRequest()
44 # rep = home_page(req)
45 #
46 # self.assertIn('itemey 1', rep.content.decode())
47 # self.assertIn('itemey 2', rep.content.decode())
48
49
50 class ListViewTest(TestCase):
51 # def test_home_page_displays_all_list_items(self):
52 def test_home_page_displays_only_items_for_that_list(self):
53 # list_ = List.objects.create()
54 # Item.objects.create(text='itemey 1', list=list_)
55 # Item.objects.create(text='itemey 2', list=list_)
56
57 correct_list = List.objects.create()
58 Item.objects.create(text='itemey 1', list=correct_list)
59 Item.objects.create(text='itemey 2', list=correct_list)
60
61 other_list = List.objects.create()
62 Item.objects.create(text='other itemey 1', list=other_list)
63 Item.objects.create(text='other itemey 2', list=other_list)
64
65 # resp = self.client.get('/list/the-only-list-in-the-world/')
66 resp = self.client.get('/list/%d/' % (correct_list.id,))
67
68 self.assertContains(resp, 'itemey 1')
69 self.assertContains(resp, 'itemey 2')
70 self.assertNotContains(resp, 'other itemey 1')
71 self.assertNotContains(resp, 'other itemey 2')
72
73 def test_uses_list_template(self):
74 # resp = self.client.get('/list/the-only-list-in-the-world/')
75 list_ = List.objects.create()
76 resp = self.client.get('/list/%d/' % (list_.id,))
77 self.assertTemplateUsed(resp, 'listsss/list.html')
78
79 def test_passes_correct_list_to_template(self):
80 other_list = List.objects.create()
81 correct_list = List.objects.create()
82 resp = self.client.get('/list/%d/' % (correct_list.id,))
83 self.assertEqual(resp.context['list'], correct_list)
84
85 def test_can_save_a_POST_to_an_existing_list(self):
86 other_list = List.objects.create()
87 correct_list = List.objects.create()
88 self.client.post('/list/%d/' % (correct_list.id,),
89 data={'item_text': 'A new item for an existiong list'})
90 self.assertEqual(Item.objects.count(), 1)
91 new_item = Item.objects.first()
92 self.assertEqual(new_item.text, 'A new item for an existiong list')
93 self.assertEqual(new_item.list, correct_list)
94
95 def test_POST_redirects_to_list_view(self):
96 other_list = List.objects.create()
97 correct_list = List.objects.create()
98 resp = self.client.post('/list/%d/' % (correct_list.id,),
99 data={'item_text': 'A new item for an existiong list'})
100 self.assertRedirects(resp, '/list/%d/' % (correct_list.id,))
101
102 def test_validation_errors_end_up_on_lists_page(self):
103 list_ = List.objects.create()
104 resp = self.client.post('/list/%d/'%(list_.id,), data={"item_text":''})
105 self.assertEqual(resp.status_code, 200)
106 self.assertTemplateUsed(resp, 'listsss/list.html')
107 ex_error=escape('You cant have an empty list item')
108 self.assertContains(resp, ex_error)
109
110 class NewListTest(TestCase):
111 def test_saving_a_POST_request(self):
112 self.client.post('/list/new', data={'item_text': 'A new list item'})
113 self.assertEqual(Item.objects.count(), 1)
114 new_item = Item.objects.first()
115 self.assertEqual(new_item.text, 'A new list item')
116 # requ = HttpRequest()
117 # requ.method = 'POST'
118 # requ.POST['item_text'] = 'A new list item'
119 #
120 # rep = home_page(requ)
121 #
122 # self.assertEqual(Item.objects.count(), 1)
123 # new_item = Item.objects.first()
124 # self.assertEqual(new_item.text, 'A new list item')
125 #
126 # # 下面这部分单独拿出去做一个 单独的单元测试
127 # # self.assertIn('A new list item', rep.content.decode())
128 # # post 请求后页面重定向
129 # # self.assertEqual(rep.status_code, 302)
130 # # self.assertEqual(rep['location'], '/')
131
132 def test_redirects_after_POST(self):
133 rep = self.client.post('/list/new', data={'item_text': 'A new list item'})
134 # self.assertEqual(rep.status_code, 302)
135
136 new_list = List.objects.first()
137 self.assertRedirects(rep, '/list/%d/' % (new_list.id,))
138 # django 的检查项
139 # self.assertRedirects(rep, '/list/the-only-list-in-the-world/')
140 # 这段重新修改
141
142 # requ = HttpRequest()
143 # requ.method = 'POST'
144 # requ.POST['item_text'] = 'A new list item'
145 #
146 # rep = home_page(requ)
147 # self.assertEqual(rep.status_code, 302)
148 # self.assertEqual(rep['location'], '/list/the-only-list-in-the-world/')
149
150 def test_validation_error_are_sent_back_to_home_page_template(self):
151 resp = self.client.post('/list/new', data={'item_text': ''})
152 self.assertEqual(resp.status_code, 200)
153 self.assertTemplateUsed(resp, 'listsss/home.html')
154 ex_error = escape("You cant have an empty list item")
155 print(resp.content.decode())
156 self.assertContains(resp, ex_error)
157
158 def test_invalid_list_items_arent_saved(self):
159 self.client.post('/list/new', data={"item_text": ''})
160 self.assertEqual(List.objects.count(), 0)
161 self.assertEqual(Item.objects.count(), 0)
162
| 24 - warning: unused-variable
80 - warning: unused-variable
86 - warning: unused-variable
96 - warning: unused-variable
8 - warning: unused-import
|
1 from django.test import TestCase
2 from django.urls import resolve
3 from django.http import HttpRequest
4 from django.template.loader import render_to_string
5 from listsss.models import Item, List
6 from listsss.views import home_page
7 import unittest
8 from django.core.exceptions import ValidationError
9
10 class ListAndItemModelsTest(TestCase):
11 def test_saving_and_retrieving_items(self):
12 list_ = List()
13 list_.save()
14
15 first_item = Item()
16 first_item.text = 'The first (ever) list item'
17 first_item.list = list_
18 first_item.save()
19
20 second_item = Item()
21 second_item.text = 'Item the second'
22 second_item.list = list_
23 second_item.save()
24
25 saved_liat = List.objects.first()
26 self.assertEqual(saved_liat, list_)
27
28 saved_items = Item.objects.all()
29 self.assertEqual(saved_items.count(), 2)
30
31 first_save_item = saved_items[0]
32 second_save_item = saved_items[1]
33 self.assertEqual(first_save_item.text, 'The first (ever) list item')
34 self.assertEqual(first_save_item.list, list_)
35 self.assertEqual(second_save_item.text, 'Item the second')
36 self.assertEqual(second_save_item.list, list_)
37
38 def test_cannot_save_empty_list_items(self):
39 list_=List.objects.create()
40 item = Item(list= list_, text='')
41 with self.assertRaises(ValidationError):
42 item.save()
43 item.full_clean()
44
45 def test_get_absolute_url(self):
46 list_ = List.objects.create()
47 self.assertEqual(list_.get_absolute_url(), '/list/%d/'%(list_.id,))
| 2 - warning: unused-import
3 - warning: unused-import
4 - warning: unused-import
6 - warning: unused-import
7 - warning: unused-import
|
1 from django.shortcuts import render, redirect # redirect是python的重定向方法
2 from django.http import HttpResponse
3 from listsss.models import Item, List
4 from django.core.exceptions import ValidationError
5
6
7 # Create your views here.
8 def home_page(request):
9 # return HttpResponse("<html><title>To-Do lists</title></html>")
10 # if (request.method=='POST'):
11 # return HttpResponse(request.POST['item_text'])
12
13 # 新加了页面这里就可以删除了
14 # if (request.method == 'POST'):
15 # new_item_text = request.POST['item_text']
16 # Item.objects.create(text=new_item_text)
17 # return redirect('/list/the-only-list-in-the-world/')
18
19 ##第二种方法
20 # else:
21 # new_item_text = ''
22 # return render(request, 'listsss/home.html', {'new_item_text':new_item_text})
23
24 ##第一种方法
25 # item = Item()
26 # item.text = request.POST.get('item_text', '')
27 # item.save()
28 # return render(request, 'listsss/home.html', {'new_item_text':request.POST.get('item_text','')})
29
30 # 这里首页不用展示相关的数据了
31 # items_list = Item.objects.all()
32 # return render(request, 'listsss/home.html', {'items_list': items_list})
33 return render(request, 'listsss/home.html')
34
35
36 def view_list(request, list_id):
37 error = None
38 list_ = List.objects.get(id=list_id)
39 if request.method == 'POST':
40 try:
41 item = Item.objects.create(text=request.POST['item_text'], list=list_)
42 item.full_clean()
43 item.save()
44 #简化
45 #return redirect('/list/%d/' % (list_.id,))
46 return redirect(list_)
47 except ValidationError:
48 item.delete() # 不知道为什么要加这一步,书里面没有这步骤,书上说抓取到这个错误就不会存到数据库里面了,可还是存进去了
49 error = 'You cant have an empty list item'
50 return render(request, 'listsss/list.html', {'list': list_, 'error': error})
51
52
53 def new_list(request):
54 list_ = List.objects.create()
55 item = Item.objects.create(text=request.POST['item_text'], list=list_)
56 try:
57 item.full_clean()
58 item.save()
59 except ValidationError:
60 list_.delete()
61 item.delete() # 不知道为什么要加这一步,书里面没有这步骤,书上说抓取到这个错误就不会存到数据库里面了,可还是存进去了
62 error = 'You cant have an empty list item'
63 return render(request, 'listsss/home.html', {"error": error})
64 # 重新定义到有效地址
65 # return redirect('/list/the-only-list-in-the-world/')
66 # 去除硬编码
67 # return redirect('/list/%d/' % (list_.id,))
68 return redirect('view_list', list_.id)
69
70
71 def add_item(request, list_id):
72 list_ = List.objects.get(id=list_id)
73 Item.objects.create(text=request.POST['item_text'], list=list_)
74 return redirect('/list/%d/' % (list_.id,))
75
76
77 class home_page_class():
78 pass
79
80
| 77 - refactor: too-few-public-methods
2 - warning: unused-import
|
1 # -*- coding: utf-8 -*-
2 # @Time : 2018/6/25 20:15
3 # @Author : Mat
4 # @Email : mat_wu@163.com
5 # @File : functional_tests1.py
6 # @Software: PyCharm
7
8 from selenium import webdriver
9 from selenium.webdriver.common.keys import Keys
10 from django.test import LiveServerTestCase
11 from django.contrib.staticfiles.testing import StaticLiveServerTestCase
12 import unittest
13 from unittest import skip
14 from .base import FunctionalTest
15
16 class LayoutAndStylingTest(FunctionalTest):
17
18 def test_layout_and_styling(self):
19 self.driver.get(self.live_server_url)
20 self.driver.set_window_size(1024, 768)
21
22 # 查看页面元素居中
23 inputbox = self.driver.find_element_by_id('id_new_item')
24 self.assertAlmostEqual(inputbox.location['x'] + inputbox.size['width'] / 2, 512, delta=10)
25
26 # 保存成功后,清单列表的输入框也居中
27 inputbox.send_keys('testing')
28 inputbox.send_keys(Keys.ENTER)
29 inputbox = self.driver.find_element_by_id('id_new_item')
30 self.assertAlmostEqual(inputbox.location['x'] + inputbox.size['width'] / 2, 512, delta=10)
| 14 - error: relative-beyond-top-level
16 - refactor: too-few-public-methods
8 - warning: unused-import
10 - warning: unused-import
11 - warning: unused-import
12 - warning: unused-import
13 - warning: unused-import
|
1 # -*- coding: utf-8 -*-
2 # @Time : 2018/6/25 20:15
3 # @Author : Mat
4 # @Email : mat_wu@163.com
5 # @File : functional_tests1.py
6 # @Software: PyCharm
7
8 from selenium import webdriver
9 from selenium.webdriver.common.keys import Keys
10 from django.test import LiveServerTestCase
11 from django.contrib.staticfiles.testing import StaticLiveServerTestCase
12 import unittest
13 from unittest import skip
14 from .base import FunctionalTest
15
16
17 class ItemValidationTest(FunctionalTest):
18 def test_cannot_add_empty_list_items(self):
19 self.driver.get(self.live_server_url)
20 self.driver.find_element_by_id('id_new_item').send_keys('\n')
21 error = self.driver.find_element_by_css_selector('.has-error')
22 self.assertEqual(error.text, "You cant have an empty list item")
23
24 self.driver.find_element_by_id('id_new_item').send_keys('Buy milk\n')
25 self.check_for_row_in_list_table('1:Buy milk')
26
27 self.driver.find_element_by_id('id_new_item').send_keys('\n')
28 self.check_for_row_in_list_table('1:Buy milk')
29 error = self.driver.find_element_by_css_selector('.has-error')
30 self.assertEqual(error.text, "You cant have an empty list item")
31
32 self.driver.find_element_by_id('id_new_item').send_keys('Buy tea\n')
33 self.check_for_row_in_list_table('1:Buy milk')
34 self.check_for_row_in_list_table('2:Buy tea')
35 self.fail("write me!")
| 14 - error: relative-beyond-top-level
17 - refactor: too-few-public-methods
8 - warning: unused-import
9 - warning: unused-import
10 - warning: unused-import
11 - warning: unused-import
12 - warning: unused-import
13 - warning: unused-import
|
1 # -*- coding: utf-8 -*-
2 # @Time : 2018/6/25 20:15
3 # @Author : Mat
4 # @Email : mat_wu@163.com
5 # @File : functional_tests1.py
6 # @Software: PyCharm
7
8 from selenium import webdriver
9 from selenium.webdriver.common.keys import Keys
10 from django.test import LiveServerTestCase
11 from django.contrib.staticfiles.testing import StaticLiveServerTestCase
12 import unittest
13 from unittest import skip
14 from .base import FunctionalTest
15
16
17 class NewVisitorTest(FunctionalTest):
18
19 def test_can_start_a_list_and_retrieve_it_later(self):
20 # 类继承LiveServerTestCase 后将不使用实际部署的localhost 地址,使用 django提供的self.live_server_url地址
21 # self.driver.get("http://localhost:8000")
22 self.driver.get(self.live_server_url)
23
24 # 发现页面上显示的 TO-DO 字样
25 self.assertIn('To-Do', self.driver.title)
26 header_text = self.driver.find_element_by_tag_name('h1').text
27 self.assertIn('To-Do', header_text)
28
29 # 应用邀请输入一个代办事项
30 inputbox = self.driver.find_element_by_id('id_new_item')
31 self.assertEqual(inputbox.get_attribute('placeholder'), 'Enter a to-do item')
32
33 # 在输入框中输入购买孔雀羽毛
34 inputbox.send_keys('Buy peacock feathers')
35
36 # 点击回车后页面更新
37 # 代办事项中显示 ‘1:Buy peacock feathers’
38 inputbox.send_keys(Keys.ENTER)
39
40 edith_list_url = self.driver.current_url
41 self.assertRegex(edith_list_url, '/list/.+?')
42
43 table = self.driver.find_element_by_id('id_list_table')
44 rows = table.find_elements_by_tag_name('tr')
45 # self.assertTrue(any(row.text == '1:Buy peacock feathers' for row in rows), 'New to-do item did not appear in table - - its text was:\n%s' % (table.text))
46
47 # 页面又显示了一个文本框,可以输入其他代办事项
48 # 输入‘Use peacock feathers to make a fly’
49 inputbox = self.driver.find_element_by_id('id_new_item')
50 inputbox.send_keys('Use peacock feathers to make a fly')
51 inputbox.send_keys(Keys.ENTER)
52 table = self.driver.find_element_by_id('id_list_table')
53 rows = table.find_elements_by_tag_name('tr')
54 self.assertIn('1:Buy peacock feathers', [row.text for row in rows])
55 self.assertIn('2:Use peacock feathers to make a fly', [row.text for row in rows])
56
57 ##我们需要新打开一个浏览器,并且不让cookice相互干扰
58 # 让录入的清单不会被别人看到
59 self.driver.quit()
60
61 # 其他人访问页面看不到刚才录入的清单
62 self.driver = webdriver.Firefox()
63 self.driver.get(self.live_server_url)
64 page_text = self.driver.find_element_by_tag_name('body').text
65 self.assertNotIn('Buy peacock feathers', page_text)
66 self.assertNotIn('make a fly', page_text)
67
68 # 他输入了新的代办事项,创建了一个新的代办清单
69 inputbox = self.driver.find_element_by_id('id_new_item')
70 inputbox.send_keys('Buy milk')
71 inputbox.send_keys(Keys.ENTER)
72
73 # 他获得了一个属于他自己的url
74 francis_list_url = self.driver.current_url
75 self.assertRegex(edith_list_url, '/list/.+?')
76 self.assertNotEquals(francis_list_url, edith_list_url)
77
78 # 这个页面还是没有其他人的清单
79 # 但是这个页面包含他自己的清单
80 page_text = self.driver.find_element_by_tag_name('body').text
81 self.assertNotIn('Buy peacock feathers', page_text)
82 self.assertIn('Buy milk', page_text)
83 # self.fail('Finisth the test')
| 14 - error: relative-beyond-top-level
22 - error: access-member-before-definition
25 - error: access-member-before-definition
26 - error: access-member-before-definition
30 - error: access-member-before-definition
40 - error: access-member-before-definition
43 - error: access-member-before-definition
49 - error: access-member-before-definition
52 - error: access-member-before-definition
59 - error: access-member-before-definition
62 - warning: attribute-defined-outside-init
17 - refactor: too-few-public-methods
10 - warning: unused-import
11 - warning: unused-import
12 - warning: unused-import
13 - warning: unused-import
|
1 # -*- coding: utf-8 -*-
2 # @Time : 2018/6/25 20:15
3 # @Author : Mat
4 # @Email : mat_wu@163.com
5 # @File : functional_tests1.py
6 # @Software: PyCharm
7
8 from selenium import webdriver
9 from selenium.webdriver.common.keys import Keys
10 from django.test import LiveServerTestCase
11 from django.contrib.staticfiles.testing import StaticLiveServerTestCase
12 import unittest
13 from unittest import skip
14
15
16 class FunctionalTest(StaticLiveServerTestCase):
17
18 #不知道为什么加上下面两个方法之后就报错了
19 # @classmethod
20 # def setUpClass(cls):
21 # pass
22 #
23 # @classmethod
24 # def tearDownClass(cls):
25 # pass
26
27 def setUp(self):
28 self.driver = webdriver.Firefox()
29 self.driver.implicitly_wait(3)
30
31 def tearDown(self):
32 self.driver.quit()
33
34 def check_for_row_in_list_table(self, row_text):
35 table = self.driver.find_element_by_id('id_list_table')
36 rows = table.find_elements_by_tag_name('tr')
37 self.assertIn(row_text, [row.text for row in rows])
38
| 9 - warning: unused-import
10 - warning: unused-import
12 - warning: unused-import
13 - warning: unused-import
|
1 from airflow import DAG
2 from airflow.operators.dummy import DummyOperator
3 from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator
4 from airflow.utils.dates import days_ago
5
6 fraud_features_jar = "/tmp/applications/spark-optimization-features-assembly-0.1.0-SNAPSHOT.jar"
7 sparklens_jar = "https://repos.spark-packages.org/qubole/sparklens/0.3.2-s_2.11/sparklens-0.3.2-s_2.11.jar"
8
9 with DAG(dag_id='spark_optimization_features', default_args={'owner': 'Airflow'}, schedule_interval=None,
10 start_date=days_ago(1), tags=['fraud_features_set'], catchup=False, concurrency=1, max_active_runs=1) as dag:
11
12 start = DummyOperator(task_id="start")
13
14 book_fraud = SparkSubmitOperator(
15 task_id="book_fraud",
16 conn_id="spark.default",
17 name="Book Fraud",
18 application=fraud_features_jar,
19 conf={
20 "spark.default.parallelism": 200,
21 "spark.dynamicAllocation.enabled": "false",
22 "spark.network.timeout": 360000,
23 "spark.shuffle.service.enabled": "false",
24 "spark.sql.autoBroadcastJoinThreshold": -1,
25 "spark.port.maxRetries": 10,
26 "spark.yarn.maxAppAttempts": 1,
27 "spark.executor.extraJavaOptions": "-XX:+UseG1GC",
28 "spark.extraListeners": "com.qubole.sparklens.QuboleJobListener",
29 "spark.sparklens.data.dir": "/tmp/data/history/sparklens"
30 },
31 jars=sparklens_jar,
32 num_executors=1,
33 executor_cores=1,
34 executor_memory="512m",
35 driver_memory="1G",
36 java_class="com.github.fernandobontorin.jobs.FraudBookProcessor",
37 application_args=[
38 "--dataframes",
39 "file:///tmp/data/fraudTest.csv,file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv,"
40 "file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv",
41 "--output",
42 "file:///tmp/data/fraud_book_features"
43 ]
44 )
45
46 book_fraud_optimized = SparkSubmitOperator(
47 task_id="book_fraud_optimized",
48 conn_id="spark.default",
49 name="Book Fraud Optimized",
50 application=fraud_features_jar,
51 conf={
52 "spark.default.parallelism": 1,
53 "spark.dynamicAllocation.enabled": "false",
54 "spark.network.timeout": 360000,
55 "spark.shuffle.service.enabled": "false",
56 "spark.sql.autoBroadcastJoinThreshold": -1,
57 "spark.port.maxRetries": 10,
58 "spark.yarn.maxAppAttempts": 1,
59 "spark.executor.extraJavaOptions": "-XX:+UseG1GC",
60 "spark.extraListeners": "com.qubole.sparklens.QuboleJobListener",
61 "spark.sparklens.data.dir": "/tmp/data/history/sparklens"
62 },
63 jars=sparklens_jar,
64 num_executors=1,
65 executor_cores=1,
66 executor_memory="512m",
67 driver_memory="1G",
68 java_class="com.github.fernandobontorin.jobs.FraudBookProcessor",
69 application_args=[
70 "--dataframes",
71 "file:///tmp/data/fraudTest.csv,file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv,"
72 "file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv",
73 "--output",
74 "file:///tmp/data/fraud_book_features"
75 ]
76 )
77
78 aggregation_fraud = SparkSubmitOperator(
79 task_id="aggregation_fraud",
80 conn_id="spark.default",
81 name="Agg Fraud Set",
82 application=fraud_features_jar,
83 conf={
84 "spark.default.parallelism": 200,
85 "spark.dynamicAllocation.enabled": "false",
86 "spark.network.timeout": 360000,
87 "spark.shuffle.service.enabled": "false",
88 "spark.sql.autoBroadcastJoinThreshold": -1,
89 "spark.port.maxRetries": 10,
90 "spark.yarn.maxAppAttempts": 1,
91 "spark.executor.extraJavaOptions": "-XX:+UseG1GC",
92 "spark.extraListeners": "com.qubole.sparklens.QuboleJobListener",
93 "spark.sparklens.data.dir": "/tmp/data/history/sparklens"
94 },
95 jars=sparklens_jar,
96 num_executors=1,
97 executor_cores=1,
98 executor_memory="512m",
99 driver_memory="1G",
100 java_class="com.github.fernandobontorin.jobs.AggregationProcessor",
101 application_args=[
102 "--dataframes",
103 "file:///tmp/data/fraudTest.csv,file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv,"
104 "file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv",
105 "--output",
106 "file:///tmp/data/aggregation_fraud"
107 ]
108 )
109
110 aggregation_fraud_par = SparkSubmitOperator(
111 task_id="aggregation_fraud_par",
112 conn_id="spark.default",
113 name="Agg Fraud Set Par",
114 application=fraud_features_jar,
115 conf={
116 "spark.default.parallelism": 200,
117 "spark.dynamicAllocation.enabled": "false",
118 "spark.network.timeout": 360000,
119 "spark.shuffle.service.enabled": "false",
120 "spark.sql.autoBroadcastJoinThreshold": -1,
121 "spark.port.maxRetries": 10,
122 "spark.yarn.maxAppAttempts": 1,
123 "spark.executor.extraJavaOptions": "-XX:+UseG1GC",
124 "spark.extraListeners": "com.qubole.sparklens.QuboleJobListener",
125 "spark.sparklens.data.dir": "/tmp/data/history/sparklens"
126 },
127 jars=sparklens_jar,
128 num_executors=1,
129 executor_cores=1,
130 executor_memory="512m",
131 driver_memory="1G",
132 java_class="com.github.fernandobontorin.jobs.ParAggregationProcessor",
133 application_args=[
134 "--dataframes",
135 "file:///tmp/data/fraudTest.csv,file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv,"
136 "file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv,file:///tmp/data/fraudTrain.csv",
137 "--output",
138 "file:///tmp/data/aggregation_fraud_par"
139 ]
140 )
141
142 end = DummyOperator(task_id="end")
143
144 start >> book_fraud >> book_fraud_optimized >> (aggregation_fraud, aggregation_fraud_par) >> end
145
146
| 144 - warning: pointless-statement
|
1 import gzip
2 import bz2
3
4
5 if __name__ == "__main__":
6 # gzip作用于一个已经打开的二进制文件 new character
7 f = open('file.gz', 'rb')
8 with gzip.open(f, 'rb') as f:
9 print(f.read())
10 # with语句结束自动会关闭文件
11 with gzip.open('file', 'wt') as f:
12 f.read("test")
13 print("new line")
14 with bz2.open('file', 'wt') as f:
15 f.read("test")
16 print("end") | 7 - refactor: consider-using-with
|
1 if __name__ == "__main__":
2 # list,dict,set是不可hash的
3 # int,float,str,tuple是可以hash的
4 data = [1, 2, '232', (2, 3)]
5 data1 = [2, 3, '213', (2, 3)]
6
7 # 两个list取补集,元素在data中,不在data1中
8 diff_list = list(set(data).difference(set(data1)))
9 print(diff_list)
10
11 # 取交集
12 inter_list = list(set(data).intersection(set(data1)))
13 print(inter_list)
14
15 # 取并集
16 union_list = list(set(data).union(set(data1)))
17 print(union_list) | Clean Code: No Issues Detected
|
1 import threading
2 from socket import socket, AF_INET, SOCK_STREAM
3 from functools import partial
4 from contextlib import contextmanager
5
6
7 # State to stored info on locks already acquired
8 _local = threading.local()
9
10
11 @contextmanager
12 def acquire(*locks):
13 locks = sorted(locks, key=lambda x: id(x))
14
15 acquired = getattr(_local, 'acquire', [])
16 if acquired and max(id(lock) for lock in acquired) >= id(locks[0]):
17 raise RuntimeError('Lock order violation')
18
19 acquired.extends(locks)
20 _local.acquired = acquired
21
22 try:
23 for lock in locks:
24 lock.acquire()
25 yield
26 finally:
27 for lock in reversed(locks):
28 lock.release()
29 del acquired[-len(locks):]
30
31
32 class LazyConnection:
33 def __init__(self, address, family=AF_INET, socket_type=SOCK_STREAM):
34 self.address = address
35 self.family = family
36 self.socket_type = socket_type
37 self.local = threading.local()
38
39 def __enter__(self):
40 if hasattr(self.local, 'sock'):
41 raise RuntimeError('connection existed')
42 self.local.sock = socket(self.family, self.socket_type)
43 self.local.sock.connect(self.address)
44 return self.local.sock
45
46 def __exit__(self, exc_type, exc_val, exc_tb):
47 self.local.sock.close()
48 del self.local.sock
49
50
51 def test(conn):
52 with conn as c:
53 c.send(b'test\n')
54 resp = b''.join(iter(partial(c.recv, 8192), b''))
55 print(len(resp))
56
57
58 if __name__ == "__main__":
59 conn = LazyConnection(("www.test.com", 8081))
60 t1 = threading.Thread(target=test, args=(conn,))
61 t2 = threading.Thread(target=test, args=(conn,))
62 t1.start()
63 t2.start()
64 t1.join()
65 t2.join()
| 13 - warning: unnecessary-lambda
19 - error: no-member
51 - warning: redefined-outer-name
|
1 import base64
2 import binascii
3
4
5 if __name__ == "__main__":
6 s = b'hello world!'
7 # 2进制转换成16进制
8 h = binascii.b2a_hex(s)
9 print(h)
10 # 16进制转换成2进制
11 print(binascii.a2b_hex(h))
12 h1 = base64.b16encode(s)
13 print(h1)
14 print(base64.b16decode(h1)) | Clean Code: No Issues Detected
|
1 import re
2
3
4 text = '/* http new s */'
5 r = re.compile(r'/\*(.*?)\*/')
6 print(r.findall(text))
| Clean Code: No Issues Detected
|
1 if __name__ == "__main__":
2 x = 1234
3 # 函数形式
4 print(bin(x))
5 print(oct(x))
6 print(hex(x))
7 # format形式,没有前缀 0b,0o,0x
8 print(format(x, 'b'))
9 print(format(x, 'o'))
10 print(format(x, 'x'))
11 #将进制的数据转换成整数字符串
12 a = format(x, 'b')
13 b = format(x, 'x')
14 print(int(a, 2))
15 print(int(b, 16)) | Clean Code: No Issues Detected
|
1 from urllib.request import urlopen
2
3
4 def urltemplate(template):
5 def opener(**kwargs):
6 return template.format_map(kwargs)
7 # return urlopen(template.format_map(kwargs))
8 return opener
9
10
11 if __name__ == "__main__":
12 url = urltemplate('http://www.baidu.com?name={name}&age={age}')
13 print(url)
14 test = 'http://www.kingsoft.com?name={name}&age={age}'
15 s1 = test.format_map({'name': 'mac', 'age': 23})
16 print(s1)
17 s = url(name='Alex', age=23)
18 print(s) | 1 - warning: unused-import
|
1 data = ['test', 90, 80, (1995, 8, 30)]
2
3
4 if __name__ == "__main__":
5 _, start, end, (_, _, day) = data
6 print(start)
7 print(end)
8 print(day) | Clean Code: No Issues Detected
|
1 from operator import itemgetter
2 from itertools import groupby
3
4
5 data = [
6 {"date": 2019},
7 {"date": 2018},
8 {"date": 2020}
9 ]
10 data.sort(key=itemgetter('date'))
11 print(data)
12 for date, item in groupby(data, key=itemgetter('date')):
13 print(date)
14 print(item)
15 for i in item:
16 print(type(i), i) | Clean Code: No Issues Detected
|
1 import io
2
3
4 if __name__ == "__main__":
5 s = io.StringIO()
6 s_byte = io.BytesIO()
7 print('test', file=s, end="\t")
8 s_byte.write(b'bytes')
9 print("new")
10 print(s.getvalue())
11 print(s_byte.getvalue())
| Clean Code: No Issues Detected
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-07 18:46
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test17.py
7 # ----------------------------------------------
8
9
10 def test():
11 # 在函数内部使用 global 声名全局变量
12 global A
13 A = 1
14 print(A)
15
16
17 if __name__ == "__main__":
18 # input 函数与用户交互使用
19
20 # 解释一下 python 中 pass 的作用。
21 # 是空语句,是为了保持程序结构的完整性。不做任何事情,一般用做占位语句。
22
23 # is == 的区别,== 是比较两个对象的 value 值是否相等,is 判断两个对象的 id 是否相等
24 # python 对象包含3个基本要素,value id type
25
26 # python 中的作用域,global,nonlocal 语句,全局作用域,在函数内部对函数外部的非全局变量的使用
27
28 # 三元运算符的用法
29 b = "1"
30 a = "0" if b == "0" else "1"
31 print(a)
32 # enumerate 模块,遍历会带上索引
33 for i, v in enumerate(range(1, 11)):
34 print(i, v)
35 # python 中的标准模块,functools collections logging
36 test()
37 A = 2
38 print(A)
39 # 断言成功继续往下执行,失败就报异常信息
40 assert 1 == 1
41 print("end")
42 # dir 用于查看对象的 属性和方法
43 a = [1, 2, [1, 2]]
44 b = a
45 import copy
46 c = copy.copy(a)
47 d = copy.deepcopy(a)
48 a[2].append(3)
49 print(a, b , c, d)
50 data = [1, 2, 3, 4]
51 print(data[::-1])
52 d = [1, 2, 3, 4]
53 e = d
54 print(id(d), id(e)) | 12 - warning: global-statement
40 - refactor: comparison-with-itself
40 - refactor: comparison-of-constants
|
1 import os.path
2 import time
3 import glob
4 import fnmatch
5
6
7 if __name__ == "__main__":
8 dir_path = '/data/proc/log'
9 file_name = [name for name in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, name))]
10 dir_name = [name for name in os.listdir(dir_path) if os.path.isdir(os.path.join(dir_path, name))]
11 pyfile = [name for name in os.listdir(dir_path) if name.endswith('.py')]
12 path = '/data/prolog/log/test.log'
13 print(os.path.basename(path))
14 print(os.path.dirname(path))
15 print(os.path.split(path))
16 print(os.path.join('root', 'tmp', os.path.basename(path)))
17 # 测试文件或者目录是否存在 指定类型判断
18 if os.path.exists(path):
19 print(True)
20 os.path.isfile(path)
21 os.path.isdir(path)
22 # 测试是否是软连接
23 os.path.islink(path)
24 # 得到软连接的完整路径
25 os.path.realpath(path)
26 os.path.getsize(path)
27 # 得到文件的创建时间
28 os.path.getmtime(path)
29 # 修改文件的创建时间
30 time.ctime(os.path.getmtime(path)) | 3 - warning: unused-import
4 - warning: unused-import
|
1 from itertools import compress
2 import re
3 import arrow
4
5
6 addresses = [
7 '5412 N CLARK',
8 '5148 N CLARK',
9 '5800 E 58TH',
10 '2122 N CLARK',
11 '5645 N RAVENSWOOD',
12 '1060 W ADDISON',
13 '4801 N BROADWAY',
14 '1039 W GRANVILLE',
15 ]
16 counts = [0, 3, 10, 4, 1, 7, 6, 1]
17
18 new = [n > 5 for n in counts]
19
20 l = list(compress(addresses, new))
21 print(l)
22 test = '12 23, 34; 1213'
23 print(re.split(r'\s*[,;\s]\s*', test))
24
25 print(arrow.now().isoformat())
26 t = arrow.get('2018-12-01 10:23')
27 print(t.isoformat().split('.')[0])
| Clean Code: No Issues Detected
|
1 import re
2 import os
3
4
5 if __name__ == "__main__":
6 s = " hello new world \n"
7 # strip用于取出首尾指定字符
8 print(s.strip())
9 print(s.lstrip())
10 print(s.rstrip())
11 s = "test ?"
12 s1 = s.replace('?', 'new')
13 print(s1)
14 s2 = re.sub('new', 'fresh', s1, flags=re.IGNORECASE)
15 print(s2) | 2 - warning: unused-import
|
1 from functools import partial
2 from socket import socket, AF_INET, SOCK_STREAM
3
4
5 class LazyConnection:
6 def __init__(self, address, family=AF_INET, type=SOCK_STREAM):
7 self.address = address
8 self.family = family
9 self.type = type
10 self.connections = []
11
12 def __enter__(self):
13 sock = socket(self.family, self.type)
14 sock.connect(self.address)
15 self.connections.append(sock)
16 return sock
17
18 def __exit__(self, exc_type, exc_val, exc_tb):
19 self.connections.pop().close()
20
21
22 if __name__ == "__main__":
23 conn = LazyConnection(('http://www.baidu.com', 80))
24 # 嵌套使用conn
25 with conn as s1:
26 pass
27 with conn as s2:
28 pass | 6 - warning: redefined-builtin
26 - warning: unnecessary-pass
1 - warning: unused-import
|
1 import arrow
2
3
4 bracket_dct = {'(': ')', '{': '}', '[': ']', '<': '>'}
5
6
7 def bracket(arg: str):
8 match_stack = []
9 for char in arg:
10 if char in bracket_dct.keys():
11 match_stack.append(char)
12 elif char in bracket_dct.values():
13 if len(match_stack) > 0 and bracket_dct[match_stack.pop()] == char:
14 continue
15 else:
16 return False
17 else:
18 continue
19 return True
20
21
22 if __name__ == "__main__":
23 test = '(12121){}dasda[oio{dad}232<asfsd>232]'
24 print(arrow.now().format('YYYY-MM-DD HH:MM:SS'))
25 print(bracket(test))
| 13 - refactor: no-else-continue
|
1 from functools import total_ordering
2 import re
3
4
5 class Room:
6 def __init__(self, name, length, width):
7 self.name = name
8 self.length = length
9 self.width = width
10 self.squre_foot = self.length*self.width
11
12
13 @total_ordering
14 class House:
15 def __init__(self, name, style):
16 self.name = name
17 self.style = style
18 self.rooms = list()
19
20 @property
21 def living_space_footage(self):
22 return sum(r.squre_foot for r in self.rooms)
23
24 def append_room(self, room):
25 self.rooms.append(room)
26
27 def __str__(self):
28 return '{} area is {}, style is {}'.format(self.name, self.living_space_footage, self.style)
29
30 def __eq__(self, other):
31 return self.living_space_footage == other.living_space_footage
32
33 def __lt__(self, other):
34 return self.living_space_footage < other.living_space_footage
35
36
37 if __name__ == "__main__":
38 # a = Room('bed_room', 20, 30)
39 # # b = Room('living_room', 30, 40)
40 # # c = Room('kitchen_room', 10, 20)
41 # # h = House('home', 'Asia')
42 # # h1 = House('new-home', 'Europe')
43 # # h.append_room(a)
44 # # h.append_room(b)
45 # # h1.append_room(c)
46 # # if h1 > h:
47 # # print('{} area > {}'.format(h1.living_space_footage, h.living_space_footage))
48 # # else:
49 # # print('{} area is {} and < {} area is {}'.format(h1.name, h1.living_space_footage, h.name, h.living_space_footage))
50 # #
51 # # data = [1, 3, 3, 2, 5, 7, 5, 4, 5]
52 # # a = list({k:'' for k in data})
53 # # print(a)
54 s = re.compile(r'[0-9]+')
55 if s.match('1'):
56 print('yes')
57 data = [1,2,3,5,7,8]
58 new = [23, 45, 1]
59 new.reverse()
60
61 print(new)
62 print(data+new)
63 print(round(7/3, 2)) | 5 - refactor: too-few-public-methods
18 - refactor: use-list-literal
|
1 from ruamel.yaml import YAML
2
3
4 if __name__ == "__main__":
5 # yaml文件解析
6 with open('deployments.yaml') as fp:
7 content = fp.read()
8 yaml = YAML()
9 print(content)
10 content = yaml.load_all(content)
11 print(type(content))
12 data = []
13 for c in content:
14 data.append(c)
15 print(data[0])
16 c = data[0]
17 tmp = c['spec']['template']['spec']['containers'][0]['args'][2]
18 c['spec']['template']['spec']['containers'][0]['args'][2] = tmp.format('http')
19 data[0] = c
20 content = (d for d in data)
21 print(content)
22 with open('new.yaml', 'w') as f:
23 yaml.dump_all(content, f)
| 6 - warning: unspecified-encoding
22 - warning: unspecified-encoding
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2019-11-08 11:42
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test-requests.py
7 # ----------------------------------------------
8 import requests
9
10
11 if __name__ == "__main__":
12 url = "https://cn.bing.com/"
13 resp = requests.get("https://"+"cn.bing.com", verify=True)
14 print(resp.status_code)
15 print(resp.url) | 13 - warning: missing-timeout
|
1 from collections import OrderedDict
2
3
4 def dedupe(items):
5 """
6 删除一个迭代器中重复的元素,并保持顺序
7 :param items: 迭代器
8 :return:
9 """
10 a = set()
11 for item in items:
12 if item not in a:
13 yield item
14 a.add(item)
15
16
17 # 找出一个字符串中最长的没有重复字符的字段
18 def cutout(test: str):
19 max_data = []
20 for s in test:
21 if s not in max_data:
22 max_data.append(s)
23 else:
24 yield max_data
25 max_data = []
26 max_data.append(s)
27 yield max_data
28
29
30 if __name__ == "__main__":
31 data = [1, 2, 2, 1, 4, 5, 4]
32 print(list(dedupe(data)))
33
34 # 简单方法
35 order_dct = OrderedDict()
36 for item in data:
37 order_dct[item] = item
38 print(list(order_dct.keys()))
39 data = 'anmninminuc'
40 for item in cutout(data):
41 print(''.join(item))
42
43 output = ''.join(max(cutout(data), key=lambda s: len(s)))
44 print(output) | 11 - warning: redefined-outer-name
43 - warning: unnecessary-lambda
|
1 from functools import partial
2 import math
3
4
5 def distance(p1, p2):
6 x1, y1 = p1
7 x2, y2 = p2
8 return math.hypot(x2-x1, y2-y1)
9
10
11 if __name__ == "__main__":
12 points = [(1, 2), (3, 4), (7, 8), (5, 6)]
13 pt = (5, 6)
14 points.sort(key=partial(distance, pt))
15 print(points)
| Clean Code: No Issues Detected
|
1 # 插入排序 时间复杂度O(N^2)
2 # 具体过程如下 每次循环往已经排好序的数组从后往前插入一个元素,第一趟比较两个元素的大小,第二趟插入元素
3 # 与前两个元素进行比较,放到合适的位置,以此类推。
4
5
6 def insert_sort(data: list):
7 for i in range(1, len(data)):
8 key = data[i]
9 # 相当于相邻元素进行比较,但是逻辑更清楚一点
10 for j in range(i-1, -1, -1):
11 if data[j] > key:
12 data[j+1] = data[j]
13 data[j] = key
14 return data
15
16
17 if __name__ == "__main__":
18 t_data = [2, 4, 1, 5, 3, 5, 9, 10, 8, 7]
19 print(insert_sort(t_data)) | Clean Code: No Issues Detected
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-01 12:33
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test04.py
7 # ----------------------------------------------
8 if __name__ == "__main__":
9 # 字典操作
10 dct = {"a": 1, "b": 2}
11 a = dct.pop("a")
12 print(a)
13 print(dct)
14 del dct["b"]
15 print(dct)
16 # 合并两个字典
17 a = {"a": 1, "b": 2}
18 b = {"c": 3, "d": 4}
19 a.update(b)
20 print(a)
21 # 生成器的方式生成一个字典,dict 直接初始化 必须是元组的 list 形式才可以
22 values = [1, 2, 3]
23 keys = ["a", "b", "c"]
24 dct = {k: v for k, v in zip(keys, values)}
25 print(dct)
26 dct2 = dict(zip(keys, values))
27 dct3 = dict([("a", 1), ("b", 2)])
28 print(dct2)
29 print(dct3) | 24 - refactor: unnecessary-comprehension
|
1 def async_apply(func, args, *, callback):
2 result = func(*args)
3 callback(result)
4
5
6 def make_handle():
7 sequence = 0
8 while True:
9 result = yield
10 sequence += 1
11 print('[{}] result is {}'.format(sequence, result))
12
13
14 if __name__ == "__main__":
15 # 协程处理
16 handle = make_handle()
17 next(handle)
18 add = lambda x, y: x+y
19 async_apply(add, (2, 3), callback=handle.send)
20 async_apply(add, (3, 4), callback=handle.send) | Clean Code: No Issues Detected
|
1 # 希尔排序 时间复杂度是O(NlogN)
2 # 又称缩小增量排序 首先设置一个基础增量d,对每间隔d的元素分组,然后对每个分组的元素进行直接插入排序
3 # 然后缩小增量,用同样的方法,直到增量小于0时,排序完成
4
5
6 def shell_sort(data: list):
7 n = len(data)
8 gap = int(n / 2) # 设置基础增量
9 # 当增量小于0时,排序完成
10 while gap > 0:
11 for i in range(gap, n):
12 j = i
13 while j >= gap and data[j-gap] > data[j]:
14 data[j-gap], data[j] = data[j], data[j-gap]
15 j -= gap
16 gap = int(gap / 2)
17 return data
18
19
20 if __name__ == "__main__":
21 t_data = [3, 2, 5, 4, 1]
22 print(shell_sort(t_data)) | Clean Code: No Issues Detected
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-01 12:45
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test05.py
7 # ----------------------------------------------
8
9
10 # 定义一个生成器的函数,需要用到 yield
11 def my_generate(nums):
12 for i in nums:
13 yield i
14
15
16 if __name__ == "__main__":
17 # 一行代码搞定交换字典的 key value 值
18 dct1 = {"A": 1, "B": 2}
19 dct2 = {str(v): k for k, v in dct1.items()}
20 print(dct2)
21 # 实现 tuple 和 list 的转换
22 a = (1, 2, 3)
23 print(a)
24 b = list(a)
25 print(b)
26 # 把 列表转换成生成器
27 c = [i for i in range(3)]
28 g = my_generate(c)
29 print(g)
30 # 遍历生成器
31 for i in g:
32 print(i, end=" ")
33 print("")
34 # 编码
35 a = "hello"
36 b = "你好"
37 print(a.encode("utf-8"))
38 print(b.encode("utf-8")) | 12 - warning: redefined-outer-name
12 - refactor: use-yield-from
27 - refactor: unnecessary-comprehension
|
1 import pandas as pd
2 import numpy as np
3 import logging
4
5 logging.basicConfig(level=logging.DEBUG,
6 format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
7 datefmt='%a, %d %b %Y %H:%M:%S',
8 filename='test.log',
9 filemode='w')
10
11
12 if __name__ == "__main__":
13 datas = pd.read_csv('test.csv')
14 print(datas)
15 # 输出每一列的数据类型
16 print(datas.dtypes)
17 # 输出前几行,会自动把header输出,不算行
18 print(datas.head(2))
19 # 每一列都有什么特征
20 print(datas.columns)
21 # 输出csv文件有多少行和列,不算header
22 print(datas.shape)
23 # pandas.Series传递一个list为参数
24 s = pd.Series([1, 2, 3, np.nan, 5, 6])
25 print(s)
26 dates = pd.date_range('20181201', periods=12)
27 print(dates)
28 da = np.random.randn(3, 4)
29 print(da)
30 # 传递一个np数组
31 df = pd.DataFrame(data=np.random.randn(12, 6), index=dates, columns=list('ABCDEF'))
32 print(df)
33 # 传递一个dict对象
34 df2 = pd.DataFrame({"a": [i for i in range(4)],
35 "b": "test"})
36 print(df2)
37 # view head or tail 元素,head default n=5
38 print(df.head())
39 print(df.tail(2))
40 # view index, columns, values
41 print(df.index)
42 print(df.columns)
43 print(df.values)
44 # describe 快速显示DataFrame的各项指标
45 print(df.describe())
46 # df.loc[] useful
47 print(df.loc[dates[0]])
48 print(df.loc[dates[0], ['A', 'B']])
49 print(df.loc[dates[0]:dates[2], ['A', 'B', 'C']])
50 print(df.iloc[0:2])
51 print(df.iloc[0:2, 3:4])
52 logging.info('new')
53 df3 = df.copy()
54 print(df3)
55 print(df3.mean())
56 print(df3.mean(1))
| 34 - refactor: unnecessary-comprehension
|
1 import numpy as np
2
3
4 if __name__ == "__main__":
5 """
6 使用numpy模块来对数组进行运算
7 """
8 x = [1, 2, 3, 4]
9 y = [5, 6, 7, 8]
10 print(x+y)
11 print(x*2)
12 nx = np.array(x)
13 ny = np.array(y)
14 print(nx*2)
15 print(nx+10)
16 print(nx+ny)
17 print(np.sqrt(nx))
18 print(np.cos(nx))
19 # 二维数组操作
20 a = np.array([[1, 2, 3], [2, 3, 4]])
21 # select row 1
22 print(a[1])
23 # select column 1
24 print(a[:, 1])
25 print(np.where(a > 1, a, 0)) | 5 - warning: pointless-string-statement
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-07 12:18
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test15.py
7 # ----------------------------------------------
8
9
10 if __name__ == "__main__":
11 # filter 方法,func + iterator
12 data = [i for i in range(1, 11)]
13 print(list(filter(lambda x: x % 2 == 0, data)))
14 # 什么是猴子补丁
15 # 运行是动态替换模块的方法
16 # python 是如何管理内存的,引用计数和分代垃圾回收的机制
17 # 当退出 python3 时,是否会释放所有内存分配,答案时否定的,对于循环引用和相互引用的内存还不会释放
| 12 - refactor: unnecessary-comprehension
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-01 11:28
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test03.py
7 # ----------------------------------------------
8 if __name__ == "__main__":
9 # 对列表元素去重
10 aList = [1, 2, 3, 2, 1]
11 b = set(aList)
12 print(list(b))
13 # 2,太简单 不说了
14 s1 = "1,2,3"
15 print(s1.split(","))
16 # 3,找出两个列表中相同元素和不同元素
17 a = [1, 2, 5, 3, 2]
18 b = [4, 5, 6, 1, 2]
19 common_l = list(set(a) & set(b))
20 print(common_l)
21 only_in_a = list(set(a) - set(common_l))
22 only_in_b = list(set(b) - set(common_l))
23 print(only_in_a)
24 print(only_in_b)
25 # 一行代码展开 list,nice
26 a = [[1, 2], [3, 4], [5, 6]]
27 b = [j for i in a for j in i]
28 print(b)
29 # numpy 实现,flatten 方法,然后转换成 list
30 import numpy as np
31 c = np.array(a).flatten().tolist()
32 print(c)
33 # 合并列表,list 可以用 extend 方法
34 a = [1, 2, 3]
35 b = [4, 5, 6]
36 a.extend(b)
37 print(a)
38 # 打乱一个列表
39 import random
40 a = [1, 2, 3, 4, 5]
41 random.shuffle(a)
42 print(a)
43 print(random.randint(1, 10)) | Clean Code: No Issues Detected
|
1 from collections import defaultdict
2
3 counter_words = defaultdict(list)
4
5
6 # 定位文件中的每一行出现某个字符串的次数
7 def locate_word(test_file):
8 with open(test_file, 'r') as f:
9 lines = f.readlines()
10 for num, line in enumerate(lines, 1):
11 for word in line.split():
12 counter_words[word].append(num)
13 return counter_words
14
15
16 if __name__ == "__main__":
17 file = 'data/test.txt'
18 ret = locate_word(file)
19 print(ret.get('test', []))
| 8 - warning: unspecified-encoding
|
1 import jsane
2
3
4 if __name__ == "__main__":
5 # jsane是一个json解析器
6 # loads 解析一个json字符串
7 j = jsane.loads('{"name": "wulj", "value": "pass"}')
8 print(j.name.r())
9 # from_dict 解析字典
10 j2 = jsane.from_dict({'key': ['v1', 'v2', ['v3', 'v4', {'inner': 'value'}]]})
11 print(j2.key[2][2].inner.r())
12 # 当解析找不到key时,设置默认值
13 print(j2.key.new.r(default="test"))
| Clean Code: No Issues Detected
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2019-12-25 21:25
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : kafka-producer.py
7 # ----------------------------------------------
8 from kafka import KafkaProducer
9 from time import sleep
10
11
12 def start_producer():
13 producer = KafkaProducer(bootstrap_servers='kafka-0-0.kafka-0-inside-svc.kafka.svc.cluster.local:32010,'
14 'kafka-1-0.kafka-1-inside-svc.kafka.svc.cluster.local:32011,'
15 'kafka-2-0.kafka-2-inside-svc.kafka.svc.cluster.local:32012,'
16 'kafka-3-0.kafka-3-inside-svc.kafka.svc.cluster.local:32013,'
17 'kafka-4-0.kafka-4-inside-svc.kafka.svc.cluster.local:32014,'
18 'kafka-5-0.kafka-5-inside-svc.kafka.svc.cluster.local:32015')
19 for i in range(0, 100000):
20 msg = 'msg is ' + str(i)
21 print(msg)
22 producer.send('my_test_topic1', msg.encode('utf-8'))
23 sleep(3)
24
25
26 if __name__ == '__main__':
27 start_producer()
| Clean Code: No Issues Detected
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-04 16:38
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test10.py
7 # ----------------------------------------------
8 import redis
9 import uuid
10 import time
11 from threading import Thread
12
13
14 redis_client = redis.Redis(host="127.0.0.1", port=6379, username="test", password="test", db=0)
15
16
17 def acquire_lock(lock_name, acquire_time=10, time_out=10):
18 """
19 :param lock_name: 锁名称
20 :param acquire_time: 客户端等待获取锁的时间
21 :param time_out: 锁的超时时间
22 :return: True or False
23 """
24 identifier = str(uuid.uuid4())
25 end = time.time() + acquire_time
26 lock = "string:lock:" + lock_name
27 while time.time() < end:
28 # 成功设置,则插入数据,返回1,否则已经有相同 key,返回0
29 if redis_client.setnx(lock, identifier):
30 # 设置 key 失效时间
31 redis_client.expire(lock, time_out)
32 # 获取成功,返回 identifier
33 return identifier
34 # 每次请求都更新锁名称的失效时间
35 elif not redis_client.ttl(lock):
36 redis_client.expire(lock, time_out)
37 time.sleep(0.001)
38 return False
39
40
41 def release_lock(lock_name, identifier):
42 """
43 :param lock_name: 锁名称
44 :param identifier: uid
45 :return: True or False
46 """
47 lock = "string:lock:" + lock_name
48 pip = redis_client.pipeline(True)
49 while True:
50 try:
51 pip.watch(lock)
52 lock_value = redis_client.get(lock)
53 if not lock_value:
54 return True
55
56 if lock_value.decode() == identifier:
57 pip.multi()
58 pip.delete(lock)
59 pip.execute()
60 return True
61 pip.unwatch()
62 break
63 except redis.exceptions.WatchError:
64 pass
65 return False
66
67
68 def sec_kill():
69 identifier = acquire_lock("resource")
70 print(Thread.getName(), "acquire resource")
71 release_lock("resource", identifier)
72
73
74 if __name__ == "__main__":
75 for i in range(50):
76 t = Thread(target=sec_kill)
77 t.start()
| 29 - refactor: no-else-return
70 - warning: deprecated-method
70 - error: no-value-for-parameter
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2019-11-07 18:50
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test-sanic.py
7 # ----------------------------------------------
8 from sanic import Sanic
9 from sanic import response
10 from pprint import pprint
11
12
13 app = Sanic()
14
15
16 @app.route('/', methods=['POST'])
17 async def g(request):
18 data = request.json
19 resp = []
20 for k, v in data:
21 for d in v:
22 resp.append(sorted(d.items()))
23 pprint(sorted(resp))
24 return response.json(True)
25
26
27 if __name__ == "__main__":
28 app.run(host='0.0.0.0', port=10000, debug=True)
| 20 - warning: unused-variable
|
1 import sqlite3
2
3
4 if __name__ == "__main__":
5 data = [
6 (1, 2, 3),
7 (2, 3, 4),
8 ]
9 s = sqlite3.connect('database.db')
10 # 给数据库建立游标,就可以执行sql查询语句了
11 db = s.cursor()
12 db.execute('create table wulj (name, number, rate)')
13 print(db)
14 s.commit()
15 db.executemany('insert into wulj (?,?,?)', data)
16 s.commit()
17 for row in db.execute('select * from wulj'):
18 print(row)
19 number = 10
20 # 用户输入参数用于交互查询,?代表占位符
21 for row in db.execute('select * from wulj where num > ?', (number,)):
22 print(row) | Clean Code: No Issues Detected
|
1 from collections import Counter, defaultdict
2 import requests
3 import arrow
4
5
6 class Data:
7 def __init__(self, data):
8 self.data = data
9
10
11 if __name__ == "__main__":
12 url = 'http://10.100.51.45/rate/repair?start={}&end={}'
13 start = '2019-04-01 23:10'
14 end = '2019-04-07 23:10'
15 ret = requests.get(url.format(start, end))
16 print(ret.status_code)
17 # dct = {}
18 # d = Data('1')
19 # dct['re'] = d
20 # print(dct)
21 # test = defaultdict()
22 # data = [{'key1': 1}, {'key2': 2}]
23 # for d in data:
24 # test.update(d)
25 # print(test)
26 # dct = {'data': test}
27 # for k, v in dct.items():
28 # print(k)
29 # for k1, v1 in v.items():
30 # print(k1)
31 # print(v1)
32 # data = [1, 2, 3, 5, 5]
33 # data2 = [2, 3, 4, 6, 2]
34 # a = set(d for d in data)
35 # print(a)
36 # b = set(d for d in data2)
37 # print(b)
38 # print(a & b)
39 # print(a - (a & b))
40 # t = tuple(d for d in data)
41 # for i in t:
42 # print(i)
43 # print(tuple(d for d in data))
44 # link = 'http://jira.op.ksyun.com/browse/BIGDATA-614/test'
45 # print(link.split('/')[-2])
46 # print('http'.upper())
47 # for dct in data:
48 # for key in ('key1', 'key2'):
49 # if key not in dct.keys():
50 # dct[key] = 0
51 # print(data)
52 # ret = defaultdict(Counter)
53 # data1 = {'name': {'key1': [1, 2, 3]}}
54 # data2 = {'name': {'key1': [2, 3, 4]}}
55 # for d in (data1, data2):
56 # for name, data in d.items():
57 # ret[name] += Counter(data)
58 # print(ret) | 6 - refactor: too-few-public-methods
15 - warning: missing-timeout
1 - warning: unused-import
1 - warning: unused-import
3 - warning: unused-import
|
1 import random
2
3
4 if __name__ == "__main__":
5 values = [1, 2, 3, 4, 5]
6 # 随机选取一个元素
7 print(random.choice(values))
8 # 随机选取几个元素且不重复
9 print(random.sample(values, 3))
10 # 打乱原序列中的顺序
11 print(random.shuffle(values))
12 # 生成随机整数,包括边界值
13 print(random.randint(0, 10))
14 # 生成0-1的小数
15 print(random.random())
16 # 获取N位随机数的整数
17 print(random.getrandbits(10)) | Clean Code: No Issues Detected
|
1 from decimal import Decimal, localcontext
2
3
4 def main(a, b):
5 a = Decimal(a)
6 b = Decimal(b)
7 return a+b
8
9
10 if __name__ == "__main__":
11 sum = main('3.2', '4.3')
12 # 使用上下文管理器更改输出的配置信息
13 with localcontext() as ctx:
14 ctx.prec = 3
15 print(Decimal('3.2')/Decimal('2.3'))
16 print(sum == 7.5)
| 11 - warning: redefined-builtin
|
1 if __name__ == "__main__":
2 names = set()
3 dct = {"test": "new"}
4 data = ['wulinjiang1', 'test', 'test', 'wulinjiang1']
5 print('\n'.join(data))
6 from collections import defaultdict
7 data1 = defaultdict(list)
8 # print(data1)
9 # for d in data:
10 # data1[d].append("1")
11 # print(data1)
12 content = 'aydsad'
13 for k, v in data1.items():
14 print(k)
15 content += '\n'.join(v)
16 print('\n'.join(v))
17 print(content)
18 if data1:
19 print(True)
20 # dct = {"test1": "wulinjiang1",}
21 # for i in range(3):
22 # dct.update({'content': i})
23 # print(dct)
24 # for d in data:
25 # names.add(d)
26 # for name in names:
27 # print(name)
28 # with open('deployments.yaml') as fp:
29 # content = fp.readlines()
30 # print(content[25].format('http://www.baidu.com'))
31 # content[25] = content[25].format('http://www.baidu.com')
32 # with open('deployments.yaml', 'w') as fp:
33 # for c in content:
34 # fp.writeline | Clean Code: No Issues Detected
|
1 from functools import partial
2
3
4 # 从指定文件按固定大小迭代
5 with open('file', 'rb') as f:
6 re_size = 32
7 records = iter(partial(f.read, re_size), b'')
8 for r in records:
9 print(r) | Clean Code: No Issues Detected
|
1 from collections import defaultdict
2
3
4 if __name__ == "__main__":
5 d = {
6 "1": 1,
7 "2": 2,
8 "5": 5,
9 "4": 4,
10 }
11 print(d.keys())
12 print(d.values())
13 print(zip(d.values(), d.keys()))
14 max_value = max(zip(d.values(), d.keys()))
15 min_value = min(zip(d.values(), d.keys()))
16 print(max_value)
17 print(min_value) | 1 - warning: unused-import
|
1 from operator import itemgetter, attrgetter
2
3
4 class User:
5 def __init__(self, uid, name):
6 self.uid = uid
7 self.name = name
8
9 def get_name(self):
10 return self.name
11
12
13 if __name__ == "__main__":
14 datas = [
15 {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
16 {'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
17 {'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
18 {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
19 ]
20 row1 = sorted(datas, key=itemgetter('fname', 'lname'))
21 print(row1)
22 row2 = sorted(datas, key=lambda x: x['uid'])
23 print(row2)
24 users = [User(1, 'first'), User(3, 'second'), User(2, 'third')]
25 row3 = sorted(users, key=attrgetter('uid', 'name'))
26 min_user = min(users, key=attrgetter('uid'))
27 max_user = max(users, key=lambda u: u.name)
28 print(min_user.uid, min_user.name)
29 print(max_user.uid, max_user.name)
30 print(row3) | 4 - refactor: too-few-public-methods
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-08 12:13
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test20.py
7 # ----------------------------------------------
8 from collections import defaultdict
9
10
11 if __name__ == "__main__":
12 # 找出列表中重复的元素
13 data = [1, 2, 3, 4, 3, 5, 5, 1]
14 dct = defaultdict(list)
15 for d in data:
16 dct[str(d)].append(d)
17 print(dct)
18 for k, v in dct.items():
19 if len(v) > 1:
20 print(k)
21 s = "+++--++--"
22 print("".join(sorted(s))) | Clean Code: No Issues Detected
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-01-13 14:30
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : kafka-consumer.py
7 # ----------------------------------------------
8 from kafka import KafkaConsumer
9 import time
10
11
12 def start_consumer():
13 consumer = KafkaConsumer('my_test_topic1',
14 bootstrap_servers='kafka-0-0.kafka-0-inside-svc.kafka.svc.cluster.local:32010,'
15 'kafka-1-0.kafka-1-inside-svc.kafka.svc.cluster.local:32011,'
16 'kafka-2-0.kafka-2-inside-svc.kafka.svc.cluster.local:32012,'
17 'kafka-3-0.kafka-3-inside-svc.kafka.svc.cluster.local:32013,'
18 'kafka-4-0.kafka-4-inside-svc.kafka.svc.cluster.local:32014,'
19 'kafka-5-0.kafka-5-inside-svc.kafka.svc.cluster.local:32015')
20 for msg in consumer:
21 print(msg)
22 print("topic = %s" % msg.topic) # topic default is string
23 print("partition = %d" % msg.offset)
24 print("value = %s" % msg.value.decode()) # bytes to string
25 print("timestamp = %d" % msg.timestamp)
26 print("time = ", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(msg.timestamp/1000)))
27
28
29 if __name__ == '__main__':
30 start_consumer()
| Clean Code: No Issues Detected
|
1 import arrow
2 import re
3 import pdb
4 import tempfile
5
6
7 if __name__ == "__main__":
8 # print(arrow.now().shift(days=-1).format('YYYY-MM-DD'))
9 # data = ['merge', '1', 'commit', 'merge']
10 # data.remove('1')
11 # print(data)
12 # d = [{'code': 12}, {'code': 11}, {'code': 13}]
13 # d.sort(key=lambda x: x['code'])
14 # print(d)
15 # s = ' --hello -world+ '
16 # print(re.sub("[' ', '-', '+']", '', s))
17 with tempfile.NamedTemporaryFile('w+t') as f:
18 print(f.name)
19 f.write('hello world!')
20 f.seek(0)
21 print(f.read()) | 1 - warning: unused-import
2 - warning: unused-import
3 - warning: unused-import
|
1 # 快速排序 时间复杂度时O(NlogN)
2 # 具体过程如下 采用一种分治递归的算法 从数组中任意选择一个数作为基准值,然后将数组中比基准值小的放在左边
3 # 比基准值大的放在右边,然后对左右两边的数使用递归的方法排序
4
5
6 def partition(data, start, end):
7 i = start - 1
8 for j in range(start, end):
9 # 刚开始以data[end]的值作为基准值
10 if data[j] < data[end]:
11 i += 1
12 # 如果j所在的位置的值小于end,则i往前进一步,并与j的值交换,即将一个新的值加入到小于end的区域
13 data[i], data[j] = data[j], data[i]
14 i += 1
15 data[i], data[end] = data[end], data[i]
16 return i
17
18
19 def quick_sort(data: list, start, end):
20 if start < end:
21 mid = partition(data, start, end)
22 quick_sort(data, start, mid-1)
23 quick_sort(data, mid+1, end)
24 return data
25
26
27 if __name__ == "__main__":
28 t_data = [5, 4, 3, 2, 1]
29 print(quick_sort(t_data, 0, 4)) | Clean Code: No Issues Detected
|
1 import heapq
2
3
4 class PriorityQueue:
5 def __init__(self):
6 self._queue = []
7 self._index = 0
8
9 def push(self, priority, item):
10 heapq.heappush(self._queue, (-priority, self._index, item))
11 self._index += 1
12
13 def pop(self):
14 return heapq.heappop(self._queue)[-1]
15
16
17 class Item:
18 def __init__(self, name):
19 self.name = name
20
21 def __repr__(self):
22 return self.name
23
24
25 if __name__ == "__main__":
26 nums = [1, 5, 2, 4, 3]
27 a = heapq.nlargest(3, nums)
28 print(a)
29 b = heapq.nsmallest(3, nums)
30 print(b)
31 print(type(b))
32 # 对集合进行堆排序放入列表中,返回值为 None
33 c = heapq.heapify(nums)
34 print(c)
35 print(nums)
36 nums2 = [1, 5, 2, 4, 3]
37 # heappop,heappush
38 d = heapq.heappop(nums2)
39 print(d)
40 e = heapq.heappop(nums2)
41 print(e)
42 print(nums2)
43 heapq.heappush(nums2, 1)
44 print(nums2)
45 f = heapq.heappop(nums2)
46 print(f)
47 # deque 保留最后插入的 N 个元素,返回值是可迭代对象
48 from collections import deque
49 q = deque(maxlen=3)
50 q.append(1)
51 q.appendleft(2)
52 print(q)
53 q.appendleft(3)
54 q.appendleft(4)
55 print(q)
56 q.append(5)
57 print(type(q))
58 a, *b, c = q
59 print(a, b, c)
60 # sorted 排序可迭代对象,通过切片,左闭右开,切记!
61 nums3 = [1, 5, 3, 2]
62 print(sorted(nums3)[1:])
63 # re 模块
64 t = 'asdf fjdk; afed, fjek,asdf, foo'
65 import re
66 # 多个分隔符,不保留分隔符分组
67 f1 = re.split(r'[;,\s]\s*', t)
68 # 多个分隔符,保留分隔符分组
69 f2 = re.split(r'(;|,|\s)\s*', t)
70 # 多个分隔符,不保留分隔符分组
71 f3 = re.split(r'(?:;|,|\s)\s*', t)
72 print(f1)
73 print(f2)
74 print(f3)
| 17 - refactor: too-few-public-methods
|
1 from marshmallow import Schema, fields, pprint, post_load, post_dump, ValidationError
2 from datetime import datetime
3
4
5 class VideoLog(object):
6 """
7 vlog基础类
8 """
9 def __init__(self, **data):
10 for k, v in data.items():
11 setattr(self, k, v)
12
13 def __str__(self):
14 return '<VideoLog_str(name={self.name})>'.format(self=self)
15
16 def __repr__(self):
17 return '<VideoLog_repr(name={self.name})>'.format(self=self)
18
19
20 class User(object):
21 """
22 user基础类
23 """
24 def __init__(self, name, age, email, videos=None):
25 self.name = name
26 self.age = age
27 self.email = email
28 self.videos = videos or []
29
30 def __str__(self):
31 return '<User_str(name={self.name})>'.format(self=self)
32
33 def __repr__(self):
34 return '<User_repr(name={self.name})>'.format(self=self)
35
36
37 class VideoLogSchema(Schema):
38 title = fields.Str(required=True)
39 content = fields.Str(required=True)
40 created_time = fields.DateTime()
41
42 @post_load
43 def make_data(self, data):
44 return VideoLog(**data)
45
46
47 class UserSchema(Schema):
48 name = fields.Str()
49 age = fields.Int()
50 email = fields.Email()
51 videos = fields.Nested(VideoLogSchema, many=True)
52
53 @post_load
54 def make_data(self, data):
55 return User(**data)
56
57
58 # 继承前面定义好的schema类
59 class ProVideoSchema(VideoLogSchema):
60 fans = fields.Nested(UserSchema, many=True)
61
62 @post_load
63 def make_data(self, data):
64 return VideoLog(**data)
65
66
67 class TestAttributeSchema(Schema):
68 new_name = fields.Str(attribute='name')
69 age = fields.Int()
70 email_addr = fields.Email(attribute='email')
71 new_videos = fields.Nested(VideoLogSchema, many=True)
72
73 @post_load
74 def make_data(self, data):
75 return User(**data)
76
77
78 # 重构,隐式字段创建
79 class NewUserSchema(Schema):
80 uppername = fields.Function(lambda obj: obj.name.upper())
81
82 class Meta:
83 fields = ("name", "age", "email", "videos", "uppername")
84
85
86 if __name__ == "__main__":
87 # 序列化为字典 example
88 video = VideoLog(title='example', content='test', created_time=datetime.now())
89 video_schema = VideoLogSchema()
90 video_ret = video_schema.dump(video)
91 pprint(video_ret.data)
92
93 # 反序列化为类 example
94 user_dct = {'name': 'wulj', 'age': 24, 'email': 'wuljfly@icloud.com', 'videos': [video_ret.data]}
95 user_schema = UserSchema()
96 user_ret = user_schema.load(user_dct)
97 pprint(user_ret.data)
98
99 # 测试validate error
100 test_video = {'title': 'test_validate'}
101 try:
102 print('test')
103 schema = VideoLogSchema()
104 ret = schema.load(test_video)
105 pprint(ret.data)
106 except ValidationError as err:
107 print('error')
108 pprint(err.valid_data)
109
110 # 测试partial,处理required=True的
111 partial_video = {'title': 'partial', 'created_time': datetime.now()}
112 ret = VideoLogSchema().load(partial_video, partial=('content', ))
113 print(ret)
114 new_ret = VideoLogSchema(partial=('content', )).load(partial_video)
115 new1_ret = VideoLogSchema(partial=True).load(partial_video)
116 new2_ret = VideoLogSchema().load(partial_video, partial=True)
117
118 # 测试attribute,指定属性名称
119 test_user_attribute = User(name='attribute', age=23, email='new@test.com', videos=[])
120 attribute_ret = TestAttributeSchema().dump(test_user_attribute)
121 pprint(attribute_ret.data)
122
123
124
| 5 - refactor: useless-object-inheritance
14 - warning: missing-format-attribute
17 - warning: missing-format-attribute
20 - refactor: useless-object-inheritance
37 - refactor: too-few-public-methods
47 - refactor: too-few-public-methods
59 - refactor: too-few-public-methods
67 - refactor: too-few-public-methods
82 - refactor: too-few-public-methods
79 - refactor: too-few-public-methods
1 - warning: unused-import
|
1 import glob
2 import fnmatch
3 import os.path
4
5
6 if __name__ == "__main__":
7 dir_path = '/root/tmp/test'
8 path = '/root/tmp/test/*.py'
9 pyfiles = glob.glob(path)
10 pyfiles2 = [name for name in os.listdir(dir_path) if fnmatch(name, '*.py')] | 10 - error: not-callable
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-08 11:30
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test19.py
7 # ----------------------------------------------
8 # 单例模式的 N 种实现方法,就是程序在不同位置都可以且仅可以取到同一个实例
9
10
11 # 函数装饰器实现
12 def singleton(cls):
13 _instance = {}
14
15 def inner():
16 if cls not in _instance:
17 # cls 作为 key,value 值为 cls 的实例化
18 _instance[cls] = cls()
19 return _instance[cls]
20 return inner
21
22
23 @singleton
24 class Cls(object):
25 def __init__(self):
26 print("__init__")
27
28
29 # 类装饰器实现
30 class Singleton:
31 def __init__(self, cls):
32 self._cls = cls
33 self._instance = {}
34
35 def __call__(self, *args, **kwargs):
36 if self._cls not in self._instance:
37 self._instance[self._cls] = self._cls()
38 return self._instance[self._cls]
39
40
41 @Singleton
42 class Cls2:
43 def __init__(self):
44 print("__init__2")
45
46
47 # 使用 new 关键字实现单例模式
48 class Singleton1(object):
49 # 类属性,公共属性
50 _instance = None
51
52 def __new__(cls, *args, **kwargs):
53 if cls._instance is None:
54 cls._instance = object.__new__(cls, *args, **kwargs)
55 return cls._instance
56
57 def __init__(self):
58 print("__init__3")
59
60
61 # 使用 metaclass 实现单例模式
62 class Singleton3(type):
63 _instance = {}
64
65 def __call__(cls, *args, **kwargs):
66 if cls not in cls._instance:
67 cls._instance[cls] = super(Singleton3, cls).__call__(*args, **kwargs)
68 return cls._instance[cls]
69
70
71 class Singleton4(metaclass=Singleton3):
72 def __init__(self):
73 print("__init__4")
74
75
76 if __name__ == "__main__":
77 c = Cls()
78 d = Cls()
79 print(id(c) == id(d))
80 e = Cls2()
81 f = Cls2()
82 print(id(e) == id(f))
83 g = Singleton1()
84 h = Singleton1()
85 print(id(g) == id(h))
86 i = Singleton4()
87 j = Singleton4()
88 print(id(i) == id(j)) | 24 - refactor: useless-object-inheritance
24 - refactor: too-few-public-methods
30 - refactor: too-few-public-methods
42 - refactor: too-few-public-methods
48 - refactor: useless-object-inheritance
48 - refactor: too-few-public-methods
71 - refactor: too-few-public-methods
|
1 # 选择排序 时间复杂度时O(N^2)
2 # 具体过程如下 首先在n个元素的数组中找到最小值放在数组的最左端,然后在剩下的n-1个元素中找到最小值放在左边第二个位置
3 # 以此类推,直到所有元素的顺序都已经确定
4
5
6 def select_sort(data: list):
7 # 外部循环只需遍历n-1次
8 for i in range(len(data)-1):
9 for j in range(i+1, len(data)):
10 if data[i] > data[j]:
11 data[i], data[j] = data[j], data[i]
12 return data
13
14
15 if __name__ == "__main__":
16 t_data = [5, 4, 3, 2, 1]
17 print(select_sort(t_data)) | Clean Code: No Issues Detected
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-06 10:58
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test14.py
7 # ----------------------------------------------
8
9
10 class Demo(object):
11 # 类的属性
12 count = 0
13
14 def __init__(self, x, y):
15 self.x = x
16 self.y = y
17 print("__init__ 方法被执行")
18
19 def __new__(cls, *args, **kwargs):
20 print("__new__ 方法被执行")
21 # 调用 cls 类才会执行 __init__ 方法
22 return object.__new__(cls)
23
24 def __str__(self):
25 return "str test"
26
27 def __repr__(self):
28 return "repr test"
29
30 def __del__(self):
31 print("del")
32
33 def __getattribute__(self, item):
34 # 属性访问拦截器
35 if item == "x":
36 return "redirect x"
37 else:
38 return object.__getattribute__(self, item)
39
40 def __call__(self, *args, **kwargs):
41 self.x, self.y = args
42 print("__call__")
43
44
45 def test(a):
46 print(a)
47 print(id(a))
48
49
50 if __name__ == "__main__":
51 # 列举你所知道的 python 的魔法方法及用途
52 # python 有一些内置定义好的方法,这些方法在特定的时期会被自动调用
53 # __init__ 函数,创建实例化对象为其赋值使用,是在 __new__ 之后使用,没有返回值
54 # __new__ 是实例的构造函数,返回一个实例对象,__init__ 负责实例初始化操作,必须有返回值,返回一个实例对象
55 d = Demo(1, 2)
56 print(d)
57 print(d.x)
58 print(d.y)
59 # 获取指定类的所有父类
60 print(Demo.__bases__)
61 d(3, 4)
62 print(d.x)
63 print(d.y)
64 # print(type(d))
65 # # 获取已知对象的类
66 # print(d.__class__)
67 # type 用于查看 python 对象类型
68 print(type(d))
69 # 对于可变数据类型和不可变数据类型有差异,可变数据类型用引用传参,不可变数据类型用传值
70 # 不可变数据类型包括,数字,字符串,元组
71 # 可变数据类型包括,列表,字典,集合
72 a = 1
73 print(a)
74 print(id(a))
75 test(a)
76
77 a = [1, 2]
78 print(a)
79 print(id(a))
80 test(a)
81
82 a = {1, 2}
83 print(a)
84 print(id(a))
85 test(a)
86
87 # 简述 any(),all() 方法
88 # any 数组中的所有元素只要有一个为 True 就返回 True
89 if any([True, False]):
90 print("any")
91 # all 数组中的所有元素只要有一个为 False 就返回 False
92 if all([True, False]):
93 print("all")
94 else:
95 print("not all")
96
97
98
| 10 - refactor: useless-object-inheritance
35 - refactor: no-else-return
45 - warning: redefined-outer-name
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-05 20:00
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test12.py
7 # ----------------------------------------------
8 from abc import abstractmethod, ABCMeta
9
10
11 class Interface(object):
12 __metaclass__ = ABCMeta
13
14 @abstractmethod
15 def test(self):
16 pass
17
18 def new(self):
19 pass
20
21
22 class NewTest(Interface):
23 def __init__(self):
24 print("interface")
25
26 def test(self):
27 print("test")
28
29 def new(self):
30 print("new")
31
32
33 if __name__ == "__main__":
34 print("test")
35 # nt = NewTest()
36 # nt.test()
37 # nt.new() | 11 - refactor: useless-object-inheritance
|
1 from plumbum import local, FG, BG, cli, SshMachine, colors
2 from plumbum.cmd import grep, awk, wc, head, cat, ls, tail, sudo, ifconfig
3
4
5 if __name__ == "__main__":
6 ls = local["ls"]
7 print(ls())
8 # 环境在linux
9 # 管道符 pipe
10 command = ls["-a"] | awk['{if($2="100") print $2}'] | wc["-l"]
11 print(command())
12 # 重定向
13 command = cat['test.file'] | head["-n", 5]
14 print(command())
15 # 后台运行和当前终端运行
16 command = (cat['test.file'] | grep["-v", "test"] | (tail["-n", 5] > "out.file")) & FG
17 print(command())
18 command = (awk['-F', '\t', '{print $1, $2}', 'test.file'] | (head['-n', 5] >> 'out.file')) & BG
19 print(command())
20 # 嵌套命令
21 command = sudo[ifconfig['-a']]
22 command1 = (sudo[ifconfig["-a"]] | grep["-i", "loop"]) & FG
23 print(command())
24 print(command1())
| 1 - warning: unused-import
1 - warning: unused-import
1 - warning: unused-import
|
1 from marshmallow import Schema, fields, post_load, pprint
2 from hashlib import md5
3
4 sort_key = ['name', 'role']
5
6
7 class Actor(object):
8 """
9 创建actor基础类
10 """
11 def __init__(self, name, role, grade):
12 self.name = name
13 self.role = role
14 self.grade = grade
15
16 def __str__(self):
17 return '<Actor_str(name={self.name!r})>'.format(self=self)
18
19 def __repr__(self):
20 return '<Actor_repr(name={self.name!r})>'.format(self=self)
21
22 def __eq__(self, other):
23 bools = []
24 for key in sort_key:
25 bools.append(getattr(self, key) == getattr(other, key))
26 return all(bools)
27
28 @staticmethod
29 def get_hash(self):
30 source = ''.join([getattr(self, key) for key in sort_key])
31 m = md5(source.encode('utf-8'))
32 return m.hexdigest()
33
34
35 class Movie(object):
36 """
37 创建movie基础类
38 """
39 def __init__(self, name, actors):
40 self.name = name
41 self.actors = actors
42
43 # 重构内置的str函数
44 def __str__(self):
45 return '<Movie_str(name={self.name!r})>'.format(self=self)
46
47 # 重构内置的repr函数
48 def __repr__(self):
49 return '<Movie_repr(name={self.name!r})>'.format(self=self)
50
51 # 重构内置的 == 函数
52 def __eq__(self, other):
53 bools = []
54 act1 = {actor.get_hash(): actor for actor in self.actors}
55 act2 = {actor.get_hash(): actor for actor in other.actors}
56 common_key = set(act1) & set(act2)
57 for key in common_key:
58 bools.append(act1.pop(key) == act2.pop(key))
59 unique_count = len(act1.values()) + len(act2.values())
60 bl = (self.name == other.name)
61 return bl and all(bools) and (unique_count == 0)
62
63
64 class ActorScm(Schema):
65 """
66 创建actor schema基础类
67 """
68 name = fields.Str()
69 role = fields.Str()
70 grade = fields.Int()
71
72 @post_load
73 def make_data(self, data):
74 return Actor(**data)
75
76
77 class MovieScm(Schema):
78 """
79 创建movie schema基础类
80 """
81 name = fields.Str()
82 actors = fields.Nested(ActorScm, many=True)
83
84 @post_load
85 def make_data(self, data):
86 return Movie(**data)
87
88
89 if __name__ == "__main__":
90 # 将字典反序列化为movie基础类
91 actor1 = {'name': 'lucy', 'role': 'hero', 'grade': 9}
92 actor2 = {'name': 'mike', 'role': 'boy', 'grade': 10}
93 movie = {'name': 'green', 'actors': [actor1, actor2]}
94 schema = MovieScm()
95 ret = schema.load(movie)
96 # print 输出类时,调用的是__str__函数
97 print(ret)
98 # pprint 输出类时,调用的是__repr__函数
99 pprint(ret.data)
100
101 # 将movie基础类序列化为字典
102 schema = MovieScm()
103 ret_dct = schema.dump(ret.data)
104 pprint(ret_dct.data)
105
106
| 7 - refactor: useless-object-inheritance
29 - warning: bad-staticmethod-argument
35 - refactor: useless-object-inheritance
64 - refactor: too-few-public-methods
77 - refactor: too-few-public-methods
|
1 from itertools import dropwhile, islice
2 from itertools import permutations, combinations
3 from itertools import combinations_with_replacement
4
5
6 def parser(filename):
7 with open(filename, 'rt') as f:
8 for lineno, line in enumerate(f, 1):
9 print(lineno, line)
10 fields = line.split()
11 try:
12 count = float(fields[0])
13 except ValueError as e:
14 print('Lineno {} parser {}'.format(lineno, e))
15
16
17 if __name__ == "__main__":
18 l1 = [1, 2, 3, 4]
19 l2 = [2, 3, 4, 5]
20 a = [(x, y) for x, y in zip(l1, l2)]
21 print(a)
22 for index, (x, y) in enumerate(a):
23 print(index, x, y)
24 line_text = 'test new world'
25 print(line_text.split())
26 items = [1, 2, 3, 4]
27 for i in enumerate(items):
28 print(i)
29 # 指定行号
30 for i in enumerate(items, 2):
31 print(i)
32 # 允许同一个元素被选取,在一个元祖中
33 cp = [i for i in combinations_with_replacement(items, 2)]
34 p_test = [i for i in permutations(items, 2)]
35 c_test = [i for i in combinations(items, 2)]
36 print(p_test)
37 print(c_test)
38 print(cp)
39 with open('../data-struct-algorithm/tmp/test') as f:
40 r = f.readlines()
41 print(r)
42 st = ['#new', '#test', 'test']
43 s = islice(st, 1, None)
44 for s1 in s:
45 print(s1)
46 print(s)
47 ret = list(filter(lambda x: x.startswith('#'), r))
48 print(ret)
49 for line in dropwhile(lambda x: x.startswith("#"), f):
50 print(line, end=" ") | 7 - warning: redefined-outer-name
8 - warning: redefined-outer-name
7 - warning: unspecified-encoding
12 - warning: unused-variable
20 - refactor: unnecessary-comprehension
33 - refactor: unnecessary-comprehension
34 - refactor: unnecessary-comprehension
35 - refactor: unnecessary-comprehension
39 - warning: unspecified-encoding
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-05 20:43
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test13.py
7 # ----------------------------------------------
8 import test10
9
10
11 if __name__ == "__main__":
12 # python3 高级特性,反射
13 # 字符串返回映射到代码的一种机制,python3 提供了四个内置函数 getattr setattr hasattr delattr
14 obj = getattr(test10, "acquire_lock")
15 if hasattr(test10, "acquire_lock"):
16 print("test")
17 else:
18 print("new")
19
20 # metaclass 作用以及应用场景
21 # 元类是一个创建类的类
| Clean Code: No Issues Detected
|
1 records = [('foo', 1, 2),
2 ('bar', 'hello'),
3 ('foo', 3, 4),
4 ]
5
6
7 def drop_first_last(grades):
8 _, *middle, _ = grades
9 return middle
10
11
12 def do_foo(x, y):
13 print('foo', x, y)
14
15
16 def do_bar(s):
17 print('bar', s)
18
19
20 if __name__ == "__main__":
21 for tag, *args in records:
22 print(args)
23 print(*args)
24 if tag == 'foo':
25 do_foo(*args)
26 elif tag == 'bar':
27 do_bar(*args)
28 print("done") | 27 - error: too-many-function-args
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-04 10:32
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test08.py
7 # ----------------------------------------------
8 import redis
9
10
11 if __name__ == "__main__":
12 # redis 现有的数据类型
13 # 1. String 二进制安全,可以包含任何数据,一个 key 对应一个 value
14 # SET key value,GET key,DEL key
15 # 2. Hash 数据类型,键值对集合,适合存储对象的属性
16 # HMSET key field1 value1 field2 value2,HGET key field1
17 # 3. List 数据类型,双向链表,消息队列
18 # lpush key value,lrange key 0 10
19 # 4. Set 数据类型,hash 表实现,元素不重复
20 # sadd key value,smembers key
21 # 5. zset 数据类型,有序集合
22 # zadd key score member,排行榜,带权重的消息队列
23
24 # python 连接 redis
25 # 普通的连接方式
26 redis_conn = redis.Redis(host="127.0.0.1", port=6379, username="test", password="test", db=0)
27 # 连接池的方式
28 redis_pool = redis.ConnectionPool(host="127.0.0.1", port=6379, username="test", password="test", db=0)
29 redis_conn1 = redis.Redis(connection_pool=redis_pool)
30
31 # String 字符串
32 # set 操作,ex 过期时间(秒),px 过期时间(毫秒),nx (name 不存在时,当前操作才执行),xx (name 存在时,当前操作才执行)
33 redis_conn.set(name="test", value="test", ex="300", px=None, nx=True, xx=False)
34 # get 操作
35 v = redis_conn.get("test")
36 print(v)
37 # mset 设置多个值
38 redis_conn.mset({"1": 1, "2": 2})
39 # mget 获取多个值
40 m = redis_conn.mget(["1", "2"])
41 # getset 给已有的键设置新值
42 v = redis_conn.getset("1", 2)
43 # setrange 根据索引修改某个键的value值,返回的是值的长度
44 lg = redis_conn.setrange("1", 0, "232")
45 # getrange 根据索引获取键的部分value值,当所给键不存在时,返回 b''
46 v1 = redis_conn.getrange("key", 1, 2)
47 # strlen 获取value长度,如果没有key 返回 0
48 lg1 = redis_conn.strlen("key")
49 # incr/decr,int 类型的值或者字符串的数值,默认为1
50 v2 = redis_conn.incr("key", amount=1)
51 v3 = redis_conn.decr("key", amount=1)
52 # incrbyfloat,浮点数自增
53 v4 = redis_conn.incrbyfloat("key", amount=1.0)
54 # append,追加字符串,如果不存在 key 就设置新值,返回value的长度
55 lg2 = redis_conn.append("key", "666")
56
57 # List,在redis中,1个key对应一个列表
58 # lpush/rpush,返回列表的大小,当键不存在时,创建新的列表
59 lg3 = redis_conn.lpush("key", 1, 2, "test")
60 # lpushx/rpushx,当键不存在时,不添加也不创建新的列表
61 lg4 = redis_conn.lpushx("key", "value")
62 # llen,获取所给key列表的大小
63 lg5 = redis_conn.llen("key")
64 # linsert,在指定位置插入新值,ref_key 不存在就返回 0 ,否则就返回插入后list的长度
65 lg6 = redis_conn.linsert("key", "AFTER", "ref_key", "value")
66 # lset 通过索引赋值,返回 boolean 值
67 bl = redis_conn.lset("key", 0, "value")
68 # lindex 通过索引获取列表中的值
69 v6 = redis_conn.lindex("key", 0)
70 # lrange,获取列表中的一段数据
71 v7 = redis_conn.lrange("key", 0, 5)
72 # lpop/rpop 删除左边或者右边第一个值,返回被删除元素的值
73 v8 = redis_conn.lpop("key")
74 # lrem 删除列表中N个相同的值,返回被删除元素的个数
75 v9 = redis_conn.lrem("key", "value", -2)
76 # ltrim 删除列表范围外的所有元素
77 v10 = redis_conn.ltrim("key", 5, 6)
78 # blpop 删除并返回列表最左边的值,返回一个元组 (key, value)
79 v11 = redis_conn.blpop("key")
80 # rpoplpush 一个列表最右边的元素取出后添加到列表的最左边,返回取出的元素值
81 v12 = redis_conn.rpoplpush("key1", "key2")
82
83 # Hash,value 值一个 map
84 # hset,返回添加成功的个数
85 v13 = redis_conn.hset("key", "key1", "value")
86 # hmset 添加多个键值对
87 v14 = redis_conn.hmset("key", {"1": 1, "2": 2})
88 # hmget 获取多个键值对
89 v15 = redis_conn.hmget("key", ["1", "2"])
90 # hget
91 v16 = redis_conn.hget("key", "1")
92 # hgetall,获取所有的键值对
93 v17 = redis_conn.hgetall("name")
94 # hlen 获取键值对的个数
95 v18 = redis_conn.hlen("name")
96 # hkeys 获取所有的键
97 v19 = redis_conn.hkeys("name")
98 # hvals 获取所有的value
99 v20 = redis_conn.hvals("name")
100 # hexists 检查 hash 中是否存在某个 key
101 v21 = redis_conn.hexists("name", "key")
102 # hdel 删除 hash 中的键值对
103 v22 = redis_conn.hdel("name", "key1", "key2")
104 # hincrby 自增 hash 中的 value 值
105 v23 = redis_conn.hincrby("name", "key", -1)
106 # hincrbyfloat
107 v24 = redis_conn.hincrbyfloat("name", "key", 1.0)
108 # expire 设置某个键的过期时间
109 v25 = redis_conn.expire("name", "key")
110
111 # Set
112 # sadd 插入元素到集合中
113 s = redis_conn.sadd("name", "1", 3, 4)
114 # scard 返回集合中元素的个数
115 s1 = redis_conn.scard("name")
116 # smembers 获取集合中所有的元素
117 s2 = redis_conn.smembers("name")
118 # srandmember 随机获取一个或者N个元素
119 s3 = redis_conn.srandmember("name", number=2)
120 # sismember 判断一个值是否在集合中
121 s4 = redis_conn.sismember("name", "value")
122 # spop 随机删除集合中的元素
123 s5 = redis_conn.spop("name")
124 # srem 删除集合中的一个或者多个元素,返回删除元素的个数
125 s6 = redis_conn.srem("name", "a", "b")
126 # smove 将集合中的一个元素移动到另一个集合中去
127 s7 = redis_conn.smove("name1", "name2", "a")
128 # sdiff 两个集合求差集
129 s8 = redis_conn.sdiff("name1", "name2")
130 # sinter 两个集合求交集
131 s9 = redis_conn.sinter("name1", "name2")
132 # sunion 并集
133 s10 = redis_conn.sunion("name1", "name2")
134
135 # Zset
136
137 # redis 的事务
138 # MULTI 开始事务,命令入队,EXEC 执行事务,DISCARD 放弃事务。
139 # 与 mysql 事务的概念有所区别,不是原子性的,如果事务中途有命令失败,不会回滚,并继续往下执行。
140 # redis 对于单个命令的执行是原子性的
141
142 # 分布式锁是什么
143 # 分布式锁主要用于分布式集群服务互斥共享累或者方法中的变量,对于单机应用而言,可以采用并行处理互斥
144 # 分布式锁具备那些条件
145 # 1. 在分布式系统环境下,一个方法在同一时间只能被一个机器的一个线程执行
146 # 2. 高可用的获取锁与释放锁
147 # 3. 高性能的获取锁与释放锁
148 # 4. 具备可重入特性
149 # 5. 具备锁失效机制,防止死锁
150 # 6. 具备非阻塞锁特性,即没有获取到锁将直接返回获取锁失败 | Clean Code: No Issues Detected
|
1 # 使用lambda对list排序,正数在前,从小到大,负数在后,从大到小
2 # lambda设置2个条件,先将小于0的排在后面,再对每一部分绝对值排序
3 data = [-5, 8, 0, 4, 9, -4, -20, -2, 8, 2, -4]
4 a = sorted(data, key=lambda x: (x < 0, abs(x)))
5 print(a) | Clean Code: No Issues Detected
|
1 # 冒泡排序 该算法的事件复杂度未O(N^2)
2 # 具体过程如下 首先遍历数组中的n个元素,对数组中的相邻元素进行比较,如果左边的元素大于右边的元素,则交换两个元素所在的
3 # 位置,至此,数组的最右端的元素变成最大的元素,接着对剩下的n-1个元素执行相同的操作。
4
5
6 def bubble_sort(data: list):
7 # 外面的循环控制内部循环排序的次数,例如5个数,只需要4次排序就行了
8 for i in range(len(data)-1):
9 change = False
10 # 内部循环比较相邻元素,找到剩下元素的最大值放在数组的右边
11 for j in range(len(data)-i-1):
12 if data[j] > data[j+1]:
13 data[j], data[j+1] = data[j+1], data[j]
14 change = True
15 # 当change=False时,说明没有交换的情况发生,说明该数组已经排序完成
16 # 减少了循环的次数
17 if not change:
18 break
19 return data
20
21
22 if __name__ == "__main__":
23 t_data = [5, 4, 3, 2, 1]
24 print(bubble_sort(t_data)) | Clean Code: No Issues Detected
|
1 from selenium import webdriver
2 from selenium.webdriver.common.by import By
3
4
5 if __name__ == "__main__":
6 # 加载浏览器
7 browser = webdriver.Chrome()
8 # 获取页面
9 browser.get('https://www.baidu.com')
10 print(browser.page_source)
11 # 查找单个元素
12 input_first = browser.find_element_by_id('q')
13 input_second = browser.find_element_by_css_selector('#q')
14 input_third = browser.find_element(By.ID, 'q')
15 # 查找多个元素
16 input_elements = browser.find_elements(By.ID, 'q')
17 # 元素交互操作,搜索框查询
| Clean Code: No Issues Detected
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-01 10:39
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test02.py
7 # ----------------------------------------------
8 if __name__ == "__main__":
9 # gbk 和 utf-8 格式之间的转换
10 # gbk 编码,针对于中文字符
11 t1 = "中国加油"
12 t1_gbk = t1.encode("gbk")
13 print(t1.encode("gbk"))
14 # utf-8 字符
15 t2_utf = t1_gbk.decode("gbk").encode("utf-8")
16 print(t2_utf)
17 print(t1.encode("utf-8"))
18 # 正则切分字符串
19 s1 = "info : xiaoZhang 33 shandong"
20 import re
21 # 非捕获分组
22 c1 = re.compile(r'\s*[:\s]\s*')
23 l1 = re.split(c1, s1)
24 print(l1)
25 # 捕获分组
26 c2 = re.compile(r'(\s*:\s*|\s)')
27 l2 = re.split(c2, s1)
28 print(l2)
29 # 如果仍需使用圆括号输出非捕获分组的话
30 c3 = re.compile(r'(?:\s*:\s*|\s)')
31 l3 = re.split(c3, s1)
32 print(l3)
33 # 去除多余空格
34 a = "你好 中国 "
35 a = a.rstrip()
36 print(a)
37 # 字符串转换成小写
38 b = "sdsHOJOK"
39 print(b.lower())
40 # 单引号 双引号 三引号的区别
41 # 单引号 和 双引号 输出结果一样,都显示转义后的字符
42 a = '-\t-\\-\'-%-/-\n'
43 b = "-\t-\\-\'-%-/-\n"
44 print(a)
45 print(b)
46 c = r"-\t-\\-\'-%-/-\n"
47 print(c) | Clean Code: No Issues Detected
|
1 # import smtplib
2 # from email.mime.text import MIMEText
3 # from email.header import Header
4 #
5 # # 第三方 SMTP 服务
6 # mail_host = "smtp.qq.com" # 设置服务器
7 # mail_user = "" # 用户名
8 # mail_pass = "XXXXXX" # 口令
9 #
10 # sender = 'from@runoob.com'
11 # receivers = ['429240967@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
12 #
13 # message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
14 # message['From'] = Header("菜鸟教程", 'utf-8')
15 # message['To'] = Header("测试", 'utf-8')
16 #
17 # subject = 'Python SMTP 邮件测试'
18 # message['Subject'] = Header(subject, 'utf-8')
19 #
20 # try:
21 # smtpObj = smtplib.SMTP()
22 # smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号
23 # smtpObj.login(mail_user, mail_pass)
24 # smtpObj.sendmail(sender, receivers, message.as_string())
25 # print("邮件发送成功")
26 # except smtplib.SMTPException:
27 # print("Error: 无法发送邮件")
28
29 import arrow
30 import json
31 import os
32 from pathlib import Path
33
34
35 if __name__ == "__main__":
36 print(1)
37 print(Path(__file__).resolve().parent)
38 # with open('test.json', 'r') as config:
39 # print(config)
40 # print(type(json.load(config)))
41 # print(arrow.now())
42 # data = [1,2,3,4,5,6]
43 # print(data[3:]) | 29 - warning: unused-import
30 - warning: unused-import
31 - warning: unused-import
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-04 23:48
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test11.py
7 # ----------------------------------------------
8
9
10 class Demo:
11 def __init__(self, x, y, z):
12 self.x = x
13 self.y = y
14 self.z = z
15
16 def __call__(self, *args, **kwargs):
17 """ 改变实例的状态 """
18 self.x, self.y = args
19
20
21 class Counter:
22 def __init__(self, func):
23 self.func = func
24 self.count = 0
25
26 def __call__(self, *args, **kwargs):
27 self.count += 1
28 return self.func(*args, **kwargs)
29
30
31 @Counter
32 def foo(name):
33 print(name)
34
35
36 class Test:
37 # 静态属性
38 x = 1
39 y = 2
40
41 def __init__(self, x=7, y=8):
42 # 成员属性
43 self.x = x
44 self.y = y
45
46 def normal_func(self):
47 print("normal", self.x, self.y)
48
49 @staticmethod
50 def static_func():
51 print("static", Test().x, Test().y)
52 print(Test(3, 4).normal_func())
53
54 @classmethod
55 def class_func(cls):
56 print("class", Test.x, Test.y)
57 print(cls(5, 6).normal_func())
58
59
60 if __name__ == "__main__":
61 data = "sastfftsasdsh"
62 print(5/2)
63 q = [True if x % 3 == 0 else -x for x in range(1, 101)]
64 d = [True if data[i] == data[len(data)-i-1] else False for i in range(int(len(data)/2))]
65 print(d)
66
67 # 装饰器有什么作用
68 # 用于给给现有函数增加额外功能,接收一个函数作为参数
69 # 定义的装饰器函数可以带参数,函数本身也可以带参数
70
71 # python 垃圾回收机制
72 # 1. 引用计数器回收,引用计数器为0时,就会被解释器的 gc 回收
73 # 2. 分代垃圾回收机制,对于对象的相互引用和循环引用,第一种回收方式时无法实现的,具体分为第一代,第二代,第三代
74 # 第一代主要用于去除同一代中的相互索引和循环索引,存活的对象放入第二代,以此类推。
75
76 # __call__ 使用
77 # 可调用对象,对于类,函数,但凡是可以把()应用到一个对象上的情况都是可调用对象
78 # 如果一个类中实现了 __call__ 函数,就可以将一个实例对象变成一个可调用对象
79 demo = Demo(1, 2, 3)
80 print(demo.x, demo.y)
81 # 将实例对象当成函数调用,直接调用类中定义的 __call__ 函数,用于改变对象状态最直接优雅的方法
82 demo(5, 6)
83 print(demo.x, demo.y)
84
85 for i in range(10):
86 foo(i)
87 print(foo.count)
88
89 # 判断一个对象是函数还是方法
90 # 与类和实例无绑定关系的function都是函数
91 # 与类和实例有绑定关系的function都是方法
92
93 # @staticmethod 和 @classmethod
94 # @staticmethod 静态方法,与类和实例无关
95 # @classmethod 类方法
96
97 Test.static_func()
98 Test.class_func()
99 Test.x = 10
100 t = Test(1, 2)
101 print(t.x)
102 print(Test.x)
| 10 - refactor: too-few-public-methods
21 - refactor: too-few-public-methods
64 - refactor: simplifiable-if-expression
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2019-11-07 18:50
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test-sanic.py
7 # ----------------------------------------------
8 from sanic import Sanic
9 from sanic.response import json
10 from pprint import pprint
11
12
13 app = Sanic()
14
15
16 @app.route('/', methods=['POST'])
17 async def bili_flv(request):
18 pprint(request.raw_args)
19 return json(True)
20
21
22 if __name__ == "__main__":
23 app.run(host='0.0.0.0', port=8821, debug=True)
| Clean Code: No Issues Detected
|
1 import collections
2 import bisect
3
4
5 class ItemSequence(collections.Sequence):
6 def __init__(self, initial=None):
7 self._items = sorted(initial) if initial is not None else []
8
9 def __getitem__(self, item):
10 return self._items[item]
11
12 def __len__(self):
13 return len(self._items)
14
15 # bisect 插入item到有序队列里,并按照顺序排列
16 def add(self, item):
17 bisect.insort(self._items, item)
18
19
20 if __name__ == "__main__":
21 test = ItemSequence([1, 2, 3]) | 5 - error: no-member
|
1 from struct import Struct
2
3
4 def record_data(records, format, file):
5 record_struct = Struct(format)
6 for r in records:
7 file.write(record_struct.pack(*r))
8
9
10 def read_data(format, f):
11 """
12 增量块的形式迭代
13 :param format:
14 :param f:
15 :return:
16 """
17 read_struct = Struct(format)
18 chunks = iter(lambda: f.read(read_struct.size), b'')
19 return (read_struct.unpack(chunk) for chunk in chunks)
20
21
22 def unpack_data(format, f):
23 """
24 全量迭代
25 :param format:
26 :param f:
27 :return:
28 """
29 unpack_data = Struct(format)
30 return (unpack_data.unpack_from(f, offset) for offset in range(0, len(f), unpack_data.size))
31
32
33 if __name__ == "__main__":
34 records = [
35 (1, 2, 3),
36 (2, 3, 4),
37 (3, 4, 5),
38 ]
39 with open('test.file', 'wb') as f:
40 record_data(records, '<idd', f) | 4 - warning: redefined-outer-name
4 - warning: redefined-builtin
10 - warning: redefined-builtin
10 - warning: redefined-outer-name
22 - warning: redefined-builtin
22 - warning: redefined-outer-name
29 - warning: redefined-outer-name
|
1 from collections import Iterable
2 import random
3 import heapq
4
5
6 # 处理嵌套列表
7 def flatten(items, ignore_types=(str, bytes)):
8 for item in items:
9 if isinstance(item, Iterable) and not isinstance(item, ignore_types):
10 yield from flatten(item)
11 else:
12 yield item
13
14
15 if __name__ == "__main__":
16 l1 = [1, 2, 3, 4, 5, 10, 9]
17 l2 = [2, 3, 4, 5, 8, 6, 11]
18 for i in heapq.merge(l1, l2):
19 print(i)
20 print("end")
21 items = [1, 2, 3, [2, 3, 4], [5, 6, 7]]
22 for i in flatten(items):
23 print(i)
24 # 改变输出的分割符和行尾符
25 print(1, 2, sep=' ', end='#\n')
26 # str.join()只能连接字符串,非字符串的需要用sep方式隔开
27 d = ["wulj", 1, 2]
28 print(*d, sep=',')
29 data = {'name1': ['vau1', 'vau2'], 'name2': ['vau1', 'vau2'], 'name3': ['vau1', 'vau2']}
30 print(list(data.items()))
31 k, v = random.choice(list(data.items()))
32 data = {
33 k: random.choice(v)
34 }
35 random.choice()
36 print(data) | 1 - warning: deprecated-class
1 - error: no-name-in-module
7 - warning: redefined-outer-name
35 - error: no-value-for-parameter
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-08 11:05
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test18.py
7 # ----------------------------------------------
8
9
10 def search_2(data, l):
11 """ 二分查找法 """
12 length = len(l)
13 # 递归一定要写出退出条件
14 if length <= 1:
15 if length <= 0:
16 return False
17 elif data == l[0]:
18 return 0, l[0]
19 else:
20 return False
21 mid_index = int(length/2)
22 mid = l[mid_index]
23 if data > mid:
24 f_index = mid_index + 1
25 return search_2(data, l[f_index:])
26 elif data < mid:
27 return search_2(data, l[:mid_index])
28 else:
29 return mid_index, mid
30
31
32 if __name__ == "__main__":
33 data = 0
34 l = [i for i in range(10)]
35 if search_2(data, l):
36 index, value = search_2(data, l)
37 print(index, value)
38 else:
39 print(False)
| 10 - warning: redefined-outer-name
10 - warning: redefined-outer-name
15 - refactor: no-else-return
23 - refactor: no-else-return
34 - refactor: unnecessary-comprehension
|
1 import array
2
3
4 if __name__ == "__main__":
5 # xt模式测试写入文件不能直接覆盖,只能写入到不存在的文件里面
6 with open('test.file', 'xt') as f:
7 f.write('test not exist')
8 print("end", end='#') | 6 - warning: unspecified-encoding
1 - warning: unused-import
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-01 13:05
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test06.py
7 # ----------------------------------------------
8 import json
9 from datetime import datetime
10 from json import JSONEncoder
11 from functools import wraps
12
13
14 class Man:
15 def __init__(self, name, age):
16 self.name = name
17 self.age = age
18
19
20 class ComplexEncoder(JSONEncoder):
21 def default(self, o):
22 if isinstance(o, datetime):
23 return o.strftime("%Y-%m-%d %H:%M:%S")
24 else:
25 return super(ComplexEncoder, self).default(o)
26
27
28 def bb(n: int):
29 def multi(args):
30 return n*args
31 return multi
32
33
34 # 函数定义成装饰器的时候,建议加上 wraps,他能保留装饰器定义函数的原有名称和docstring
35 def dt(func):
36 @wraps(func)
37 def new(*args, **kwargs):
38 res = func(args)
39 return res
40 return new
41
42
43 if __name__ == "__main__":
44 # 交换两个变量的值,可以直接赋值
45 a, b = 1, 2
46 print(a, b)
47 print(id(a), id(b))
48 a, b = b, a
49 print(a, b)
50 print(id(a), id(b))
51 # read,readline,readlines
52 # read 是直接读取整个文件内容
53 # readline 是读取文件的一行内容,从最开始读起
54 # readlines 是读取文件所有内容,按行分隔成 list,会把换行符也带上
55 with open('test.txt', 'r') as f:
56 # r1 = f.read()
57 # print("r1 "+r1)
58 # r2 = f.readline()
59 # print("r2 "+r2)
60 r3 = f.readlines()
61 print(r3)
62 # json 序列化支持的数据类型有哪些
63 # 基本上 python3 的基本数据类型都支持
64 d1 = {"d1": 1}
65 d2 = {"d2": "2"}
66 d3 = {"d3": dict()}
67 d4 = {"d4": list()}
68 d5 = {"d5": tuple()}
69 d6 = {"d6": True}
70 print(json.dumps(d1))
71 # json 序列化对象支持 datetime 对象,定义一个函数或者类,把 datetime 对象转换成字符串即可
72 # 一般自己定义的类是有 self.__dict__ 方法的
73 m = Man("test", 24)
74 d7 = {"d7": m}
75 print(json.dumps(d7, default=lambda obj: obj.__dict__))
76 d8 = {"d8": datetime.now()}
77 print(json.dumps(d8, cls=ComplexEncoder))
78 # json 序列化的时候,遇到中文会默认转换成 unicode,要求让他保留中文格式
79 d9 = {"hello": "你好"}
80 print(json.dumps(d9))
81 print(json.dumps(d9, ensure_ascii=False))
82 # 合并文件信息,按顺序排列
83 with open('test1.txt', 'r') as f1:
84 t1 = f1.read()
85 with open('test2.txt', 'r') as f2:
86 t2 = f2.read()
87 print("t1 ", t1)
88 print("t2 ", t2)
89 # 字符串属于可迭代对象,sorted 过后返回一个 list
90 t = sorted(t1 + t2)
91 print("t ", "".join(t))
92 # 当前日期计算函数
93 dt1 = "20190530"
94 import datetime
95 dt1 = datetime.datetime.strptime(dt1, "%Y%m%d")
96 print(dt1)
97 dt2 = dt1 + datetime.timedelta(days=5)
98 print(dt2.strftime("%Y%m%d"))
99 import arrow
100 dt1 = "2019-05-30"
101 dt1 = arrow.get(dt1)
102 print(dt1)
103 dt2 = dt1.shift(days=+5)
104 print(dt2.isoformat())
105 # 1 行代码实现 1-100 之间的偶数
106 # range 方法是左闭右开
107 t = [i for i in range(1, 100) if i % 2 == 0]
108 print(t)
109 # with 语句的作用,用作上下文管理器,一般用于文件读写,方式没有及时关闭文件
110 # 如果一个对象有 self.__enter__(self) 和 self.__exit__(self) 方法的话,可以用 with 做上下文管理器
111 # python 计算一个文件中大写字母的个数
112 with open('test1.txt', 'r') as f:
113 t = f.read()
114 print(t)
115 l = [i for i in t if "A" <= i <= "Z"]
116 print(l)
117 print(len(l)) | 14 - refactor: too-few-public-methods
22 - refactor: no-else-return
25 - refactor: super-with-arguments
37 - warning: unused-argument
55 - warning: unspecified-encoding
66 - refactor: use-dict-literal
67 - refactor: use-list-literal
83 - warning: unspecified-encoding
85 - warning: unspecified-encoding
94 - warning: reimported
112 - warning: unspecified-encoding
|
1 # ----------------------------------------------
2 # -*- coding: utf-8 -*-
3 # @Time : 2020-03-03 20:58
4 # @Author : 吴林江
5 # @Email : wulinjiang1@kingsoft.com
6 # @File : test07.py
7 # ----------------------------------------------
8 from pymongo import MongoClient
9
10
11 class PyMongoDemo:
12 def __init__(self):
13 self.client = MongoClient("mongodb://{username}:{password}@{host}:{port}"
14 .format(username="test", password="test", host="test", port=27137))
15 self.db = self.client.my_db # 数据库
16 self.tb = self.db.tb # 表名
17
18 def insert_data(self):
19 users = [{"name": "test", "age": 10}, {"name": "nb", "age": 18}]
20 self.tb.insert(users)
21
22 def get_data(self):
23 self.insertData()
24 for data in self.tb.find():
25 print(data)
26
27
28 if __name__ == "__main__":
29 m = PyMongoDemo()
30 m.get_data()
31 col = MongoClient("the_client").get_database("the_db").get_collection("the_col")
32 col.create_index([("field", 1)], unique=False) | 23 - error: no-member
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.