code
stringlengths
20
13.2k
label
stringlengths
21
6.26k
1 # -*- coding: utf-8 -*- 2 3 import os.path 4 5 import scrapy 6 from scrapy.linkextractors import LinkExtractor 7 import vmprof 8 9 10 class Spider(scrapy.Spider): 11 name = 'spider' 12 13 def __init__(self): 14 with open(os.path.join( 15 os.path.dirname(__file__), '..', 'top-1k.txt')) as f: 16 self.start_urls = ['http://{}'.format(line.strip()) for line in f] 17 18 self.le = LinkExtractor() 19 self.images_le = LinkExtractor( 20 tags=['img'], attrs=['src'], deny_extensions=[]) 21 self.files_le = LinkExtractor( 22 tags=['a'], attrs=['href'], deny_extensions=[]) 23 24 # Set up profiling 25 self.profile_filename = _get_prof_filename('vmprof') 26 self.profile = open(self.profile_filename, 'wb') 27 vmprof.enable(self.profile.fileno()) 28 29 super(Spider, self).__init__() 30 31 def parse(self, response): 32 get_urls = lambda le: {link.url for link in le.extract_links(response)} 33 page_urls = get_urls(self.le) 34 for url in page_urls: 35 yield scrapy.Request(url) 36 file_urls = ( 37 get_urls(self.images_le) | get_urls(self.files_le) - page_urls) 38 yield { 39 'url': response.url, 40 'file_urls': file_urls, 41 } 42 43 def closed(self, _): 44 vmprof.disable() 45 self.profile.close() 46 self.logger.info('vmprof saved to {}'.format(self.profile_filename)) 47 48 49 def _get_prof_filename(prefix): 50 i = 1 51 while True: 52 filename = '{}_{}.vmprof'.format(prefix, i) 53 if not os.path.exists(filename): 54 return filename 55 i += 1
14 - warning: unspecified-encoding 29 - refactor: super-with-arguments 26 - refactor: consider-using-with
1 # -*- coding: utf-8 -*- 2 3 BOT_NAME = 's3bench' 4 5 SPIDER_MODULES = ['s3bench.spiders'] 6 NEWSPIDER_MODULE = 's3bench.spiders' 7 8 USER_AGENT = ( 9 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) ' 10 'AppleWebKit/537.36 (KHTML, like Gecko) ' 11 'Chrome/51.0.2704.84 Safari/537.36') 12 13 ROBOTSTXT_OBEY = False 14 15 CONCURRENT_REQUESTS = 32 16 CONCURRENT_REQUESTS_PER_DOMAIN = 4 17 18 DOWNLOAD_MAXSIZE = 1*1024*1024 19 20 ITEM_PIPELINES = {'scrapy.pipelines.files.FilesPipeline': 1} 21 22 COOKIES_ENABLED = False 23 24 TELNETCONSOLE_ENABLED = False 25 26 CLOSESPIDER_TIMEOUT = 30 27 DOWNLOAD_TIMEOUT = 15 28 29 LOG_LEVEL = 'INFO'
Clean Code: No Issues Detected
1 #!/usr/bin/python -tt 2 from elementtree import ElementTree 3 from subprocess import Popen, PIPE 4 from urllib2 import urlopen, URLError, HTTPError 5 from socket import gethostname 6 from email import MIMEMultipart, MIMEText 7 import smtplib 8 import yaml 9 import re 10 11 class Omreport: 12 """ 13 Use omreport to determine if system firmware is up-to-date 14 15 """ 16 17 def __init__(self): 18 """ 19 Grab XML output from omreport and store it 20 21 """ 22 23 self.storage_tree = self._system_xml('storage controller') 24 self.system_tree = self._system_xml('system summary') 25 self.model = self._system_model() 26 self.hostname = gethostname() 27 28 def _system_xml(self, report): 29 """ 30 31 Call omreport and storage output as an element tree 32 @param: Report is a string, command line options for omreport 33 34 """ 35 36 try: 37 output = Popen('/opt/dell/srvadmin/bin/omreport %s -fmt xml' % (report), stdout=PIPE, shell=True).communicate()[0] 38 except OSError, e: 39 print "Execution failure: %s" % (e) 40 return 41 try: 42 root = ElementTree.fromstring(output) 43 tree = ElementTree.ElementTree(root) 44 except Exception, e: 45 print "Exception: %s" % (e) 46 return 47 return tree 48 49 def _system_model(self): 50 """ 51 52 Use facter to determine productname, i.e., r710, 2950 ,etc 53 54 """ 55 56 try: 57 output = Popen("facter | awk '/productname/ {print $NF}'", stdout=PIPE, shell=True).communicate()[0] 58 except OSError, e: 59 print "Execution failure: %s" % (e) 60 return 61 return output.strip() 62 63 def notify(om, yaml_data, mail_config): 64 65 tmpl = '-%s out of date, system version: %s -- latest version: %s <br>' 66 msg = "<strong>%s</strong>: <br>" % (om.hostname) 67 68 if 'bios' in om.errors: 69 msg += (tmpl) % ('BIOS', om.bios_ver, yaml_data['bios']) 70 71 if 'perc' in om.errors: 72 for (key, val) in om.outofdate.items(): 73 msg += (tmpl) % (key, val, yaml_data['percs'][key]) 74 75 message = MIMEMultipart.MIMEMultipart('alternative') 76 message['from'] = mail_config['from'] 77 message['to'] = mail_config['to'] 78 message['subject'] = mail_config['subject'] 79 body = MIMEText.MIMEText(msg, 'html') 80 message.attach(body) 81 s = smtplib.SMTP('localhost') 82 s.sendmail(message['from'], message['to'], message.as_string()) 83 s.quit() 84 85 def main(types, mail_config): 86 """ 87 88 Params: dict that contains the name of controller type, dict containing mail configuration 89 Gather omreport data and compare to yaml data corresponding to this machines model 90 91 """ 92 93 om = Omreport() 94 om.errors = [] 95 om.percs = {} 96 om.outofdate = {} 97 pattern = re.compile(r'%s' % (types['controller']), re.I) 98 url = "http://rhn.missouri.edu/pub/dell-yaml/%s.yaml" % (om.model) 99 try: 100 req = urlopen(url) 101 except URLError, e: 102 print ("URLError: %s") % (e) 103 except HTTPError, e: 104 print ("HTTPError: %s") % (e) 105 106 yaml_data = yaml.load(req) 107 # Gather PERC name and firmware version 108 for node in om.storage_tree.findall('//DCStorageObject'): 109 perc_name = node.find('Name').text 110 perc_ver = node.find('FirmwareVer').text 111 om.percs[perc_name] = perc_ver 112 113 # BIOS version is easy 114 om.bios_ver = om.system_tree.find('//SystemBIOS/Version').text 115 116 # Compare with yaml_data 117 for perc_name, version in om.percs.items(): 118 if version < yaml_data['percs'][perc_name]: 119 om.errors.append('perc') 120 om.outofdate[perc_name] = version 121 122 if om.bios_ver < yaml_data['bios']: 123 om.errors.append('bios') 124 125 if om.errors: 126 notify(om, yaml_data, mail_config) 127 128 if __name__ == "__main__": 129 types = {'controller': 'perc'} 130 mail_config = { 131 'subject': 'Firmware_report', 132 'to': 'bakerlu@missouri.edu', 133 'from': 'root@%s' % (gethostname()), 134 } 135 main(types, mail_config)
38 - error: syntax-error
1 from .models import Post 2 from django import forms 3 4 5 6 class PostForm(forms.ModelForm): 7 class Meta: 8 model = Post 9 fields = [ 10 'title', 11 'Tourtype', 12 'Country', 13 'City', 14 'Language', 15 'DetailContent', 16 'BriefContent', 17 'HashTag', 18 'MeetingPoint', 19 'MeetingTime', 20 'Map', 21 'Direction', 22 'CourseName', 23 'Duration', 24 'Price', 25 'Minimum', 26 'Maximum', 27 'Price_include', 28 'NotDate', 29 'GuestInfo', 30 ] 31 32 def save(self, commit=True): 33 post = Post(**self.cleaned_data) 34 if commit: 35 post.save() 36 return post
1 - error: relative-beyond-top-level 7 - refactor: too-few-public-methods 6 - refactor: too-few-public-methods
1 #!/usr/bin/env python 2 3 # reads config and pushes data 4 5 import ConfigParser 6 from PushToFtp import Push 7 8 Grouplist = "../grouplist.txt" 9 GroupNames = ["Group01", "Group02", "Group03", "Group04", "Group05", "Group06", "Group07", "Group08" ] 10 11 12 if __name__ == "__main__": 13 #config = ConfigParser.ConfigParser() 14 config = ConfigParser.SafeConfigParser( {'port': '21', 'passive': False, 'sftp': False }) 15 config.read( Grouplist ) 16 17 for group in GroupNames: 18 print "Group: %s"%group 19 try: 20 Username = config.get(group, 'user' ) 21 FtpServer = config.get(group, 'ip' ) 22 Passwd = config.get(group, 'pass' ) 23 WebUrl = config.get(group, 'weburl' ) 24 port = config.get(group, 'port' ) 25 passive = config.get(group, 'passive' ) 26 sftp = config.get(group, 'sftp') 27 Push( FtpServer, Username, Passwd, port=port, 28 passive=True if passive == 'True' else False, 29 Sftp=True if sftp == 'True' else False) 30 except Exception, e: 31 print "Something went wrong: %s"%e 32
18 - error: syntax-error
1 #!/usr/bin/env python 2 3 4 import sys 5 import urllib2 6 import json 7 8 9 def FetchBaseData( URL ): 10 11 print 'Fetching basedata from %s :'%(URL,) 12 13 # fetch data 14 req = urllib2.Request(URL) 15 response = urllib2.urlopen(req) 16 jsondata = response.read() 17 response.close() 18 19 # parsing json 20 data = json.loads( jsondata ) 21 22 print 'Data fetched: hostname: %s, php version: %s, timestamp: %s'%(data['hostname'], data['version'], data['date']) 23 24 return data 25 26 if __name__ == '__main__': 27 28 # command line args. 29 if len(sys.argv) < 3: 30 print "usage %s <id> <URL>"%sys.argv[0] 31 exit( 1 ) 32 33 GroupId = sys.argv[1] 34 URL = sys.argv[2] 35 36 37 # parsing json 38 data = FetchBaseData( URL ) 39 40 41 42 43
11 - error: syntax-error
1 #!/usr/bin/env python 2 3 # reads config and pushes data 4 5 import ConfigParser 6 from CheckBaseData import FetchBaseData 7 8 Grouplist = "../grouplist.txt" 9 GroupNames = ["Group01", "Group02", "Group03", "Group04", "Group05", "Group06", "Group07", "Group08" ] 10 11 12 if __name__ == "__main__": 13 #config = ConfigParser.ConfigParser() 14 config = ConfigParser.SafeConfigParser() 15 config.read( Grouplist ) 16 17 for group in GroupNames: 18 print "Group: %s"%group 19 try: 20 WebUrl = config.get(group, 'weburl' ) 21 FetchBaseData( WebUrl+'basedata.php') 22 except Exception, e: 23 print "Something went wrong: %s"%e 24
18 - error: syntax-error
1 #!/usr/bin/env python 2 3 # pushes data to a given server 4 5 from ftplib import FTP, FTP_TLS 6 import sys 7 import os 8 import paramiko 9 10 FilesToPut = ['../php/basedata.php'] 11 12 def Push( FtpServer, Username, Password, uploadlist = FilesToPut, port = 21, passive = False, Sftp = False ): 13 print "Login to %s:%s using %s:%s (%s)"%(FtpServer, port, Username, 'xxx', 14 'passive' if passive else 'active') 15 16 if Sftp: 17 paramiko.util.log_to_file('/tmp/paramiko.log') 18 transport = paramiko.Transport((FtpServer,int(port))) 19 transport.connect(username = Username, password = Password) 20 sftp = paramiko.SFTPClient.from_transport(transport) 21 22 for f in uploadlist: 23 print "uploading %s"%f 24 sftp.put(f, os.path.basename(f)) 25 sftp.close() 26 transport.close() 27 28 else: 29 ftp = FTP() 30 ftp.connect( FtpServer, port ) 31 ftp.login( Username, Password ) 32 ftp.set_pasv( passive ) 33 for f in uploadlist: 34 print "uploading %s"%f 35 fp = open( f, 'rb') 36 ftp.storbinary('STOR %s'%os.path.basename(f), fp) # send the file 37 38 ftp.quit() 39 40 if __name__ == "__main__": 41 if len(sys.argv) < 5: 42 print >> sys.stderr, "usage %s <server> <port> <username> <password>"%sys.argv[0] 43 exit( 1 ) 44 45 FtpServer = sys.argv[1] 46 Port = sys.argv[2] 47 Username = sys.argv[3] 48 Passwd = sys.argv[4] 49 50 Push( FtpServer, Username, Passwd, port = Port ) 51 print >> sys.stderr, "Done"
13 - error: syntax-error
1 # coding: utf-8 2 3 """ 4 StockX API 5 6 PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501 7 8 OpenAPI spec version: 1.0.0 9 10 Generated by: https://github.com/swagger-api/swagger-codegen.git 11 """ 12 13 14 import pprint 15 import re # noqa: F401 16 17 import six 18 19 from io_stockx.models.product_info_attributes_traits import ProductInfoAttributesTraits # noqa: F401,E501 20 21 22 class ProductInfoAttributes(object): 23 """NOTE: This class is auto generated by the swagger code generator program. 24 25 Do not edit the class manually. 26 """ 27 28 """ 29 Attributes: 30 swagger_types (dict): The key is attribute name 31 and the value is attribute type. 32 attribute_map (dict): The key is attribute name 33 and the value is json key in definition. 34 """ 35 swagger_types = { 36 'product_uuid': 'str', 37 'sku': 'str', 38 'traits': 'ProductInfoAttributesTraits' 39 } 40 41 attribute_map = { 42 'product_uuid': 'product_uuid', 43 'sku': 'sku', 44 'traits': 'traits' 45 } 46 47 def __init__(self, product_uuid=None, sku=None, traits=None): # noqa: E501 48 """ProductInfoAttributes - a model defined in Swagger""" # noqa: E501 49 50 self._product_uuid = None 51 self._sku = None 52 self._traits = None 53 self.discriminator = None 54 55 if product_uuid is not None: 56 self.product_uuid = product_uuid 57 if sku is not None: 58 self.sku = sku 59 if traits is not None: 60 self.traits = traits 61 62 @property 63 def product_uuid(self): 64 """Gets the product_uuid of this ProductInfoAttributes. # noqa: E501 65 66 67 :return: The product_uuid of this ProductInfoAttributes. # noqa: E501 68 :rtype: str 69 """ 70 return self._product_uuid 71 72 @product_uuid.setter 73 def product_uuid(self, product_uuid): 74 """Sets the product_uuid of this ProductInfoAttributes. 75 76 77 :param product_uuid: The product_uuid of this ProductInfoAttributes. # noqa: E501 78 :type: str 79 """ 80 81 self._product_uuid = product_uuid 82 83 @property 84 def sku(self): 85 """Gets the sku of this ProductInfoAttributes. # noqa: E501 86 87 88 :return: The sku of this ProductInfoAttributes. # noqa: E501 89 :rtype: str 90 """ 91 return self._sku 92 93 @sku.setter 94 def sku(self, sku): 95 """Sets the sku of this ProductInfoAttributes. 96 97 98 :param sku: The sku of this ProductInfoAttributes. # noqa: E501 99 :type: str 100 """ 101 102 self._sku = sku 103 104 @property 105 def traits(self): 106 """Gets the traits of this ProductInfoAttributes. # noqa: E501 107 108 109 :return: The traits of this ProductInfoAttributes. # noqa: E501 110 :rtype: ProductInfoAttributesTraits 111 """ 112 return self._traits 113 114 @traits.setter 115 def traits(self, traits): 116 """Sets the traits of this ProductInfoAttributes. 117 118 119 :param traits: The traits of this ProductInfoAttributes. # noqa: E501 120 :type: ProductInfoAttributesTraits 121 """ 122 123 self._traits = traits 124 125 def to_dict(self): 126 """Returns the model properties as a dict""" 127 result = {} 128 129 for attr, _ in six.iteritems(self.swagger_types): 130 value = getattr(self, attr) 131 if isinstance(value, list): 132 result[attr] = list(map( 133 lambda x: x.to_dict() if hasattr(x, "to_dict") else x, 134 value 135 )) 136 elif hasattr(value, "to_dict"): 137 result[attr] = value.to_dict() 138 elif isinstance(value, dict): 139 result[attr] = dict(map( 140 lambda item: (item[0], item[1].to_dict()) 141 if hasattr(item[1], "to_dict") else item, 142 value.items() 143 )) 144 else: 145 result[attr] = value 146 147 return result 148 149 def to_str(self): 150 """Returns the string representation of the model""" 151 return pprint.pformat(self.to_dict()) 152 153 def __repr__(self): 154 """For `print` and `pprint`""" 155 return self.to_str() 156 157 def __eq__(self, other): 158 """Returns true if both objects are equal""" 159 if not isinstance(other, ProductInfoAttributes): 160 return False 161 162 return self.__dict__ == other.__dict__ 163 164 def __ne__(self, other): 165 """Returns true if both objects are not equal""" 166 return not self == other
22 - refactor: useless-object-inheritance 28 - warning: pointless-string-statement 15 - warning: unused-import 19 - warning: unused-import
1 # coding: utf-8 2 3 """ 4 StockX API 5 6 PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501 7 8 OpenAPI spec version: 1.0.0 9 10 Generated by: https://github.com/swagger-api/swagger-codegen.git 11 """ 12 13 14 from __future__ import absolute_import 15 16 import unittest 17 18 import io_stockx 19 from io_stockx.models.portfolio_id_del_response_portfolio_item_product_media import PortfolioIdDelResponsePortfolioItemProductMedia # noqa: E501 20 from io_stockx.rest import ApiException 21 22 23 class TestPortfolioIdDelResponsePortfolioItemProductMedia(unittest.TestCase): 24 """PortfolioIdDelResponsePortfolioItemProductMedia unit test stubs""" 25 26 def setUp(self): 27 pass 28 29 def tearDown(self): 30 pass 31 32 def testPortfolioIdDelResponsePortfolioItemProductMedia(self): 33 """Test PortfolioIdDelResponsePortfolioItemProductMedia""" 34 # FIXME: construct object with mandatory attributes with example values 35 # model = io_stockx.models.portfolio_id_del_response_portfolio_item_product_media.PortfolioIdDelResponsePortfolioItemProductMedia() # noqa: E501 36 pass 37 38 39 if __name__ == '__main__': 40 unittest.main()
34 - warning: fixme 36 - warning: unnecessary-pass 18 - warning: unused-import 19 - warning: unused-import 20 - warning: unused-import
1 # coding: utf-8 2 3 """ 4 StockX API 5 6 PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501 7 8 OpenAPI spec version: 1.0.0 9 10 Generated by: https://github.com/swagger-api/swagger-codegen.git 11 """ 12 13 14 import pprint 15 import re # noqa: F401 16 17 import six 18 19 20 class CustomerObjectMerchant(object): 21 """NOTE: This class is auto generated by the swagger code generator program. 22 23 Do not edit the class manually. 24 """ 25 26 """ 27 Attributes: 28 swagger_types (dict): The key is attribute name 29 and the value is attribute type. 30 attribute_map (dict): The key is attribute name 31 and the value is json key in definition. 32 """ 33 swagger_types = { 34 'merchant_id': 'str', 35 'paypal_email': 'str', 36 'preferred_payout': 'str', 37 'account_name': 'str' 38 } 39 40 attribute_map = { 41 'merchant_id': 'merchantId', 42 'paypal_email': 'paypalEmail', 43 'preferred_payout': 'preferredPayout', 44 'account_name': 'accountName' 45 } 46 47 def __init__(self, merchant_id=None, paypal_email=None, preferred_payout=None, account_name=None): # noqa: E501 48 """CustomerObjectMerchant - a model defined in Swagger""" # noqa: E501 49 50 self._merchant_id = None 51 self._paypal_email = None 52 self._preferred_payout = None 53 self._account_name = None 54 self.discriminator = None 55 56 if merchant_id is not None: 57 self.merchant_id = merchant_id 58 if paypal_email is not None: 59 self.paypal_email = paypal_email 60 if preferred_payout is not None: 61 self.preferred_payout = preferred_payout 62 if account_name is not None: 63 self.account_name = account_name 64 65 @property 66 def merchant_id(self): 67 """Gets the merchant_id of this CustomerObjectMerchant. # noqa: E501 68 69 70 :return: The merchant_id of this CustomerObjectMerchant. # noqa: E501 71 :rtype: str 72 """ 73 return self._merchant_id 74 75 @merchant_id.setter 76 def merchant_id(self, merchant_id): 77 """Sets the merchant_id of this CustomerObjectMerchant. 78 79 80 :param merchant_id: The merchant_id of this CustomerObjectMerchant. # noqa: E501 81 :type: str 82 """ 83 84 self._merchant_id = merchant_id 85 86 @property 87 def paypal_email(self): 88 """Gets the paypal_email of this CustomerObjectMerchant. # noqa: E501 89 90 91 :return: The paypal_email of this CustomerObjectMerchant. # noqa: E501 92 :rtype: str 93 """ 94 return self._paypal_email 95 96 @paypal_email.setter 97 def paypal_email(self, paypal_email): 98 """Sets the paypal_email of this CustomerObjectMerchant. 99 100 101 :param paypal_email: The paypal_email of this CustomerObjectMerchant. # noqa: E501 102 :type: str 103 """ 104 105 self._paypal_email = paypal_email 106 107 @property 108 def preferred_payout(self): 109 """Gets the preferred_payout of this CustomerObjectMerchant. # noqa: E501 110 111 112 :return: The preferred_payout of this CustomerObjectMerchant. # noqa: E501 113 :rtype: str 114 """ 115 return self._preferred_payout 116 117 @preferred_payout.setter 118 def preferred_payout(self, preferred_payout): 119 """Sets the preferred_payout of this CustomerObjectMerchant. 120 121 122 :param preferred_payout: The preferred_payout of this CustomerObjectMerchant. # noqa: E501 123 :type: str 124 """ 125 126 self._preferred_payout = preferred_payout 127 128 @property 129 def account_name(self): 130 """Gets the account_name of this CustomerObjectMerchant. # noqa: E501 131 132 133 :return: The account_name of this CustomerObjectMerchant. # noqa: E501 134 :rtype: str 135 """ 136 return self._account_name 137 138 @account_name.setter 139 def account_name(self, account_name): 140 """Sets the account_name of this CustomerObjectMerchant. 141 142 143 :param account_name: The account_name of this CustomerObjectMerchant. # noqa: E501 144 :type: str 145 """ 146 147 self._account_name = account_name 148 149 def to_dict(self): 150 """Returns the model properties as a dict""" 151 result = {} 152 153 for attr, _ in six.iteritems(self.swagger_types): 154 value = getattr(self, attr) 155 if isinstance(value, list): 156 result[attr] = list(map( 157 lambda x: x.to_dict() if hasattr(x, "to_dict") else x, 158 value 159 )) 160 elif hasattr(value, "to_dict"): 161 result[attr] = value.to_dict() 162 elif isinstance(value, dict): 163 result[attr] = dict(map( 164 lambda item: (item[0], item[1].to_dict()) 165 if hasattr(item[1], "to_dict") else item, 166 value.items() 167 )) 168 else: 169 result[attr] = value 170 171 return result 172 173 def to_str(self): 174 """Returns the string representation of the model""" 175 return pprint.pformat(self.to_dict()) 176 177 def __repr__(self): 178 """For `print` and `pprint`""" 179 return self.to_str() 180 181 def __eq__(self, other): 182 """Returns true if both objects are equal""" 183 if not isinstance(other, CustomerObjectMerchant): 184 return False 185 186 return self.__dict__ == other.__dict__ 187 188 def __ne__(self, other): 189 """Returns true if both objects are not equal""" 190 return not self == other
20 - refactor: useless-object-inheritance 20 - refactor: too-many-instance-attributes 26 - warning: pointless-string-statement 15 - warning: unused-import
1 # coding: utf-8 2 3 """ 4 StockX API 5 6 PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501 7 8 OpenAPI spec version: 1.0.0 9 10 Generated by: https://github.com/swagger-api/swagger-codegen.git 11 """ 12 13 14 from __future__ import absolute_import 15 16 import unittest 17 18 import io_stockx 19 from io_stockx.api.stock_x_api import StockXApi # noqa: E501 20 from io_stockx.rest import ApiException 21 22 23 class TestStockXApi(unittest.TestCase): 24 """StockXApi unit test stubs""" 25 26 def setUp(self): 27 self.api = io_stockx.api.stock_x_api.StockXApi() # noqa: E501 28 29 def tearDown(self): 30 pass 31 32 def test_delete_portfolio(self): 33 """Test case for delete_portfolio 34 35 Deletes a portfolio item from the market with the specified id. # noqa: E501 36 """ 37 pass 38 39 def test_delete_webhook(self): 40 """Test case for delete_webhook 41 42 """ 43 pass 44 45 def test_get_open_orders(self): 46 """Test case for get_open_orders 47 48 """ 49 pass 50 51 def test_get_portfolio(self): 52 """Test case for get_portfolio 53 54 Returns a market portfolio identified by request parameters. # noqa: E501 55 """ 56 pass 57 58 def test_get_portfolio_item(self): 59 """Test case for get_portfolio_item 60 61 """ 62 pass 63 64 def test_get_product_by_id(self): 65 """Test case for get_product_by_id 66 67 """ 68 pass 69 70 def test_get_product_market_data(self): 71 """Test case for get_product_market_data 72 73 Provides historical market data for a given product. # noqa: E501 74 """ 75 pass 76 77 def test_get_subscriptions(self): 78 """Test case for get_subscriptions 79 80 """ 81 pass 82 83 def test_get_webhook(self): 84 """Test case for get_webhook 85 86 """ 87 pass 88 89 def test_get_webhooks(self): 90 """Test case for get_webhooks 91 92 """ 93 pass 94 95 def test_login(self): 96 """Test case for login 97 98 Attempts to log the user in with a username and password. # noqa: E501 99 """ 100 pass 101 102 def test_lookup_product(self): 103 """Test case for lookup_product 104 105 """ 106 pass 107 108 def test_new_portfolio_ask(self): 109 """Test case for new_portfolio_ask 110 111 Creates a new seller ask on the market for a given product. # noqa: E501 112 """ 113 pass 114 115 def test_new_portfolio_bid(self): 116 """Test case for new_portfolio_bid 117 118 Creates a new buyer bid on the market for a given product. # noqa: E501 119 """ 120 pass 121 122 def test_post_webhooks(self): 123 """Test case for post_webhooks 124 125 """ 126 pass 127 128 def test_search(self): 129 """Test case for search 130 131 Searches for products by keyword. # noqa: E501 132 """ 133 pass 134 135 136 if __name__ == '__main__': 137 unittest.main()
37 - warning: unnecessary-pass 43 - warning: unnecessary-pass 49 - warning: unnecessary-pass 56 - warning: unnecessary-pass 62 - warning: unnecessary-pass 68 - warning: unnecessary-pass 75 - warning: unnecessary-pass 81 - warning: unnecessary-pass 87 - warning: unnecessary-pass 93 - warning: unnecessary-pass 100 - warning: unnecessary-pass 106 - warning: unnecessary-pass 113 - warning: unnecessary-pass 120 - warning: unnecessary-pass 126 - warning: unnecessary-pass 133 - warning: unnecessary-pass 19 - warning: unused-import 20 - warning: unused-import
1 from __future__ import print_function 2 3 import time 4 import io_stockx 5 from example_constants import ExampleConstants 6 from io_stockx.rest import ApiException 7 from pprint import pprint 8 9 # Configure API key authorization: api_key 10 configuration = io_stockx.Configuration() 11 12 configuration.host = "https://gateway.stockx.com/stage" 13 configuration.api_key['x-api-key'] = ExampleConstants.AWS_API_KEY 14 15 # create an instance of the API class 16 stockx = io_stockx.StockXApi(io_stockx.ApiClient(configuration)) 17 login = io_stockx.LoginRequest(email=ExampleConstants.STOCKX_USERNAME, password=ExampleConstants.STOCKX_PASSWORD) 18 19 try: 20 # Attempts to log the user in with a username and password. 21 api_response = stockx.login_with_http_info(login) 22 23 # Get the customer object after login 24 customer = api_response[0] 25 26 # Get the login's assigned jwt token 27 jwt_token = api_response[2]['Jwt-Authorization'] 28 29 # Use the jwt token to authenticate future requests 30 stockx.api_client.set_default_header('jwt-authorization', jwt_token) 31 32 # Search for a type of product 33 search_result = stockx.search('Jordan Retro Black Cat') 34 35 first_hit = search_result.hits[0] 36 style_id = first_hit.style_id 37 38 # Lookup the first product returned from the search 39 product = stockx.lookup_product(identifier=style_id, size='11') 40 41 # Get the current market data for the product (highest bid info, etc.) 42 attributes = product.data[0].attributes 43 id = product.data[0].id 44 uuid = attributes.product_uuid 45 46 # Get the product market data 47 market_data = stockx.get_product_market_data(id, sku=uuid) 48 49 # Get the lowest ask for the product and decrement it 50 lowest_ask = market_data.market.lowest_ask 51 lowest_ask += 1 52 53 # Create a portfolio item request with a higher bid 54 item = io_stockx.PortfolioRequestPortfolioItem() 55 56 item.amount = lowest_ask 57 item.sku_uuid = "bae25b67-a721-4f57-ad5a-79973c7d0a5c" 58 item.matched_with_date = "2018-12-12T05:00:00+0000" 59 item.expires_at = "2018-12-12T12:39:07+00:00" 60 61 request = io_stockx.PortfolioRequest() 62 request.portfolio_item = item 63 request.customer = customer 64 request.timezone = "America/Detroit" 65 66 # Submit the ask 67 ask_resp = stockx.new_portfolio_ask(request) 68 69 pprint(ask_resp) 70 except ApiException as e: 71 print("Exception when calling StockXApi->new_portfolio_ask: %s\n" % e)
43 - warning: redefined-builtin 3 - warning: unused-import
1 # coding: utf-8 2 3 """ 4 StockX API 5 6 PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501 7 8 OpenAPI spec version: 1.0.0 9 10 Generated by: https://github.com/swagger-api/swagger-codegen.git 11 """ 12 13 14 import pprint 15 import re # noqa: F401 16 17 import six 18 19 20 class SearchHitSearchableTraits(object): 21 """NOTE: This class is auto generated by the swagger code generator program. 22 23 Do not edit the class manually. 24 """ 25 26 """ 27 Attributes: 28 swagger_types (dict): The key is attribute name 29 and the value is attribute type. 30 attribute_map (dict): The key is attribute name 31 and the value is json key in definition. 32 """ 33 swagger_types = { 34 'style': 'str', 35 'colorway': 'str', 36 'retail_price': 'int', 37 'release_date': 'str' 38 } 39 40 attribute_map = { 41 'style': 'Style', 42 'colorway': 'Colorway', 43 'retail_price': 'Retail Price', 44 'release_date': 'Release Date' 45 } 46 47 def __init__(self, style=None, colorway=None, retail_price=None, release_date=None): # noqa: E501 48 """SearchHitSearchableTraits - a model defined in Swagger""" # noqa: E501 49 50 self._style = None 51 self._colorway = None 52 self._retail_price = None 53 self._release_date = None 54 self.discriminator = None 55 56 if style is not None: 57 self.style = style 58 if colorway is not None: 59 self.colorway = colorway 60 if retail_price is not None: 61 self.retail_price = retail_price 62 if release_date is not None: 63 self.release_date = release_date 64 65 @property 66 def style(self): 67 """Gets the style of this SearchHitSearchableTraits. # noqa: E501 68 69 70 :return: The style of this SearchHitSearchableTraits. # noqa: E501 71 :rtype: str 72 """ 73 return self._style 74 75 @style.setter 76 def style(self, style): 77 """Sets the style of this SearchHitSearchableTraits. 78 79 80 :param style: The style of this SearchHitSearchableTraits. # noqa: E501 81 :type: str 82 """ 83 84 self._style = style 85 86 @property 87 def colorway(self): 88 """Gets the colorway of this SearchHitSearchableTraits. # noqa: E501 89 90 91 :return: The colorway of this SearchHitSearchableTraits. # noqa: E501 92 :rtype: str 93 """ 94 return self._colorway 95 96 @colorway.setter 97 def colorway(self, colorway): 98 """Sets the colorway of this SearchHitSearchableTraits. 99 100 101 :param colorway: The colorway of this SearchHitSearchableTraits. # noqa: E501 102 :type: str 103 """ 104 105 self._colorway = colorway 106 107 @property 108 def retail_price(self): 109 """Gets the retail_price of this SearchHitSearchableTraits. # noqa: E501 110 111 112 :return: The retail_price of this SearchHitSearchableTraits. # noqa: E501 113 :rtype: int 114 """ 115 return self._retail_price 116 117 @retail_price.setter 118 def retail_price(self, retail_price): 119 """Sets the retail_price of this SearchHitSearchableTraits. 120 121 122 :param retail_price: The retail_price of this SearchHitSearchableTraits. # noqa: E501 123 :type: int 124 """ 125 126 self._retail_price = retail_price 127 128 @property 129 def release_date(self): 130 """Gets the release_date of this SearchHitSearchableTraits. # noqa: E501 131 132 133 :return: The release_date of this SearchHitSearchableTraits. # noqa: E501 134 :rtype: str 135 """ 136 return self._release_date 137 138 @release_date.setter 139 def release_date(self, release_date): 140 """Sets the release_date of this SearchHitSearchableTraits. 141 142 143 :param release_date: The release_date of this SearchHitSearchableTraits. # noqa: E501 144 :type: str 145 """ 146 147 self._release_date = release_date 148 149 def to_dict(self): 150 """Returns the model properties as a dict""" 151 result = {} 152 153 for attr, _ in six.iteritems(self.swagger_types): 154 value = getattr(self, attr) 155 if isinstance(value, list): 156 result[attr] = list(map( 157 lambda x: x.to_dict() if hasattr(x, "to_dict") else x, 158 value 159 )) 160 elif hasattr(value, "to_dict"): 161 result[attr] = value.to_dict() 162 elif isinstance(value, dict): 163 result[attr] = dict(map( 164 lambda item: (item[0], item[1].to_dict()) 165 if hasattr(item[1], "to_dict") else item, 166 value.items() 167 )) 168 else: 169 result[attr] = value 170 171 return result 172 173 def to_str(self): 174 """Returns the string representation of the model""" 175 return pprint.pformat(self.to_dict()) 176 177 def __repr__(self): 178 """For `print` and `pprint`""" 179 return self.to_str() 180 181 def __eq__(self, other): 182 """Returns true if both objects are equal""" 183 if not isinstance(other, SearchHitSearchableTraits): 184 return False 185 186 return self.__dict__ == other.__dict__ 187 188 def __ne__(self, other): 189 """Returns true if both objects are not equal""" 190 return not self == other
20 - refactor: useless-object-inheritance 20 - refactor: too-many-instance-attributes 26 - warning: pointless-string-statement 15 - warning: unused-import
1 # coding: utf-8 2 3 """ 4 StockX API 5 6 PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501 7 8 OpenAPI spec version: 1.0.0 9 10 Generated by: https://github.com/swagger-api/swagger-codegen.git 11 """ 12 13 14 import pprint 15 import re # noqa: F401 16 17 import six 18 19 20 class PortfolioIdDelResponsePortfolioItemProductShipping(object): 21 """NOTE: This class is auto generated by the swagger code generator program. 22 23 Do not edit the class manually. 24 """ 25 26 """ 27 Attributes: 28 swagger_types (dict): The key is attribute name 29 and the value is attribute type. 30 attribute_map (dict): The key is attribute name 31 and the value is json key in definition. 32 """ 33 swagger_types = { 34 'total_days_to_ship': 'int', 35 'has_additional_days_to_ship': 'bool', 36 'delivery_days_lower_bound': 'int', 37 'delivery_days_upper_bound': 'int' 38 } 39 40 attribute_map = { 41 'total_days_to_ship': 'totalDaysToShip', 42 'has_additional_days_to_ship': 'hasAdditionalDaysToShip', 43 'delivery_days_lower_bound': 'deliveryDaysLowerBound', 44 'delivery_days_upper_bound': 'deliveryDaysUpperBound' 45 } 46 47 def __init__(self, total_days_to_ship=None, has_additional_days_to_ship=None, delivery_days_lower_bound=None, delivery_days_upper_bound=None): # noqa: E501 48 """PortfolioIdDelResponsePortfolioItemProductShipping - a model defined in Swagger""" # noqa: E501 49 50 self._total_days_to_ship = None 51 self._has_additional_days_to_ship = None 52 self._delivery_days_lower_bound = None 53 self._delivery_days_upper_bound = None 54 self.discriminator = None 55 56 self.total_days_to_ship = total_days_to_ship 57 self.has_additional_days_to_ship = has_additional_days_to_ship 58 self.delivery_days_lower_bound = delivery_days_lower_bound 59 self.delivery_days_upper_bound = delivery_days_upper_bound 60 61 @property 62 def total_days_to_ship(self): 63 """Gets the total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 64 65 66 :return: The total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 67 :rtype: int 68 """ 69 return self._total_days_to_ship 70 71 @total_days_to_ship.setter 72 def total_days_to_ship(self, total_days_to_ship): 73 """Sets the total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. 74 75 76 :param total_days_to_ship: The total_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 77 :type: int 78 """ 79 if total_days_to_ship is None: 80 raise ValueError("Invalid value for `total_days_to_ship`, must not be `None`") # noqa: E501 81 82 self._total_days_to_ship = total_days_to_ship 83 84 @property 85 def has_additional_days_to_ship(self): 86 """Gets the has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 87 88 89 :return: The has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 90 :rtype: bool 91 """ 92 return self._has_additional_days_to_ship 93 94 @has_additional_days_to_ship.setter 95 def has_additional_days_to_ship(self, has_additional_days_to_ship): 96 """Sets the has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. 97 98 99 :param has_additional_days_to_ship: The has_additional_days_to_ship of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 100 :type: bool 101 """ 102 if has_additional_days_to_ship is None: 103 raise ValueError("Invalid value for `has_additional_days_to_ship`, must not be `None`") # noqa: E501 104 105 self._has_additional_days_to_ship = has_additional_days_to_ship 106 107 @property 108 def delivery_days_lower_bound(self): 109 """Gets the delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 110 111 112 :return: The delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 113 :rtype: int 114 """ 115 return self._delivery_days_lower_bound 116 117 @delivery_days_lower_bound.setter 118 def delivery_days_lower_bound(self, delivery_days_lower_bound): 119 """Sets the delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. 120 121 122 :param delivery_days_lower_bound: The delivery_days_lower_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 123 :type: int 124 """ 125 if delivery_days_lower_bound is None: 126 raise ValueError("Invalid value for `delivery_days_lower_bound`, must not be `None`") # noqa: E501 127 128 self._delivery_days_lower_bound = delivery_days_lower_bound 129 130 @property 131 def delivery_days_upper_bound(self): 132 """Gets the delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 133 134 135 :return: The delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 136 :rtype: int 137 """ 138 return self._delivery_days_upper_bound 139 140 @delivery_days_upper_bound.setter 141 def delivery_days_upper_bound(self, delivery_days_upper_bound): 142 """Sets the delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. 143 144 145 :param delivery_days_upper_bound: The delivery_days_upper_bound of this PortfolioIdDelResponsePortfolioItemProductShipping. # noqa: E501 146 :type: int 147 """ 148 if delivery_days_upper_bound is None: 149 raise ValueError("Invalid value for `delivery_days_upper_bound`, must not be `None`") # noqa: E501 150 151 self._delivery_days_upper_bound = delivery_days_upper_bound 152 153 def to_dict(self): 154 """Returns the model properties as a dict""" 155 result = {} 156 157 for attr, _ in six.iteritems(self.swagger_types): 158 value = getattr(self, attr) 159 if isinstance(value, list): 160 result[attr] = list(map( 161 lambda x: x.to_dict() if hasattr(x, "to_dict") else x, 162 value 163 )) 164 elif hasattr(value, "to_dict"): 165 result[attr] = value.to_dict() 166 elif isinstance(value, dict): 167 result[attr] = dict(map( 168 lambda item: (item[0], item[1].to_dict()) 169 if hasattr(item[1], "to_dict") else item, 170 value.items() 171 )) 172 else: 173 result[attr] = value 174 175 return result 176 177 def to_str(self): 178 """Returns the string representation of the model""" 179 return pprint.pformat(self.to_dict()) 180 181 def __repr__(self): 182 """For `print` and `pprint`""" 183 return self.to_str() 184 185 def __eq__(self, other): 186 """Returns true if both objects are equal""" 187 if not isinstance(other, PortfolioIdDelResponsePortfolioItemProductShipping): 188 return False 189 190 return self.__dict__ == other.__dict__ 191 192 def __ne__(self, other): 193 """Returns true if both objects are not equal""" 194 return not self == other
20 - refactor: useless-object-inheritance 20 - refactor: too-many-instance-attributes 26 - warning: pointless-string-statement 15 - warning: unused-import
1 from __future__ import print_function 2 import time 3 import io_stockx 4 from example_constants import ExampleConstants 5 from io_stockx.rest import ApiException 6 from pprint import pprint 7 8 # Configure API key authorization: api_key 9 configuration = io_stockx.Configuration() 10 11 configuration.host = "https://gateway.stockx.com/stage" 12 configuration.api_key['x-api-key'] = ExampleConstants.AWS_API_KEY 13 14 # create an instance of the API class 15 stockx = io_stockx.StockXApi(io_stockx.ApiClient(configuration)) 16 login = io_stockx.LoginRequest(email=ExampleConstants.STOCKX_USERNAME, password=ExampleConstants.STOCKX_PASSWORD) 17 18 try: 19 # Attempts to log the user in with a username and password. 20 api_response = stockx.login(login) 21 pprint(api_response) 22 except ApiException as e: 23 print("Exception when calling StockXApi->login: %s\n" % e)
2 - warning: unused-import
1 # coding: utf-8 2 3 """ 4 StockX API 5 6 PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501 7 8 OpenAPI spec version: 1.0.0 9 10 Generated by: https://github.com/swagger-api/swagger-codegen.git 11 """ 12 13 14 import pprint 15 import re # noqa: F401 16 17 import six 18 19 20 class PortfolioIdDelRequest(object): 21 """NOTE: This class is auto generated by the swagger code generator program. 22 23 Do not edit the class manually. 24 """ 25 26 """ 27 Attributes: 28 swagger_types (dict): The key is attribute name 29 and the value is attribute type. 30 attribute_map (dict): The key is attribute name 31 and the value is json key in definition. 32 """ 33 swagger_types = { 34 'chain_id': 'str', 35 'notes': 'str' 36 } 37 38 attribute_map = { 39 'chain_id': 'chain_id', 40 'notes': 'notes' 41 } 42 43 def __init__(self, chain_id=None, notes=None): # noqa: E501 44 """PortfolioIdDelRequest - a model defined in Swagger""" # noqa: E501 45 46 self._chain_id = None 47 self._notes = None 48 self.discriminator = None 49 50 self.chain_id = chain_id 51 self.notes = notes 52 53 @property 54 def chain_id(self): 55 """Gets the chain_id of this PortfolioIdDelRequest. # noqa: E501 56 57 58 :return: The chain_id of this PortfolioIdDelRequest. # noqa: E501 59 :rtype: str 60 """ 61 return self._chain_id 62 63 @chain_id.setter 64 def chain_id(self, chain_id): 65 """Sets the chain_id of this PortfolioIdDelRequest. 66 67 68 :param chain_id: The chain_id of this PortfolioIdDelRequest. # noqa: E501 69 :type: str 70 """ 71 if chain_id is None: 72 raise ValueError("Invalid value for `chain_id`, must not be `None`") # noqa: E501 73 74 self._chain_id = chain_id 75 76 @property 77 def notes(self): 78 """Gets the notes of this PortfolioIdDelRequest. # noqa: E501 79 80 81 :return: The notes of this PortfolioIdDelRequest. # noqa: E501 82 :rtype: str 83 """ 84 return self._notes 85 86 @notes.setter 87 def notes(self, notes): 88 """Sets the notes of this PortfolioIdDelRequest. 89 90 91 :param notes: The notes of this PortfolioIdDelRequest. # noqa: E501 92 :type: str 93 """ 94 if notes is None: 95 raise ValueError("Invalid value for `notes`, must not be `None`") # noqa: E501 96 97 self._notes = notes 98 99 def to_dict(self): 100 """Returns the model properties as a dict""" 101 result = {} 102 103 for attr, _ in six.iteritems(self.swagger_types): 104 value = getattr(self, attr) 105 if isinstance(value, list): 106 result[attr] = list(map( 107 lambda x: x.to_dict() if hasattr(x, "to_dict") else x, 108 value 109 )) 110 elif hasattr(value, "to_dict"): 111 result[attr] = value.to_dict() 112 elif isinstance(value, dict): 113 result[attr] = dict(map( 114 lambda item: (item[0], item[1].to_dict()) 115 if hasattr(item[1], "to_dict") else item, 116 value.items() 117 )) 118 else: 119 result[attr] = value 120 121 return result 122 123 def to_str(self): 124 """Returns the string representation of the model""" 125 return pprint.pformat(self.to_dict()) 126 127 def __repr__(self): 128 """For `print` and `pprint`""" 129 return self.to_str() 130 131 def __eq__(self, other): 132 """Returns true if both objects are equal""" 133 if not isinstance(other, PortfolioIdDelRequest): 134 return False 135 136 return self.__dict__ == other.__dict__ 137 138 def __ne__(self, other): 139 """Returns true if both objects are not equal""" 140 return not self == other
20 - refactor: useless-object-inheritance 26 - warning: pointless-string-statement 15 - warning: unused-import
1 # coding: utf-8 2 3 # flake8: noqa 4 """ 5 StockX API 6 7 PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501 8 9 OpenAPI spec version: 1.0.0 10 11 Generated by: https://github.com/swagger-api/swagger-codegen.git 12 """ 13 14 15 from __future__ import absolute_import 16 17 # import models into model package 18 from io_stockx.models.address_object import AddressObject 19 from io_stockx.models.billing_object import BillingObject 20 from io_stockx.models.customer_object import CustomerObject 21 from io_stockx.models.customer_object_merchant import CustomerObjectMerchant 22 from io_stockx.models.customer_object_security import CustomerObjectSecurity 23 from io_stockx.models.customer_object_shipping import CustomerObjectShipping 24 from io_stockx.models.customers_id_selling_current import CustomersIdSellingCurrent 25 from io_stockx.models.customers_id_selling_current_pagination import CustomersIdSellingCurrentPagination 26 from io_stockx.models.customers_id_selling_current_paging import CustomersIdSellingCurrentPaging 27 from io_stockx.models.login_request import LoginRequest 28 from io_stockx.models.login_response import LoginResponse 29 from io_stockx.models.market_data import MarketData 30 from io_stockx.models.market_data_market import MarketDataMarket 31 from io_stockx.models.portfolio_id_del_request import PortfolioIdDelRequest 32 from io_stockx.models.portfolio_id_del_response import PortfolioIdDelResponse 33 from io_stockx.models.portfolio_id_del_response_portfolio_item import PortfolioIdDelResponsePortfolioItem 34 from io_stockx.models.portfolio_id_del_response_portfolio_item_merchant import PortfolioIdDelResponsePortfolioItemMerchant 35 from io_stockx.models.portfolio_id_del_response_portfolio_item_product import PortfolioIdDelResponsePortfolioItemProduct 36 from io_stockx.models.portfolio_id_del_response_portfolio_item_product_market import PortfolioIdDelResponsePortfolioItemProductMarket 37 from io_stockx.models.portfolio_id_del_response_portfolio_item_product_media import PortfolioIdDelResponsePortfolioItemProductMedia 38 from io_stockx.models.portfolio_id_del_response_portfolio_item_product_meta import PortfolioIdDelResponsePortfolioItemProductMeta 39 from io_stockx.models.portfolio_id_del_response_portfolio_item_product_shipping import PortfolioIdDelResponsePortfolioItemProductShipping 40 from io_stockx.models.portfolio_id_del_response_portfolio_item_tracking import PortfolioIdDelResponsePortfolioItemTracking 41 from io_stockx.models.portfolio_request import PortfolioRequest 42 from io_stockx.models.portfolio_request_portfolio_item import PortfolioRequestPortfolioItem 43 from io_stockx.models.portfolio_response import PortfolioResponse 44 from io_stockx.models.portfolio_response_portfolio_item import PortfolioResponsePortfolioItem 45 from io_stockx.models.portfolio_response_portfolio_item_product import PortfolioResponsePortfolioItemProduct 46 from io_stockx.models.portfolio_response_portfolio_item_product_market import PortfolioResponsePortfolioItemProductMarket 47 from io_stockx.models.portfolio_response_portfolio_item_product_media import PortfolioResponsePortfolioItemProductMedia 48 from io_stockx.models.portfolio_response_portfolio_item_tracking import PortfolioResponsePortfolioItemTracking 49 from io_stockx.models.portfolioitems_id_get_response import PortfolioitemsIdGetResponse 50 from io_stockx.models.portfolioitems_id_get_response_portfolio_item import PortfolioitemsIdGetResponsePortfolioItem 51 from io_stockx.models.portfolioitems_id_get_response_portfolio_item_product import PortfolioitemsIdGetResponsePortfolioItemProduct 52 from io_stockx.models.portfolioitems_id_get_response_portfolio_item_product_market import PortfolioitemsIdGetResponsePortfolioItemProductMarket 53 from io_stockx.models.product_info import ProductInfo 54 from io_stockx.models.product_info_attributes import ProductInfoAttributes 55 from io_stockx.models.product_info_attributes_traits import ProductInfoAttributesTraits 56 from io_stockx.models.product_info_data import ProductInfoData 57 from io_stockx.models.product_info_meta import ProductInfoMeta 58 from io_stockx.models.product_info_product import ProductInfoProduct 59 from io_stockx.models.product_info_product_attributes import ProductInfoProductAttributes 60 from io_stockx.models.product_lookup_response import ProductLookupResponse 61 from io_stockx.models.product_response import ProductResponse 62 from io_stockx.models.product_response_product import ProductResponseProduct 63 from io_stockx.models.product_response_product_children import ProductResponseProductChildren 64 from io_stockx.models.product_response_product_children_productid import ProductResponseProductChildrenPRODUCTID 65 from io_stockx.models.product_response_product_children_productid_market import ProductResponseProductChildrenPRODUCTIDMarket 66 from io_stockx.models.product_response_product_media import ProductResponseProductMedia 67 from io_stockx.models.product_response_product_meta import ProductResponseProductMeta 68 from io_stockx.models.search_hit import SearchHit 69 from io_stockx.models.search_hit_media import SearchHitMedia 70 from io_stockx.models.search_hit_searchable_traits import SearchHitSearchableTraits 71 from io_stockx.models.search_results import SearchResults 72 from io_stockx.models.subscriptions_response import SubscriptionsResponse 73 from io_stockx.models.webhooks_get_response import WebhooksGetResponse 74 from io_stockx.models.webhooks_id_get_response import WebhooksIdGetResponse 75 from io_stockx.models.webhooks_post_request import WebhooksPostRequest 76 from io_stockx.models.webhooks_post_response import WebhooksPostResponse
18 - warning: unused-import 19 - warning: unused-import 20 - warning: unused-import 21 - warning: unused-import 22 - warning: unused-import 23 - warning: unused-import 24 - warning: unused-import 25 - warning: unused-import 26 - warning: unused-import 27 - warning: unused-import 28 - warning: unused-import 29 - warning: unused-import 30 - warning: unused-import 31 - warning: unused-import 32 - warning: unused-import 33 - warning: unused-import 34 - warning: unused-import 35 - warning: unused-import 36 - warning: unused-import 37 - warning: unused-import 38 - warning: unused-import 39 - warning: unused-import 40 - warning: unused-import 41 - warning: unused-import 42 - warning: unused-import 43 - warning: unused-import 44 - warning: unused-import 45 - warning: unused-import 46 - warning: unused-import 47 - warning: unused-import 48 - warning: unused-import 49 - warning: unused-import 50 - warning: unused-import 51 - warning: unused-import 52 - warning: unused-import 53 - warning: unused-import 54 - warning: unused-import 55 - warning: unused-import 56 - warning: unused-import 57 - warning: unused-import 58 - warning: unused-import 59 - warning: unused-import 60 - warning: unused-import 61 - warning: unused-import 62 - warning: unused-import 63 - warning: unused-import 64 - warning: unused-import 65 - warning: unused-import 66 - warning: unused-import 67 - warning: unused-import 68 - warning: unused-import 69 - warning: unused-import 70 - warning: unused-import 71 - warning: unused-import 72 - warning: unused-import 73 - warning: unused-import 74 - warning: unused-import 75 - warning: unused-import 76 - warning: unused-import
1 # coding: utf-8 2 3 """ 4 StockX API 5 6 PRERELEASE API - Subject to change before release. Provides access to StockX's public services, allowing end users to query for product and order information. # noqa: E501 7 8 OpenAPI spec version: 1.0.0 9 10 Generated by: https://github.com/swagger-api/swagger-codegen.git 11 """ 12 13 14 import pprint 15 import re # noqa: F401 16 17 import six 18 19 from io_stockx.models.search_hit import SearchHit # noqa: F401,E501 20 21 22 class SearchResults(object): 23 """NOTE: This class is auto generated by the swagger code generator program. 24 25 Do not edit the class manually. 26 """ 27 28 """ 29 Attributes: 30 swagger_types (dict): The key is attribute name 31 and the value is attribute type. 32 attribute_map (dict): The key is attribute name 33 and the value is json key in definition. 34 """ 35 swagger_types = { 36 'hits': 'list[SearchHit]', 37 'nb_hits': 'int' 38 } 39 40 attribute_map = { 41 'hits': 'hits', 42 'nb_hits': 'nbHits' 43 } 44 45 def __init__(self, hits=None, nb_hits=None): # noqa: E501 46 """SearchResults - a model defined in Swagger""" # noqa: E501 47 48 self._hits = None 49 self._nb_hits = None 50 self.discriminator = None 51 52 if hits is not None: 53 self.hits = hits 54 if nb_hits is not None: 55 self.nb_hits = nb_hits 56 57 @property 58 def hits(self): 59 """Gets the hits of this SearchResults. # noqa: E501 60 61 62 :return: The hits of this SearchResults. # noqa: E501 63 :rtype: list[SearchHit] 64 """ 65 return self._hits 66 67 @hits.setter 68 def hits(self, hits): 69 """Sets the hits of this SearchResults. 70 71 72 :param hits: The hits of this SearchResults. # noqa: E501 73 :type: list[SearchHit] 74 """ 75 76 self._hits = hits 77 78 @property 79 def nb_hits(self): 80 """Gets the nb_hits of this SearchResults. # noqa: E501 81 82 83 :return: The nb_hits of this SearchResults. # noqa: E501 84 :rtype: int 85 """ 86 return self._nb_hits 87 88 @nb_hits.setter 89 def nb_hits(self, nb_hits): 90 """Sets the nb_hits of this SearchResults. 91 92 93 :param nb_hits: The nb_hits of this SearchResults. # noqa: E501 94 :type: int 95 """ 96 97 self._nb_hits = nb_hits 98 99 def to_dict(self): 100 """Returns the model properties as a dict""" 101 result = {} 102 103 for attr, _ in six.iteritems(self.swagger_types): 104 value = getattr(self, attr) 105 if isinstance(value, list): 106 result[attr] = list(map( 107 lambda x: x.to_dict() if hasattr(x, "to_dict") else x, 108 value 109 )) 110 elif hasattr(value, "to_dict"): 111 result[attr] = value.to_dict() 112 elif isinstance(value, dict): 113 result[attr] = dict(map( 114 lambda item: (item[0], item[1].to_dict()) 115 if hasattr(item[1], "to_dict") else item, 116 value.items() 117 )) 118 else: 119 result[attr] = value 120 121 return result 122 123 def to_str(self): 124 """Returns the string representation of the model""" 125 return pprint.pformat(self.to_dict()) 126 127 def __repr__(self): 128 """For `print` and `pprint`""" 129 return self.to_str() 130 131 def __eq__(self, other): 132 """Returns true if both objects are equal""" 133 if not isinstance(other, SearchResults): 134 return False 135 136 return self.__dict__ == other.__dict__ 137 138 def __ne__(self, other): 139 """Returns true if both objects are not equal""" 140 return not self == other
22 - refactor: useless-object-inheritance 28 - warning: pointless-string-statement 15 - warning: unused-import 19 - warning: unused-import
1 from __future__ import print_function 2 import time 3 import io_stockx 4 from io_stockx.rest import ApiException 5 from pprint import pprint 6 7 class ExampleConstants: 8 9 AWS_API_KEY = "<API Key>" 10 11 STOCKX_USERNAME = "<StockX Username>" 12 13 STOCKX_PASSWORD = "<StockX Password>" 14 15 DEMO_PRODUCT_ID = "air-jordan-1-retro-high-off-white-chicago" 16 17 DEMO_CUSTOMER_ID = "1471698" 18 19 ENABLE_DEBUG = True 20 21 JWT_HEADER = "Jwt-Authorization"
7 - refactor: too-few-public-methods 2 - warning: unused-import 3 - warning: unused-import 4 - warning: unused-import 5 - warning: unused-import
1 from django.http import HttpResponseRedirect 2 from django.shortcuts import get_object_or_404, render 3 from django.urls import reverse 4 from django.views import generic 5 from django.utils import timezone 6 7 from .models import Answer, Question 8 9 10 def index(request): 11 latest_question_list = Question.objects.order_by('id')[:20] 12 context = {'latest_question_list': latest_question_list} 13 return render(request, 'survey/index.html', context) 14 15 16 def process(request): 17 print('Made it!') 18 return "Hi!"
7 - error: relative-beyond-top-level 16 - warning: unused-argument 1 - warning: unused-import 2 - warning: unused-import 3 - warning: unused-import 4 - warning: unused-import 5 - warning: unused-import 7 - warning: unused-import
1 from django.apps import AppConfig 2 3 4 class SplitterConfig(AppConfig): 5 name = 'splitter'
4 - refactor: too-few-public-methods
1 from django.forms import forms, ModelForm 2 from django.utils.translation import gettext_lazy as _ 3 4 from .models import Bill 5 6 7 class BillCreateForm(ModelForm): 8 class Meta: 9 model = Bill 10 fields = ('title', 'tax_percent', 'tip_percent',) 11 labels = { 12 'title': _('Name'), 13 } 14 help_texts = { 15 'title': _('The current date and time will be used if name field is empty.'), 16 'tax_percent': _('Please enter a percentage value. You can leave this blank and change it later.'), 17 'tip_percent': _('Please enter a percentage value. You can leave this blank and change it later.'), 18 } 19 error_messages = { 20 'title': { 21 'max_length': _("Name is too long."), 22 }, 23 'tax_percent': { 24 'max_digits': _("Too many digits.") 25 }, 26 'tip_percent': { 27 'max_digits': _("Too many digits.") 28 } 29 } 30 31 32 class BillUpdateForm(ModelForm): 33 34 class Meta: 35 model = Bill 36 fields = ('title',) 37 labels = { 38 'title': _('Name'), 39 } 40 41 42 class BillUpdateTaxPercentForm(ModelForm): 43 44 # def __init__(self, *args, **kwargs): 45 # initial = kwargs.get('initial', {}) 46 # initial['tax'] = 0 47 # kwargs['initial'] = initial 48 # super(BillUpdateTaxPercentForm, self).__init__(*args, **kwargs) 49 50 class Meta: 51 model = Bill 52 fields = ('tax_percent',) 53 help_texts = { 54 'tax_percent': _('Please enter a percent(%) amount.') 55 } 56 57 58 class BillUpdateTaxAmountForm(ModelForm): 59 class Meta: 60 model = Bill 61 fields = ('tax',) 62 help_texts = { 63 'tax': _('Please enter a currency amount.') 64 } 65 66 67 class BillUpdateTipForm(ModelForm): 68 class Meta: 69 model = Bill 70 fields = ('tip',) 71 labels = { 72 'tip': _('Tip/Service Charge'), 73 } 74 help_texts = { 75 'tip': _('Please enter currency amount.') 76 } 77 78 79 class BillUpdateTipPercentForm(ModelForm): 80 class Meta: 81 model = Bill 82 fields = ('tip_percent',) 83 labels = { 84 'tip_percent': _('Tip/Service Charge Percent'), 85 } 86 help_texts = { 87 'tip': _('Please enter a percent(%) amount.') 88 }
4 - error: relative-beyond-top-level 8 - refactor: too-few-public-methods 7 - refactor: too-few-public-methods 34 - refactor: too-few-public-methods 32 - refactor: too-few-public-methods 50 - refactor: too-few-public-methods 42 - refactor: too-few-public-methods 59 - refactor: too-few-public-methods 58 - refactor: too-few-public-methods 68 - refactor: too-few-public-methods 67 - refactor: too-few-public-methods 80 - refactor: too-few-public-methods 79 - refactor: too-few-public-methods 1 - warning: unused-import
1 # Generated by Django 3.1.2 on 2020-10-12 14:37 2 3 from django.db import migrations, models 4 5 6 class Migration(migrations.Migration): 7 8 dependencies = [ 9 ('splitter', '0009_merge_20201012_2025'), 10 ] 11 12 operations = [ 13 migrations.AddField( 14 model_name='bill', 15 name='tax_percent', 16 field=models.DecimalField(blank=True, decimal_places=5, max_digits=10, null=True), 17 ), 18 ]
6 - refactor: too-few-public-methods
1 # Generated by Django 3.1.2 on 2020-10-15 04:19 2 3 from django.db import migrations, models 4 5 6 class Migration(migrations.Migration): 7 8 dependencies = [ 9 ('splitter', '0010_bill_tax_percent'), 10 ] 11 12 operations = [ 13 migrations.AddField( 14 model_name='bill', 15 name='tip_percent', 16 field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True), 17 ), 18 ]
6 - refactor: too-few-public-methods
1 from django.test import TestCase, RequestFactory 2 from django.urls import reverse 3 from django.contrib.auth import get_user_model 4 from decimal import Decimal 5 6 from .models import Bill, Person, Item 7 8 9 # Create your tests here. 10 class SplitterTests(TestCase): 11 12 def setUp(self): 13 self.user = get_user_model().objects.create_user( 14 username='testuser', 15 email='testuser@email.com', 16 password='testpass', 17 ) 18 self.bill = Bill.objects.create( 19 title='testbill', 20 tip=12.00, 21 tax=13.00, 22 owner=self.user, 23 ) 24 self.person = Person.objects.create( 25 name='testperson', 26 bill=self.bill 27 ) 28 self.item = Item.objects.create( 29 title='testitem', 30 price=14.00, 31 person=self.person, 32 bill=self.bill, 33 ) 34 self.shared_item = Item.objects.create( 35 title='testshareditem', 36 price=15.00, 37 bill=self.bill, 38 shared=True, 39 ) 40 # Testing tax percent/amount 41 self.bill_two = Bill.objects.create( 42 title='testbill2', 43 tip_percent=15, 44 tax_percent=8.875, 45 owner=self.user, 46 ) 47 self.item_two = Item.objects.create( 48 title='testitem2', 49 price=14.00, 50 bill=self.bill_two, 51 shared=True, 52 ) 53 self.bill_total = self.item.price + self.shared_item.price + self.bill.tax + self.bill.tip 54 self.shared_item_total = self.bill.tip + self.bill.tax + self.shared_item.price 55 self.bill_detail_response = self.client.get(self.bill.get_absolute_url()) 56 self.bill_two_response = self.client.get(self.bill_two.get_absolute_url()) 57 58 def test_bill_object(self): 59 self.assertEqual(self.bill.title, 'testbill') 60 self.assertEqual(self.bill.tip, 12.00) 61 self.assertEqual(self.bill.tax, 13.00) 62 self.assertEqual(self.bill.owner, self.user) 63 64 def test_bill_list_view_for_logged_in_user(self): 65 self.client.login(email='testuser@email.com', password='testpass') 66 response = self.client.get(reverse('bill-list')) 67 self.assertEqual(response.status_code, 200) 68 self.assertContains(response, 'testbill'.title()) 69 self.assertTemplateUsed(response, 'splitter/bill_list.html') 70 71 def test_bill_list_view_for_logged_out_users(self): 72 response = self.client.get(reverse('bill-list')) 73 self.assertEqual(response.status_code, 200) 74 75 def test_bill_detail_view(self): 76 no_response = self.client.get('/bill/12345/') 77 self.assertEqual(self.bill_detail_response.status_code, 200) 78 self.assertEqual(no_response.status_code, 404) 79 self.assertContains(self.bill_detail_response, 'testbill'.title()) 80 self.assertContains(self.bill_detail_response, '12.00') 81 self.assertContains(self.bill_detail_response, '13.00') 82 self.assertContains(self.bill_detail_response, self.item.price) 83 self.assertContains(self.bill_detail_response, self.shared_item.price) 84 self.assertContains(self.bill_detail_response, self.bill_total) 85 self.assertTemplateUsed(self.bill_detail_response, 'splitter/bill_detail.html') 86 87 def test_person_object(self): 88 self.assertEqual(self.person.name, 'testperson') 89 self.assertEqual(self.person.bill, self.bill) 90 91 def test_person_object_in_bill_detail_view(self): 92 self.assertContains(self.bill_detail_response, 'testperson'.title()) 93 94 def test_item_object(self): 95 self.assertEqual(self.item.title, 'testitem') 96 self.assertEqual(self.item.price, 14.00) 97 self.assertEqual(self.item.bill, self.bill) 98 self.assertEqual(self.item.person, self.person) 99 100 def test_item_object_in_bill_detail_view(self): 101 self.assertContains(self.bill_detail_response, 'testitem') 102 self.assertContains(self.bill_detail_response, 14.00) 103 104 def test_shared_item_object(self): 105 self.assertEqual(self.shared_item.title, 'testshareditem') 106 self.assertEqual(self.shared_item.price, 15.00) 107 self.assertEqual(self.shared_item.bill, self.bill) 108 109 def test_shared_item_object_in_bill_detail_view(self): 110 self.assertContains(self.bill_detail_response, 'testshareditem') 111 self.assertContains(self.bill_detail_response, 15.00) 112 113 def test_bill_model_methods(self): 114 """Tests for Bill model methods.""" 115 116 # Bill.get_order_total() 117 self.assertEqual(self.bill.get_order_grand_total(), self.bill_total) 118 119 # Bill.get_shared_items_total() 120 self.assertEqual(self.bill.get_shared_items_total(), self.shared_item.price) 121 122 def test_person_model_methods(self): 123 """Tests for Person model methods.""" 124 125 # Person.get_shared_items_split() 126 self.assertEqual(self.person.get_shared_items_split(), self.shared_item_total) 127 128 # Person.get_person_total() 129 self.assertEqual(self.person.get_person_total(), self.bill.get_order_grand_total()) 130 131 def test_bill_calculate_tax(self): 132 self.assertContains(self.bill_two_response, Decimal(self.bill_two.get_tax_amount())) 133 self.assertContains(self.bill_two_response, self.bill_two.tax_percent) 134 self.bill_two.tax = 12.00 135 self.assertContains(self.bill_two_response, Decimal(self.bill_two.tax)) 136 137 def test_bill_calculate_tip(self): 138 self.assertContains(self.bill_two_response, Decimal(self.bill_two.get_tip_amount())) 139 self.assertContains(self.bill_two_response, self.bill_two.tip_percent) 140 self.bill_two.tip = 12.00 141 self.assertContains(self.bill_two_response, Decimal(self.bill_two.tip)) 142 143 def test_bill_saves_session(self): 144 self.client.session.create() 145 self.bill_three = Bill.objects.create( 146 title='testbill3', 147 session=self.client.session.session_key, 148 ) 149 self.assertEqual(self.bill_three.session, self.client.session.session_key)
6 - error: relative-beyond-top-level 10 - refactor: too-many-instance-attributes 145 - warning: attribute-defined-outside-init 1 - warning: unused-import
1 """ 2 Django settings for config project. 3 Generated by 'django-admin startproject' using Django 3.1.1. 4 For more information on this file, see 5 https://docs.djangoproject.com/en/3.1/topics/settings/ 6 For the full list of settings and their values, see 7 https://docs.djangoproject.com/en/3.1/ref/settings/ 8 """ 9 10 from pathlib import Path 11 from environs import Env 12 13 env = Env() 14 env.read_env() 15 16 17 # Build paths inside the project like this: BASE_DIR / 'subdir'. 18 BASE_DIR = Path(__file__).resolve().parent.parent 19 20 21 # Quick-start development settings - unsuitable for production 22 # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ 23 24 # SECURITY WARNING: keep the secret key used in production secret! 25 SECRET_KEY = env("DJANGO_SECRET_KEY") 26 27 # SECURITY WARNING: don't run with debug turned on in production! 28 DEBUG = env.bool("DJANGO_DEBUG", default=False) 29 30 ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=[]) 31 32 # Application definition 33 34 INSTALLED_APPS = [ 35 'django.contrib.admin', 36 'django.contrib.auth', 37 'django.contrib.contenttypes', 38 'django.contrib.sessions', 39 'django.contrib.messages', 40 'whitenoise.runserver_nostatic', 41 'django.contrib.staticfiles', 42 'django.contrib.sites', 43 44 # Third party apps 45 'crispy_forms', 46 'allauth', 47 'allauth.account', 48 'debug_toolbar', 49 50 # My apps 51 'users', 52 'pages', 53 'splitter', 54 ] 55 56 MIDDLEWARE = [ 57 'django.middleware.security.SecurityMiddleware', 58 'whitenoise.middleware.WhiteNoiseMiddleware', 59 'django.contrib.sessions.middleware.SessionMiddleware', 60 'django.middleware.common.CommonMiddleware', 61 'django.middleware.csrf.CsrfViewMiddleware', 62 'django.contrib.auth.middleware.AuthenticationMiddleware', 63 'django.contrib.messages.middleware.MessageMiddleware', 64 'django.middleware.clickjacking.XFrameOptionsMiddleware', 65 'debug_toolbar.middleware.DebugToolbarMiddleware', 66 ] 67 68 # # Cache settings 69 # CACHE_MIDDLEWARE_ALIAS = 'default' 70 # CACHE_MIDDLEWARE_SECONDS = 604800 71 # CACHE_MIDDLEWARE_KEY_PREFIX = '' 72 73 ROOT_URLCONF = 'config.urls' 74 75 TEMPLATES = [ 76 { 77 'BACKEND': 'django.template.backends.django.DjangoTemplates', 78 'DIRS': [str(BASE_DIR.joinpath('templates'))], 79 'APP_DIRS': True, 80 'OPTIONS': { 81 'context_processors': [ 82 'django.template.context_processors.debug', 83 'django.template.context_processors.request', 84 'django.contrib.auth.context_processors.auth', 85 'django.contrib.messages.context_processors.messages', 86 ], 87 }, 88 }, 89 ] 90 91 WSGI_APPLICATION = 'config.wsgi.application' 92 93 94 # Database 95 # https://docs.djangoproject.com/en/3.1/ref/settings/#databases 96 97 DATABASES = { 98 'default': env.dj_db_url( 99 "DATABASE_URL", default="postgres://postgres@db/postgres") 100 } 101 102 103 # Password validation 104 # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators 105 106 AUTH_PASSWORD_VALIDATORS = [ 107 { 108 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 109 }, 110 { 111 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 112 }, 113 { 114 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 115 }, 116 { 117 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 118 }, 119 ] 120 121 122 # Internationalization 123 # https://docs.djangoproject.com/en/3.1/topics/i18n/ 124 125 LANGUAGE_CODE = 'en-us' 126 127 TIME_ZONE = 'UTC' 128 129 USE_I18N = True 130 131 USE_L10N = True 132 133 USE_TZ = True 134 135 136 # Static files (CSS, JavaScript, Images) 137 # https://docs.djangoproject.com/en/3.1/howto/static-files/ 138 139 # Static file settings 140 STATIC_URL = '/static/' 141 STATICFILES_DIRS = (str(BASE_DIR.joinpath('static')),) 142 STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles')) 143 STATICFILES_FINDERS = [ 144 "django.contrib.staticfiles.finders.FileSystemFinder", 145 "django.contrib.staticfiles.finders.AppDirectoriesFinder", 146 ] 147 STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' 148 149 AUTH_USER_MODEL = 'users.CustomUser' 150 151 # Crispy settings 152 CRISPY_TEMPLATE_PACK = 'bootstrap4' 153 154 # django-allauth config 155 LOGIN_REDIRECT_URL = 'home' 156 ACCOUNT_LOGOUT_REDIRECT_URL = 'home' 157 SITE_ID = 1 158 AUTHENTICATION_BACKENDS = ( 159 'django.contrib.auth.backends.ModelBackend', 160 'allauth.account.auth_backends.AuthenticationBackend', 161 ) 162 EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', 163 default='django.core.mail.backends.console.EmailBackend') 164 ACCOUNT_USERNAME_REQUIRED = False 165 ACCOUNT_EMAIL_REQUIRED = True 166 ACCOUNT_AUTHENTICATION_METHOD = "email" 167 ACCOUNT_UNIQUE_EMAIL = True 168 ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False 169 170 171 # Email settings 172 DEFAULT_FROM_EMAIL = 'lamgoesbam@gmail.com' 173 EMAIL_HOST = 'smtp.sendgrid.net' 174 EMAIL_HOST_USER = 'apikey' 175 EMAIL_HOST_PASSWORD = env("DJANGO_EMAIL_HOST_PASSWORD", default='') 176 EMAIL_PORT = 587 177 EMAIL_USE_TLS = True 178 179 # django-debug-toolbar 180 import socket 181 hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) 182 INTERNAL_IPS = [ip[:-1] + "1" for ip in ips] 183 184 # Security settings 185 SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) 186 SECURE_HSTS_SECONDS = env.int("DJANGO_SECURE_HSTS_SECONDS", default=2592000) 187 SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True) 188 SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True) 189 SESSION_COOKIE_SECURE = env.bool("DJANGO_SESSION_COOKIE_SECURE", default=True) 190 CSRF_COOKIE_SECURE = env.bool("DJANGO_CSRF_COOKIE_SECURE", default=True) 191 SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
Clean Code: No Issues Detected
1 from django.test import TestCase 2 from django.urls import reverse, resolve 3 from django.contrib.auth import get_user_model 4 from .views import HomePageView 5 6 7 # Create your tests here. 8 class HomepageTests(TestCase): 9 10 def setUp(self): 11 url = reverse('home') 12 self.response = self.client.get(url) 13 self.user = get_user_model().objects.create_user( 14 username='testuser', 15 email='testuser@email.com', 16 password='testpass', 17 ) 18 19 def test_homepage_status_code(self): 20 self.assertEqual(self.response.status_code, 200) 21 22 def test_homepage_template(self): 23 self.assertTemplateUsed(self.response, 'home.html') 24 25 def test_homepage_contains_correct_html_while_logged_out(self): 26 self.assertContains(self.response, 'Create a new split. Log in or sign up to save your splits.') 27 self.assertContains(self.response, 'Sign up') 28 29 def test_homepage_contains_correct_html_while_logged_in(self): 30 self.client.login(email='testuser@email.com', password='testpass') 31 self.assertContains(self.response, 'Create a new split.') 32 33 def test_homepage_does_not_contain_incorrect_html(self): 34 self.assertNotContains(self.response, 'Should not contain this') 35 36 def test_homepage_url_resolves_homepageview(self): 37 view = resolve('/') 38 self.assertEqual( 39 view.func.__name__, HomePageView.as_view().__name__ 40 ) 41 42
4 - error: relative-beyond-top-level
1 # Generated by Django 3.1.2 on 2020-10-08 03:39 2 3 from django.db import migrations, models 4 5 6 class Migration(migrations.Migration): 7 8 dependencies = [ 9 ('splitter', '0002_auto_20201007_2310'), 10 ] 11 12 operations = [ 13 migrations.AlterField( 14 model_name='bill', 15 name='tax', 16 field=models.DecimalField(blank=True, decimal_places=2, max_digits=15, null=True), 17 ), 18 migrations.AlterField( 19 model_name='bill', 20 name='tip', 21 field=models.DecimalField(blank=True, decimal_places=2, max_digits=15, null=True), 22 ), 23 ]
6 - refactor: too-few-public-methods
1 # Generated by Django 3.1.2 on 2020-10-08 03:10 2 3 from django.db import migrations, models 4 5 6 class Migration(migrations.Migration): 7 8 dependencies = [ 9 ('splitter', '0001_initial'), 10 ] 11 12 operations = [ 13 migrations.AlterField( 14 model_name='item', 15 name='title', 16 field=models.CharField(blank=True, max_length=50, null=True), 17 ), 18 migrations.AlterField( 19 model_name='person', 20 name='name', 21 field=models.CharField(max_length=30), 22 ), 23 ]
6 - refactor: too-few-public-methods
1 # Generated by Django 3.1.2 on 2020-10-08 02:57 2 3 from django.conf import settings 4 from django.db import migrations, models 5 import django.db.models.deletion 6 import uuid 7 8 9 class Migration(migrations.Migration): 10 11 initial = True 12 13 dependencies = [ 14 migrations.swappable_dependency(settings.AUTH_USER_MODEL), 15 ] 16 17 operations = [ 18 migrations.CreateModel( 19 name='Bill', 20 fields=[ 21 ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), 22 ('title', models.CharField(blank=True, max_length=50, null=True)), 23 ('date_created', models.DateTimeField(auto_now_add=True)), 24 ('tip', models.DecimalField(blank=True, decimal_places=2, max_digits=15)), 25 ('tax', models.DecimalField(blank=True, decimal_places=2, max_digits=15)), 26 ('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), 27 ], 28 ), 29 migrations.CreateModel( 30 name='Person', 31 fields=[ 32 ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), 33 ('name', models.CharField(max_length=20)), 34 ('bill', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='people', to='splitter.bill')), 35 ], 36 options={ 37 'verbose_name_plural': 'people', 38 }, 39 ), 40 migrations.CreateModel( 41 name='Item', 42 fields=[ 43 ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), 44 ('title', models.CharField(max_length=50)), 45 ('price', models.DecimalField(decimal_places=2, max_digits=15)), 46 ('shared', models.BooleanField(default=False)), 47 ('bill', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='splitter.bill')), 48 ('person', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='items', to='splitter.person')), 49 ], 50 ), 51 ]
9 - refactor: too-few-public-methods
1 # Generated by Django 3.1.2 on 2020-10-09 02:06 2 3 from django.db import migrations, models 4 5 6 class Migration(migrations.Migration): 7 8 dependencies = [ 9 ('splitter', '0003_auto_20201007_2339'), 10 ] 11 12 operations = [ 13 migrations.AlterField( 14 model_name='bill', 15 name='tax', 16 field=models.DecimalField(blank=True, decimal_places=2, default=0, max_digits=15, null=True), 17 ), 18 migrations.AlterField( 19 model_name='bill', 20 name='tip', 21 field=models.DecimalField(blank=True, decimal_places=2, default=0, max_digits=15, null=True), 22 ), 23 ]
6 - refactor: too-few-public-methods
1 # Generated by Django 3.1.2 on 2020-10-12 20:25 2 3 from django.db import migrations 4 5 6 class Migration(migrations.Migration): 7 8 dependencies = [ 9 ('splitter', '0008_auto_20201011_1907'), 10 ('splitter', '0008_auto_20201011_0301'), 11 ] 12 13 operations = [ 14 ]
6 - refactor: too-few-public-methods
1 from django.contrib import admin 2 from .models import Bill, Person, Item 3 4 # Register your models here. 5 admin.site.register(Bill) 6 admin.site.register(Person) 7 admin.site.register(Item)
2 - error: relative-beyond-top-level
1 class BillUpdateViewMixin(object): 2 3 def form_valid(self, form): 4 bill = get_object_or_404(Bill, id=self.kwargs['pk']) 5 form.instance.bill = bill 6 return super().form_valid(form)
1 - refactor: useless-object-inheritance 4 - error: undefined-variable 4 - error: undefined-variable 1 - refactor: too-few-public-methods
1 # Generated by Django 3.1.2 on 2020-10-09 14:38 2 3 from django.db import migrations 4 5 6 class Migration(migrations.Migration): 7 8 dependencies = [ 9 ('splitter', '0004_auto_20201008_2206'), 10 ('splitter', '0004_auto_20201009_1430'), 11 ] 12 13 operations = [ 14 ]
6 - refactor: too-few-public-methods
1 # Generated by Django 3.1.2 on 2020-10-16 21:25 2 3 from django.db import migrations, models 4 5 6 class Migration(migrations.Migration): 7 8 dependencies = [ 9 ('splitter', '0011_bill_tip_percent'), 10 ] 11 12 operations = [ 13 migrations.AddField( 14 model_name='bill', 15 name='session', 16 field=models.CharField(blank=True, max_length=40, null=True), 17 ), 18 ]
6 - refactor: too-few-public-methods
1 # Generated by Django 3.1.2 on 2020-10-09 16:06 2 3 from django.db import migrations, models 4 5 6 class Migration(migrations.Migration): 7 8 dependencies = [ 9 ('splitter', '0006_auto_20201009_1603'), 10 ] 11 12 operations = [ 13 migrations.AddIndex( 14 model_name='item', 15 index=models.Index(fields=['id'], name='item_id_index'), 16 ), 17 migrations.AddIndex( 18 model_name='person', 19 index=models.Index(fields=['id'], name='person_id_index'), 20 ), 21 ]
6 - refactor: too-few-public-methods
1 from django.test import TestCase 2 from django.contrib.auth import get_user_model 3 from django.urls import reverse, resolve 4 from .forms import CustomUserCreationForm, CustomUserChangeForm 5 6 7 # Create your tests here. 8 class CustomUserTests(TestCase): 9 10 def test_create_user(self): 11 User = get_user_model() 12 user = User.objects.create( 13 username='test', 14 email='test@email.com', 15 password='test123', 16 ) 17 self.assertEqual(user.username, 'test') 18 self.assertEqual(user.email, 'test@email.com') 19 self.assertTrue(user.is_active) 20 self.assertFalse(user.is_staff) 21 self.assertFalse(user.is_superuser) 22 23 def test_create_superuser(self): 24 User = get_user_model() 25 super_user = User.objects.create_superuser( 26 username='superuser', 27 email='superuser@email.com', 28 password='super123', 29 ) 30 self.assertEqual(super_user.username, 'superuser') 31 self.assertEqual(super_user.email, 'superuser@email.com') 32 self.assertTrue(super_user.is_active) 33 self.assertTrue(super_user.is_staff) 34 self.assertTrue(super_user.is_superuser) 35 36 37 class SignupPageTests(TestCase): 38 39 username = 'testuser' 40 email = 'testuser@email.com' 41 42 def setUp(self): 43 url = reverse('account_signup') 44 self.response = self.client.get(url) 45 46 def test_signup_template(self): 47 self.assertEqual(self.response.status_code, 200) 48 self.assertTemplateUsed(self.response, 'account/signup.html') 49 self.assertContains(self.response, 'Sign up') 50 self.assertNotContains(self.response, 'Should not contain this') 51 52 def test_signup_form(self): 53 new_user = get_user_model().objects.create_user( 54 self.username, self.email 55 ) 56 self.assertEqual(get_user_model().objects.all().count(), 1) 57 self.assertEqual( 58 get_user_model().objects.all()[0].username, 'testuser' 59 ) 60 self.assertEqual( 61 get_user_model().objects.all()[0].email, 'testuser@email.com' 62 )
4 - error: relative-beyond-top-level 53 - warning: unused-variable 3 - warning: unused-import 4 - warning: unused-import 4 - warning: unused-import
1 import uuid 2 from django.db import models 3 from django.contrib.auth import get_user_model 4 from django.urls import reverse 5 from decimal import Decimal 6 7 from .utils import _check_tip_tax_then_add 8 9 10 # Create your models here. 11 class Bill(models.Model): 12 id = models.UUIDField( 13 primary_key=True, 14 default=uuid.uuid4, 15 editable=False 16 ) 17 title = models.CharField(max_length=50, blank=True, null=True) 18 owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, blank=True) 19 session = models.CharField(max_length=40, null=True, blank=True) 20 date_created = models.DateTimeField(auto_now_add=True) 21 tip = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) 22 tip_percent = models.DecimalField(max_digits=10, decimal_places=3, blank=True, null=True) 23 tax = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) 24 tax_percent = models.DecimalField(max_digits=10, decimal_places=5, blank=True, null=True) 25 26 class Meta: 27 indexes = [ 28 models.Index(fields=['id'], name='id_index'), 29 ] 30 31 def __str__(self): 32 if not self.title: 33 return self.date_created.strftime("%m/%d/%y %I:%M%p") 34 else: 35 return self.title.title() 36 37 def get_tax_amount(self): 38 subtotal = self.get_order_subtotal() 39 if self.tax_percent: 40 tax_amount = (subtotal * (Decimal(self.tax_percent / 100))) 41 bill = Bill.objects.get(id=self.id) 42 bill.tax = tax_amount 43 bill.save() 44 return Decimal(tax_amount).quantize(Decimal('.01')) 45 elif self.tax: 46 return Decimal(self.tax).quantize(Decimal('.01')) 47 else: 48 return 0 49 50 def get_tip_amount(self): 51 subtotal = self.get_order_subtotal() + self.get_tax_amount() 52 if self.tip_percent: 53 tip_amount = (subtotal * (Decimal(self.tip_percent / 100))) 54 bill = Bill.objects.get(id=self.id) 55 bill.tip = tip_amount 56 bill.save() 57 return Decimal(tip_amount).quantize(Decimal('.01')) 58 elif self.tip: 59 return Decimal(self.tip).quantize(Decimal('.01')) 60 else: 61 return 0 62 63 def get_order_grand_total(self): 64 # Returns the sum of all items including tax and tip 65 total = _check_tip_tax_then_add(self) + self.get_order_subtotal() 66 return Decimal(total) 67 68 def get_order_subtotal(self): 69 total = 0 70 items = Item.objects.filter(bill=self) 71 for item in items: 72 total += Decimal(item.price) 73 return Decimal(total) 74 75 def get_shared_items_total(self): 76 # Returns sum of shared items only 77 total = 0 78 items = Item.objects.filter(shared=True, bill=self) 79 for item in items: 80 total += Decimal(item.price) 81 return Decimal(total) 82 83 def get_absolute_url(self): 84 return reverse('bill-detail', args=[self.id]) 85 86 87 class Person(models.Model): 88 id = models.UUIDField( 89 primary_key=True, 90 default=uuid.uuid4, 91 editable=False 92 ) 93 name = models.CharField(max_length=30) 94 bill = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='people') 95 96 class Meta: 97 verbose_name_plural = 'people' 98 indexes = [ 99 models.Index(fields=['id'], name='person_id_index'), 100 ] 101 102 def __str__(self): 103 return self.name.title() 104 105 def get_shared_items_split(self): 106 # Returns the amount every person owes inside the shared items including tax and tip 107 total = _check_tip_tax_then_add(self.bill) 108 person_count = self.bill.people.all().count() 109 items = self.bill.items.filter(shared=True) 110 for item in items: 111 total += Decimal(item.price) 112 split_amount = Decimal(total / person_count) 113 return Decimal(split_amount) 114 115 def get_person_total(self): 116 # Returns the sum of the person's items and their share of the shared items total 117 total = 0 118 items = Item.objects.filter(person=self) 119 for item in items: 120 total += Decimal(item.price) 121 return Decimal(total + self.get_shared_items_split()).quantize(Decimal('.01')) 122 123 def get_absolute_url(self): 124 return reverse('bill-detail', args=[self.bill.id]) 125 126 127 class Item(models.Model): 128 id = models.UUIDField( 129 primary_key=True, 130 default=uuid.uuid4, 131 editable=False 132 ) 133 title = models.CharField(max_length=50, blank=True, null=True) 134 price = models.DecimalField(max_digits=15, decimal_places=2) 135 person = models.ForeignKey( 136 Person, 137 on_delete=models.CASCADE, 138 related_name='items', 139 blank=True, 140 null=True 141 ) 142 bill = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='items') 143 shared = models.BooleanField(default=False) 144 145 class Meta: 146 indexes = [ 147 models.Index(fields=['id'], name='item_id_index'), 148 ] 149 150 def __str__(self): 151 return self.title 152 153 def get_absolute_url(self): 154 return reverse('bill-detail', args=[self.bill.id])
7 - error: relative-beyond-top-level 26 - refactor: too-few-public-methods 32 - refactor: no-else-return 39 - refactor: no-else-return 52 - refactor: no-else-return 96 - refactor: too-few-public-methods 145 - refactor: too-few-public-methods
1 from django.urls import path 2 3 from .views import ( 4 BillCreateView, 5 BillDetailView, 6 PersonCreateView, 7 PersonDeleteView, 8 BillListView, 9 ItemCreateView, 10 ItemDeleteView, 11 SharedItemCreateView, 12 BillUpdateView, 13 BillUpdateTaxPercentView, 14 BillUpdateTaxAmountView, 15 BillUpdateTipAmountView, 16 BillUpdateTipPercentView, 17 BillDeleteView, 18 ) 19 20 21 urlpatterns = [ 22 # Bill links 23 path('new/', BillCreateView.as_view(), name='bill-create'), 24 path('<uuid:pk>/', BillDetailView.as_view(), name='bill-detail'), 25 path('archive/', BillListView.as_view(), name='bill-list'), 26 path('<uuid:pk>/update/', BillUpdateView.as_view(), name='bill-update'), 27 path('<uuid:pk>/update-tax-percent/', 28 BillUpdateTaxPercentView.as_view(), 29 name='bill-update-tax-percent'), 30 path('<uuid:pk>/update-tax-amount/', 31 BillUpdateTaxAmountView.as_view(), 32 name='bill-update-tax-amount'), 33 path('<uuid:pk>/update-tip-amount/', BillUpdateTipAmountView.as_view(), name='bill-update-tip'), 34 path('<uuid:pk>/update-tip-percent/', 35 BillUpdateTipPercentView.as_view(), 36 name='bill-update-tip-percent'), 37 path('<uuid:pk>/delete/', BillDeleteView.as_view(), name='bill-delete'), 38 39 # Person links 40 path('<uuid:pk>/add-person/', PersonCreateView.as_view(), name='person-create'), 41 path('person/<uuid:pk>/delete/', PersonDeleteView.as_view(), name='person-delete'), 42 43 # Item links 44 path('<uuid:bill_id>/<uuid:person_id>/add-item/', 45 ItemCreateView.as_view(), 46 name='item-create' 47 ), 48 path('<uuid:bill_id>/add-shared-item/', 49 SharedItemCreateView.as_view(), 50 name='shared-item-create' 51 ), 52 path('item/<uuid:pk>/item-delete/', ItemDeleteView.as_view(), name='item-delete'), 53 ]
3 - error: relative-beyond-top-level
1 from django.views.generic import CreateView, DetailView, DeleteView, ListView, UpdateView 2 from django.shortcuts import get_object_or_404 3 from django.urls import reverse_lazy 4 from django.http import Http404 5 from decimal import Decimal 6 7 from .models import Bill, Person, Item 8 from .forms import (BillCreateForm, 9 BillUpdateForm, 10 BillUpdateTaxPercentForm, 11 BillUpdateTaxAmountForm, 12 BillUpdateTipForm, 13 BillUpdateTipPercentForm) 14 # from .mixins import BillUpdateViewMixin 15 16 17 # Create your views here. 18 class BillCreateView(CreateView): 19 template_name = 'splitter/bill_create.html' 20 form_class = BillCreateForm 21 22 def form_valid(self, form): 23 if self.request.user.is_authenticated: 24 form.instance.owner = self.request.user 25 return super().form_valid(form) 26 else: 27 self.request.session.create() 28 form.instance.session = self.request.session.session_key 29 return super().form_valid(form) 30 31 32 class BillDetailView(DetailView): 33 model = Bill 34 template_name = 'splitter/bill_detail.html' 35 context_object_name = 'bill' 36 37 def get_context_data(self, **kwargs): 38 context = super().get_context_data(**kwargs) 39 context['people'] = Person.objects.filter( 40 bill=self.object.id) 41 context['shared_items'] = Item.objects.filter(bill=self.object.id, shared=True) 42 if self.object.tax_percent: 43 context['tax_percentage'] = Decimal(self.object.tax_percent).quantize(Decimal('0.001')) 44 if self.object.tip_percent: 45 context['tip_percentage'] = Decimal(self.object.tip_percent.quantize(Decimal('0'))) 46 return context 47 48 def get_object(self, queryset=None): 49 pk = self.kwargs.get('pk') 50 obj = get_object_or_404(Bill, id=pk) 51 if self.request.user.is_authenticated and self.request.user == obj.owner: 52 return obj 53 elif self.request.session.session_key == obj.session: 54 return obj 55 else: 56 raise Http404 57 58 59 class PersonCreateView(CreateView): 60 model = Person 61 template_name = 'splitter/person_create.html' 62 fields = ('name',) 63 64 def form_valid(self, form): 65 bill = get_object_or_404(Bill, id=self.kwargs['pk']) 66 form.instance.bill = bill 67 return super().form_valid(form) 68 69 70 class BillDeleteView(DeleteView): 71 model = Bill 72 template_name = 'splitter/bill_delete.html' 73 74 def get_success_url(self): 75 return reverse_lazy('bill-list') 76 77 78 class BillListView(ListView): 79 template_name = 'splitter/bill_list.html' 80 context_object_name = 'bills' 81 82 def get_queryset(self): 83 if self.request.user.is_authenticated: 84 qs = Bill.objects.filter(owner=self.request.user).order_by('-date_created') 85 elif self.request.session.session_key: 86 qs = Bill.objects.filter(session=self.request.session.session_key).order_by('-date_created') 87 else: 88 qs = None 89 return qs 90 91 92 class PersonDeleteView(DeleteView): 93 model = Person 94 template_name = 'splitter/person_delete.html' 95 96 def get_success_url(self): 97 return reverse_lazy('bill-detail', args=[self.object.bill.id]) 98 99 100 class ItemCreateView(CreateView): 101 model = Item 102 template_name = 'splitter/item_create.html' 103 fields = ('title', 'price',) 104 105 def form_valid(self, form): 106 bill = get_object_or_404(Bill, id=self.kwargs['bill_id']) 107 person = get_object_or_404(Person, id=self.kwargs['person_id']) 108 form.instance.bill = bill 109 form.instance.person = person 110 return super().form_valid(form) 111 112 113 class SharedItemCreateView(CreateView): 114 model = Item 115 template_name = "splitter/item_create.html" 116 fields = ('title', 'price',) 117 118 def form_valid(self, form): 119 bill = get_object_or_404(Bill, id=self.kwargs['bill_id']) 120 form.instance.bill = bill 121 form.instance.shared = True 122 return super().form_valid(form) 123 124 125 class ItemDeleteView(DeleteView): 126 model = Item 127 template_name = 'splitter/item_delete.html' 128 129 def get_success_url(self): 130 return reverse_lazy('bill-detail', args=[self.object.bill.id]) 131 132 133 class BillUpdateView(UpdateView): 134 model = Bill 135 template_name = 'splitter/bill_update.html' 136 form_class = BillUpdateForm 137 138 def form_valid(self, form): 139 bill = get_object_or_404(Bill, id=self.kwargs['pk']) 140 form.instance.bill = bill 141 return super().form_valid(form) 142 143 144 class BillUpdateTaxPercentView(UpdateView): 145 model = Bill 146 form_class = BillUpdateTaxPercentForm 147 template_name = 'splitter/bill_update_tax_percent.html' 148 149 def form_valid(self, form): 150 bill = get_object_or_404(Bill, id=self.kwargs['pk']) 151 form.instance.bill = bill 152 form.instance.tax = None 153 return super().form_valid(form) 154 155 156 class BillUpdateTaxAmountView(UpdateView): 157 model = Bill 158 form_class = BillUpdateTaxAmountForm 159 template_name = 'splitter/bill_update_tax_amount.html' 160 161 def form_valid(self, form): 162 bill = get_object_or_404(Bill, id=self.kwargs['pk']) 163 form.instance.bill = bill 164 form.instance.tax_percent = None 165 return super().form_valid(form) 166 167 168 class BillUpdateTipAmountView(UpdateView): 169 model = Bill 170 form_class = BillUpdateTipForm 171 template_name = 'splitter/bill_update_tip.html' 172 173 def form_valid(self, form): 174 bill = get_object_or_404(Bill, id=self.kwargs['pk']) 175 form.instance.bill = bill 176 form.instance.tip_percent = None 177 return super().form_valid(form) 178 179 180 class BillUpdateTipPercentView(UpdateView): 181 model = Bill 182 form_class = BillUpdateTipPercentForm 183 template_name = 'splitter/bill_update_tip_percent.html' 184 185 def form_valid(self, form): 186 bill = get_object_or_404(Bill, id=self.kwargs['pk']) 187 form.instance.bill = bill 188 form.instance.tip = None 189 return super().form_valid(form)
7 - error: relative-beyond-top-level 8 - error: relative-beyond-top-level 23 - refactor: no-else-return 18 - refactor: too-few-public-methods 51 - refactor: no-else-return 48 - warning: unused-argument 59 - refactor: too-few-public-methods 70 - refactor: too-few-public-methods 78 - refactor: too-few-public-methods 92 - refactor: too-few-public-methods 100 - refactor: too-few-public-methods 113 - refactor: too-few-public-methods 125 - refactor: too-few-public-methods 133 - refactor: too-few-public-methods 144 - refactor: too-few-public-methods 156 - refactor: too-few-public-methods 168 - refactor: too-few-public-methods 180 - refactor: too-few-public-methods
1 # Generated by Django 3.1.2 on 2020-10-09 16:03 2 3 from django.db import migrations, models 4 5 6 class Migration(migrations.Migration): 7 8 dependencies = [ 9 ('splitter', '0005_merge_20201009_1438'), 10 ] 11 12 operations = [ 13 migrations.AddIndex( 14 model_name='bill', 15 index=models.Index(fields=['id'], name='id_index'), 16 ), 17 ]
6 - refactor: too-few-public-methods
1 from decimal import Decimal 2 3 4 def _check_tip_tax_then_add(self): 5 # Checks to see if tip or tax is null before adding them to total else it returns 0 6 total = 0 7 tip = self.get_tip_amount() 8 tax = self.get_tax_amount() 9 if tip: 10 total += tip 11 if tax: 12 total += tax 13 return Decimal(total)
Clean Code: No Issues Detected
1 __author__ = 'spotapov' 2 import unittest 3 import string 4 import random 5 from selenium import webdriver 6 7 class HomePageTest(unittest.TestCase): 8 @classmethod 9 def setUpClass(cls): 10 # create a FF window 11 cls.driver = webdriver.Firefox() 12 cls.driver.implicitly_wait(30) 13 cls.driver.maximize_window() 14 15 #go to app HomePage 16 cls.driver.get("http://enterprise-demo.user.magentotrial.com//") 17 18 def test_full_cart(self): 19 # insert some goods to the cart 20 self.driver.get("http://enterprise-demo.user.magentotrial.com/bowery-chino-pants-545.html") 21 22 color = self.driver.find_element_by_xpath("//img[@alt='Charcoal']") 23 color.click() 24 size = self.driver.find_element_by_xpath("//*[@title='32']") 25 size.click() 26 add_to_cart = self.driver.find_element_by_class_name("add-to-cart-buttons") 27 add_to_cart.click() 28 cart = self.driver.find_element_by_css_selector("#header > div > div.skip-links > div > div > a > span.icon") 29 # click on cart 30 cart.click() 31 self.assertTrue("Bowery Chino Pants", self.driver.find_element_by_xpath("//*[@id='cart-sidebar']/li/div/p/a").text) 32 self.assertTrue("$140.00", self.driver.find_element_by_class_name("price").text)
31 - warning: redundant-unittest-assert 32 - warning: redundant-unittest-assert 3 - warning: unused-import 4 - warning: unused-import
1 __author__ = 'spotapov' 2 import unittest 3 import string 4 import random 5 from selenium import webdriver 6 7 class HomePageTest(unittest.TestCase): 8 @classmethod 9 def setUpClass(cls): 10 # create a FF window 11 cls.driver = webdriver.Firefox() 12 cls.driver.implicitly_wait(30) 13 cls.driver.maximize_window() 14 15 #go to app HomePage 16 cls.driver.get("http://enterprise-demo.user.magentotrial.com//") 17 18 def test_search_text_field_max(self): 19 self.driver.get("http://enterprise-demo.user.magentotrial.com//") 20 # get search text box 21 search_field = self.driver.find_element_by_id("search") 22 # check that max attribute is 128 23 self.assertEqual("128", search_field.get_attribute("maxlength")) 24 25 def test_search_text_really_128_max(self): 26 self.driver.get("http://enterprise-demo.user.magentotrial.com//") 27 # get search text box 28 search_field = self.driver.find_element_by_id("search") 29 30 31 text = '' 32 for i in range(0,129): 33 text +=random.choice(string.ascii_letters) 34 35 search_field.send_keys(text) 36 entered_text = search_field.get_attribute("value") 37 self.assertNotEqual(text,entered_text) 38 39 def test_search_button_enabled(self): 40 self.driver.get("http://enterprise-demo.user.magentotrial.com//") 41 # get search button 42 search_button = self.driver.find_element_by_class_name("button") 43 self.assertTrue(search_button.is_enabled()) 44 45 def test_account_link_is_visible(self): 46 self.driver.get("http://enterprise-demo.user.magentotrial.com//") 47 # get link ACCOUNT 48 account_link = self.driver.find_element_by_link_text("ACCOUNT") 49 self.assertTrue(account_link.is_displayed()) 50 51 def test_number_of_links_with_account(self): 52 self.driver.get("http://enterprise-demo.user.magentotrial.com//") 53 # get all links which have Account text 54 account_links = self.driver.find_elements_by_partial_link_text("ACCO") 55 print(account_links) 56 self.assertEqual(2, len(account_links)) 57 for i in account_links: 58 self.assertTrue(i.is_displayed()) 59 60 def test_if_there_are_3_banners(self): 61 self.driver.get("http://enterprise-demo.user.magentotrial.com//") 62 # get promo banners 63 banner_list = self.driver.find_element_by_class_name("promos") 64 print(banner_list) 65 banners = banner_list.find_elements_by_tag_name("img") 66 self.assertEqual(3, len(banners)) 67 68 def test_gift_promo(self): 69 self.driver.get("http://enterprise-demo.user.magentotrial.com//") 70 gift_promo = self.driver.find_element_by_xpath("//img[@alt='Physical & Virtual Gift Cards']") 71 self.assertTrue(gift_promo.is_displayed()) 72 gift_promo.click() 73 # check vip promo is displayed 74 self.assertEqual("Gift Card", self.driver.title) 75 76 def test_shopping_cart_status(self): 77 self.driver.get("http://enterprise-demo.user.magentotrial.com//") 78 # get shopping cart 79 cart = self.driver.find_element_by_css_selector("div.header-minicart span.icon") 80 cart.click() 81 # get message 82 message = self.driver.find_element_by_css_selector("p.empty").text 83 self.assertEqual(message, "You have no items in your shopping cart.") 84 close = self.driver.find_element_by_css_selector("div.minicart-wrapper a.close.skip-link-close") 85 close.click() 86 87 def test_full_cart(self): 88 # insert some goods to the cart 89 self.driver.get("http://enterprise-demo.user.magentotrial.com/bowery-chino-pants-545.html") 90 91 color = self.driver.find_element_by_xpath("//img[@alt='Charcoal']") 92 color.click() 93 size = self.driver.find_element_by_xpath("//*[@title='32']") 94 size.click() 95 add_to_cart = self.driver.find_element_by_class_name("add-to-cart-buttons") 96 add_to_cart.click() 97 cart = self.driver.find_element_by_css_selector("#header > div > div.skip-links > div > div > a > span.icon") 98 # click on cart 99 cart.click() 100 self.assertTrue("Bowery Chino Pants", self.driver.find_element_by_xpath("//*[@id='cart-sidebar']/li/div/p/a").text) 101 self.assertTrue("$140.00", self.driver.find_element_by_class_name("price").text) 102 103 @classmethod 104 def tearDownClass(cls): 105 #close bro 106 cls.driver.quit() 107 if __name__ == '__main__': 108 unittest.main(verbosity=2) 109 110 111
32 - warning: unused-variable 100 - warning: redundant-unittest-assert 101 - warning: redundant-unittest-assert
1 __author__ = 'spotapov' 2 import string 3 import random 4 5 #makes random string of 129 characters 6 def big_text(): 7 text = '' 8 l = 0 9 for i in range(0,129): 10 text += random.choice(string.ascii_letters) 11 print(text) 12 13 for k in text: 14 l = l + 1 15 print(l) 16 17 18 big_text() 19
9 - warning: unused-variable 13 - warning: unused-variable
1 import torch 2 from torch.utils.data import Dataset 3 from PIL import Image, ImageFile 4 5 import numpy as np 6 import pandas as pd 7 from sklearn.model_selection import train_test_split 8 import albumentations as A 9 import torchvision.transforms as transforms 10 11 12 import operator 13 14 ImageFile.LOAD_TRUNCATED_IMAGES = True 15 16 17 class DatasetUtils: 18 """ 19 This class contains utilities for making a Pytorch Dataset. 20 """ 21 22 def __init__( 23 self, train_df, image_path_column, target_column, train_tfms, valid_tfms 24 ): 25 self.train_df = train_df 26 self.image_path_column = image_path_column 27 self.target_column = target_column 28 self.train_tfms = train_tfms 29 self.valid_tfms = valid_tfms 30 31 def splitter(self, valid_size=0.25): 32 train_images, valid_images, train_labels, valid_labels = train_test_split( 33 self.train_df[self.image_path_column], 34 self.train_df[self.target_column], 35 test_size=valid_size, 36 random_state=42, 37 ) 38 return ( 39 train_images.values, 40 train_labels.values, 41 valid_images.values, 42 valid_labels.values, 43 ) 44 45 def make_dataset( 46 self, resize, train_idx=None, val_idx=None, valid_size=0.25, is_CV=None 47 ): 48 if is_CV: 49 train_dataset = CVDataset( 50 train_df, 51 train_idx, 52 self.image_path_column, 53 self.target_column, 54 transform=self.train_tfms, 55 resize=resize, 56 ) 57 58 valid_dataset = CVDataset( 59 train_df, 60 val_idx, 61 self.image_path_column, 62 self.target_column, 63 transform=self.valid_tfms, 64 resize=resize, 65 ) 66 else: 67 68 ( 69 train_image_paths, 70 train_labels, 71 valid_image_paths, 72 valid_labels, 73 ) = self.splitter(valid_size=valid_size) 74 75 train_dataset = SimpleDataset( 76 train_image_paths, train_labels, transform=self.train_tfms 77 ) 78 79 valid_dataset = SimpleDataset( 80 valid_image_paths, valid_labels, transform=self.valid_tfms 81 ) 82 83 return train_dataset, valid_dataset 84 85 86 class SimpleDataset(Dataset): 87 def __init__(self, image_paths, targets, transform=None, resize=224): 88 self.image_paths = image_paths 89 self.targets = targets 90 self.default_tfms = transforms.Compose( 91 [ 92 transforms.Resize((resize, resize)), 93 transforms.ToTensor(), 94 transforms.Normalize( 95 mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] 96 ), 97 ] 98 ) 99 self.transform = transform 100 101 def __getitem__(self, index: int): 102 image = Image.open(self.image_paths[index]) 103 target = self.targets[index] 104 105 if self.transform: 106 image = self.transform(image) 107 108 image = self.default_tfms(image) 109 110 target = torch.tensor(target) 111 112 return image, target 113 114 def __len__(self): 115 return len(self.image_paths) 116 117 118 class CVDataset(Dataset): 119 def __init__( 120 self, 121 df: pd.DataFrame, 122 indices: np.ndarray, 123 image_paths, 124 target_cols, 125 transform=None, 126 resize=224, 127 ): 128 self.df = df 129 self.indices = indices 130 self.transform = transform 131 self.default_tfms = transforms.Compose( 132 [ 133 transforms.Resize((resize, resize)), 134 transforms.ToTensor(), 135 transforms.Normalize( 136 mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] 137 ), 138 ] 139 ) 140 self.image_paths = image_paths 141 self.target_cols = target_cols 142 143 def __getitem__(self, idx: int): 144 image_ids = operator.itemgetter(*self.indices)(self.df[[self.image_paths]]) 145 labels = operator.itemgetter(*self.indices)(self.df[[self.target_cols]]) 146 147 image = Image.open(image_ids[idx]) 148 label = torch.tensor(labels[idx]) 149 150 if self.transform: 151 image = self.transform(image) 152 153 image = self.default_tfms(image) 154 155 return image, label 156 157 def __len__(self): 158 return len(self.indices)
9 - refactor: consider-using-from-import 22 - refactor: too-many-arguments 22 - refactor: too-many-positional-arguments 45 - refactor: too-many-arguments 45 - refactor: too-many-positional-arguments 50 - error: undefined-variable 59 - error: undefined-variable 119 - refactor: too-many-arguments 119 - refactor: too-many-positional-arguments 8 - warning: unused-import
1 import pandas as pd 2 3 4 def make_multiclass_labels(df, label_column, start_from): 5 """ 6 Takes in a pandas dataframe, the label column & a start index. 7 makes the categorical labels into integers 8 You can specify which index to start labelling from 0 or 1. 9 returns a dictionary mapping the label to it's integer value. 10 11 :param df: pd.Dataframe 12 :param label_column: str 13 :param start_from: int(0 or 1) 14 15 :return: Dict 16 """ 17 label_dict = {} 18 for k, v in enumerate(df[label_column].unique(), start=start_from): 19 label_dict[v] = k 20 21 return label_dict
1 - warning: unused-import
1 from tqdm import tqdm 2 import torch 3 import numpy as np 4 5 from tabulate import tabulate 6 7 from ..utils import Meters 8 from MyVision import metrics 9 10 import os 11 import time 12 from itertools import chain 13 import abc 14 15 16 class Trainer: 17 def __init__( 18 self, 19 train_loader, 20 val_loader, 21 test_loader, 22 device, 23 loss, 24 optimizer, 25 model, 26 lr_scheduler, 27 accumulation_steps=1, 28 ): 29 self.train_loader = train_loader 30 self.val_loader = val_loader 31 self.test_loader = test_loader 32 self.device = device 33 self.criterion = loss 34 self.optimizer = optimizer 35 self.model = model 36 self.lr_scheduler = lr_scheduler 37 self.accumulation_steps = accumulation_steps 38 39 def train(self): 40 losses = Meters.AverageMeter("Loss", ":.4e") 41 42 self.model.train() 43 44 tl = tqdm(self.train_loader) 45 for batch_idx, (images, targets) in enumerate(tl, 1): 46 47 self.optimizer.zero_grad() 48 49 images = images.to(self.device) 50 targets = targets.to(self.device) 51 52 outputs = self.model(images) 53 54 loss = self.criterion(outputs, targets) 55 56 loss.backward() 57 58 if batch_idx % self.accumulation_steps == 0: 59 self.optimizer.step() 60 61 losses.update(val=loss.item(), n=images.size(0)) 62 63 return losses.avg 64 65 def validate(self): 66 losses = Meters.AverageMeter("Loss", ":.4e") 67 68 self.model.eval() 69 70 predictions = [] 71 gts = [] 72 73 vl = tqdm(self.val_loader) 74 for batch_idx, (images, targets) in enumerate(vl, 1): 75 images = images.to(self.device) 76 targets = targets.to(self.device) 77 78 outputs = self.model(images) 79 80 loss = self.criterion(outputs, targets) 81 82 predictions = chain(predictions, outputs.detach().cpu().numpy()) 83 gts = chain(gts, targets.detach().cpu().numpy()) 84 85 losses.update(val=loss.item(), n=images.size(0)) 86 87 return np.array(list(predictions)), np.array(list(gts)), losses.avg 88 89 def fit(self, epochs, metric): 90 91 best_loss = 1 92 table_list = [] 93 94 for epoch in range(epochs): 95 96 train_loss = self.train() 97 98 preds, gts, valid_loss = self.validate() 99 100 if valid_loss < best_loss: 101 102 if not os.path.exists("models"): 103 os.mkdir("models") 104 print("[SAVING].....") 105 torch.save( 106 self.model.state_dict(), f"models\\best_model-({epoch}).pth.tar" 107 ) 108 109 if len(np.unique(preds)) > 2: 110 111 multiclass_metrics = ["accuracy"] 112 113 preds = [np.argmax(p) for p in preds] 114 115 score = metrics.ClassificationMetrics()( 116 metric, y_true=gts, y_pred=preds, y_proba=None 117 ) 118 else: 119 binary_metrics = ["auc", "f1", "recall", "precision"] 120 121 preds = [1 if p >= 0.5 else 0 for p in preds] 122 123 score = metrics.ClassificationMetrics()( 124 metric, y_true=gts, y_pred=preds, y_proba=None 125 ) 126 127 table_list.append((epoch, train_loss, valid_loss, score)) 128 129 print( 130 tabulate( 131 table_list, 132 headers=("Epoch", "Train loss", "Validation loss", metric), 133 ) 134 ) 135 136 if self.lr_scheduler: 137 self.lr_scheduler.step(score)
7 - error: relative-beyond-top-level 16 - refactor: too-many-instance-attributes 17 - refactor: too-many-arguments 17 - refactor: too-many-positional-arguments 74 - warning: unused-variable 111 - warning: unused-variable 119 - warning: unused-variable 11 - warning: unused-import 13 - warning: unused-import
1 ''' 2 Project: To build vocabulary. 3 '''
Clean Code: No Issues Detected
1 import sys, socket, subprocess, time, os 2 3 def ricevi(conn): 4 while(True): 5 richiesta = conn.recv(1048000) 6 cmd = richiesta.decode() 7 if cmd.startswith("cd "): 8 os.chdir(cmd) 9 s.send(b"$ ") 10 continue 11 12 risposta = subprocess.run(cmd, shell = True, capture_output = True) 13 data = risposta.stdout + risposta.stderr 14 conn.send(data) 15 16 def conne_client(indirizzo, backlog = 1): 17 try: 18 s = socket.socket() 19 s.bind(indirizzo) 20 s.listen(backlog) 21 print("server in ascolto") 22 except socket.error as errore: 23 print(f"frate qualcosa non va.\nforse c'è un altro server aperto \ncodice erorre: {errore}") 24 time.sleep(15) 25 sys.exit(0) 26 27 conn, indirizzo_client = s.accept() 28 print(f"conne stabilita con il client: {indirizzo_client}") 29 ricevi(conn) 30 31 conne_client(("192.168.1.1", 15000)) # devi cambiare l'indirizzo ip se è differente 32
9 - error: undefined-variable 12 - warning: subprocess-run-check
1 import socket, sys, time 2 3 def comandi(s): 4 while(True): 5 try: 6 print(''' 7 8 Digita un qualsiasi comando. 9 Per uscire dal server e dal progrmma premi "ctrl + c" 10 11 ''') 12 com = input("\n--> ") 13 s.send(com.encode()) 14 dati = s.recv(1048000) 15 print(str(dati, "utf-8")) 16 continue 17 except KeyboardInterrupt: 18 print("uscita dal server in corso...") 19 s.close() 20 time.sleep(4) 21 sys.exit(0) 22 23 except UnicodeDecodeError: 24 print("ATTENZIONE\nil comando inserito non supporta la codifica utf-8, di conseguenza verrà ritornata la sua versione originale.") 25 print(dati) 26 27 28 def conne_server(indirizzo): 29 try: 30 s = socket.socket() 31 s.connect(indirizzo) 32 print(f"conne stabilita con il server all'indirizzo: {indirizzo}") 33 except socket.error as errore: 34 print(f"qualcosa è andato storto durnte la connesione\n{errore}") 35 retry = input("riprovare? Y/N: ") 36 if retry == "Y" or retry == "y": 37 conne_server(indirizzo) 38 else: 39 print("nessuna connessione stabilita. uscita..") 40 sys.exit(0) 41 comandi(s) 42 43 44 if __name__ == "__main__": 45 46 print("Attesa di una connessione al server...") 47 conne_server(("192.168.1.1", 15000)) # devi cambiare l'indirizzo ip se è differente
36 - refactor: consider-using-in
1 import os 2 import glob 3 import time 4 5 os.system('modprobe w1-gpio') 6 os.system('modprobe w1-therm') 7 8 base_dir = '/sys/bus/w1/devices/' 9 10 def get_devices(): 11 devices = glob.glob(base_dir + '28*') 12 for device in devices: 13 yield device + '/w1_slave' 14 15 def read_temp_raw(): 16 devices = get_devices() 17 for device in devices: 18 f = open(device, 'r') 19 lines = f.readlines() 20 f.close() 21 yield device, lines 22 23 def read_temp(): 24 data = read_temp_raw() 25 for item in data: 26 device, lines = item 27 if lines[0].strip()[-3:] != 'YES': 28 print('Device ' + device + ' not ready') 29 continue; 30 print('Read device ' + device) 31 equals_pos = lines[1].find('t=') 32 if equals_pos != -1: 33 temp_string = lines[1][equals_pos+2:] 34 temp_c = float(temp_string) / 1000.0 35 temp_f = temp_c * 9.0 / 5.0 + 32.0 36 yield device, temp_c, temp_f 37 38 while True: 39 data = read_temp() 40 for item in data: 41 print(item) 42 time.sleep(1) 43
11 - warning: bad-indentation 12 - warning: bad-indentation 13 - warning: bad-indentation 16 - warning: bad-indentation 17 - warning: bad-indentation 18 - warning: bad-indentation 19 - warning: bad-indentation 20 - warning: bad-indentation 21 - warning: bad-indentation 24 - warning: bad-indentation 25 - warning: bad-indentation 26 - warning: bad-indentation 27 - warning: bad-indentation 28 - warning: bad-indentation 29 - warning: bad-indentation 29 - warning: unnecessary-semicolon 30 - warning: bad-indentation 31 - warning: bad-indentation 32 - warning: bad-indentation 33 - warning: bad-indentation 34 - warning: bad-indentation 35 - warning: bad-indentation 36 - warning: bad-indentation 39 - warning: bad-indentation 40 - warning: bad-indentation 41 - warning: bad-indentation 42 - warning: bad-indentation 18 - warning: unspecified-encoding 18 - refactor: consider-using-with 24 - warning: redefined-outer-name 25 - warning: redefined-outer-name
1 import os 2 import time 3 import math 4 import pygame, sys 5 from pygame.locals import * 6 import RPi.GPIO as GPIO 7 8 boardRevision = GPIO.RPI_REVISION 9 GPIO.setmode(GPIO.BCM) # use real GPIO numbering 10 GPIO.setup(17,GPIO.IN, pull_up_down=GPIO.PUD_UP) 11 12 pygame.init() 13 14 VIEW_WIDTH = 0 15 VIEW_HEIGHT = 0 16 pygame.display.set_caption('Flow') 17 18 pouring = False 19 lastPinState = False 20 pinState = 0 21 lastPinChange = int(time.time() * 1000) 22 pourStart = 0 23 pinChange = lastPinChange 24 pinDelta = 0 25 hertz = 0 26 flow = 0 27 litersPoured = 0 28 pintsPoured = 0 29 tweet = '' 30 BLACK = (0,0,0) 31 WHITE = (255, 255, 255) 32 33 windowSurface = pygame.display.set_mode((VIEW_WIDTH,VIEW_HEIGHT), FULLSCREEN, 32) 34 FONTSIZE = 48 35 LINEHEIGHT = 52 36 basicFont = pygame.font.SysFont(None, FONTSIZE) 37 38 def renderThings(lastPinChange, pinChange, pinDelta, hertz, flow, pintsPoured, pouring, pourStart, tweet, windowSurface, basicFont): 39 # Clear the screen 40 windowSurface.fill(BLACK) 41 42 # Draw LastPinChange 43 text = basicFont.render('Last Pin Change: '+time.strftime('%H:%M:%S', time.localtime(lastPinChange/1000)), True, WHITE, BLACK) 44 textRect = text.get_rect() 45 windowSurface.blit(text, (40,1*LINEHEIGHT)) 46 47 # Draw PinChange 48 text = basicFont.render('Pin Change: '+time.strftime('%H:%M:%S', time.localtime(pinChange/1000)), True, WHITE, BLACK) 49 textRect = text.get_rect() 50 windowSurface.blit(text, (40,2*LINEHEIGHT)) 51 52 # Draw PinDelta 53 text = basicFont.render('Pin Delta: '+str(pinDelta) + ' ms', True, WHITE, BLACK) 54 textRect = text.get_rect() 55 windowSurface.blit(text, (40,3*LINEHEIGHT)) 56 57 # Draw hertz 58 text = basicFont.render('Hertz: '+str(hertz) + 'Hz', True, WHITE, BLACK) 59 textRect = text.get_rect() 60 windowSurface.blit(text, (40,4*LINEHEIGHT)) 61 62 # Draw instantaneous speed 63 text = basicFont.render('Flow: '+str(flow) + ' L/sec', True, WHITE, BLACK) 64 textRect = text.get_rect() 65 windowSurface.blit(text, (40,5*LINEHEIGHT)) 66 67 # Draw Liters Poured 68 text = basicFont.render('Pints Poured: '+str(pintsPoured) + ' pints', True, WHITE, BLACK) 69 textRect = text.get_rect() 70 windowSurface.blit(text, (40,6*LINEHEIGHT)) 71 72 # Draw Pouring 73 text = basicFont.render('Pouring: '+str(pouring), True, WHITE, BLACK) 74 textRect = text.get_rect() 75 windowSurface.blit(text, (40,7*LINEHEIGHT)) 76 77 # Draw Pour Start 78 text = basicFont.render('Last Pour Started At: '+time.strftime('%H:%M:%S', time.localtime(pourStart/1000)), True, WHITE, BLACK) 79 textRect = text.get_rect() 80 windowSurface.blit(text, (40,8*LINEHEIGHT)) 81 82 # Draw Tweet 83 text = basicFont.render('Tweet: '+str(tweet), True, WHITE, BLACK) 84 textRect = text.get_rect() 85 windowSurface.blit(text, (40,9*LINEHEIGHT)) 86 87 # Display everything 88 pygame.display.flip() 89 90 while True: 91 currentTime = int(time.time() * 1000) 92 if GPIO.input(17): 93 pinState = True 94 else: 95 pinState = False 96 97 for event in pygame.event.get(): 98 if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): 99 pygame.quit() 100 sys.exit() 101 102 # If we have changed pin states low to high... 103 if(pinState != lastPinState and pinState == True): 104 if(pouring == False): 105 pourStart = currentTime 106 pouring = True 107 # get the current time 108 pinChange = currentTime 109 pinDelta = pinChange - lastPinChange 110 if (pinDelta < 1000): 111 # calculate the instantaneous speed 112 hertz = 1000.0000 / pinDelta 113 flow = hertz / (60 * 7.5) # L/s 114 litersPoured += flow * (pinDelta / 1000.0000) 115 pintsPoured = litersPoured * 2.11338 116 117 renderThings(lastPinChange, pinChange, pinDelta, hertz, flow, pintsPoured, pouring, pourStart, tweet, windowSurface, basicFont) 118 lastPinChange = pinChange 119 lastPinState = pinState 120 121
40 - warning: bad-indentation 43 - warning: bad-indentation 44 - warning: bad-indentation 45 - warning: bad-indentation 48 - warning: bad-indentation 49 - warning: bad-indentation 50 - warning: bad-indentation 53 - warning: bad-indentation 54 - warning: bad-indentation 55 - warning: bad-indentation 58 - warning: bad-indentation 59 - warning: bad-indentation 60 - warning: bad-indentation 63 - warning: bad-indentation 64 - warning: bad-indentation 65 - warning: bad-indentation 68 - warning: bad-indentation 69 - warning: bad-indentation 70 - warning: bad-indentation 73 - warning: bad-indentation 74 - warning: bad-indentation 75 - warning: bad-indentation 78 - warning: bad-indentation 79 - warning: bad-indentation 80 - warning: bad-indentation 83 - warning: bad-indentation 84 - warning: bad-indentation 85 - warning: bad-indentation 88 - warning: bad-indentation 91 - warning: bad-indentation 92 - warning: bad-indentation 93 - warning: bad-indentation 94 - warning: bad-indentation 95 - warning: bad-indentation 97 - warning: bad-indentation 98 - warning: bad-indentation 99 - warning: bad-indentation 100 - warning: bad-indentation 103 - warning: bad-indentation 104 - warning: bad-indentation 105 - warning: bad-indentation 106 - warning: bad-indentation 108 - warning: bad-indentation 109 - warning: bad-indentation 110 - warning: bad-indentation 112 - warning: bad-indentation 113 - warning: bad-indentation 114 - warning: bad-indentation 115 - warning: bad-indentation 117 - warning: bad-indentation 118 - warning: bad-indentation 119 - warning: bad-indentation 5 - warning: wildcard-import 6 - refactor: consider-using-from-import 33 - error: undefined-variable 38 - refactor: too-many-arguments 38 - refactor: too-many-positional-arguments 38 - warning: redefined-outer-name 38 - warning: redefined-outer-name 38 - warning: redefined-outer-name 38 - warning: redefined-outer-name 38 - warning: redefined-outer-name 38 - warning: redefined-outer-name 38 - warning: redefined-outer-name 38 - warning: redefined-outer-name 38 - warning: redefined-outer-name 38 - warning: redefined-outer-name 38 - warning: redefined-outer-name 44 - warning: unused-variable 92 - refactor: simplifiable-if-statement 98 - error: undefined-variable 98 - error: undefined-variable 98 - error: undefined-variable 1 - warning: unused-import 3 - warning: unused-import
1 from datetime import datetime 2 3 from flask import render_template, flash, redirect, url_for, request 4 from flask_login import current_user, login_user, logout_user, login_required 5 from flask_babel import _ 6 from werkzeug.urls import url_parse 7 8 from blog import app, db 9 from blog.forms import LoginForm, RegisterForm, EditProfileForm, PostForm, EmptyForm 10 from blog.models import User, Post 11 12 13 @app.before_request 14 def before_request(): 15 if current_user.is_authenticated: 16 current_user.last_seen = datetime.utcnow() 17 db.session.commit() 18 19 20 @app.route('/', methods=['GET', 'POST']) 21 @login_required 22 def index(): 23 form = PostForm() 24 if form.validate_on_submit(): 25 post = Post(body=form.post.data, author=current_user) 26 db.session.add(post) 27 db.session.commit() 28 flash(_('Your post is live now!'), 'info') 29 return redirect(url_for('index')) 30 page = request.args.get('page', 1, type=int) 31 posts = current_user.get_followed_posts().paginate(page, app.config['POST_PER_PAGE'], False) 32 next_url = url_for('index', page=posts.next_num) if posts.has_next else None 33 prev_url = url_for('index', page=posts.prev_num) if posts.has_prev else None 34 app.logger.info('message') 35 return render_template('index.html', posts=posts.items, form=form, next_url=next_url, prev_url=prev_url) 36 37 38 @app.route('/explore') 39 @login_required 40 def explore(): 41 page = request.args.get('page', 1, type=int) 42 posts = Post.query.order_by(Post.timestamp.desc()).paginate(page, app.config['POST_PER_PAGE'], False) 43 next_url = url_for('index', page=posts.next_num) if posts.has_next else None 44 prev_url = url_for('index', page=posts.prev_num) if posts.has_prev else None 45 return render_template('index.html', posts=posts.items, next_url=next_url, prev_url=prev_url) 46 47 48 @app.route('/login', methods=['GET', 'POST']) 49 def login(): 50 if current_user.is_authenticated: 51 return redirect(url_for('index')) 52 form = LoginForm() 53 if form.validate_on_submit(): 54 user = User.query.filter_by(username=form.username.data).first_or_404() 55 if not user or not user.check_password(form.password.data): 56 flash('Invalid username or password', 'error') 57 return redirect(url_for('login')) 58 login_user(user, remember=form.remember_me.data) 59 flash(f'Login successful for {user.username} ({user.email})', 'success') 60 next_page = request.args.get('next') 61 if not next_page or url_parse(next_page).netloc != '': 62 next_page = url_for('index') 63 return redirect(next_page) 64 return render_template('login.html', title='Sign In', form=form) 65 66 67 @app.route('/register', methods=['GET', 'POST']) 68 def register(): 69 if current_user.is_authenticated: 70 redirect(url_for('index')) 71 form = RegisterForm() 72 if form.validate_on_submit(): 73 user = User(username=form.username.data, email=form.email.data) 74 user.set_password(form.password.data) 75 db.session.add(user) 76 db.session.commit() 77 flash('Congratulations, you successfully registered!', 'success') 78 return redirect(url_for('index')) 79 form = RegisterForm() 80 return render_template('register.html', title='Registration', form=form) 81 82 83 @app.route('/logout') 84 def logout(): 85 logout_user() 86 return redirect(url_for('index')) 87 88 89 @app.route('/user/<username>') 90 @login_required 91 def user(username): 92 user = User.query.filter_by(username=username).first_or_404() 93 page = request.args.get('page', 1, type=int) 94 if user == current_user: 95 posts = user.get_followed_posts().paginate(page, app.config['POST_PER_PAGE'], False) 96 else: 97 posts = user.posts.order_by(Post.timestamp.desc()).paginate(page, app.config['POST_PER_PAGE'], False) 98 next_url = url_for('user', username=user.username, page=posts.next_num) if posts.has_next else None 99 prev_url = url_for('user', username=user.username, page=posts.prev_num) if posts.has_prev else None 100 form = EmptyForm() 101 return render_template('user.html', user=user, form=form, posts=posts.items, next_url=next_url, prev_url=prev_url) 102 103 104 @app.route('/edit_profile', methods=['GET', 'POST']) 105 @login_required 106 def edit_profile(): 107 form = EditProfileForm(formdata=request.form, obj=current_user) 108 if form.validate_on_submit(): 109 form.populate_obj(current_user) 110 db.session.commit() 111 flash('Profile successfully updated', 'success') 112 return redirect(url_for('user', username=current_user.username)) 113 return render_template('edit_profile.html', title='Edit Profile', form=form) 114 115 116 @app.route('/follow/<username>', methods=['POST']) 117 @login_required 118 def follow(username): 119 form = EmptyForm() 120 if form.validate_on_submit(): 121 user = User.query.filter_by(username=username).first_or_404() 122 if not user: 123 flash(f'User {username} is not found', 'info') 124 return redirect(url_for('index')) 125 elif user == current_user: 126 flash('You cannot follow yourself', 'info') 127 return redirect(url_for('user', username=username)) 128 else: 129 current_user.follow(user) 130 db.session.commit() 131 flash(f'You are following {username}!', 'success') 132 return redirect(url_for('user', username=username)) 133 else: 134 return redirect(url_for('index')) 135 136 137 @app.route('/unfollow/<username>', methods=['POST']) 138 @login_required 139 def unfollow(username): 140 form = EmptyForm() 141 if form.validate_on_submit(): 142 user = User.query.filter_by(username=username).first_or_404() 143 if not user: 144 flash(f'User {username} is not found', 'info') 145 return redirect(url_for('index')) 146 elif user == current_user: 147 flash('You cannot unfollow yourself', 'info') 148 return redirect(url_for('user', username=username)) 149 else: 150 current_user.unfollow(user) 151 db.session.commit() 152 flash(f'You are unfollowing {username}!', 'info') 153 return redirect(url_for('user', username=username)) 154 else: 155 return redirect(url_for('index'))
54 - warning: redefined-outer-name 73 - warning: redefined-outer-name 92 - warning: redefined-outer-name 121 - warning: redefined-outer-name 122 - refactor: no-else-return 142 - warning: redefined-outer-name 143 - refactor: no-else-return
1 from blog import app, db 2 from blog import routes, models, errors, set_logger 3 4 5 @app.shell_context_processor 6 def make_shell_context(): 7 return { 8 'db': db, 9 'User': models.User, 10 'Post': models.Post 11 } 12 13 14 if __name__ == '__main__': 15 app.run(debug=True)
2 - warning: unused-import 2 - warning: unused-import 2 - warning: unused-import
1 """Add two new column to User 2 3 Revision ID: 5e12ea69ab10 4 Revises: a89dbfef15cc 5 Create Date: 2021-03-29 20:46:23.445651 6 7 """ 8 from alembic import op 9 import sqlalchemy as sa 10 11 12 # revision identifiers, used by Alembic. 13 revision = '5e12ea69ab10' 14 down_revision = 'a89dbfef15cc' 15 branch_labels = None 16 depends_on = None 17 18 19 def upgrade(): 20 # ### commands auto generated by Alembic - please adjust! ### 21 op.add_column('users', sa.Column('about_me', sa.String(length=160), nullable=True)) 22 op.add_column('users', sa.Column('last_seen', sa.DateTime(), nullable=True)) 23 # ### end Alembic commands ### 24 25 26 def downgrade(): 27 # ### commands auto generated by Alembic - please adjust! ### 28 op.drop_column('users', 'last_seen') 29 op.drop_column('users', 'about_me') 30 # ### end Alembic commands ###
Clean Code: No Issues Detected
1 """fix create followers relationship 2 3 Revision ID: 89b140c56c4d 4 Revises: 7d84ff36825f 5 Create Date: 2021-03-30 14:57:47.528704 6 7 """ 8 from alembic import op 9 import sqlalchemy as sa 10 11 12 # revision identifiers, used by Alembic. 13 revision = '89b140c56c4d' 14 down_revision = '7d84ff36825f' 15 branch_labels = None 16 depends_on = None 17 18 19 def upgrade(): 20 # ### commands auto generated by Alembic - please adjust! ### 21 op.create_table('followed_followers', 22 sa.Column('followed_id', sa.Integer(), nullable=True), 23 sa.Column('follower_id', sa.Integer(), nullable=True), 24 sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ), 25 sa.ForeignKeyConstraint(['follower_id'], ['users.id'], ) 26 ) 27 # ### end Alembic commands ### 28 29 30 def downgrade(): 31 # ### commands auto generated by Alembic - please adjust! ### 32 op.drop_table('followed_followers') 33 # ### end Alembic commands ###
Clean Code: No Issues Detected
1 from blog import app, db, manager 2 from blog.models import * 3 4 if __name__ == '__main__': 5 manager.run()
2 - warning: wildcard-import 1 - warning: unused-import 1 - warning: unused-import
1 from flask import Flask, request 2 from flask_sqlalchemy import SQLAlchemy 3 from flask_migrate import Migrate, MigrateCommand 4 from flask_script import Manager 5 from flask_login import LoginManager 6 from flask_bootstrap import Bootstrap 7 from flask_moment import Moment 8 from flask_babel import Babel, lazy_gettext as _l 9 from flask_admin import Admin 10 from flask_admin.contrib.sqla import ModelView 11 12 from config import Config 13 14 15 app = Flask(__name__) 16 app.config.from_object(Config) 17 18 login = LoginManager(app) 19 login.login_view = 'login' 20 login.login_message = _l('Please log in to access this page') 21 login.login_message_category = 'info' 22 23 bootstrap = Bootstrap(app) 24 moment = Moment(app) 25 babel = Babel(app) 26 db = SQLAlchemy(app) 27 migrate = Migrate(app, db) 28 manager = Manager(app) 29 manager.add_command('db', MigrateCommand) 30 31 32 @babel.localeselector 33 def get_locale(): 34 return request.accept_languages.best_match(app.config['LANGUAGES']) 35 36 # from blog import routes, models, errors 37 from blog.models import User, Post 38 39 # Admin Panel 40 admin = Admin(app) 41 admin.add_view(ModelView(User, db.session)) 42 admin.add_view(ModelView(Post, db.session)) 43 44 45 46 47 48
Clean Code: No Issues Detected
1 from openpyxl import Workbook 2 from django.core.exceptions import PermissionDenied 3 from django.http import HttpResponse 4 from datetime import datetime, date 5 from openpyxl.styles import Font 6 from unidecode import unidecode 7 8 class ExportExcelAction: 9 @classmethod 10 def generate_header(cls, admin, model, list_display): 11 def default_format(value): 12 return value.replace('_', ' ').upper() 13 14 header = [] 15 for field_display in list_display: 16 is_model_field = field_display in [f.name for f in model._meta.fields] 17 is_admin_field = hasattr(admin, field_display) 18 if is_model_field: 19 field = model._meta.get_field(field_display) 20 field_name = getattr(field, 'verbose_name', field_display) 21 header.append(default_format(field_name)) 22 elif is_admin_field: 23 field = getattr(admin, field_display) 24 field_name = getattr(field, 'short_description', default_format(field_display)) 25 header.append(default_format(field_name)) 26 else: 27 header.append(default_format(field_display)) 28 return header 29 30 def style_output_file(file): 31 black_font = Font(color='000000', bold=True) 32 for cell in file["1:1"]: 33 cell.font = black_font 34 35 for column_cells in file.columns: 36 length = max(len((cell.value)) for cell in column_cells) 37 length += 10 38 file.column_dimensions[column_cells[0].column_letter].width = length 39 40 return file 41 42 def convert_data_date(value): 43 return value.strftime('%d.%m.%Y') 44 45 def convert_boolean_field(value): 46 if value: 47 return 'Yes' 48 return 'No' 49 50 51 def export_as_xls(self, request, queryset): 52 if not request.user.is_staff: 53 raise PermissionDenied 54 opts = self.model._meta 55 field_names = self.list_display 56 file_name = unidecode(opts.verbose_name) 57 wb = Workbook() 58 ws = wb.active 59 ws.append(ExportExcelAction.generate_header(self, self.model, field_names)) 60 61 for obj in queryset: 62 row = [] 63 for field in field_names: 64 is_admin_field = hasattr(self, field) 65 if is_admin_field: 66 value = getattr(self, field)(obj) 67 else: 68 value = getattr(obj, field) 69 if isinstance(value, datetime) or isinstance(value, date): 70 value = convert_data_date(value) 71 elif isinstance(value, bool): 72 value = convert_boolean_field(value) 73 row.append(str(value)) 74 ws.append(row) 75 76 ws = style_output_file(ws) 77 response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') 78 response['Content-Disposition'] = f'attachment; filename={file_name}.xlsx' 79 wb.save(response) 80 return response 81 export_as_xls.short_description = "Export as excel"
16 - warning: protected-access 19 - warning: protected-access 8 - refactor: too-few-public-methods 54 - warning: protected-access 69 - refactor: consider-merging-isinstance
1 from setuptools import setup 2 3 setup( 4 name='django-admin-export-xlsx', 5 version='1.0.0', 6 author='Rune Hansén Steinnes', 7 author_email='rune.steinnes@renroros.no', 8 packages=['export_xlsx'], 9 url='http://github.com/Ren-Roros-Digital/django-admin-export-xlsx', 10 license='LICENSE.txt', 11 description='Admin action to export xlsx from list_display', 12 long_description=open('README.rst').read(), 13 install_requires=[ 14 "Django >= 3", 15 "unidecode >=1.2", 16 "openpyxl >= 3", 17 ], 18 )
12 - refactor: consider-using-with 12 - warning: unspecified-encoding
1 import pygame 2 from controller import * 3 from menu import * 4 from constants import * 5 6 7 def main(): 8 pygame.init() 9 10 screen = pygame.display.set_mode((display_width, display_height)) 11 12 pygame.display.set_caption("Cannon defend v0.08") 13 14 clock = pygame.time.Clock() 15 16 controller = Controller(screen, pygame.time.Clock()) 17 18 while True: 19 20 controller.set_menu() 21 22 while not controller.game_started: # main menu loop 23 for event in pygame.event.get(): 24 if event.type == pygame.QUIT: 25 return 0 26 else: 27 controller.menu_action(event) 28 controller.draw_new_screen() 29 pygame.display.flip() 30 clock.tick(FPS) 31 32 controller.start_game() 33 34 35 if __name__ == "__main__": 36 main()
2 - warning: wildcard-import 3 - warning: wildcard-import 4 - warning: wildcard-import 10 - error: undefined-variable 10 - error: undefined-variable 16 - error: undefined-variable 24 - refactor: no-else-return 30 - error: undefined-variable
1 import pygame 2 from constants import * 3 4 5 class Death_screen: 6 def __init__(self, screen, *buttons): 7 self.main_block = pygame.Surface((display_width - 200, display_height - 100)) 8 self.main_block.fill(pygame.Color('sienna2')) 9 self.screen = screen 10 self.buttons = buttons 11 12 def draw(self, score): 13 font = pygame.font.Font('freesansbold.ttf', 16) 14 self.draw_main_block() 15 self.screen.blit(font.render("Your score is: {}".format(score), True, BLACK), (80, 70)) 16 for button in self.buttons: 17 button.draw(self.screen) 18 19 def draw_main_block(self): 20 self.screen.blit(self.main_block, (100, 50))
2 - warning: wildcard-import 7 - error: undefined-variable 7 - error: undefined-variable 15 - error: undefined-variable
1 import os.path 2 3 display_height = 600 4 display_width = 1000 5 6 CHARGER_HEIGHT = 60 7 COOLDOWN_WIDTH = 50 8 9 PLAYER_POS_X = 50 10 PLAYER_POS_Y = 430 11 START_CANNON_ANGLE = 25 12 13 MISSILE_POS_X = 70 14 MISSILE_POS_Y = 470 15 ACCELERATION = -2 16 MAX_SHOT_POWER = 50 17 POWER_CHARGE = 5 18 COOLDOWN = 40 19 20 ENEMY_VELOCITY_X = 0 21 ENEMY_VELOCITY_Y = 4 22 TIME_BETWEEN_ENEMIES = 100 23 24 WHITE = (255, 255, 255) 25 BLACK = (0, 0, 0) 26 YELLOW = (255, 255, 51) 27 RED = (255, 0, 0) 28 GREEN = (0, 255, 0) 29 BLUE = (0, 0, 255) 30 31 STOP = 0 32 UP = 1 33 DOWN = -1 34 35 FPS = 30 36 37 # extracting images from their folders 38 start_button_img = os.path.join("data", "start_button.png") 39 quit_button_img = os.path.join("data", "quit_button.png") 40 leaderboard_button_img = os.path.join("data", "leaderboard_button.png") 41 back_button_img = os.path.join("data", "back_button.png") 42 player_img = os.path.join("data", "player_image.png") 43 missile_img = os.path.join("data", "missile_image.png") 44 enemy1_img = os.path.join("data", "enemy1.png") 45 enemy2_img = os.path.join("data", "enemy2.png") 46 enemy3_img = os.path.join("data", "enemy3.png") 47 48 leaderboard_storage = os.path.join("data", "leaderboard.db") 49 computer_scores = dict([ 50 ("Vlad", 100000), 51 ("Misha", 5000), 52 ("Arthur", 2500), 53 ("Max", 2000), 54 ("Kirrilishche", 10) 55 ]) 56
Clean Code: No Issues Detected
1 import shelve 2 import pygame 3 from constants import * 4 5 6 class Leaderboard: 7 def __init__(self, filename, screen): 8 self.file = shelve.open(filename) 9 self.closed = True 10 self.screen = screen 11 self.sorted_leaderboard = [] 12 self.text = [] 13 self.rendered_text = [] 14 self.sorted_leaderboard = [] 15 16 def draw(self): # draw scores one by one 17 counter = 0 18 for score in self.rendered_text: 19 self.screen.blit(score, (display_width / 4, 20 + counter)) # make indent between scores 20 counter += 20 21 22 def generate_text(self): # get scores by one and add it to a str list 23 self.sort_leaderboard() 24 for i in range(len(self.sorted_leaderboard), 0, -1): 25 player_name = self.sorted_leaderboard[i - 1][0] 26 score = self.sorted_leaderboard[i - 1][1] 27 self.text.append("{} |==| {}".format(player_name, score)) 28 29 def render_text(self): 30 font = pygame.font.Font('freesansbold.ttf', 16) 31 for score in self.text: 32 self.rendered_text.append(font.render(score, True, BLACK, WHITE)) 33 34 def add_score(self, player_name, score): 35 if player_name in self.file.keys() and score > self.file[player_name]: 36 self.file[player_name] = score 37 elif player_name not in self.file.keys(): 38 self.file[player_name] = score 39 40 def renew_board(self): 41 self.text = [] 42 self.rendered_text = [] 43 44 def sort_leaderboard(self): 45 self.sorted_leaderboard = [(k, v) for k, v in sorted(self.file.items(), key=lambda item: item[1])] 46
3 - warning: wildcard-import 19 - error: undefined-variable 32 - error: undefined-variable 32 - error: undefined-variable 45 - refactor: unnecessary-comprehension
1 import pygame 2 from constants import * 3 4 5 class MenuButton: 6 """Create a button """ 7 8 def __init__(self, pos_x, pos_y, image, button_type): 9 self.button_type = button_type 10 self.image = pygame.image.load(image).convert_alpha() 11 self.size = self.image.get_rect().size 12 self.rect_pos = self.image.get_rect().move((pos_x, pos_y)) 13 14 def draw(self, screen): 15 screen.blit(self.image, self.rect_pos) 16 17 18 class MainMenu: 19 """manage all of the buttons in menu """ 20 21 def __init__(self, screen, *buttons): 22 self.buttons = buttons 23 self.screen = screen 24 25 def draw(self): 26 for button in self.buttons: 27 self.screen.blit(button.image, button.rect_pos)
2 - warning: wildcard-import 5 - refactor: too-few-public-methods 18 - refactor: too-few-public-methods
1 import pygame 2 from constants import * 3 4 class Terrain: 5 def __init__(self): 6 pass
2 - warning: wildcard-import 4 - refactor: too-few-public-methods 1 - warning: unused-import
1 import pygame 2 import sys 3 import menu 4 import player 5 import leaderboard 6 import death_screen 7 import terrain 8 from constants import * 9 10 11 class Controller: 12 """ 13 Class that control all game actions 14 """ 15 16 def __init__(self, screen, clock): 17 self.screen = screen 18 self.clock = clock 19 20 self.game_started = False 21 22 self.quit_button = menu.MenuButton(display_width / 2 - 150, display_height / 2, quit_button_img, "quit") 23 self.start_button = menu.MenuButton(display_width / 2 - 150, display_height / 4, start_button_img, "start") 24 self.leaderboard_button = menu.MenuButton(display_width / 2 - 450, display_height / 6, leaderboard_button_img, 25 "leaderboard") 26 self.back_button = menu.MenuButton(display_width / 4, display_height - 100, back_button_img, "back") 27 28 self.menu_table = menu.MainMenu(self.screen, self.quit_button, self.start_button, self.leaderboard_button) 29 self.leaderboard_table = leaderboard.Leaderboard(leaderboard_storage, screen) 30 self.create_start_leaderboard() 31 32 self.death_screen_table = death_screen.Death_screen(screen, self.back_button) 33 34 self.game_surface = terrain.Terrain() 35 self.player = player.Player(PLAYER_POS_X, PLAYER_POS_Y, self.screen) 36 37 self.army = player.AlienArmy(self.player, self.screen) 38 39 def menu_action(self, event): 40 if event.type == pygame.MOUSEBUTTONDOWN: 41 for button in self.menu_table.buttons: 42 if button.rect_pos.collidepoint(event.pos): # trigger pressed button 43 self.trigger(button) 44 else: 45 pass 46 47 def back_button_action(self, event): 48 if event.type == pygame.MOUSEBUTTONDOWN and self.back_button.rect_pos.collidepoint(event.pos): 49 self.back_pressed() 50 51 def trigger(self, button): 52 if button.button_type == "quit": 53 self.quit_pressed() 54 elif button.button_type == "start": 55 self.start_pressed() 56 elif button.button_type == "leaderboard": 57 self.leaderboard_pressed() 58 self.show_leaderboard() 59 60 def quit_pressed(self): 61 sys.exit() 62 63 def start_pressed(self): 64 self.game_started = True # make main game loop in main.py start 65 66 def leaderboard_pressed(self): 67 self.leaderboard_table.closed = False 68 69 def back_pressed(self): 70 if not self.leaderboard_table.closed: 71 self.leaderboard_table.closed = True 72 self.leaderboard_table.renew_board() 73 elif self.game_started: 74 self.game_started = False 75 76 def show_leaderboard(self): 77 self.leaderboard_table.generate_text() 78 self.leaderboard_table.render_text() 79 80 while not self.leaderboard_table.closed: 81 for event in pygame.event.get(): 82 if event.type == pygame.QUIT: 83 sys.exit() 84 else: 85 self.back_button_action(event) 86 87 self.screen.fill(WHITE) 88 self.leaderboard_table.draw() 89 self.draw_back_button() 90 pygame.display.flip() 91 self.clock.tick(FPS) 92 93 def create_start_leaderboard(self): 94 for key, item in computer_scores.items(): 95 self.leaderboard_table.add_score(key, item) 96 97 def draw_back_button(self): 98 self.back_button.draw(self.screen) 99 100 def draw_new_screen(self): 101 self.screen.fill(WHITE) 102 self.set_menu() 103 104 def set_menu(self): 105 self.menu_table.draw() 106 107 def start_game(self): 108 self.player_name = self.get_player_name() 109 self.screen.fill(WHITE) 110 self.game_loop() 111 112 def get_player_name(self): 113 player_name = "" 114 flag = True 115 while flag: 116 for event in pygame.event.get(): 117 if event.type == pygame.QUIT: 118 sys.exit() 119 if event.type == pygame.KEYDOWN: 120 if event.key == pygame.K_0: 121 return player_name 122 elif event.key == pygame.K_BACKSPACE: 123 player_name = player_name[:-1] # delete last element of name if backspace pressed 124 elif 97 <= event.key <= 122: 125 player_name += chr(event.key) 126 else: 127 pass 128 self.display_player_name(player_name) 129 130 def display_player_name(self, player_name): 131 font = pygame.font.Font('freesansbold.ttf', 16) 132 left = (display_width / 2) - 250 133 top = (display_height / 2) - 100 134 self.screen.fill(WHITE) 135 pygame.draw.rect(self.screen, YELLOW, (left, top, 320, 150)) 136 self.screen.blit(font.render(player_name, True, BLACK), (left + 80, top + 70)) 137 pygame.display.flip() 138 139 def game_over(self): 140 self.leaderboard_table.add_score(self.player_name, self.army.kill_count) 141 self.death_screen_table.draw(self.army.kill_count) 142 self.army.renew_kill_count() 143 while self.game_started: 144 for event in pygame.event.get(): 145 if event.type == pygame.QUIT: 146 sys.exit() 147 else: 148 self.back_button_action(event) 149 pygame.display.flip() 150 151 def check_for_pause(self, event): 152 if event.type == pygame.KEYDOWN: 153 if event.key == pygame.K_ESCAPE: 154 self.pause_game() 155 156 def pause_game(self): 157 while True: 158 self.draw_back_button() 159 pygame.display.flip() 160 for event in pygame.event.get(): 161 if event.type == pygame.QUIT: 162 sys.exit() 163 if event.type == pygame.KEYDOWN: 164 if event.key == pygame.K_ESCAPE: 165 return 166 167 def game_loop(self): 168 self.player.draw() 169 170 while self.game_started: 171 172 for event in pygame.event.get(): 173 self.player.action(event) 174 self.check_for_pause(event) 175 176 self.player.update_game_elements() 177 self.player.draw_game_elements() 178 179 self.army.update_enemies() 180 181 if self.army.defeat(): 182 self.game_over() 183 184 pygame.display.flip() 185 186 self.clock.tick(FPS)
8 - warning: wildcard-import 11 - refactor: too-many-instance-attributes 22 - error: undefined-variable 22 - error: undefined-variable 22 - error: undefined-variable 23 - error: undefined-variable 23 - error: undefined-variable 23 - error: undefined-variable 24 - error: undefined-variable 24 - error: undefined-variable 24 - error: undefined-variable 26 - error: undefined-variable 26 - error: undefined-variable 26 - error: undefined-variable 29 - error: undefined-variable 35 - error: undefined-variable 35 - error: undefined-variable 87 - error: undefined-variable 91 - error: undefined-variable 94 - error: undefined-variable 101 - error: undefined-variable 109 - error: undefined-variable 120 - refactor: no-else-return 112 - refactor: inconsistent-return-statements 132 - error: undefined-variable 133 - error: undefined-variable 134 - error: undefined-variable 135 - error: undefined-variable 136 - error: undefined-variable 186 - error: undefined-variable 108 - warning: attribute-defined-outside-init
1 #! /usr/bin/python 2 3 header_file = "./blast_config/include/command_list.h" 4 start = False 5 header_single_commands = [] 6 for line in open(header_file, 'r'): 7 if line.startswith("enum singleCommand"): 8 start = True 9 if start: 10 if "}" in line: 11 break 12 line = line.replace("\n", '') 13 line = line.replace(" ", '') 14 line = line.replace("\t", '') 15 words = line.split(",") 16 header_single_commands.extend(words) 17 18 start = False 19 header_multi_commands = [] 20 for line in open(header_file, 'r'): 21 if line.startswith("enum multiCommand"): 22 start = True 23 if start: 24 if "}" in line: 25 break 26 line = line.replace("\n", '') 27 line = line.replace(" ", '') 28 line = line.replace("\t", '') 29 words = line.split(",") 30 header_multi_commands.extend(words) 31 32 header_single_commands = [element for element in header_single_commands if not element.startswith("enum")] 33 header_single_commands = [element for element in header_single_commands if (element != "")] 34 header_multi_commands = [element for element in header_multi_commands if not element.startswith("enum")] 35 header_multi_commands = [element for element in header_multi_commands if (element != "")] 36 37 #print header_single_commands 38 #print header_multi_commands 39 40 #command_list_file = "./blast_config/command_list.c" 41 command_list_file = "./mcp/commanding/commands.c" 42 43 if False: 44 s_commands_not_in_main_list = [] 45 start = False; 46 for single_command in header_single_commands: 47 command_found = False 48 for line in open(command_list_file, 'r'): 49 if "MultiCommand" in line: 50 start = True 51 if start: 52 #if "COMMAND" in line: 53 if "case" in line: 54 if single_command in line: 55 command_found = True 56 print 'I found command', single_command, 'in line: ', line 57 if start and ("default:" in line): 58 start = False 59 if not command_found: 60 s_commands_not_in_main_list.append(single_command) 61 62 #print 'single commands in MultiCommands in commands.c file:', s_commands_not_in_main_list 63 64 if True: 65 m_commands_not_in_main_list = [] 66 start = False; 67 for multi_command in header_multi_commands: 68 command_found = False 69 for line in open(command_list_file, 'r'): 70 #if "COMMAND" in line: 71 if "SingleCommand" in line: 72 start = True 73 if start: 74 if "case" in line: 75 if multi_command in line: 76 command_found = True 77 print 'I found command', multi_command, 'in line: ', line 78 if start and ("default:" in line): 79 start = False 80 if not command_found: 81 m_commands_not_in_main_list.append(multi_command) 82 83 #print '\nmulti commands in SingleCommand in command.c file:', m_commands_not_in_main_list
56 - error: syntax-error
1 #! /usr/bin/env python 2 3 import os 4 import pylab 5 import pyfits 6 7 image_width = 1536 8 image_height = 1024 9 10 def convert(infilename): 11 infile = open(infilename, "r") 12 contents = infile.read() 13 infile.close() 14 flat_data = pylab.fromstring(contents, "uint16") 15 if len(flat_data) != image_width*image_height: 16 print "data has length", len(flat_data), "which does not match", image_width, "*", image_height 17 exit() 18 19 data = [] 20 for j in range(image_height): 21 data.append(flat_data[j*image_width: (j+1)*image_width]) 22 data = pylab.array(data) 23 24 header = pyfits.core.Header() 25 header.update("SIMPLE", "T") 26 header.update("BITPIX", 16) 27 header.update("EXTEND", "T") 28 pyfits.writeto(infilename.replace(".raw", ".fits"), data, header) 29 30 for filename in os.listdir("."): 31 if filename.endswith(".raw"): 32 print "converting", filename 33 convert(filename) 34
16 - error: syntax-error
1 #! /usr/bin/env python 2 3 import pylab 4 import Image 5 6 class Header: 7 pass 8 9 def parse_header(header_str): 10 header = Header() 11 header.tex_width = pylab.fromstring(header_str[4:8], "int32")[0] 12 header.tex_height = pylab.fromstring(header_str[8:12], "int32")[0] 13 header.start_char = pylab.fromstring(header_str[12:16], "int32")[0] 14 header.end_char = pylab.fromstring(header_str[16:20], "int32")[0] 15 return header 16 17 def create_glf(original_filename, image): 18 infile = open(original_filename, "r") 19 contents = infile.read() 20 infile.close() 21 header = parse_header(contents[0:24]) 22 num_chars = header.end_char - header.start_char + 1 23 return contents[0: 24+num_chars*24] + image.tostring() 24 25 def save_file(outdata, outfilename): 26 outfile = open(outfilename, "wb") 27 outfile.write(outdata) 28 outfile.close() 29 30 original_filename = "arial24.glf" 31 infilename = "arial24_with_degrees.png" 32 image = Image.open(infilename) 33 outdata = create_glf(original_filename, image) 34 save_file(outdata, infilename.replace(".png", ".glf")) 35 36
11 - warning: attribute-defined-outside-init 12 - warning: attribute-defined-outside-init 13 - warning: attribute-defined-outside-init 14 - warning: attribute-defined-outside-init 6 - refactor: too-few-public-methods 17 - warning: redefined-outer-name 17 - warning: redefined-outer-name 18 - warning: unspecified-encoding 18 - refactor: consider-using-with 25 - warning: redefined-outer-name 26 - refactor: consider-using-with
1 #!/usr/bin/env /usr/bin/python 2 3 import re 4 from sedobjects import * 5 6 #LABEL -> MATE pins "description" [alpha] [bcd] [M-Mmate] [F-Fmate] 7 connRE = re.compile(r'^' 8 r'([A-Z0-9_]{1,16})\s+->\s+' #LABEL 9 r'([A-Z0-9_]{1,16})\s+' #MATE 10 r'(\d{1,3})\s+' #pins 11 r'"([^"]{1,255})"' #description 12 r'(?:\s*(alpha))?' #alpha 13 r'(?:\s*(bcd))?' #bcd 14 r'(?:\s+M-([mMfF]))?' #mmate 15 r'(?:\s+F-([mMfF]))?' #fmate 16 r'$') 17 18 #CMPNAME "Description of the COMPONENT" [< PARTOF] 19 compRE = re.compile(r'^' 20 r'([A-Z_][A-Z0-9_]{0,7})\s+' #CMPNAME 21 r'"([^"]{1,65})"' #description 22 r'(?:\s+<\s+([A-Z0-9_]{1,8}))?' #PARTOF 23 r'$') 24 25 #JACK [IN] [&]ref "label" CONN/G -> DEST[/jack] [CABLE [&C##] "[desc]" [len]] 26 jackRE = re.compile(r'^JACK' 27 '(?:\s*(IN))?\s+' #IN 28 r'((?:&J?\d{1,5})|[a-z0-9]+)\s+' #ref 29 r'"([^"]{1,32})"\s+' #label 30 r'([A-Z0-9_]{1,16}/[mMfF])\s+->\s+' #CONN/G 31 r'(&?[A-Z0-9_]{1,8})' #DEST 32 r'(?:/((?:&J?\d{1,5})|[a-z0-9]+))?' #/jack 33 r'(?:\s+CABLE' #CABLE 34 r'(?:\s+(&C?[0-9]{1,8}))?\s+' # &C## 35 r'"([^"]{0,64})"' # desc 36 r'(?:\s+(\d+))?' # len 37 r')?$') 38 39 #LINE "description" (jack;pin[,pin2,...])[,(jack;pin[,pin2,...]), ...] 40 lineRE = re.compile(r'^LINE\s+' 41 r'"([^"]{1,64})"\s+' #description 42 r'((?:' 43 r'\((?:(?:&J?\d{1,5})|[a-z0-9]+)[;,]' #jack 44 r'(?:\s*[A-Za-z0-9]{1,3},?)*\),?\s*' #pin 45 r')+)$') 46 47 #CABLE [&]C## "description" [len] 48 cableRE = re.compile(r'^CABLE\s+' 49 r'(&?C?[0-9]{1,8})\s+' #C## 50 r'"([^"]{1,64})"' #description 51 r'(?:\s+([0-9]+))?' #len 52 r'$') 53 54 #lookup table of regular expressions corresponding to object classes 55 RElookup = {Connector: connRE, Component: compRE, Jack: jackRE, 56 Line: lineRE, Cable: cableRE} 57 58 def parse(type, line): 59 """parses the string: line into an object of class: type and returns it""" 60 match = RElookup[type].match(line) 61 if match: 62 return type(*match.groups()) 63 else: 64 return None 65 66 67 if __name__ == "__main__": 68 print "\nCONNECTOR tests" 69 conn1 = ('TYPE -> MATE 10 "TYPE has 10 male pins that go with female MATE" ' 70 'alpha bcd M-F') 71 conn2 = 'CONN -> CONN 0 "A connector with variable num of pins" alpha F-F' 72 conn3 = 'COMM -> COMM 0 "A connector with non-alphanumeric pins" F-F' 73 conn4 = 'TEST -> TEST 10 "A connector to test jack mating" M-F F-M' 74 print (conn1), '\n', parse(Connector,conn1) 75 print (conn2), '\n', parse(Connector, conn2) 76 print (conn3), '\n', parse(Connector, conn3) 77 test_connector = parse(Connector, conn4) 78 test_connector.mate = test_connector 79 print (conn4), '\n', test_connector 80 81 print "\nCOMPONENT tests" 82 comp1 = 'COMPA "COMPA is part of COMP1" < COMP1' 83 comp2 = 'COMP1 "COMP1 is not part of anything"' 84 comp3 = 'some random string that does not match' #bad declaration 85 print (comp1), '\n', parse(Component,comp1) 86 print (comp2), '\n', parse(Component,comp2) 87 print (comp3), '\n', parse(Component,comp3) 88 89 print "\nCABLE tests" 90 cab1 = 'CABLE 12345 "This cable has no length"' 91 cab2 = 'CABLE &C12346 "This cable is 350mm long" 350' 92 print (cab1), '\n', parse(Cable, cab1) 93 print (cab2), '\n', parse(Cable, cab2) 94 95 print "\n JACK tests" 96 jack1 = 'JACK 1 "connects to COMPA with no cable" CONN/M -> COMPA' 97 jack2 = 'JACK &J2 "now has cable" CONN2/F -> COMPB/2 CABLE &C4 "cable, len=?"' 98 jack3 = 'JACK j3 "now has cable" CONN2/F -> COMPB CABLE "cable, len=300" 300' 99 jack4 = 'JACK 4 "cable desc is blank" TEST/M -> COMP CABLE ""' 100 jack5 = 'JACK 5 "a possible mate for jack 4" TEST/M -> COMP CABLE "soemthing"' 101 print (jack1), '\n', parse(Jack, jack1) 102 print (jack2), '\n', parse(Jack, jack2) 103 print (jack3), '\n', parse(Jack, jack3) 104 j4 = parse(Jack, jack4) 105 j4.conn = test_connector 106 print (jack4), '\n', j4 107 j5 = parse(Jack, jack5) 108 j5.conn = test_connector 109 print (jack5), '\n', j5 110 if j5.canMate(j4): print "It CAN mate with jack 4" 111 else: print "It CAN NOT mate with jack 4" 112 113 print "\nLINE tests" 114 line1 = 'LINE "this line has one pin" (&J22,1)' 115 line2 = 'LINE "this one has 4 pins" (0,1),(0,2),(1,A),(1,C)' 116 line3 = 'LINE "shortform for above" (0;1,2),(1;A,C)' 117 print (line1), '\n', parse(Line, line1) 118 print (line2), '\n', parse(Line, line2) 119 print (line3), '\n', parse(Line, line3)
68 - error: syntax-error
1 #!/usr/bin/env /usr/bin/python 2 3 import time 4 import sys 5 import mpd 6 import re 7 import random 8 import pygetdata as gd 9 import numpy as np 10 11 #setup for the mpd connection 12 mpdHost = "galadriel.blast" 13 mpdPort = 6606 14 mpdPass = "250micron" 15 16 #setup for the dirfile 17 dirfilePath = "/data/etc/fox.lnk" 18 19 20 #region to song mapping 21 songNameLookup = { 22 "VYCma": ('title', "YMCA", \ 23 'artist', "Village People, The"), 24 "CG12": ('title', "Don't Stop Believin'", \ 25 'artist', "Journey"), 26 "Spearhead": ('title', 'Theme from "Shaft"', \ 27 'artist', "Hayes, Isaac"), 28 "Mickey": ('title', "Hey Mickey", \ 29 'artist', "Basil, Toni"), 30 "Lupus1a": ('title', "Hungry Like the Wolf", \ 31 'artist', "Duran Duran"), 32 "Lupus1b": ('title', "Walking on Sunshine", \ 33 'artist', "Katrina & the Waves"), 34 "NatsRegion": ('title', "The Good, the Bad, and the Ugly", \ 35 'artist', "Morricone, Ennio"), 36 "IRAS15100": ('title', "Home", \ 37 'artist', "Edward Sharpe & The Magnetic Zeros"), 38 "Nanten": ('title', "Turning Japanese", \ 39 'artist', "Vapors, The"), 40 "M83": ('title', "Eye of the Tiger", \ 41 'artist', "Survivor"), 42 "Axehead": ('artist', "U2"), 43 "CarinaTan": ('title', "O... Saya", \ 44 'artist', "A.R. Rahman & M.I.A."), 45 "G333": ('title', "Not Ready to Make Nice", \ 46 'artist', "Dixie Chicks"), 47 "G331": ('title', "The Cave", \ 48 'artist', "Albarn, Damon / Nyman, Michael"), 49 "G3219": ('title', "To The Dogs Or Whoever", \ 50 'artist', "Josh Ritter"), 51 "G3199": ('album', "Thriller", \ 52 'artist', "Jackson, Michael"), 53 "G3047": ('title', "Oxford Comma", \ 54 'artist', "Vampire Weekend"), 55 "G3237": ('title', "Blame Canada", \ 56 'album', "South Park - Bigger, Longer, & Uncut"), 57 "G3265": ('title', "Hallelujah", \ 58 'artist', "Cohen, Leonard", \ 59 'album', "Various Positions"), 60 "G3290": ('title', "Throne Room and Finale", \ 61 'artist', "Williams, John and the Skywalker Symphony Orchestra"), 62 "G3168": ('title', "Awesome God", \ 63 'artist', "Praise Band"), 64 "CenA": ('title', 'Danger Zone (Theme from "Top Gun")', \ 65 'artist', "Loggins, Kenny"), 66 "NGC4945": ('title', "White Winter Hymnal", \ 67 'artist', "Fleet Foxes", \ 68 'album', "Fleet Foxes") 69 } 70 71 #find songs in the database, make more useful lookup 72 songLookup = dict() 73 client = mpd.MPDClient(); 74 client.connect(mpdHost, mpdPort) 75 client.password(mpdPass) 76 77 for region in songNameLookup.iterkeys(): 78 songs = client.find(*songNameLookup[region]) 79 songLookup[region] = songs 80 print region, len(songs), "song matches" 81 82 client.close() 83 client.disconnect() 84 85 #function to pick random song from list for targets 86 def playSong(key): 87 client.connect(mpdHost, mpdPort) 88 client.password(mpdPass) 89 songs = songLookup[key] 90 song = songs[random.randint(0, len(songs)-1)] 91 pl = client.playlist() 92 cur = client.currentsong() 93 if(pl and cur): 94 idx = client.playlist().index(cur['file']) 95 client.addid(song['file'], idx+1) 96 client.play(idx+1) #length one higher now, with added song 97 else: 98 client.add(song['file']) 99 client.play(len(pl)) 100 client.close() 101 client.disconnect() 102 103 #parse schedule file passed as command line argument 104 schedparser = re.compile(r"\w+\s+(?P<day>[0-9.]+)\s+(?P<hour>[0-9.]+)[^#]*#\s*(?P<name>\S*).*") 105 schedule = []; 106 with open(sys.argv[1]) as f: 107 for line in f: 108 match = schedparser.match(line) 109 if (match): 110 lst = (float(match.group("day"))*24*3600 \ 111 + float(match.group("hour"))*3600) 112 schedule.append( (lst, match.group("name")) ) 113 114 print "\nSchedule parsed with", len(schedule), "command lines" 115 print 116 print "************************************************************" 117 print "* Starting main loop, waiting for new scans *" 118 print "************************************************************" 119 print 120 121 #main loop. read LST_SCHED and if it crosses a schedule threshold, play the song 122 try: 123 while True: 124 df = gd.dirfile(dirfilePath, gd.RDONLY) 125 lst = df.getdata("LST_SCHED", gd.FLOAT, \ 126 first_frame=df.nframes-1, num_frames=1)[0] 127 df.close() 128 newsong = False 129 try: 130 while lst > schedule[1][0]: 131 schedule.pop(0) 132 print "Passed threshold", schedule[0][0], "<", lst, \ 133 "for region", schedule[0][1] 134 newsong = True 135 if newsong: 136 #can't do direct songLookup access because names may have modifier chars 137 for region in songLookup.iterkeys(): 138 if schedule[0][1].find(region) >= 0: 139 print "New song!", schedule[0][1], "matches", region 140 playSong(region) 141 break 142 else: 143 print "Could not find song match for", schedule[0][1] 144 time.sleep(1) 145 except IndexError: 146 print "Schedule out of commands! Do something! Forget about music!" 147 sys.exit(1) 148 149 except KeyboardInterrupt: 150 print "bye" 151
80 - error: syntax-error
1 #!/usr/bin/python 2 import time 3 import numpy as np 4 from datetime import datetime 5 import pygetdata as gd 6 import soco 7 8 DEVICE_ADDRESS = "192.168.0.140" 9 DATAFILE = "/data/etc/mole.lnk" 10 11 sonos = soco.SoCo(DEVICE_ADDRESS) 12 #sonos = soco.discovery.any_soco() 13 df = gd.dirfile(DATAFILE, gd.RDONLY) 14 15 # find the tracks 16 17 def get_current_track_title(): 18 return sonos.get_current_track_info()['title'] 19 20 class AutoSonos: 21 def __init__(self, trackname, fieldname, trueval=None): 22 self.trackname = trackname 23 self.fieldname = fieldname 24 self.trueval = trueval 25 self.timeout = 0 26 self.lastval = 0 27 self.framenum = 0 28 self.changed = False 29 self.timesteady = 0 30 31 self.update() 32 self.track = sonos.music_library.get_tracks(search_term=self.trackname)[0] 33 34 # Checks to see if there is new data in the dirfile 35 # Increments a timeout when there is no new data 36 def has_update(self): 37 num = df.eof(self.fieldname) 38 retval = False 39 if (num != self.framenum): 40 self.timeout = 0 41 retval = True 42 else: 43 self.timeout += 1 44 self.framenum = num 45 return retval 46 47 # General command to be called always in the loop 48 # Loads data from dirfile if necessary 49 def update(self): 50 if (self.has_update()): 51 val = df.getdata(self.fieldname, 52 first_frame=0, 53 first_sample=self.framenum-1, 54 num_frames=0, 55 num_samples=1)[0] 56 if (val != self.lastval): 57 self.changed = True 58 self.timesteady = 0 59 else: 60 self.changed = False 61 self.timesteady += 1 62 self.lastval = val 63 64 # Queues the assigned song 65 # If the song is already playing, doesn't try to play again 66 # If persist=True, will play even if queue is stopped 67 def trigger(self, persist=True, volume=None): 68 if (get_current_track_title() != self.track.title) or (persist and sonos.get_current_transport_info()['current_transport_state'] != 'PLAYING'): 69 if (sonos.get_current_transport_info()['current_transport_state'] == 'PLAYING'): sonos.pause() 70 sonos.add_to_queue(self.track, 1) # add to queue indexing by 1 71 sonos.play_from_queue(0, True) # play from queue indexing from 0 72 if volume is not None: 73 sonos.ramp_to_volume(volume) 74 print("Playing " + self.track.title) 75 return 1 76 return 0 77 78 # Checks if the value in the dirfile has reached the assigned value 79 def truestate(self): 80 return self.lastval == self.trueval 81 82 83 # Looks at field "STATE_POTVALVE" and .truestate() == True when STATE_POTVALVE == 1 84 # When the .trigger() function is called, will play the requested song on the SONOS 85 PotvalveOpen = AutoSonos("Flagpole Sitta", "STATE_POTVALVE", 1) 86 PotvalveOpen2 = AutoSonos("Ooh Pot Valve Open", "STATE_POTVALVE", 1) 87 PotvalveYell = True 88 PotvavleSong = False 89 90 HWPMove = AutoSonos("You Spin Me Round", "MOVE_STAT_HWPR", 1) 91 92 Lunch = AutoSonos("Sandstorm", "TIME") 93 Leave = AutoSonos("End of the World as", "TIME") 94 95 while True: 96 song_requested = False 97 98 # Potvalve open 99 # Logic is in the main loop 100 PotvalveOpen.update() # must always be called in the loop 101 102 # If the truestate is reached and has been true for 20 second, then trigger the song 103 if (PotvalveOpen2.truestate() and (PotvalveOpen.timesteady >= 20) and (PotvalveYell == True)): 104 print("Potvalve is OPEN!") 105 if not song_requested: 106 PotvalveOpen.trigger() 107 song_requested = True 108 PotvalveYell = False 109 PotvavleSong = True 110 111 # If the truestate is reached and has been true for 20 second, then trigger the song 112 if (PotvalveOpen.truestate() and (PotvalveOpen.timesteady >= 20) and (PotvalveSong == True)): 113 print("Potvalve is OPEN!") 114 if not song_requested: 115 PotvalveOpen.trigger() 116 song_requested = True 117 PotvalveYell = True 118 PotvavleSong = False 119 120 # If the HWP move state is 1 we are in state "ready" so we are sending a move command 121 if (HWPMove.truestate()): 122 print("Half-wave plate is moving!") 123 if not song_requested: 124 HWPMove.trigger() 125 song_requested = True 126 127 # time to leave 128 Leave.update() 129 date = datetime.utcfromtimestamp(Leave.lastval) 130 if ((date.hour+13)%24 == 17) and (15 <= date.minute <= 25): 131 print("Time to leave!") 132 if not song_requested: 133 Leave.trigger(volume=65) 134 song_requested = True 135 136 # lunch 137 Lunch.update() 138 date = datetime.utcfromtimestamp(Lunch.lastval) 139 if ((date.hour+13)%24 == 11) and (date.minute >= 56) and (date.second >= 17) and (datetime.today().isoweekday() != 7): 140 print("Lunchtime!") 141 if not song_requested: 142 Lunch.trigger(volume=50) 143 song_requested = True 144 145 146 # reload the datafile if necessary 147 if (Lunch.timeout > 5): 148 df.close() 149 df = gd.dirfile(DATAFILE, gd.RDONLY) 150 print("Reloading \"" + DATAFILE + "\"") 151 152 time.sleep(1)
18 - warning: bad-indentation 21 - warning: bad-indentation 22 - warning: bad-indentation 23 - warning: bad-indentation 24 - warning: bad-indentation 25 - warning: bad-indentation 26 - warning: bad-indentation 27 - warning: bad-indentation 28 - warning: bad-indentation 29 - warning: bad-indentation 31 - warning: bad-indentation 32 - warning: bad-indentation 36 - warning: bad-indentation 37 - warning: bad-indentation 38 - warning: bad-indentation 39 - warning: bad-indentation 40 - warning: bad-indentation 41 - warning: bad-indentation 42 - warning: bad-indentation 43 - warning: bad-indentation 44 - warning: bad-indentation 45 - warning: bad-indentation 49 - warning: bad-indentation 50 - warning: bad-indentation 51 - warning: bad-indentation 56 - warning: bad-indentation 57 - warning: bad-indentation 58 - warning: bad-indentation 59 - warning: bad-indentation 60 - warning: bad-indentation 61 - warning: bad-indentation 62 - warning: bad-indentation 67 - warning: bad-indentation 68 - warning: bad-indentation 69 - warning: bad-indentation 70 - warning: bad-indentation 71 - warning: bad-indentation 72 - warning: bad-indentation 73 - warning: bad-indentation 74 - warning: bad-indentation 75 - warning: bad-indentation 76 - warning: bad-indentation 79 - warning: bad-indentation 80 - warning: bad-indentation 96 - warning: bad-indentation 100 - warning: bad-indentation 103 - warning: bad-indentation 104 - warning: bad-indentation 105 - warning: bad-indentation 106 - warning: bad-indentation 107 - warning: bad-indentation 108 - warning: bad-indentation 109 - warning: bad-indentation 112 - warning: bad-indentation 113 - warning: bad-indentation 114 - warning: bad-indentation 115 - warning: bad-indentation 116 - warning: bad-indentation 117 - warning: bad-indentation 118 - warning: bad-indentation 121 - warning: bad-indentation 122 - warning: bad-indentation 123 - warning: bad-indentation 124 - warning: bad-indentation 125 - warning: bad-indentation 128 - warning: bad-indentation 129 - warning: bad-indentation 130 - warning: bad-indentation 131 - warning: bad-indentation 132 - warning: bad-indentation 133 - warning: bad-indentation 134 - warning: bad-indentation 137 - warning: bad-indentation 138 - warning: bad-indentation 139 - warning: bad-indentation 140 - warning: bad-indentation 141 - warning: bad-indentation 142 - warning: bad-indentation 143 - warning: bad-indentation 147 - warning: bad-indentation 148 - warning: bad-indentation 149 - warning: bad-indentation 150 - warning: bad-indentation 152 - warning: bad-indentation 20 - refactor: too-many-instance-attributes 112 - error: undefined-variable 3 - warning: unused-import
1 #! /usr/bin/env python 2 3 import os 4 import sys 5 import pyfits 6 import pylab 7 8 def load_raw_data(filename): 9 infile = open(filename, "r") 10 data = pylab.fromstring(infile.read(), "uint16") 11 infile.close() 12 return data 13 14 def load_fits_data(filename): 15 infile = pyfits.open(filename) 16 data = infile[0].data.flatten() 17 infile.close() 18 return data 19 20 def diff_image(raw_filename, fits_filename, verbose=False): 21 filestem_raw = os.path.splitext(os.path.split(raw_filename)[-1])[0] 22 filestem_fits = os.path.splitext(os.path.split(fits_filename)[-1])[0] 23 if filestem_fits != filestem_raw: 24 print "warning: files %s and %s don't have the same stem" % (filestem_raw, filestem_fits) 25 if verbose: 26 print "comparison:" 27 raw_data = load_raw_data(raw_filename) 28 if verbose: 29 print "%64s --" % raw_filename, 30 print raw_data 31 fits_data = load_fits_data(fits_filename) 32 if verbose: 33 print "%64s --" % fits_filename, 34 print fits_data 35 differ = False 36 if len(raw_data) != len(fits_data): 37 differ = True 38 elif (raw_data-fits_data).any(): 39 differ = True 40 if differ: 41 print "file %s contents differ" % filestem_raw 42 else: 43 print "file %s contents are identical" % filestem_raw 44 45 def diff_dir(raw_dirname, fits_dirname): 46 for raw_filename in os.listdir(raw_dirname): 47 match_found = False 48 for fits_filename in os.listdir(fits_dirname): 49 full_raw_filename = os.path.join(raw_dirname, raw_filename) 50 full_fits_filename = os.path.join(fits_dirname, fits_filename) 51 raw_stem = os.path.splitext(raw_filename)[0] 52 fits_stem = os.path.splitext(fits_filename)[0] 53 if raw_stem == fits_stem: 54 match_found = True 55 diff_image(full_raw_filename, full_fits_filename, verbose=False) 56 if not match_found: 57 print "could not find match for raw image", raw_filename 58 59 60 def main(): 61 try: 62 raw_filename = sys.argv[1] 63 fits_filename = sys.argv[2] 64 except IndexError: 65 print "Usage: ./diff_raw_with_fits.py raw_filename fits_filename" 66 return 67 if os.path.isdir(raw_filename) and os.path.isdir(fits_filename): 68 diff_dir(raw_filename, fits_filename) 69 else: 70 diff_image(raw_filename, fits_filename, verbose=True) 71 72 if __name__ == "__main__": 73 sys.exit(main()) 74
24 - error: syntax-error
1 #! /usr/bin/env python 2 3 import os 4 5 for filename in os.listdir("."): 6 if filename.endswith(".ez"): 7 outfilename = filename.strip(".ez") 8 command = "ezip -d %s %s" % (filename, outfilename) 9 os.system(command) 10
Clean Code: No Issues Detected
1 #! /usr/bin/env python 2 3 import stars_log_parser 4 import pylab as pl 5 6 def plot_solution_fit(solution): 7 exaggeration = 100.0 8 star_xs = pl.array(map(lambda match: match.star.fitted_x, solution.matches)) 9 star_ys = pl.array(map(lambda match: match.star.fitted_y, solution.matches)) 10 blob_xs = pl.array(map(lambda match: match.blob.x, solution.matches)) 11 blob_ys = pl.array(map(lambda match: match.blob.y, solution.matches)) 12 error_xs = (blob_xs - star_xs)*exaggeration 13 error_ys = (blob_ys - star_ys)*exaggeration 14 pl.plot(star_xs, star_ys, 'ro', label="star_positions") 15 for i in range(len(star_xs)): 16 label = None 17 if i == 0: 18 label = "error toward blob position\n(exaggerated %.1f)"%exaggeration 19 pl.plot([star_xs[i], star_xs[i]+error_xs[i]], [star_ys[i], star_ys[i]+error_ys[i]],\ 20 'b-', label=label) 21 pl.legend() 22 pl.xlabel("pixel x-coordinate") 23 pl.ylabel("pixel y-coordinate") 24 25 last_logname = stars_log_parser.get_last_logname("../../output_dir/logs", "solving") 26 last_solution = stars_log_parser.get_solutions(last_logname)[-1] 27 plot_solution_fit(last_solution) 28 pl.show() 29
Clean Code: No Issues Detected
1 #! /usr/bin/env python 2 3 import os 4 import pylab as pl 5 import stars_log_parser as parser 6 7 def plot_fluxes(solution): 8 print "plotting flux for", solution.filename 9 print "solution had fit %d blobs and ignored %d blobs" \ 10 % (solution.fluxer.num_blobs_fit, solution.fluxer.num_blobs_ignored) 11 print "solution had best fit exposure", solution.fluxer.best_fit_exposure, "s" 12 star_fluxes = map(lambda match: match.star.flux, solution.matches) 13 blob_fluxes = map(lambda match: match.blob.flux, solution.matches) 14 pl.plot(star_fluxes, blob_fluxes, 'o') 15 xlim = list(pl.xlim()) 16 xlim[0] = 0 17 max_x = max(star_fluxes) * 1.1 18 xlim[1] = max_x 19 ylim = list(pl.ylim()) 20 ylim[0] = 0 21 pl.plot([0, max_x], [0, max_x*solution.fluxer.best_fit_line], '-') 22 pl.xlim((xlim)) 23 pl.ylim((ylim)) 24 pl.xlabel("star flux (electrons / m^s / s)") 25 pl.ylabel("blob flux (ADU)") 26 27 last_solving_logname = parser.get_last_logname("../../output_dir/logs", "solving") 28 print "using", last_solving_logname 29 print "using last solution" 30 solutions = parser.get_solutions(last_solving_logname) 31 plot_fluxes(solutions[-1]) 32 pl.show() 33
8 - error: syntax-error
1 from pylab import pi 2 3 def from_hours(angle): 4 return angle*pi/12. 5 6 def to_hours(angle): 7 return angle*12./pi 8 9 def from_degrees(angle): 10 return angle*pi/180. 11 12 def to_degrees(angle): 13 return angle*180./pi 14 15 def to_arcmin(angle): 16 return angle*180./pi*60. 17 18 def from_arcmin(angle): 19 return angle/60.*pi/180. 20 21 def to_arcsec(angle): 22 return angle*180./pi*3600. 23 24 def from_arcsec(angle): 25 return angle/3600.*pi/180. 26
Clean Code: No Issues Detected
1 #! /usr/bin/env python 2 3 import pylab 4 import Image 5 6 class Header: 7 pass 8 9 def parse_header(header_str): 10 header = Header() 11 header.tex_width = pylab.fromstring(header_str[4:8], "int32")[0] 12 header.tex_height = pylab.fromstring(header_str[8:12], "int32")[0] 13 header.start_char = pylab.fromstring(header_str[12:16], "int32")[0] 14 header.end_char = pylab.fromstring(header_str[16:20], "int32")[0] 15 return header 16 17 def load_glf(filename): 18 infile = open(filename, "r") 19 contents = infile.read() 20 infile.close() 21 header = parse_header(contents[0:24]) 22 num_chars = header.end_char - header.start_char + 1 23 characters_str = contents[24: 24+num_chars*24] 24 num_tex_bytes = header.tex_width * header.tex_height * 2; 25 tex_bytes = contents[24+num_chars*24: 24+num_chars*24 + num_tex_bytes] 26 image = Image.fromstring("LA", [header.tex_width, header.tex_height], tex_bytes) 27 return image 28 29 filename = "arial24.glf" 30 image = load_glf(filename) 31 #image.show() 32 image.save(filename.replace(".glf", ".png")) 33 34 # To preserve transparency, edit with gimp, and when saving 35 # deselect "Save color values from transparent pixels". 36
24 - warning: unnecessary-semicolon 11 - warning: attribute-defined-outside-init 12 - warning: attribute-defined-outside-init 13 - warning: attribute-defined-outside-init 14 - warning: attribute-defined-outside-init 6 - refactor: too-few-public-methods 17 - warning: redefined-outer-name 26 - warning: redefined-outer-name 18 - warning: unspecified-encoding 18 - refactor: consider-using-with 23 - warning: unused-variable
1 #!/usr/bin/env python 2 # coding: utf-8 3 4 # In[1]: 5 6 7 import requests 8 from bs4 import BeautifulSoup 9 import re 10 import pandas as pd 11 from tqdm import tqdm 12 import json 13 14 15 # In[3]: 16 17 18 with open('data.json', 'w') as f: 19 json.dump({}, f) 20 21 22 # In[ ]: 23 24 25 data={} 26 for j in tqdm(range(0,1843)): 27 url = "https://www.openrice.com/en/hongkong/restaurants?sortBy=BookmarkedDesc&page=" 28 page = j+1 29 headers = requests.utils.default_headers() 30 headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' 31 response = requests.get(url+"?page="+str(j), headers=headers) 32 response = response.text 33 soup = BeautifulSoup(response, "html.parser") 34 35 content = soup.find(class_='sr1-listing-content-cells pois-restaurant-list js-poi-list-content-cell-container') 36 37 data[j] = content.prettify() 38 39 if j % 10 == 0: 40 with open('data.json') as f: 41 file = json.load(f) 42 43 file.update(data) 44 45 with open('data.json', 'w') as f: 46 json.dump(file, f) 47 48 data = {} 49 50 51 # In[ ]: 52 53 54 55
18 - warning: unspecified-encoding 31 - warning: missing-timeout 40 - warning: unspecified-encoding 45 - warning: unspecified-encoding 9 - warning: unused-import 10 - warning: unused-import
1 #!/usr/bin/env python 2 # coding: utf-8 3 4 # In[1]: 5 6 7 import pandas as pd 8 import json 9 from random import randint 10 from time import sleep 11 import requests 12 from tqdm import tqdm 13 import numpy as np 14 15 16 # ### Clan the district, cuisine, dish columns 17 18 19 df = pd.read_csv('restaurant_clean.csv', index_col=0) 20 21 22 # In[18]: 23 24 25 def ogcioparser_dict(address): 26 data = {"q":address, "n":1} #n means only send 1 27 headers ={"Accept": "application/json"} 28 api_url = "https://www.als.ogcio.gov.hk/lookup" 29 res = requests.post(api_url, data=data, headers=headers, timeout=(5, 14)) 30 add = json.loads(res.text) 31 add_dict = {} 32 add_dict['Northing'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Northing'] 33 add_dict['Easting'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Easting'] 34 add_dict['Longitude'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Longitude'] 35 add_dict['Latitude'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Latitude'] 36 return add_dict 37 38 39 # In[28]: 40 41 42 addresses = df['address'] 43 44 45 # In[29]: 46 47 48 all_dict = {} 49 50 51 # In[31]: 52 53 54 sleep_counter = 0 55 56 57 # In[32]: 58 59 for i, a in enumerate(tqdm(addresses)): 60 all_dict[i] = ogcioparser_dict(a) 61 sleep_counter +=1 62 if sleep_counter % 500 == 0: 63 sleep(randint(5,10)) 64 65 66 # In[ ]: 67 68 df_parse = pd.DataFrame.from_dict(all_dict, orient='index') 69 70 df_parse.to_csv('parse.csv')
13 - warning: unused-import
1 #!/usr/bin/env python 2 # coding: utf-8 3 4 # In[1]: 5 6 7 import requests 8 from bs4 import BeautifulSoup 9 import re 10 import pandas as pd 11 from tqdm import tqdm 12 import json 13 14 15 # In[3]: 16 17 18 with open('data.json') as f: 19 data = json.load(f) 20 21 22 # In[2]: 23 24 25 df = pd.DataFrame(columns =['name','review','bookmark','smile','sad','address','district','cuisine','dish']) 26 27 28 # In[236]: 29 30 31 for k in tqdm(range(len(data))): 32 soup = BeautifulSoup(data[str(k)], "html.parser") 33 for i in range(len(soup.find_all(class_='title-name'))): 34 rest = {} 35 rest['name'] = soup.find_all(class_='title-name')[i].text.strip() 36 review = soup.find_all(class_="counters-container")[i].text.strip() 37 rest['review'] = int(*re.findall('\d+', review)) 38 rest['bookmark'] = soup.find_all(class_="text bookmarkedUserCount js-bookmark-count")[i]['data-count'] 39 rest['smile'] = soup.find_all(class_="emoticon-container smile-face pois-restaurant-list-cell-content-right-info-rating-happy")[i].text.strip() 40 rest['sad'] = soup.find_all(class_="emoticon-container sad-face pois-restaurant-list-cell-content-right-info-rating-sad")[i].text.strip() 41 rest['address'] = soup.find_all(class_='icon-info-wrapper')[i].find('span').find(text=True).strip() 42 rest['district'] = soup.find_all(class_='icon-info-wrapper')[i].find('a').text 43 rest['cuisine'] = soup.find_all(class_="icon-info icon-info-food-name")[i].find_all('a')[0].text 44 rest['dish'] = soup.find_all(class_="icon-info icon-info-food-name")[i].find_all('a')[1].text 45 df = df.append(rest, ignore_index=True) 46 47 48 # In[ ]: 49 50 51 df.to_csv('restaurant.csv') 52 53 54 # In[ ]: 55 56 57 58
37 - warning: anomalous-backslash-in-string 18 - warning: unspecified-encoding 7 - warning: unused-import
1 #!/usr/bin/env python 2 # coding: utf-8 3 4 # In[2]: 5 6 7 import pandas as pd 8 import json 9 from random import randint 10 from time import sleep 11 import requests 12 from tqdm import tqdm 13 import numpy as np 14 15 16 # ### Clan the district, cuisine, dish columns 17 18 # In[3]: 19 20 21 df = pd.read_csv('restaurant_clean.csv', index_col=0) 22 23 24 # In[ ]: 25 26 27 with open('all_restaurant.json', 'w') as f: 28 json.dump({}, f) 29 30 31 # In[15]: 32 33 34 re_dict={} 35 36 37 # In[18]: 38 39 40 def ogcioparser_dict(address): 41 data = {"q":address, "n":1} #n means only send 1 42 headers ={"Accept": "application/json"} 43 api_url = "https://www.als.ogcio.gov.hk/lookup" 44 res = requests.post(api_url, data=data, headers=headers, timeout=(5, 14)) 45 add = json.loads(res.text) 46 add_dict = {} 47 add_dict['Latitude'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Latitude'] 48 add_dict['Longitude'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Longitude'] 49 add_dict['Easting'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Easting'] 50 add_dict['Northing'] = add['SuggestedAddress'][0]['Address']['PremisesAddress']['GeospatialInformation'][0]['Northing'] 51 return add_dict 52 53 # In[28]: 54 55 56 addresses = df['address'] 57 58 59 # In[31]: 60 61 62 sleep_counter = 0 63 64 65 # In[32]: 66 67 68 all_dict = {} 69 working_dict = {} 70 for i, a in enumerate(tqdm(addresses)): 71 parse = ogcioparser_dict(a) 72 all_dict[i] = parse 73 working_dict[i] = parse 74 sleep_counter +=1 75 if sleep_counter % 500 == 0: 76 sleep(randint(5,10)) 77 78 with open('all_restaurant.json') as f: 79 file = json.load(f) 80 81 file.update(working_dict) 82 83 with open('all_restaurant.json', 'w') as f: 84 json.dump(file, f) 85 86 working_dict = {} 87 88 89 # In[26]: 90 91 92 df_parse = pd.DataFrame.from_dict(all_dict, orient='index') 93 94 95 # In[ ]: 96 97 98 df_parse.to_csv('parse.csv') 99
27 - warning: unspecified-encoding 78 - warning: unspecified-encoding 83 - warning: unspecified-encoding 13 - warning: unused-import
1 # -------------------------------------------------------------------------------------------------------------------- 2 # 3 # Patrick Neary 4 # Date: 11/12/2016 5 # 6 # Fin 5350 / Dr. Tyler J. Brough 7 # Trade Testing Engine: 8 # 9 # kWhiteRealityCheck.py 10 # 11 # This file is an implementation of White's Reality Check for evaluating the significance of a trading rule's 12 # predictive power. 13 # 14 # -------------------------------------------------------------------------------------------------------------------- 15 16 17 # Import standard packages 18 import random 19 from matplotlib import pyplot as plt 20 from BootstrapABC import BootstrapABC 21 22 # Import my classes 23 from BootstrapCalcTools import GetDailyReturns, GetMeanDailyReturn, GetPVal 24 25 # Global values for selecting different options 26 27 28 # -------------------------------------------------------------------------------------------------------------------- 29 30 class WhiteBootstrap(BootstrapABC): 31 32 def __init__(self): 33 self._sample_means = [] 34 self._df = None 35 self._detrended_data = None 36 self._col_name = None 37 self._num_iterations = None 38 pass 39 40 41 def init_test(self, df, col_name, num_iterations=5000): 42 """ 43 init_test initializes the White Reality Check Bootstrap test 44 45 :param df: dataframe containing data to bootstrap 46 :param col_name: name of colume in data frame containing data 47 :param num_iterations: number of iterations to build bootstrap sampling distribution 48 :return: none 49 """ 50 self._df = df 51 self._detrended_data = None 52 self._col_name = col_name 53 self._num_iterations = num_iterations 54 55 datalen = len(self._df.index) 56 57 # Detrend the data 58 meanDailyReturn, dailyreturns = GetMeanDailyReturn(self._df, self._col_name) 59 dailyreturns = dailyreturns.apply(lambda x: x-meanDailyReturn) 60 61 # Iterate over the daily returns and build a distribution of returns 62 meanList = [] 63 for meanCount in xrange(0, self._num_iterations): 64 sampleSum = 0 65 for randomReturn in xrange(0, datalen): 66 index = random.randint(0, datalen-1) 67 sampleSum += dailyreturns.iat[index, 0] 68 #sampleMean = sampleSum #/ datalen 69 #meanList.append(sampleMean) 70 meanList.append(sampleSum) 71 72 #histogram, edges = np.histogram(meanList, bins=10) 73 74 self._sample_means = meanList 75 76 pass 77 78 def plot_histogram(self, bins=20): 79 if len(self._sample_means) > 0: 80 plt.hist(self._sample_means, bins=bins) 81 plt.grid(True) 82 plt.show() 83 return 84 85 def get_histogram_data(self): 86 return self._sample_means 87 88 def has_predictive_power(self, rule_percent_return): 89 90 return GetPVal(self._sample_means, rule_percent_return) 91 92 93 # -------------------------------------------------------------------------------------------------------------------- 94 # Test functions 95 96 97 if __name__ == "__main__": 98 # Functions to run if this file is executed 99 print "Run default function for ", __file__ 100 101
99 - error: syntax-error
1 # -------------------------------------------------------------------------------------------------------------------- 2 # 3 # Patrick Neary 4 # Date: 11/12/2016 5 # 6 # Fin 5350 / Dr. Tyler J. Brough 7 # Trade Testing Engine: 8 # 9 # BootstrapABC.py 10 # 11 # Abstract base class for all tests developed to evaluate rules. 12 # 13 # -------------------------------------------------------------------------------------------------------------------- 14 15 16 # Import standard packages 17 from abc import ABCMeta, abstractmethod 18 19 20 class BootstrapABC(): 21 """ 22 Base test class for bootstrap tests. 23 24 InitTest will initialize the bootstrap test with data that it needs and parameters needed to build the 25 sampling distribution. 26 27 HasPredictivePower will take a percent gain from a rule and determine what the predictive power is 28 29 SaveOutput will generate output for the test.. maybe 30 """ 31 32 __metaclass__ = ABCMeta 33 34 @abstractmethod 35 def init_test(self): 36 pass 37 38 @abstractmethod 39 def has_predictive_power(self): 40 pass 41 42 #@abstractmethod 43 #def SaveOutput(self): 44 #s pass 45 46
Clean Code: No Issues Detected
1 # -------------------------------------------------------------------------------------------------------------------- 2 # 3 # Patrick Neary 4 # Date: 11/12/2016 5 # 6 # Fin 5350 / Dr. Tyler J. Brough 7 # Trade Testing Engine: 8 # 9 # BootstrapCalcTools.py 10 # 11 # This file contains tools common to the bootstrap processes. 12 # 13 # -------------------------------------------------------------------------------------------------------------------- 14 15 16 # Import standard packages 17 import pandas 18 import math 19 20 21 22 # -------------------------------------------------------------------------------------------------------------------- 23 24 25 def GetDailyReturns(df, colName): 26 """ 27 Generate a dataframe containing the mean daily returns from the specified data frame and column name. The daily 28 returns are calculated using log(day/prev day). 29 30 :param df: 31 :param colName: 32 :return: 33 """ 34 35 prev = None 36 returns = [] 37 for index, rowVal in df[colName].iteritems(): 38 39 if(prev == None): 40 dreturn = 0.0 41 else: 42 dreturn = math.log10(float(rowVal)/prev) 43 #print index, rowVal, dreturn 44 prev = float(rowVal) 45 returns.append(dreturn) 46 47 return pandas.DataFrame(data=returns) 48 49 50 def GetMeanDailyReturn(df, colName): 51 """ 52 Given the dataframe and column, calculate the daily return for the sequence and then determine the mean daily 53 return. 54 55 :param df: 56 :param colName: 57 :return: return the mean along with the dataframe containing the data 58 """ 59 60 dailyReturns = GetDailyReturns(df, colName) 61 meanDailyReturn = dailyReturns[0].mean() 62 63 return meanDailyReturn, dailyReturns 64 65 66 def GetDetrendedReturns(df, col_name): 67 68 # Get the daily returns and the mean daily return 69 meanDailyReturn, dailyreturns = GetMeanDailyReturn(df, col_name) 70 # Detrend the daily returns by subtracting off the mean daily return 71 detrended_returns = dailyreturns.apply(lambda x: x-meanDailyReturn) 72 73 return detrended_returns 74 75 76 def GetPVal(sample_dist, rule_percent_return): 77 ''' 78 79 :param sample_dist: sample distribution, this is assumed to be a distribution around zero 80 :param rule_percent_return: percent return of the trading rule 81 :return: return the pvalue associated with the trading rule 82 ''' 83 84 lessThanCnt = 0 85 for meanReturn in sample_dist: 86 if meanReturn < rule_percent_return: 87 lessThanCnt += 1 88 89 percentage = lessThanCnt/float(len(sample_dist)) 90 #print percentage, lessThanCnt 91 pval = 1-percentage 92 93 return pval
37 - warning: unused-variable
1 # -------------------------------------------------------------------------------------------------------------------- 2 # 3 # Patrick Neary 4 # Date: 12/14/2016 5 # 6 # Fin 5350 / Dr. Tyler J. Brough 7 # Trade Testing Engine: 8 # 9 # TTEPaperEx1.py 10 # 11 # This file shows illustrates an example of trading rules that are active during a trend that, while provfitable, 12 # fails to reject the null hypothesis. 13 # 14 # -------------------------------------------------------------------------------------------------------------------- 15 16 17 # Import standard packages 18 19 # Import my classes 20 from pytte.tte import TTE 21 22 23 def TestWhiteRealityCheck(tte, df): 24 print "White Bootstrap" 25 tte.select_bootstrap(tte.BOOTSTRAP_WHITE) 26 pval = tte.get_pvalue(iterations=5000) 27 print "pval:", pval 28 tte.plot_pdf() 29 print tte.get_trade_stats() 30 tte.plot_trades_equity() 31 32 pass 33 34 35 def TestMonteCarloBootstrap(tte, df): 36 print "Monte Carlo Bootstrap" 37 tte.select_bootstrap(tte.BOOTSTRAP_MONTE_CARLO) 38 pval = tte.get_pvalue(iterations=5000) 39 print "pval:", pval 40 tte.plot_pdf() 41 print tte.get_trade_stats() 42 #tte.plot_trades_equity() 43 tte.print_trade_history() 44 45 pass 46 47 48 def TestTTEBootstrap(tte, df): 49 print "TTE Bootstrap" 50 tte.select_bootstrap(tte.BOOTSTRAP_TTE) 51 pval = tte.get_pvalue(iterations=5000) 52 print "pval:", pval, "\n" 53 tte.plot_pdf() 54 tte.plot_trades_equity() 55 tte.print_trade_history() 56 tte.print_trade_stats() 57 58 pass 59 60 61 if __name__ == "__main__": 62 # Functions to run if this file is executed 63 print "Run default function for ", __file__ 64 65 equity = "DIA" 66 startDate = '2016-02-12' 67 endDate = '2016-04-20' 68 69 tte = TTE() 70 df = tte.get_hist_data(equity, startDate, endDate) 71 72 # Trade 1 73 tte.open_trade(0, tte.LONG) 74 tte.close_trade(5) 75 76 # Trade 2 77 tte.open_trade(10, tte.LONG) 78 tte.close_trade(15) 79 80 # Trade 3 81 tte.open_trade(10, tte.LONG) 82 tte.close_trade(20) 83 84 # Trade 4 85 #tte.open_trade(20, tte.LONG) 86 #tte.close_trade(25) 87 88 # Trade 5 89 #tte.open_trade(30, tte.LONG) 90 #tte.close_trade(35) 91 92 # Trade 6 93 #tte.open_trade(40, tte.LONG) 94 #tte.close_trade(45) 95 96 #TestWhiteRealityCheck(tte, df) 97 #TestMonteCarloBootstrap(tte, df) 98 TestTTEBootstrap(tte, df) 99 100 101
24 - error: syntax-error
1 2 3 from pytte import tte 4
3 - warning: unused-import
1 # -------------------------------------------------------------------------------------------------------------------- 2 # 3 # Patrick Neary 4 # Date: 11/12/2016 5 # 6 # Fin 5350 / Dr. Tyler J. Brough 7 # Trade Testing Engine: 8 # 9 # kWhiteRealityCheck.py 10 # 11 # This file is an implementation of White's Reality Check for evaluating the significance of a trading rule's 12 # predictive power. 13 # 14 # -------------------------------------------------------------------------------------------------------------------- 15 16 17 # Import standard packages 18 import random 19 from matplotlib import pyplot as plt 20 from BootstrapABC import BootstrapABC 21 22 # Import my classes 23 from BootstrapCalcTools import GetDailyReturns, GetMeanDailyReturn, GetDetrendedReturns, GetPVal 24 25 # Global values for selecting different options 26 27 28 # -------------------------------------------------------------------------------------------------------------------- 29 class MonteCarloBootstrap(BootstrapABC): 30 31 def __init__(self): 32 self._sample_means = [] 33 self._rules = [] 34 pass 35 36 def init_test(self, df, col_name, num_iterations=5000): 37 """ 38 init_test initializes the White Reality Check Bootstrap test 39 40 :param df: dataframe containing data to bootstrap 41 :param col_name: name of colume in data frame containing data 42 :param daily_rules: list of rules applied to the time series in the data frame. rules take on (+1, -1) values 43 :param num_iterations: number of iterations to build bootstrap sampling distribution 44 :return: none 45 """ 46 self._df = df 47 self._detrended_data = None 48 self._col_name = col_name 49 self._num_iterations = num_iterations 50 51 datalen = len(self._df.index) 52 #gain = float(self._df.at[datalen-1, col_name]) - float(self._df.at[0, col_name]) 53 #dailyGain = gain/datalen 54 55 pass 56 57 58 def plot_histogram(self, bins=20): 59 if len(self._sample_means) > 0: 60 plt.hist(self._sample_means, bins=bins) 61 plt.grid(True) 62 plt.show() 63 return 64 65 def get_histogram_data(self): 66 return self._sample_means 67 68 def run_monte_carlo_round(self, detrended_data): 69 # Run through one iteration of pairing daily rules with detrended returns. Calculate the average return 70 # and return that value. 71 72 # check length of detrended data and daily rules. They should be the same length. 73 if len(detrended_data) != len(self._rules): 74 print "Monte Carlo error! Detrended data and daily rules not the same length." 75 return -1 76 77 # Get a copy of the detrended data 78 detrended_copy = detrended_data[0].tolist() 79 80 # Cycle through the data now 81 total_val = 0 82 tradeDirection = 1 83 for index in xrange(0, len(detrended_copy)): 84 index = random.randint(0, len(detrended_copy)-1) 85 if tradeDirection == 1: 86 tradeDirection = -1 87 else: 88 tradeDirection = 1 89 total_val += tradeDirection * detrended_copy.pop(index) 90 91 #print "total_val: ", total_val 92 93 return total_val 94 95 def has_predictive_power(self, rule_percent_return): 96 97 # Get daily rules from the dataframe 98 rules = self._df['Position'].tolist() 99 #print "rules", rules 100 101 # Set daily rules 102 self._rules = rules 103 104 # Get one-day market price changes 105 106 # Detrend the data 107 detrended_returns = GetDetrendedReturns(self._df, self._col_name) 108 109 # Run through iterations and collect distribution 110 self._sample_means = [] 111 for i in range(0, self._num_iterations, 1): 112 avg_val = self.run_monte_carlo_round(detrended_returns) 113 self._sample_means.append(avg_val) 114 115 # Calculate and return the p-value for the sample mean distribution calculated above 116 return GetPVal(self._sample_means, rule_percent_return) 117 118 # -------------------------------------------------------------------------------------------------------------------- 119 # Test functions 120 121 def test_monte_carlo_round(): 122 rules = [1, 1, -1, -1, -1] 123 data = [2, 3, 4, 3, 2] 124 125 mc = MonteCarloBootstrap() 126 mc._rules = rules 127 128 mean = mc.run_monte_carlo_round(data) 129 print "mean result: ", mean 130 131 pass 132 133 def test_monte_carlo_prediction(): 134 rules = [1, 1, -1, -1, -1] 135 data = [2, 3, 4, 3, 2] 136 137 mc = MonteCarloBootstrap() 138 mc._rules = rules 139 140 mean = mc.run_monte_carlo_round(data) 141 print "mean result: ", mean 142 143 pass 144 145 if __name__ == "__main__": 146 # Functions to run if this file is executed 147 print "Run default function for ", __file__ 148 149 #test_monte_carlo_round() 150 test_monte_carlo_prediction()
74 - error: syntax-error
1 # -------------------------------------------------------------------------------------------------------------------- 2 # 3 # Patrick Neary 4 # Date: 12/14/2016 5 # 6 # Fin 5350 / Dr. Tyler J. Brough 7 # Trade Testing Engine: 8 # 9 # TTEPaperEx2.py 10 # 11 # This file illustrates an example of trading rules that are engaged in a varied environment that is profitable 12 # and rejects the null hypothesis. 13 # 14 # -------------------------------------------------------------------------------------------------------------------- 15 16 17 # Import standard packages 18 19 # Import my classes 20 from pytte.tte import TTE 21 22 23 def PrintResults(tte, title=None): 24 25 pval = tte.get_pvalue(iterations=5000) 26 print "pval:", pval, "\n" 27 tte.print_trade_history() 28 tte.print_trade_stats() 29 tte.plot_all(title) 30 31 pass 32 33 def TestWhiteRealityCheck(tte): 34 print "White Bootstrap" 35 tte.select_bootstrap(tte.BOOTSTRAP_WHITE) 36 PrintResults(tte, "White Bootstrap") 37 38 pass 39 40 41 def TestMonteCarloBootstrap(tte): 42 print "Monte Carlo Bootstrap" 43 tte.select_bootstrap(tte.BOOTSTRAP_MONTE_CARLO) 44 PrintResults(tte, "Monte Carlo Bootstrap") 45 46 pass 47 48 49 def TestTTEBootstrap(tte): 50 print "TTE Bootstrap" 51 tte.select_bootstrap(tte.BOOTSTRAP_TTE) 52 PrintResults(tte, "TTE Bootstrap") 53 54 pass 55 56 57 if __name__ == "__main__": 58 # Functions to run if this file is executed 59 print "Run default function for ", __file__ 60 61 equity = "DIA" 62 startDate = '2016-01-04' 63 endDate = '2016-03-20' 64 65 tte = TTE() 66 df = tte.get_hist_data(equity, startDate, endDate) 67 print len(df) 68 69 # Trade 1 70 tte.open_trade(0, tte.SHORT) 71 tte.close_trade(5) 72 73 # Trade 2 74 tte.open_trade(8, tte.SHORT) 75 tte.close_trade(12) 76 77 # Trade 3 78 #tte.open_trade(15, tte.LONG) 79 #tte.close_trade(20) 80 81 # Trade 4 82 tte.open_trade(29, tte.LONG) 83 tte.close_trade(34) 84 85 # Trade 5 86 # 87 tte.open_trade(39, tte.LONG) 88 tte.close_trade(46) 89 90 # Trade 6 91 tte.open_trade(47, tte.LONG) 92 tte.close_trade(50) 93 94 #TestWhiteRealityCheck(tte) 95 #TestMonteCarloBootstrap(tte) 96 TestTTEBootstrap(tte) 97 98 99
26 - error: syntax-error
1 # -------------------------------------------------------------------------------------------------------------------- 2 # Patrick Neary 3 # CS 6110 4 # Project 5 # 10/6/2016 6 # 7 # TradeDetails.py 8 # 9 # This file 10 # -------------------------------------------------------------------------------------------------------------------- 11 12 import datetime 13 import math 14 15 class TradeDetails: 16 17 CASH = 0 18 LONG = 1 19 SHORT = -1 20 21 def __init__(self): 22 self.openPrice = 0.0 23 self.closePrice = 0.0 24 self.spread = 0.0 25 self.tradeDirection = self.CASH 26 self.equityName = "" 27 self.openTimeStamp = None 28 self.closeTimeStamp = None 29 self.duration = None 30 self.currPL = 0.0 31 self.stopLoss = None 32 self.profitTarget = None 33 self.totalPL = 0.0 34 self.ID = None 35 return 36 37 def __str__(self): 38 mystr = "%s, %s, %s, %s, %s, %s, %s, %s, %s" % (self.equityName, self.openTimeStamp, self.closeTimeStamp, 39 self.duration, self.openPrice, self.closePrice, self.currPL, self.totalPL, self.ID) 40 return mystr 41 42 def OpenTrade(self, equity, openprice, spread, direction, timestamp, id=None): 43 # timestamp - needs to be a string in format of "year-month-day" or in datetime format. 44 if isinstance(timestamp, str) == True: 45 timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%d") 46 47 # Check to make sure timestamp is a date/time format 48 if isinstance(timestamp, datetime.datetime) == False: 49 print "Timestamp needs to be in datetime format" 50 return 51 52 self.openPrice = openprice 53 self.equityName = equity 54 self.spread = spread 55 self.tradeDirection = direction 56 self.openTimeStamp = timestamp 57 self.ID = id # ID of entity making the trade 58 return 59 60 def CloseTrade(self, closeprice, timestamp): 61 # timestamp - needs to be a string in format of "year-month-day" or in datetime format. 62 if isinstance(timestamp, str) == True: 63 timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%d") 64 65 # Check to make sure timestamp is a date/time format 66 if isinstance(timestamp, datetime.datetime) == False: 67 print "Timestamp needs to be in datetime format" 68 return 69 70 # Close the trade 71 self.closePrice = closeprice 72 self.closeTimeStamp = timestamp 73 #self.tradeDirection = self.CASH 74 75 self.GetCurrentPL(closeprice) 76 self.GetTradeDuration() 77 #self.ID = None 78 return 79 80 def GetCurrentPL(self, currprice): 81 # Calculate the change in price from open to now. This includes the cost of the spread. 82 83 if self.tradeDirection is self.CASH: 84 self.currPL = 0.0 85 elif self.tradeDirection is self.SHORT: 86 self.currPL = float(self.openPrice) - float(currprice) - float(self.spread) 87 else: 88 self.currPL = float(currprice) - float(self.openPrice) - float(self.spread) 89 90 #print "GetCurrentPL: ", self.currPL, self.tradeDirection, self.spread 91 92 return self.currPL 93 94 def GetTradePercentPL(self): 95 96 if self.tradeDirection is self.CASH: 97 totalPercentReturn = 0.0 98 elif self.tradeDirection is self.SHORT: 99 totalPercentReturn = math.log10(float(self.openPrice)) - math.log10(float(self.closePrice)) 100 else: 101 totalPercentReturn = math.log10(float(self.closePrice)) - math.log10(float(self.openPrice)) 102 103 return totalPercentReturn 104 105 def GetTradeDuration(self): 106 duration = self.closeTimeStamp - self.openTimeStamp 107 self.duration = duration 108 return self.duration 109 110 def RedefineDirection(self, cash, long, short): 111 self.CASH = cash 112 self.LONG = long 113 self.SHORT = short 114 return 115 116 def SetTotalPL(self, totalPL): 117 self.totalPL = totalPL 118 return 119 120 def GetCurrentTradeID(self): 121 return self.ID 122 123 # -------------------------------------------------------------------------------------------------------------------- 124 # 125 # -------------------------------------------------------------------------------------------------------------------- 126 127 def TestTradeDetails(): 128 129 openTS = datetime.datetime(2016, 04, 18) 130 closeTS = datetime.datetime(2016, 04, 19) 131 openPrice = 78.8 132 closePrice = 78.2 133 spread = 0.032 134 135 td = TradeDetails() 136 td.OpenTrade("AUDJPY", openPrice, spread, 1, openTS) 137 td.CloseTrade(closePrice, closeTS) 138 print td 139 140 return 141 142 # -------------------------------------------------------------------------------------------------------------------- 143 # Default function when the file is run 144 # -------------------------------------------------------------------------------------------------------------------- 145 146 if __name__ == "__main__": 147 # Functions to run if this file is executed 148 print "Run default function for ", __file__ 149 150 TestTradeDetails()
129 - error: syntax-error
1 # -------------------------------------------------------------------------------------------------------------------- 2 # 3 # Patrick Neary 4 # Date: 9/22/2016 5 # 6 # Fin 5350 / Dr. Tyler J. Brough 7 # Trade Testing Engine: 8 # 9 # TestFile.py 10 # 11 # This file shows how to use the TTE package 12 # 13 # -------------------------------------------------------------------------------------------------------------------- 14 15 16 # Import standard packages 17 18 # Import my classes 19 from pytte.tte import TTE 20 21 22 def TestWhiteRealityCheck(tte, df): 23 24 #tte.open_trade(4, tte.LONG) 25 #tte.close_trade(11) 26 27 tte.open_trade(10, tte.SHORT) 28 tte.close_trade(13) 29 30 tte.select_bootstrap(tte.BOOTSTRAP_WHITE) 31 pval = tte.get_pvalue(iterations=5000) 32 print "pval:", pval 33 tte.plot_pdf() 34 print tte.get_trade_stats() 35 tte.plot_trades_equity() 36 37 pass 38 39 40 def TestMonteCarloBootstrap(tte, df): 41 42 #tte.open_trade(4, tte.LONG) 43 #tte.close_trade(11) 44 45 tte.open_trade(10, tte.SHORT) 46 tte.close_trade(13) 47 48 tte.select_bootstrap(tte.BOOTSTRAP_MONTE_CARLO) 49 pval = tte.get_pvalue(iterations=5000) 50 print "pval:", pval 51 tte.plot_pdf() 52 print tte.get_trade_stats() 53 tte.plot_trades_equity() 54 55 pass 56 57 58 def TestTTEBootstrap(tte, df): 59 60 #tte.open_trade(4, tte.LONG) 61 #tte.close_trade(11) 62 63 tte.open_trade(10, tte.SHORT) 64 tte.close_trade(13) 65 66 tte.select_bootstrap(tte.BOOTSTRAP_TTE) 67 pval = tte.get_pvalue(iterations=5000) 68 print "pval:", pval, "\n" 69 tte.plot_pdf() 70 tte.plot_trades_equity() 71 tte.print_trade_history() 72 tte.print_trade_stats() 73 74 pass 75 76 def CompareBootstrapOutputs(tte, df): 77 #tte.open_trade(4, tte.LONG) 78 #tte.close_trade(11) 79 80 tte.open_trade(10, tte.SHORT) 81 tte.close_trade(13) 82 83 # Get and display TTE Bootstrap pvalue 84 #tte.select_bootstrap(tte.BOOTSTRAP_TTE) 85 #pval = tte.get_pvalue(iterations=5000) 86 #print "TTE pval:", pval 87 88 # Get and display TTE Bootstrap pvalue 89 #tte.select_bootstrap(tte.BOOTSTRAP_MONTE_CARLO) 90 #pval = tte.get_pvalue(iterations=5000) 91 #print "Monte Carlo pval:", pval 92 93 # Get and display TTE Bootstrap pvalue 94 tte.select_bootstrap(tte.BOOTSTRAP_WHITE) 95 pval = tte.get_pvalue(iterations=5000) 96 print "White pval:", pval 97 98 pass 99 100 if __name__ == "__main__": 101 # Functions to run if this file is executed 102 print "Run default function for ", __file__ 103 104 equity = "SPY" 105 startDate = '2016-08-20' 106 endDate = '2016-09-16' 107 108 tte = TTE() 109 df = tte.get_hist_data(equity, startDate, endDate) 110 111 #TestWhiteRealityCheck(tte, df) 112 #TestMonteCarloBootstrap(tte, df) 113 #TestTTEBootstrap(tte, df) 114 CompareBootstrapOutputs(tte, df) 115 116 117 118 119 120 121 122 123 124 125 126 127
32 - error: syntax-error
1 #IMDB crawler 2 import requests 3 import nltk 4 from nltk import RegexpParser 5 from nltk.corpus import treebank 6 from nltk.corpus import sentiwordnet as swn 7 from lxml import html 8 from bs4 import BeautifulSoup 9 from time import sleep 10 import sqlite3 11 #遇到亂碼可以用join函數存取 12 con = sqlite3.connect('imdb.sqlite') 13 sql = 'insert into movie_comments_rating(film_name,author,score) values(?,?,?)' 14 cur = con.cursor() 15 16 17 18 _URL = requests.get('http://www.imdb.com/chart/top?sort=us,desc&mode=simple&page=1') 19 tree = html.fromstring(_URL.text) 20 linkURL = tree.xpath("//tbody[@class='lister-list']//tr//td[@class='titleColumn']/a/@href") 21 headtitle = tree.xpath("//tbody[@class='lister-list']//tr//td[@class='titleColumn']/a/text()") #250部電影 22 yearForEachMovie = tree.xpath("//div[@class = 'lister'] // tbody[@class = 'lister-list']//tr//td[@class = 'titleColumn']//span//text()") 23 #儲存超連結網址,內容為要進入每個排名電影的超連結 24 URL_List = [] 25 26 27 28 #用來拼接到每個網頁網址的list 29 URL_To_EachMovie = [] 30 #儲存每個評論 31 Each_Comments = [] 32 #儲存每個評論給的分數 33 Each_Rate = [] 34 #儲存每個圖片的網址 35 _Score = [] 36 37 #存進資料庫 38 listscore = [] 39 headtitle_list = [] 40 comment_author_list = [] 41 #存進資料庫 42 43 44 # 抓...前20個排名高的電影(最近) 45 cnt = 1 46 for i in linkURL: 47 page = 1 #記錄換頁 IMDB裡評論的下一頁是前一頁*10 48 URL_List.append(i) 49 #print(URL_List) 50 temp = URL_List.pop() 51 52 #做拼接而且進入該網頁,因為進入每個評論的attributes都是同一個 "reviews?ref_=tt_ov_rt" 所以直接用 53 URL_Link_To_Comments_array = temp.split('/?') #結果 /title/tt2119532 54 URL_Link_To_Comments = URL_Link_To_Comments_array.pop(0) 55 #進入評論的網頁 56 Link_To_Comments = requests.get('http://www.imdb.com' + URL_Link_To_Comments + "/reviews?ref_=tt_ov_rt") 57 tree2 = html.fromstring(Link_To_Comments.text) 58 #print(tree2.text) 59 linkURL2 = tree2.xpath("//div[@id = 'tn15content']//p/text()") 60 #linkURL2 = tree2.xpath('//*[@id="tn15content"]//p/text()') 61 #join 62 # str.join(iterable) 回傳將 str 連結 iterable 各元素的字串 63 status = True #判斷有沒有到最後一頁 64 while(status == True): 65 tree3 = html.fromstring(Link_To_Comments.text) 66 author = tree3.xpath("//div[@id = 'tn15content'] // div // a[2] // text()") #print 10筆作者資料 67 for j in range(0,len(author)): 68 comment_author_list.append(author.pop(0)) #儲存作者名字 資料庫~~~~~~~~~~~~~~ 69 #print(comment_author_list) 70 71 72 #---------------------------------評分處理------------------------------------------- 73 soup = BeautifulSoup(Link_To_Comments.text) 74 for j in soup.findAll('div' , id = 'tn15content'): 75 for k in j.findAll('div'): 76 # --------------------------每段評論的標題--------------------------------- 77 if(len(k.select('h2')) == 1): 78 _head = k.select('h2') 79 _Stringhead = (str)(_head[0]) 80 _Stringhead = _Stringhead.replace('<h2>','') 81 _Stringhead = _Stringhead.replace('</h2>','') 82 #print(_Stringhead) #印出標題 83 84 # ----------------------------------------------------------------------- 85 86 s = k.select('img') 87 if(len(s)): #判斷是否為空陣列 ==> 裡面為有 88 if(len(s) == 2):#代表該作者有給評分 89 ppp = s[1]['alt'].split("/") 90 aaaa = ppp[0] #fsadfsdfsdfasdfsdfasdfsd 91 listscore.append(aaaa) 92 #print(aaaa) 93 else: #代表該作者沒有給評分 讓list為null 94 listscore.append("NULL") 95 #print("----------------------------NULL---------------------------------") 96 #print(listscore) #資料庫~~~~~~~~~~~~~~~~~~~~~~~~~~ 97 98 99 # ---------------------------------查詢有無下頁(評論)------------------------------------------ 100 for k in j.findAll('tr'): 101 for q in k.findAll('td' , nowrap = '1'): 102 isNext = k.select('img') 103 if(len(isNext) == 2): #中間頁數判斷 104 if(isNext[1]['alt'] == '[Next]'): #有下一頁就做下一頁 105 Link_To_Comments = requests.get('http://www.imdb.com'+URL_Link_To_Comments+'/reviews?start='+(str)(page*10)) 106 #print("OKOK") 107 #print(page) 108 break 109 #http://www.imdb.com/title/tt2119532/reviews?start=10 第2頁 110 else: 111 #print("Wrong1") 112 status = False 113 elif(len(isNext) == 1): #判斷最後一頁跟第一頁 114 if(isNext[0]['alt'] == '[Prev]'): 115 #print("Wrong2") 116 status = False 117 elif(isNext[0]['alt'] == '[Next]'): #第一頁 有下一頁 118 #print("OKOK") 119 #print(page) 120 Link_To_Comments = requests.get('http://www.imdb.com'+URL_Link_To_Comments+'/reviews?start='+(str)(page*10)) 121 break 122 page += 1 123 124 #--------------------------------------------------------------------------------------- 125 126 # 換電影評論 127 cnt+=1 128 if(cnt <= 100): 129 print(comment_author_list) 130 print(listscore) 131 ggg = headtitle.pop(0) 132 print(ggg) 133 print("=================================") 134 for length in range(0,len(comment_author_list)): 135 ccc = comment_author_list.pop(0) 136 ddd = listscore.pop(0) 137 #print(ccc) 138 #print(ddd) 139 ret = [ggg,ccc,ddd] 140 cur.execute(sql,ret) 141 else: 142 break 143 con.commit() 144 con.close()
18 - warning: missing-timeout 56 - warning: missing-timeout 104 - refactor: no-else-break 105 - warning: missing-timeout 120 - warning: missing-timeout 3 - warning: unused-import 4 - warning: unused-import 5 - warning: unused-import 6 - warning: unused-import 9 - warning: unused-import
1 import pytest 2 import random 3 import numpy as np 4 import networkx as nx 5 from graph_tool import Graph 6 from random_steiner_tree import random_steiner_tree 7 from random_steiner_tree.util import (from_nx, from_gt, 8 num_vertices, 9 isolate_vertex, 10 vertices, 11 edges, 12 reachable_vertices) 13 14 15 def check_feasiblity(tree, root, X): 16 X = set(X) | {int(root)} 17 # number of components 18 ncc = nx.number_connected_components(tree) 19 assert ncc == 1, 'number_connected_components: {} != 1'.format(ncc) 20 21 nodes = set(tree.nodes()) 22 assert X.issubset(nodes), 'tree does not contain all X' 23 24 # leaves are terminals 25 # no extra edges 26 for n in tree.nodes_iter(): 27 if tree.degree(n) == 1: 28 assert n in X, 'one leaf does not belong to terminal' 29 30 31 def input_data_nx(): 32 g = nx.karate_club_graph().to_directed() 33 34 for u, v in g.edges_iter(): 35 g[u][v]['weight'] = 1 36 return g, from_nx(g, 'weight'), g.number_of_nodes() 37 38 39 def input_data_gt(): 40 g_nx = nx.karate_club_graph() 41 g = Graph(directed=True) 42 g.add_vertex(g_nx.number_of_nodes()) 43 for u, v in g_nx.edges(): 44 g.add_edge(u, v) 45 g.add_edge(v, u) # the other direction 46 47 return g, from_gt(g, None), g.num_vertices() 48 49 50 @pytest.mark.parametrize("data_type", ["gt", "nx"]) 51 @pytest.mark.parametrize("method", ["loop_erased", "cut"]) 52 def test_feasiblility(data_type, method): 53 if data_type == 'nx': 54 data = input_data_nx() 55 elif data_type == 'gt': 56 data = input_data_gt() 57 g, gi, N = data 58 for i in range(10): 59 # try different number of terminals1 60 for k in range(2, N+1): 61 X = np.random.permutation(N)[:10] 62 63 if data_type == 'nx': 64 nodes = g.nodes() 65 elif data_type == 'gt': 66 nodes = list(map(int, g.vertices())) 67 68 root = random.choice(nodes) 69 tree_edges = random_steiner_tree(gi, X, root, method=method, verbose=True) 70 t = nx.Graph() 71 t.add_edges_from(tree_edges) 72 check_feasiblity(t, root, X) 73 74 75 @pytest.fixture 76 def line_g(): 77 g = Graph(directed=True) 78 g.add_edge(0, 1) 79 g.add_edge(1, 0) 80 g.add_edge(1, 2) 81 g.add_edge(2, 1) 82 return g 83 84 85 def test_edges(line_g): 86 gi = from_gt(line_g, None) 87 assert set(edges(gi)) == {(0, 1), (1, 0), (1, 2), (2, 1)} 88 89 90 def test_isolate_vertex(line_g): 91 gi = from_gt(line_g, None) 92 isolate_vertex(gi, 0) 93 assert set(edges(gi)) == {(2, 1), (1, 2)} 94 95 isolate_vertex(gi, 1) 96 assert set(edges(gi)) == set() 97 98 99 def test_isolate_vertex_num_vertices(): 100 _, gi, _ = input_data_gt() 101 prev_N = num_vertices(gi) 102 isolate_vertex(gi, 0) 103 nodes_with_edges = {u for e in edges(gi) for u in e} 104 assert 0 not in nodes_with_edges 105 106 assert prev_N == num_vertices(gi) 107 isolate_vertex(gi, 1) 108 assert prev_N == num_vertices(gi) 109 110 111 @pytest.fixture 112 def disconnected_line_graph(): 113 """0 -- 1 -- 2 3 -- 4 114 """ 115 g = nx.Graph() 116 g.add_nodes_from([0, 1, 2, 3, 4]) 117 g.add_edges_from([(0, 1), (1, 2), (3, 4)]) 118 g = g.to_directed() 119 return from_nx(g) 120 121 122 def test_remove_vertex_node_index(disconnected_line_graph): 123 gi = disconnected_line_graph 124 isolate_vertex(gi, 0) 125 assert set(vertices(gi)) == {0, 1, 2, 3, 4} 126 127 assert reachable_vertices(gi, 0) == [0] 128 assert reachable_vertices(gi, 1) == [1, 2] 129 assert reachable_vertices(gi, 3) == [3, 4] 130 131 132 @pytest.mark.parametrize("expected, pivot", [({0, 1, 2}, 1), ({3, 4}, 3)]) 133 def test_reachable_vertices(disconnected_line_graph, expected, pivot): 134 gi = disconnected_line_graph 135 nodes = reachable_vertices(gi, pivot) 136 print('num_vertices', num_vertices(gi)) 137 # 0, 1, 2 remains 138 assert set(nodes) == expected 139 140 141 @pytest.mark.parametrize("method", ['cut', 'loop_erased']) 142 def test_steiner_tree_with_disconnected_component(disconnected_line_graph, method): 143 gi = disconnected_line_graph 144 edges = random_steiner_tree(gi, X=[0, 2], root=1, method=method) 145 assert set(edges) == {(1, 0), (1, 2)}
57 - error: possibly-used-before-assignment 68 - error: possibly-used-before-assignment 58 - warning: unused-variable 60 - warning: unused-variable 85 - warning: redefined-outer-name 90 - warning: redefined-outer-name 122 - warning: redefined-outer-name 133 - warning: redefined-outer-name 142 - warning: redefined-outer-name 144 - warning: redefined-outer-name
1 import random 2 from .interface import loop_erased, cut_based 3 4 5 def random_steiner_tree(gi, X, root, method="loop_erased", seed=None, verbose=False): 6 assert method in {"loop_erased", "closure", "cut"} 7 # C++ is strict with type... 8 X = list(map(int, X)) 9 10 root = int(root) 11 if seed is None: 12 seed = random.randint(0, 2147483647) # int32 13 if method == "loop_erased": 14 return loop_erased(gi, X, root, seed, verbose) 15 elif method == "cut": 16 return cut_based(gi, X, root, seed, verbose) 17 else: 18 raise NotImplemented('yet')
2 - error: relative-beyond-top-level 5 - refactor: too-many-arguments 5 - refactor: too-many-positional-arguments 13 - refactor: no-else-return 18 - error: notimplemented-raised 18 - error: not-callable
1 # from distutils.core import setup, Extension 2 import os 3 from setuptools import setup, Extension 4 5 os.environ["CC"] = "g++" 6 os.environ["CXX"] = "g++" 7 8 core_module = Extension( 9 'random_steiner_tree/interface', 10 include_dirs=['/usr/include/python3.5/'], 11 libraries=['boost_python-py35', 'boost_graph'], 12 library_dirs=['/usr/lib/x86_64-linux-gnu/'], 13 extra_compile_args=['-std=c++11', '-O2', '-Wall'], 14 extra_link_args=['-Wl,--export-dynamic'], 15 sources=['random_steiner_tree/interface.cpp'] 16 ) 17 18 setup(name='rand_steiner_tree', 19 version='0.1', 20 description='Random Steiner tree sampling algorithm', 21 url='http://github.com/xiaohan2012/random_steiner_tree', 22 author='Han Xiao', 23 author_email='xiaohan2012@gmail.com', 24 license='MIT', 25 packages=['random_steiner_tree'], 26 ext_modules=[core_module], 27 setup_requires=['pytest-runner'], 28 tests_require=['pytest'] 29 )
Clean Code: No Issues Detected
1 import pytest 2 import numpy as np 3 from graph_tool import Graph 4 from random_steiner_tree import random_steiner_tree 5 from random_steiner_tree.util import from_gt 6 from collections import Counter 7 8 EPSILON = 1e-10 9 10 11 def graph(): 12 """ 13 0 (root) 14 / \ 15 1 2 16 \ / 17 3 (X) 18 """ 19 g = Graph() 20 g.add_vertex(4) 21 g.add_edge(0, 1) 22 g.add_edge(0, 2) 23 g.add_edge(1, 3) 24 g.add_edge(2, 3) 25 return g 26 27 28 case1 = { 29 (0, 1): 1, 30 (0, 2): EPSILON, 31 (1, 3): 1, 32 (2, 3): EPSILON 33 } 34 35 case2 = { 36 (0, 1): 1, 37 (0, 2): 2, 38 (1, 3): 1, 39 (2, 3): 1 40 } 41 42 43 def build_gi_by_weights(edge2weight): 44 g = graph() 45 weights = g.new_edge_property('float') 46 for (u, v), w in edge2weight.items(): 47 weights[g.edge(u, v)] = w 48 49 return from_gt(g, weights=weights) 50 51 52 @pytest.mark.parametrize("edge2weight,expected_fraction", [(case1, 0), (case2, 4/3)]) 53 @pytest.mark.parametrize("sampling_method", ["loop_erased"]) 54 def test_distribution(edge2weight, expected_fraction, sampling_method): 55 gi = build_gi_by_weights(edge2weight) 56 root = 0 57 X = [3] 58 n = 100000 59 steiner_node_freq = Counter() 60 for i in range(n): 61 edges = random_steiner_tree(gi, X, root, method=sampling_method, seed=None) 62 steiner_nodes = {u for e in edges for u in e} - {root} - set(X) 63 for u in steiner_nodes: 64 steiner_node_freq[u] += 1 65 66 np.testing.assert_almost_equal(steiner_node_freq[2] / steiner_node_freq[1], 67 expected_fraction, decimal=2) 68 69 # if the following assertion fails, you can buy a lottery 70 # assert steiner_node_freq[2] == 0 71 # assert steiner_node_freq[1] == n 72 73 # np.testing.assert_almost_equal(steiner_node_freq[2] / steiner_node_freq[1], 0)
16 - warning: anomalous-backslash-in-string 60 - warning: unused-variable