index
int64
0
100k
blob_id
stringlengths
40
40
code
stringlengths
7
7.27M
steps
listlengths
1
1.25k
error
bool
2 classes
700
360e661d8538a8f40b7546a54e9a9582fa64bd67
import numpy as np from sklearn.metrics import mutual_info_score def mimic_binary(max_iter=100, fitness_func=None, space=None): assert fitness_func is not None assert space is not None idx = np.random.permutation(np.arange(len(space))) pool = space[idx[:int(len(space)/2)]] # randomly sample 50% of the oringal space new_pool = [] for i in range(max_iter): print("mimic: {}|{}".format(i+1, max_iter)) theta += delta for j, parent in enumerate(pool): if j in new_pool or fitness_func(parent)<theta: continue best_score = 0 best_child = parent for k, child in enumerate(pool): if k<=j or child in new_pool: continue score = mutual_info(parent, child) if score > best_score and fitness_func(child)>=theta: best_score = score new_pool.append(parent) new_pool.append(child) return None def mutual_info(parent, child): parent = [int(x) for x in parent] child = [int(x) for x in child] return mutual_info_score(parent,child)
[ "import numpy as np\nfrom sklearn.metrics import mutual_info_score\n\ndef mimic_binary(max_iter=100, fitness_func=None, space=None):\n\n assert fitness_func is not None\n assert space is not None\n\n idx = np.random.permutation(np.arange(len(space)))\n pool = space[idx[:int(len(space)/2)]] # randomly sample 50% of the oringal space\n\n new_pool = []\n\n for i in range(max_iter):\n print(\"mimic: {}|{}\".format(i+1, max_iter))\n theta += delta\n for j, parent in enumerate(pool):\n if j in new_pool or fitness_func(parent)<theta: continue\n best_score = 0\n best_child = parent\n for k, child in enumerate(pool):\n if k<=j or child in new_pool: continue\n score = mutual_info(parent, child)\n if score > best_score and fitness_func(child)>=theta:\n best_score = score\n new_pool.append(parent)\n new_pool.append(child)\n return None\n\ndef mutual_info(parent, child):\n parent = [int(x) for x in parent]\n child = [int(x) for x in child]\n return mutual_info_score(parent,child)", "import numpy as np\nfrom sklearn.metrics import mutual_info_score\n\n\ndef mimic_binary(max_iter=100, fitness_func=None, space=None):\n assert fitness_func is not None\n assert space is not None\n idx = np.random.permutation(np.arange(len(space)))\n pool = space[idx[:int(len(space) / 2)]]\n new_pool = []\n for i in range(max_iter):\n print('mimic: {}|{}'.format(i + 1, max_iter))\n theta += delta\n for j, parent in enumerate(pool):\n if j in new_pool or fitness_func(parent) < theta:\n continue\n best_score = 0\n best_child = parent\n for k, child in enumerate(pool):\n if k <= j or child in new_pool:\n continue\n score = mutual_info(parent, child)\n if score > best_score and fitness_func(child) >= theta:\n best_score = score\n new_pool.append(parent)\n new_pool.append(child)\n return None\n\n\ndef mutual_info(parent, child):\n parent = [int(x) for x in parent]\n child = [int(x) for x in child]\n return mutual_info_score(parent, child)\n", "<import token>\n\n\ndef mimic_binary(max_iter=100, fitness_func=None, space=None):\n assert fitness_func is not None\n assert space is not None\n idx = np.random.permutation(np.arange(len(space)))\n pool = space[idx[:int(len(space) / 2)]]\n new_pool = []\n for i in range(max_iter):\n print('mimic: {}|{}'.format(i + 1, max_iter))\n theta += delta\n for j, parent in enumerate(pool):\n if j in new_pool or fitness_func(parent) < theta:\n continue\n best_score = 0\n best_child = parent\n for k, child in enumerate(pool):\n if k <= j or child in new_pool:\n continue\n score = mutual_info(parent, child)\n if score > best_score and fitness_func(child) >= theta:\n best_score = score\n new_pool.append(parent)\n new_pool.append(child)\n return None\n\n\ndef mutual_info(parent, child):\n parent = [int(x) for x in parent]\n child = [int(x) for x in child]\n return mutual_info_score(parent, child)\n", "<import token>\n<function token>\n\n\ndef mutual_info(parent, child):\n parent = [int(x) for x in parent]\n child = [int(x) for x in child]\n return mutual_info_score(parent, child)\n", "<import token>\n<function token>\n<function token>\n" ]
false
701
f489058c922d405754ad32a737f67bc03c08772b
# Copyright 2018 dhtech # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file import lib import urlparse import yaml MANIFEST_PATH = '/etc/manifest' HTTP_BASIC_AUTH = None def blackbox(name, backend, targets, params, target='target', path='/probe', labels=None): labels = {} if labels is None else labels # Strip banned OSes banned_oses = ['debian'] filtered_targets = [x for x in targets if lib.get_os(x) not in banned_oses] return { 'job_name': name, 'metrics_path': path, 'params': params, 'static_configs': [{ 'targets': sorted(filtered_targets), 'labels': labels }], 'relabel_configs': [{ 'source_labels': ['__address__'], 'regex': '(.*)(:80)?', 'target_label': '__param_%s' % target, 'replacement': '${1}', }, { 'source_labels': ['__param_%s' % target], 'regex': '(.*)', 'target_label': 'instance', 'replacement': '${1}', }, { 'source_labels': [], 'regex': '.*', 'target_label': '__address__', 'replacement': backend, }] } def generate_backend(host, local_services): scrape_configs = [] scrape_configs.extend(local_services) domain = lib.get_domain(host) basic_auth = lib.read_secret('services/monitoring:login') # Find services that wants to be monitored manifest = yaml.load(file(MANIFEST_PATH).read()) for package, spec in manifest['packages'].iteritems(): if spec is None or 'monitor' not in spec: continue urls = (spec['monitor']['url'] if isinstance(spec['monitor']['url'], dict) else {None: spec['monitor']['url']}) for url_id, url_str in urls.iteritems(): url = urlparse.urlparse(url_str) targets = [] for target in sorted( lib.get_nodes_with_package(package, domain).keys()): targets.append(target if url.port is None else '%s:%d' % ( target, url.port)) scrape_config = { 'job_name': package + ('-%s' % url_id if url_id else ''), 'metrics_path': url.path, 'scheme': url.scheme, 'static_configs': [ {'targets': sorted(targets)} ], } if 'interval' in spec['monitor']: scrape_config['scrape_interval'] = spec['monitor']['interval'] if 'labels' in spec['monitor']: scrape_config['static_configs'][0]['labels'] = spec['monitor']['labels'] # Only allow authentication over https if spec['monitor'].get('auth', False) and url.scheme == 'https': scrape_config['basic_auth'] = basic_auth scrape_configs.append(scrape_config) # Layer specific monitoring layers = lib.get_layers(domain) snmp_nodes = {} ssh_nodes = {} for layer in layers: hosts = lib.get_nodes_with_layer(layer, domain) snmp_mute = lib.get_nodes_with_layer(layer, domain, 'no-snmp') ssh_mute = lib.get_nodes_with_layer(layer, domain, 'no-ssh') snmp_nodes[layer] = list(set(hosts) - set(snmp_mute)) ssh_nodes[layer] = [x+':22' for x in set(hosts) - set(ssh_mute)] # SNMP for layer in layers: # TODO(bluecmd): Use options for this if layer == 'access': snmp_host = 'snmp2.event.dreamhack.se' else: snmp_host = 'snmp1.event.dreamhack.se' snmp = blackbox( 'snmp_%s' % layer, snmp_host, snmp_nodes[layer], {'layer': [layer]}, labels={ 'layer': layer}) snmp['scrape_interval'] = '30s' snmp['scrape_timeout'] = '30s' scrape_configs.append(snmp) # SSH for layer in layers: for ssh_host in ['jumpgate1', 'jumpgate2', 'rancid']: fqdn = ssh_host + '.event.dreamhack.se:9115' ssh = blackbox( 'ssh_%s_%s' % (layer, ssh_host), fqdn, ssh_nodes[layer], {'module': ['ssh_banner']}, labels={'layer': layer}) ssh['scrape_interval'] = '30s' ssh['scrape_timeout'] = '30s' scrape_configs.append(ssh) # Add external service-discovery external = { 'job_name': 'external', 'file_sd_configs': [{ 'files': ['/etc/prometheus/external/*.yaml'], }], } scrape_configs.append(external) if host.endswith('.event.dreamhack.se'): # Event should scrape puppet.tech.dreamhack.se to get information about # puppet runs puppet = { 'job_name': 'puppet_runs', 'metrics_path': '/metrics', 'scrape_interval': '60s', 'scrape_timeout': '55s', 'static_configs': [{ 'targets': ['puppet.tech.dreamhack.se:9100'], }], } scrape_configs.append(puppet) vcenter = { 'job_name': 'vmware_vcenter', 'metrics_path': '/metrics', 'scrape_interval': '60s', 'scrape_timeout': '55s', 'static_configs': [{ 'targets': ['provision.event.dreamhack.se:9272'], }], } scrape_configs.append(vcenter) # Make sure that all metrics have a host label. # This rule uses the existing host label if there is one, # stripping of the port (which shouldn't be part of the host label anyway) # *or* if that label does not exist it uses the instance label # (again stripping of the port) relabel = { 'regex': r':?([^:]*):?.*', 'separator': ':', 'replacement': '${1}', 'source_labels': ['host', 'instance'], 'target_label': 'host', } mrc = 'metric_relabel_configs' for scrape in scrape_configs: if mrc in scrape: scrape[mrc].append(relabel) else: scrape[mrc] = [relabel] return {'scrape_configs': scrape_configs} def requires(host, *args): return ['apache(ldap)'] def generate(host, *args): info = {} local_targets = [] local_targets.append({ 'job_name': 'prometheus', 'scheme': 'http', 'static_configs': [{'targets': ['localhost:9090']}]}) info['prometheus'] = generate_backend(host, local_targets) # Get current event info['prometheus']['current_event'] = lib.get_current_event() return info # vim: ts=4: sts=4: sw=4: expandtab
[ "# Copyright 2018 dhtech\n#\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file\nimport lib\nimport urlparse\nimport yaml\n\n\nMANIFEST_PATH = '/etc/manifest'\nHTTP_BASIC_AUTH = None\n\n\ndef blackbox(name, backend, targets, params,\n target='target', path='/probe', labels=None):\n labels = {} if labels is None else labels\n # Strip banned OSes\n banned_oses = ['debian']\n filtered_targets = [x for x in targets if lib.get_os(x) not in banned_oses]\n return {\n 'job_name': name,\n 'metrics_path': path,\n 'params': params,\n 'static_configs': [{\n 'targets': sorted(filtered_targets),\n 'labels': labels\n }],\n 'relabel_configs': [{\n 'source_labels': ['__address__'],\n 'regex': '(.*)(:80)?',\n 'target_label': '__param_%s' % target,\n 'replacement': '${1}',\n }, {\n 'source_labels': ['__param_%s' % target],\n 'regex': '(.*)',\n 'target_label': 'instance',\n 'replacement': '${1}',\n }, {\n 'source_labels': [],\n 'regex': '.*',\n 'target_label': '__address__',\n 'replacement': backend,\n }]\n }\n\n\ndef generate_backend(host, local_services):\n scrape_configs = []\n scrape_configs.extend(local_services)\n domain = lib.get_domain(host)\n\n basic_auth = lib.read_secret('services/monitoring:login')\n\n # Find services that wants to be monitored\n manifest = yaml.load(file(MANIFEST_PATH).read())\n for package, spec in manifest['packages'].iteritems():\n if spec is None or 'monitor' not in spec:\n continue\n\n urls = (spec['monitor']['url']\n if isinstance(spec['monitor']['url'], dict) else\n {None: spec['monitor']['url']})\n for url_id, url_str in urls.iteritems():\n url = urlparse.urlparse(url_str)\n targets = []\n for target in sorted(\n lib.get_nodes_with_package(package, domain).keys()):\n targets.append(target if url.port is None else '%s:%d' % (\n target, url.port))\n scrape_config = {\n 'job_name': package + ('-%s' % url_id if url_id else ''),\n 'metrics_path': url.path,\n 'scheme': url.scheme,\n 'static_configs': [\n {'targets': sorted(targets)}\n ],\n }\n if 'interval' in spec['monitor']:\n scrape_config['scrape_interval'] = spec['monitor']['interval']\n if 'labels' in spec['monitor']:\n scrape_config['static_configs'][0]['labels'] = spec['monitor']['labels']\n # Only allow authentication over https\n if spec['monitor'].get('auth', False) and url.scheme == 'https':\n scrape_config['basic_auth'] = basic_auth\n scrape_configs.append(scrape_config)\n\n # Layer specific monitoring\n layers = lib.get_layers(domain)\n\n snmp_nodes = {}\n ssh_nodes = {}\n for layer in layers:\n hosts = lib.get_nodes_with_layer(layer, domain)\n snmp_mute = lib.get_nodes_with_layer(layer, domain, 'no-snmp')\n ssh_mute = lib.get_nodes_with_layer(layer, domain, 'no-ssh')\n snmp_nodes[layer] = list(set(hosts) - set(snmp_mute))\n ssh_nodes[layer] = [x+':22' for x in set(hosts) - set(ssh_mute)]\n\n # SNMP\n for layer in layers:\n # TODO(bluecmd): Use options for this\n if layer == 'access':\n snmp_host = 'snmp2.event.dreamhack.se'\n else:\n snmp_host = 'snmp1.event.dreamhack.se'\n snmp = blackbox(\n 'snmp_%s' % layer, snmp_host,\n snmp_nodes[layer], {'layer': [layer]}, labels={\n 'layer': layer})\n snmp['scrape_interval'] = '30s'\n snmp['scrape_timeout'] = '30s'\n scrape_configs.append(snmp)\n\n # SSH\n for layer in layers:\n for ssh_host in ['jumpgate1', 'jumpgate2', 'rancid']:\n fqdn = ssh_host + '.event.dreamhack.se:9115'\n ssh = blackbox(\n 'ssh_%s_%s' % (layer, ssh_host), fqdn,\n ssh_nodes[layer], {'module': ['ssh_banner']}, labels={'layer': layer})\n ssh['scrape_interval'] = '30s'\n ssh['scrape_timeout'] = '30s'\n scrape_configs.append(ssh)\n\n # Add external service-discovery\n external = {\n 'job_name': 'external',\n 'file_sd_configs': [{\n 'files': ['/etc/prometheus/external/*.yaml'],\n }],\n }\n scrape_configs.append(external)\n\n if host.endswith('.event.dreamhack.se'):\n # Event should scrape puppet.tech.dreamhack.se to get information about\n # puppet runs\n puppet = {\n 'job_name': 'puppet_runs',\n 'metrics_path': '/metrics',\n 'scrape_interval': '60s',\n 'scrape_timeout': '55s',\n 'static_configs': [{\n 'targets': ['puppet.tech.dreamhack.se:9100'],\n }],\n }\n scrape_configs.append(puppet)\n\n vcenter = {\n 'job_name': 'vmware_vcenter',\n 'metrics_path': '/metrics',\n 'scrape_interval': '60s',\n 'scrape_timeout': '55s',\n 'static_configs': [{\n 'targets': ['provision.event.dreamhack.se:9272'],\n }],\n }\n scrape_configs.append(vcenter)\n\n # Make sure that all metrics have a host label.\n # This rule uses the existing host label if there is one,\n # stripping of the port (which shouldn't be part of the host label anyway)\n # *or* if that label does not exist it uses the instance label\n # (again stripping of the port)\n relabel = {\n 'regex': r':?([^:]*):?.*',\n 'separator': ':',\n 'replacement': '${1}',\n 'source_labels': ['host', 'instance'],\n 'target_label': 'host',\n }\n\n mrc = 'metric_relabel_configs'\n for scrape in scrape_configs:\n if mrc in scrape:\n scrape[mrc].append(relabel)\n else:\n scrape[mrc] = [relabel]\n return {'scrape_configs': scrape_configs}\n\n\ndef requires(host, *args):\n return ['apache(ldap)']\n\n\ndef generate(host, *args):\n\n info = {}\n\n local_targets = []\n local_targets.append({\n 'job_name': 'prometheus',\n 'scheme': 'http',\n 'static_configs': [{'targets': ['localhost:9090']}]})\n info['prometheus'] = generate_backend(host, local_targets)\n\n # Get current event\n info['prometheus']['current_event'] = lib.get_current_event()\n\n return info\n\n# vim: ts=4: sts=4: sw=4: expandtab\n", "import lib\nimport urlparse\nimport yaml\nMANIFEST_PATH = '/etc/manifest'\nHTTP_BASIC_AUTH = None\n\n\ndef blackbox(name, backend, targets, params, target='target', path='/probe',\n labels=None):\n labels = {} if labels is None else labels\n banned_oses = ['debian']\n filtered_targets = [x for x in targets if lib.get_os(x) not in banned_oses]\n return {'job_name': name, 'metrics_path': path, 'params': params,\n 'static_configs': [{'targets': sorted(filtered_targets), 'labels':\n labels}], 'relabel_configs': [{'source_labels': ['__address__'],\n 'regex': '(.*)(:80)?', 'target_label': '__param_%s' % target,\n 'replacement': '${1}'}, {'source_labels': ['__param_%s' % target],\n 'regex': '(.*)', 'target_label': 'instance', 'replacement': '${1}'},\n {'source_labels': [], 'regex': '.*', 'target_label': '__address__',\n 'replacement': backend}]}\n\n\ndef generate_backend(host, local_services):\n scrape_configs = []\n scrape_configs.extend(local_services)\n domain = lib.get_domain(host)\n basic_auth = lib.read_secret('services/monitoring:login')\n manifest = yaml.load(file(MANIFEST_PATH).read())\n for package, spec in manifest['packages'].iteritems():\n if spec is None or 'monitor' not in spec:\n continue\n urls = spec['monitor']['url'] if isinstance(spec['monitor']['url'],\n dict) else {None: spec['monitor']['url']}\n for url_id, url_str in urls.iteritems():\n url = urlparse.urlparse(url_str)\n targets = []\n for target in sorted(lib.get_nodes_with_package(package, domain\n ).keys()):\n targets.append(target if url.port is None else '%s:%d' % (\n target, url.port))\n scrape_config = {'job_name': package + ('-%s' % url_id if\n url_id else ''), 'metrics_path': url.path, 'scheme': url.\n scheme, 'static_configs': [{'targets': sorted(targets)}]}\n if 'interval' in spec['monitor']:\n scrape_config['scrape_interval'] = spec['monitor']['interval']\n if 'labels' in spec['monitor']:\n scrape_config['static_configs'][0]['labels'] = spec['monitor'][\n 'labels']\n if spec['monitor'].get('auth', False) and url.scheme == 'https':\n scrape_config['basic_auth'] = basic_auth\n scrape_configs.append(scrape_config)\n layers = lib.get_layers(domain)\n snmp_nodes = {}\n ssh_nodes = {}\n for layer in layers:\n hosts = lib.get_nodes_with_layer(layer, domain)\n snmp_mute = lib.get_nodes_with_layer(layer, domain, 'no-snmp')\n ssh_mute = lib.get_nodes_with_layer(layer, domain, 'no-ssh')\n snmp_nodes[layer] = list(set(hosts) - set(snmp_mute))\n ssh_nodes[layer] = [(x + ':22') for x in set(hosts) - set(ssh_mute)]\n for layer in layers:\n if layer == 'access':\n snmp_host = 'snmp2.event.dreamhack.se'\n else:\n snmp_host = 'snmp1.event.dreamhack.se'\n snmp = blackbox('snmp_%s' % layer, snmp_host, snmp_nodes[layer], {\n 'layer': [layer]}, labels={'layer': layer})\n snmp['scrape_interval'] = '30s'\n snmp['scrape_timeout'] = '30s'\n scrape_configs.append(snmp)\n for layer in layers:\n for ssh_host in ['jumpgate1', 'jumpgate2', 'rancid']:\n fqdn = ssh_host + '.event.dreamhack.se:9115'\n ssh = blackbox('ssh_%s_%s' % (layer, ssh_host), fqdn, ssh_nodes\n [layer], {'module': ['ssh_banner']}, labels={'layer': layer})\n ssh['scrape_interval'] = '30s'\n ssh['scrape_timeout'] = '30s'\n scrape_configs.append(ssh)\n external = {'job_name': 'external', 'file_sd_configs': [{'files': [\n '/etc/prometheus/external/*.yaml']}]}\n scrape_configs.append(external)\n if host.endswith('.event.dreamhack.se'):\n puppet = {'job_name': 'puppet_runs', 'metrics_path': '/metrics',\n 'scrape_interval': '60s', 'scrape_timeout': '55s',\n 'static_configs': [{'targets': ['puppet.tech.dreamhack.se:9100']}]}\n scrape_configs.append(puppet)\n vcenter = {'job_name': 'vmware_vcenter', 'metrics_path': '/metrics',\n 'scrape_interval': '60s', 'scrape_timeout': '55s', 'static_configs':\n [{'targets': ['provision.event.dreamhack.se:9272']}]}\n scrape_configs.append(vcenter)\n relabel = {'regex': ':?([^:]*):?.*', 'separator': ':', 'replacement':\n '${1}', 'source_labels': ['host', 'instance'], 'target_label': 'host'}\n mrc = 'metric_relabel_configs'\n for scrape in scrape_configs:\n if mrc in scrape:\n scrape[mrc].append(relabel)\n else:\n scrape[mrc] = [relabel]\n return {'scrape_configs': scrape_configs}\n\n\ndef requires(host, *args):\n return ['apache(ldap)']\n\n\ndef generate(host, *args):\n info = {}\n local_targets = []\n local_targets.append({'job_name': 'prometheus', 'scheme': 'http',\n 'static_configs': [{'targets': ['localhost:9090']}]})\n info['prometheus'] = generate_backend(host, local_targets)\n info['prometheus']['current_event'] = lib.get_current_event()\n return info\n", "<import token>\nMANIFEST_PATH = '/etc/manifest'\nHTTP_BASIC_AUTH = None\n\n\ndef blackbox(name, backend, targets, params, target='target', path='/probe',\n labels=None):\n labels = {} if labels is None else labels\n banned_oses = ['debian']\n filtered_targets = [x for x in targets if lib.get_os(x) not in banned_oses]\n return {'job_name': name, 'metrics_path': path, 'params': params,\n 'static_configs': [{'targets': sorted(filtered_targets), 'labels':\n labels}], 'relabel_configs': [{'source_labels': ['__address__'],\n 'regex': '(.*)(:80)?', 'target_label': '__param_%s' % target,\n 'replacement': '${1}'}, {'source_labels': ['__param_%s' % target],\n 'regex': '(.*)', 'target_label': 'instance', 'replacement': '${1}'},\n {'source_labels': [], 'regex': '.*', 'target_label': '__address__',\n 'replacement': backend}]}\n\n\ndef generate_backend(host, local_services):\n scrape_configs = []\n scrape_configs.extend(local_services)\n domain = lib.get_domain(host)\n basic_auth = lib.read_secret('services/monitoring:login')\n manifest = yaml.load(file(MANIFEST_PATH).read())\n for package, spec in manifest['packages'].iteritems():\n if spec is None or 'monitor' not in spec:\n continue\n urls = spec['monitor']['url'] if isinstance(spec['monitor']['url'],\n dict) else {None: spec['monitor']['url']}\n for url_id, url_str in urls.iteritems():\n url = urlparse.urlparse(url_str)\n targets = []\n for target in sorted(lib.get_nodes_with_package(package, domain\n ).keys()):\n targets.append(target if url.port is None else '%s:%d' % (\n target, url.port))\n scrape_config = {'job_name': package + ('-%s' % url_id if\n url_id else ''), 'metrics_path': url.path, 'scheme': url.\n scheme, 'static_configs': [{'targets': sorted(targets)}]}\n if 'interval' in spec['monitor']:\n scrape_config['scrape_interval'] = spec['monitor']['interval']\n if 'labels' in spec['monitor']:\n scrape_config['static_configs'][0]['labels'] = spec['monitor'][\n 'labels']\n if spec['monitor'].get('auth', False) and url.scheme == 'https':\n scrape_config['basic_auth'] = basic_auth\n scrape_configs.append(scrape_config)\n layers = lib.get_layers(domain)\n snmp_nodes = {}\n ssh_nodes = {}\n for layer in layers:\n hosts = lib.get_nodes_with_layer(layer, domain)\n snmp_mute = lib.get_nodes_with_layer(layer, domain, 'no-snmp')\n ssh_mute = lib.get_nodes_with_layer(layer, domain, 'no-ssh')\n snmp_nodes[layer] = list(set(hosts) - set(snmp_mute))\n ssh_nodes[layer] = [(x + ':22') for x in set(hosts) - set(ssh_mute)]\n for layer in layers:\n if layer == 'access':\n snmp_host = 'snmp2.event.dreamhack.se'\n else:\n snmp_host = 'snmp1.event.dreamhack.se'\n snmp = blackbox('snmp_%s' % layer, snmp_host, snmp_nodes[layer], {\n 'layer': [layer]}, labels={'layer': layer})\n snmp['scrape_interval'] = '30s'\n snmp['scrape_timeout'] = '30s'\n scrape_configs.append(snmp)\n for layer in layers:\n for ssh_host in ['jumpgate1', 'jumpgate2', 'rancid']:\n fqdn = ssh_host + '.event.dreamhack.se:9115'\n ssh = blackbox('ssh_%s_%s' % (layer, ssh_host), fqdn, ssh_nodes\n [layer], {'module': ['ssh_banner']}, labels={'layer': layer})\n ssh['scrape_interval'] = '30s'\n ssh['scrape_timeout'] = '30s'\n scrape_configs.append(ssh)\n external = {'job_name': 'external', 'file_sd_configs': [{'files': [\n '/etc/prometheus/external/*.yaml']}]}\n scrape_configs.append(external)\n if host.endswith('.event.dreamhack.se'):\n puppet = {'job_name': 'puppet_runs', 'metrics_path': '/metrics',\n 'scrape_interval': '60s', 'scrape_timeout': '55s',\n 'static_configs': [{'targets': ['puppet.tech.dreamhack.se:9100']}]}\n scrape_configs.append(puppet)\n vcenter = {'job_name': 'vmware_vcenter', 'metrics_path': '/metrics',\n 'scrape_interval': '60s', 'scrape_timeout': '55s', 'static_configs':\n [{'targets': ['provision.event.dreamhack.se:9272']}]}\n scrape_configs.append(vcenter)\n relabel = {'regex': ':?([^:]*):?.*', 'separator': ':', 'replacement':\n '${1}', 'source_labels': ['host', 'instance'], 'target_label': 'host'}\n mrc = 'metric_relabel_configs'\n for scrape in scrape_configs:\n if mrc in scrape:\n scrape[mrc].append(relabel)\n else:\n scrape[mrc] = [relabel]\n return {'scrape_configs': scrape_configs}\n\n\ndef requires(host, *args):\n return ['apache(ldap)']\n\n\ndef generate(host, *args):\n info = {}\n local_targets = []\n local_targets.append({'job_name': 'prometheus', 'scheme': 'http',\n 'static_configs': [{'targets': ['localhost:9090']}]})\n info['prometheus'] = generate_backend(host, local_targets)\n info['prometheus']['current_event'] = lib.get_current_event()\n return info\n", "<import token>\n<assignment token>\n\n\ndef blackbox(name, backend, targets, params, target='target', path='/probe',\n labels=None):\n labels = {} if labels is None else labels\n banned_oses = ['debian']\n filtered_targets = [x for x in targets if lib.get_os(x) not in banned_oses]\n return {'job_name': name, 'metrics_path': path, 'params': params,\n 'static_configs': [{'targets': sorted(filtered_targets), 'labels':\n labels}], 'relabel_configs': [{'source_labels': ['__address__'],\n 'regex': '(.*)(:80)?', 'target_label': '__param_%s' % target,\n 'replacement': '${1}'}, {'source_labels': ['__param_%s' % target],\n 'regex': '(.*)', 'target_label': 'instance', 'replacement': '${1}'},\n {'source_labels': [], 'regex': '.*', 'target_label': '__address__',\n 'replacement': backend}]}\n\n\ndef generate_backend(host, local_services):\n scrape_configs = []\n scrape_configs.extend(local_services)\n domain = lib.get_domain(host)\n basic_auth = lib.read_secret('services/monitoring:login')\n manifest = yaml.load(file(MANIFEST_PATH).read())\n for package, spec in manifest['packages'].iteritems():\n if spec is None or 'monitor' not in spec:\n continue\n urls = spec['monitor']['url'] if isinstance(spec['monitor']['url'],\n dict) else {None: spec['monitor']['url']}\n for url_id, url_str in urls.iteritems():\n url = urlparse.urlparse(url_str)\n targets = []\n for target in sorted(lib.get_nodes_with_package(package, domain\n ).keys()):\n targets.append(target if url.port is None else '%s:%d' % (\n target, url.port))\n scrape_config = {'job_name': package + ('-%s' % url_id if\n url_id else ''), 'metrics_path': url.path, 'scheme': url.\n scheme, 'static_configs': [{'targets': sorted(targets)}]}\n if 'interval' in spec['monitor']:\n scrape_config['scrape_interval'] = spec['monitor']['interval']\n if 'labels' in spec['monitor']:\n scrape_config['static_configs'][0]['labels'] = spec['monitor'][\n 'labels']\n if spec['monitor'].get('auth', False) and url.scheme == 'https':\n scrape_config['basic_auth'] = basic_auth\n scrape_configs.append(scrape_config)\n layers = lib.get_layers(domain)\n snmp_nodes = {}\n ssh_nodes = {}\n for layer in layers:\n hosts = lib.get_nodes_with_layer(layer, domain)\n snmp_mute = lib.get_nodes_with_layer(layer, domain, 'no-snmp')\n ssh_mute = lib.get_nodes_with_layer(layer, domain, 'no-ssh')\n snmp_nodes[layer] = list(set(hosts) - set(snmp_mute))\n ssh_nodes[layer] = [(x + ':22') for x in set(hosts) - set(ssh_mute)]\n for layer in layers:\n if layer == 'access':\n snmp_host = 'snmp2.event.dreamhack.se'\n else:\n snmp_host = 'snmp1.event.dreamhack.se'\n snmp = blackbox('snmp_%s' % layer, snmp_host, snmp_nodes[layer], {\n 'layer': [layer]}, labels={'layer': layer})\n snmp['scrape_interval'] = '30s'\n snmp['scrape_timeout'] = '30s'\n scrape_configs.append(snmp)\n for layer in layers:\n for ssh_host in ['jumpgate1', 'jumpgate2', 'rancid']:\n fqdn = ssh_host + '.event.dreamhack.se:9115'\n ssh = blackbox('ssh_%s_%s' % (layer, ssh_host), fqdn, ssh_nodes\n [layer], {'module': ['ssh_banner']}, labels={'layer': layer})\n ssh['scrape_interval'] = '30s'\n ssh['scrape_timeout'] = '30s'\n scrape_configs.append(ssh)\n external = {'job_name': 'external', 'file_sd_configs': [{'files': [\n '/etc/prometheus/external/*.yaml']}]}\n scrape_configs.append(external)\n if host.endswith('.event.dreamhack.se'):\n puppet = {'job_name': 'puppet_runs', 'metrics_path': '/metrics',\n 'scrape_interval': '60s', 'scrape_timeout': '55s',\n 'static_configs': [{'targets': ['puppet.tech.dreamhack.se:9100']}]}\n scrape_configs.append(puppet)\n vcenter = {'job_name': 'vmware_vcenter', 'metrics_path': '/metrics',\n 'scrape_interval': '60s', 'scrape_timeout': '55s', 'static_configs':\n [{'targets': ['provision.event.dreamhack.se:9272']}]}\n scrape_configs.append(vcenter)\n relabel = {'regex': ':?([^:]*):?.*', 'separator': ':', 'replacement':\n '${1}', 'source_labels': ['host', 'instance'], 'target_label': 'host'}\n mrc = 'metric_relabel_configs'\n for scrape in scrape_configs:\n if mrc in scrape:\n scrape[mrc].append(relabel)\n else:\n scrape[mrc] = [relabel]\n return {'scrape_configs': scrape_configs}\n\n\ndef requires(host, *args):\n return ['apache(ldap)']\n\n\ndef generate(host, *args):\n info = {}\n local_targets = []\n local_targets.append({'job_name': 'prometheus', 'scheme': 'http',\n 'static_configs': [{'targets': ['localhost:9090']}]})\n info['prometheus'] = generate_backend(host, local_targets)\n info['prometheus']['current_event'] = lib.get_current_event()\n return info\n", "<import token>\n<assignment token>\n\n\ndef blackbox(name, backend, targets, params, target='target', path='/probe',\n labels=None):\n labels = {} if labels is None else labels\n banned_oses = ['debian']\n filtered_targets = [x for x in targets if lib.get_os(x) not in banned_oses]\n return {'job_name': name, 'metrics_path': path, 'params': params,\n 'static_configs': [{'targets': sorted(filtered_targets), 'labels':\n labels}], 'relabel_configs': [{'source_labels': ['__address__'],\n 'regex': '(.*)(:80)?', 'target_label': '__param_%s' % target,\n 'replacement': '${1}'}, {'source_labels': ['__param_%s' % target],\n 'regex': '(.*)', 'target_label': 'instance', 'replacement': '${1}'},\n {'source_labels': [], 'regex': '.*', 'target_label': '__address__',\n 'replacement': backend}]}\n\n\n<function token>\n\n\ndef requires(host, *args):\n return ['apache(ldap)']\n\n\ndef generate(host, *args):\n info = {}\n local_targets = []\n local_targets.append({'job_name': 'prometheus', 'scheme': 'http',\n 'static_configs': [{'targets': ['localhost:9090']}]})\n info['prometheus'] = generate_backend(host, local_targets)\n info['prometheus']['current_event'] = lib.get_current_event()\n return info\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef requires(host, *args):\n return ['apache(ldap)']\n\n\ndef generate(host, *args):\n info = {}\n local_targets = []\n local_targets.append({'job_name': 'prometheus', 'scheme': 'http',\n 'static_configs': [{'targets': ['localhost:9090']}]})\n info['prometheus'] = generate_backend(host, local_targets)\n info['prometheus']['current_event'] = lib.get_current_event()\n return info\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n\n\ndef requires(host, *args):\n return ['apache(ldap)']\n\n\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
702
5299f2c66fd287be667ecbe11b8470263eafab5c
import logging class ConsoleLogger: handlers = [ (logging.StreamHandler, dict(), "[%(name)s]\t %(asctime)s [%(levelname)s] %(message)s ", logging.DEBUG) ] def set_level(self, level): self.logger.setLevel(level) def debug(self, message): self.logger.debug(message) def info(self, message): self.logger.info(message) def warning(self, message): self.logger.warning(message) def error(self, message): self.logger.error(message) def exception(self, message): self.logger.exception(message) def __init__(self, name=__name__, default_level=logging.DEBUG): self.logger = logging.Logger(name) if not self.logger.handlers or len(self.logger.handlers) < 1: for handler_class, params, formatted, level in self.handlers: handler = handler_class(**params) handler.setFormatter(logging.Formatter(formatted)) handler.setLevel(level if not default_level else default_level) self.logger.addHandler(handler)
[ "import logging\n\n\nclass ConsoleLogger:\n\n handlers = [\n (logging.StreamHandler,\n dict(),\n \"[%(name)s]\\t %(asctime)s [%(levelname)s] %(message)s \",\n logging.DEBUG)\n ]\n\n def set_level(self, level):\n self.logger.setLevel(level)\n\n def debug(self, message):\n self.logger.debug(message)\n\n def info(self, message):\n self.logger.info(message)\n\n def warning(self, message):\n self.logger.warning(message)\n\n def error(self, message):\n self.logger.error(message)\n\n def exception(self, message):\n self.logger.exception(message)\n\n def __init__(self, name=__name__, default_level=logging.DEBUG):\n self.logger = logging.Logger(name)\n if not self.logger.handlers or len(self.logger.handlers) < 1:\n for handler_class, params, formatted, level in self.handlers:\n handler = handler_class(**params)\n handler.setFormatter(logging.Formatter(formatted))\n handler.setLevel(level if not default_level else default_level)\n\n self.logger.addHandler(handler)\n", "import logging\n\n\nclass ConsoleLogger:\n handlers = [(logging.StreamHandler, dict(),\n '[%(name)s]\\t %(asctime)s [%(levelname)s] %(message)s ', logging.DEBUG)\n ]\n\n def set_level(self, level):\n self.logger.setLevel(level)\n\n def debug(self, message):\n self.logger.debug(message)\n\n def info(self, message):\n self.logger.info(message)\n\n def warning(self, message):\n self.logger.warning(message)\n\n def error(self, message):\n self.logger.error(message)\n\n def exception(self, message):\n self.logger.exception(message)\n\n def __init__(self, name=__name__, default_level=logging.DEBUG):\n self.logger = logging.Logger(name)\n if not self.logger.handlers or len(self.logger.handlers) < 1:\n for handler_class, params, formatted, level in self.handlers:\n handler = handler_class(**params)\n handler.setFormatter(logging.Formatter(formatted))\n handler.setLevel(level if not default_level else default_level)\n self.logger.addHandler(handler)\n", "<import token>\n\n\nclass ConsoleLogger:\n handlers = [(logging.StreamHandler, dict(),\n '[%(name)s]\\t %(asctime)s [%(levelname)s] %(message)s ', logging.DEBUG)\n ]\n\n def set_level(self, level):\n self.logger.setLevel(level)\n\n def debug(self, message):\n self.logger.debug(message)\n\n def info(self, message):\n self.logger.info(message)\n\n def warning(self, message):\n self.logger.warning(message)\n\n def error(self, message):\n self.logger.error(message)\n\n def exception(self, message):\n self.logger.exception(message)\n\n def __init__(self, name=__name__, default_level=logging.DEBUG):\n self.logger = logging.Logger(name)\n if not self.logger.handlers or len(self.logger.handlers) < 1:\n for handler_class, params, formatted, level in self.handlers:\n handler = handler_class(**params)\n handler.setFormatter(logging.Formatter(formatted))\n handler.setLevel(level if not default_level else default_level)\n self.logger.addHandler(handler)\n", "<import token>\n\n\nclass ConsoleLogger:\n <assignment token>\n\n def set_level(self, level):\n self.logger.setLevel(level)\n\n def debug(self, message):\n self.logger.debug(message)\n\n def info(self, message):\n self.logger.info(message)\n\n def warning(self, message):\n self.logger.warning(message)\n\n def error(self, message):\n self.logger.error(message)\n\n def exception(self, message):\n self.logger.exception(message)\n\n def __init__(self, name=__name__, default_level=logging.DEBUG):\n self.logger = logging.Logger(name)\n if not self.logger.handlers or len(self.logger.handlers) < 1:\n for handler_class, params, formatted, level in self.handlers:\n handler = handler_class(**params)\n handler.setFormatter(logging.Formatter(formatted))\n handler.setLevel(level if not default_level else default_level)\n self.logger.addHandler(handler)\n", "<import token>\n\n\nclass ConsoleLogger:\n <assignment token>\n <function token>\n\n def debug(self, message):\n self.logger.debug(message)\n\n def info(self, message):\n self.logger.info(message)\n\n def warning(self, message):\n self.logger.warning(message)\n\n def error(self, message):\n self.logger.error(message)\n\n def exception(self, message):\n self.logger.exception(message)\n\n def __init__(self, name=__name__, default_level=logging.DEBUG):\n self.logger = logging.Logger(name)\n if not self.logger.handlers or len(self.logger.handlers) < 1:\n for handler_class, params, formatted, level in self.handlers:\n handler = handler_class(**params)\n handler.setFormatter(logging.Formatter(formatted))\n handler.setLevel(level if not default_level else default_level)\n self.logger.addHandler(handler)\n", "<import token>\n\n\nclass ConsoleLogger:\n <assignment token>\n <function token>\n\n def debug(self, message):\n self.logger.debug(message)\n <function token>\n\n def warning(self, message):\n self.logger.warning(message)\n\n def error(self, message):\n self.logger.error(message)\n\n def exception(self, message):\n self.logger.exception(message)\n\n def __init__(self, name=__name__, default_level=logging.DEBUG):\n self.logger = logging.Logger(name)\n if not self.logger.handlers or len(self.logger.handlers) < 1:\n for handler_class, params, formatted, level in self.handlers:\n handler = handler_class(**params)\n handler.setFormatter(logging.Formatter(formatted))\n handler.setLevel(level if not default_level else default_level)\n self.logger.addHandler(handler)\n", "<import token>\n\n\nclass ConsoleLogger:\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def warning(self, message):\n self.logger.warning(message)\n\n def error(self, message):\n self.logger.error(message)\n\n def exception(self, message):\n self.logger.exception(message)\n\n def __init__(self, name=__name__, default_level=logging.DEBUG):\n self.logger = logging.Logger(name)\n if not self.logger.handlers or len(self.logger.handlers) < 1:\n for handler_class, params, formatted, level in self.handlers:\n handler = handler_class(**params)\n handler.setFormatter(logging.Formatter(formatted))\n handler.setLevel(level if not default_level else default_level)\n self.logger.addHandler(handler)\n", "<import token>\n\n\nclass ConsoleLogger:\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def warning(self, message):\n self.logger.warning(message)\n\n def error(self, message):\n self.logger.error(message)\n <function token>\n\n def __init__(self, name=__name__, default_level=logging.DEBUG):\n self.logger = logging.Logger(name)\n if not self.logger.handlers or len(self.logger.handlers) < 1:\n for handler_class, params, formatted, level in self.handlers:\n handler = handler_class(**params)\n handler.setFormatter(logging.Formatter(formatted))\n handler.setLevel(level if not default_level else default_level)\n self.logger.addHandler(handler)\n", "<import token>\n\n\nclass ConsoleLogger:\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def error(self, message):\n self.logger.error(message)\n <function token>\n\n def __init__(self, name=__name__, default_level=logging.DEBUG):\n self.logger = logging.Logger(name)\n if not self.logger.handlers or len(self.logger.handlers) < 1:\n for handler_class, params, formatted, level in self.handlers:\n handler = handler_class(**params)\n handler.setFormatter(logging.Formatter(formatted))\n handler.setLevel(level if not default_level else default_level)\n self.logger.addHandler(handler)\n", "<import token>\n\n\nclass ConsoleLogger:\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def __init__(self, name=__name__, default_level=logging.DEBUG):\n self.logger = logging.Logger(name)\n if not self.logger.handlers or len(self.logger.handlers) < 1:\n for handler_class, params, formatted, level in self.handlers:\n handler = handler_class(**params)\n handler.setFormatter(logging.Formatter(formatted))\n handler.setLevel(level if not default_level else default_level)\n self.logger.addHandler(handler)\n", "<import token>\n\n\nclass ConsoleLogger:\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
703
e73e40a63b67ee1a6cca53a328af05e3eb3d8519
import pytest from debbiedowner import make_it_negative, complain_about def test_negativity(): assert make_it_negative(8) == -8 assert complain_about('enthusiasm') == "I hate enthusiasm. Totally boring." def test_easy(): assert 1 == 1 def test_cleverness(): assert make_it_negative(-3) == 3
[ "import pytest\n\nfrom debbiedowner import make_it_negative, complain_about\n\ndef test_negativity():\n assert make_it_negative(8) == -8\n assert complain_about('enthusiasm') == \"I hate enthusiasm. Totally boring.\"\n\ndef test_easy():\n assert 1 == 1\n\ndef test_cleverness():\n assert make_it_negative(-3) == 3", "import pytest\nfrom debbiedowner import make_it_negative, complain_about\n\n\ndef test_negativity():\n assert make_it_negative(8) == -8\n assert complain_about('enthusiasm') == 'I hate enthusiasm. Totally boring.'\n\n\ndef test_easy():\n assert 1 == 1\n\n\ndef test_cleverness():\n assert make_it_negative(-3) == 3\n", "<import token>\n\n\ndef test_negativity():\n assert make_it_negative(8) == -8\n assert complain_about('enthusiasm') == 'I hate enthusiasm. Totally boring.'\n\n\ndef test_easy():\n assert 1 == 1\n\n\ndef test_cleverness():\n assert make_it_negative(-3) == 3\n", "<import token>\n<function token>\n\n\ndef test_easy():\n assert 1 == 1\n\n\ndef test_cleverness():\n assert make_it_negative(-3) == 3\n", "<import token>\n<function token>\n\n\ndef test_easy():\n assert 1 == 1\n\n\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n" ]
false
704
01b615f8282d4d42c5e83181fffc2d7cb612c096
import sys def saludar(saludo): print saludo def iniciales(nombre,ape1,ape2): iniciales=nombre[0]+'.'+ape1[0]+'.'+ape2[0]+'.' return "Tus iniciales son:"+iniciales.upper() def iniciales1(nombre,ape1,*apellidos): iniciales=nombre[0]+'.'+ape1[0] for ape in apellidos: iniciales=iniciales+'.'+ape[0] return iniciales.upper()
[ "import sys \n\n\ndef saludar(saludo):\n\tprint saludo\n\ndef iniciales(nombre,ape1,ape2):\n\tiniciales=nombre[0]+'.'+ape1[0]+'.'+ape2[0]+'.'\n\treturn \"Tus iniciales son:\"+iniciales.upper()\n\n\ndef iniciales1(nombre,ape1,*apellidos):\n\tiniciales=nombre[0]+'.'+ape1[0]\n\tfor ape in apellidos:\n\t\tiniciales=iniciales+'.'+ape[0]\n\treturn iniciales.upper()\n\n\n\n\n\n\n" ]
true
705
eeb87891d1a02484a61537745ec6f13387017929
import os import shutil import json from django.shortcuts import render, HttpResponse from django.utils.encoding import escape_uri_path from django.db import transaction from web_pan.settings import files_folder from disk import models # Create your views here. def logined(func): def wrapper(request, *args, **kwargs): session = request.session.get('user') if not session: return render(request, 'login.html') else: return func(request, *args, **kwargs) return wrapper def api_check(func): def wrapper(request, *args, **kwargs): session = request.session.get('user') if not session: res = dict( state_code=-3, error_msg="登陆过期" ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') else: return func(request, *args, **kwargs) return wrapper def login(request): if request.method == 'GET': if request.session.get('user'): return render(request, 'index.html') return render(request, 'login.html') else: req = json.loads(request.body) user = req.get('username') pwd = req.get('pwd') obj_user = models.Users.objects.filter(user_name=user).all() if not obj_user: res = dict( state_code=1, error_msg="用户不存在" ) else: password = obj_user.first().password if str(pwd) != str(password): res = dict( state_code=2, error_msg="密码错误" ) else: request.session['user'] = user request.session.set_expiry(60*60*4) res = dict( state_code=0, error_msg="密码错误" ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') def logout(request): if request.session.get('user'): del request.session['user'] return render(request, 'login.html') @logined def index(request): return render(request, 'index.html') @api_check def get_dir_list(request): user = request.session.get('user') obj_dir = models.Dirs.objects.filter(user_name=user).all() dir_list = [] for dirs in obj_dir: user_dir = dirs.dir dir_list.append(user_dir) res = dict( state_code=0, error_msg='ok', data={ "dir_list": dir_list } ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') @api_check def user_mkdir(request): req = json.loads(request.body) dir_name = req.get('dir_name') if not dir_name: res = dict( state_code=-2, error_msg='参数错误' ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') dir_path = os.path.join(files_folder, dir_name) if os.path.exists(dir_path): res = dict( state_code=1, error_msg="该目录已被使用" ) else: user = request.session.get('user') if user: models.Dirs.objects.create( user_name=user, dir=dir_name ) os.mkdir(dir_path) res = dict( state_code=0, error_msg='ok' ) else: res = dict( state_code=-3, error_msg="登陆过期" ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') @api_check def del_dir(request): req = json.loads(request.body) dir_name = req.get('dir_name') if not dir_name: res = dict( state_code=-2, error_msg='参数错误' ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') dir_path = os.path.join(files_folder, dir_name) if not os.path.exists(dir_path): res = dict( state_code=1, error_msg='目录不存在' ) else: with transaction.atomic(): obj_dir = models.Dirs.objects.filter(dir=dir_name).all() if obj_dir: obj_dir.delete() shutil.rmtree(dir_path) res = dict( state_code=0, eror_msg='ok' ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') @api_check def upload_file(request): dir_name = request.POST.get('dir_name') if not dir_name: res = dict( state_code=-2, error_msg='参数错误' ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') dir_path = os.path.join(files_folder, dir_name) if not os.path.exists(dir_path): res = dict( state_code=1, error_msg='目录不存在' ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') # 获取上传的文件,如果没有文件,则默认为None; File = request.FILES.get("file", None) if File is None: res = dict( state_code=-2, error_msg='参数错误' ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') file_name = File.name file_path = os.path.join(dir_path, file_name) # 打开特定的文件进行二进制的写操作; with open(file_path, 'wb+') as f: # 分块写入文件; for chunk in File.chunks(): f.write(chunk) res = dict( state_code=0, error_msg='ok', ) return HttpResponse(json.dumps(res), content_type='application/json') @api_check def query_file(request): req = json.loads(request.body) dir_name = req.get('dir_name') dir_path = os.path.join(files_folder, dir_name) cmd_info = os.popen("ls -l -h {}".format(dir_path)).read() file_list = cmd_info.split('\n')[1:-1] file_list_data = [] for file_info_cmd in file_list: file_info_list = file_info_cmd.split(' ') file_info = list(filter(None, file_info_list)) file = file_info[-1] file_size = file_info[4] name_type = file.rsplit('.', 1) if len(name_type) < 2: name_type.append('未知') file_name, file_type = name_type file_list_data.append({ 'file_name': file_name, 'file_type': file_type, 'file_size': file_size }) res = dict( state_code=0, error_msg='ok', data={ 'file_list': file_list_data } ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') @api_check def del_file(request): req = json.loads(request.body) dir_name = req.get('dir_name') file_name = req.get('file_name') file_type = req.get('file_type') file = file_name + '.' + file_type if file_type != '未知' else file_name file_path = os.path.join(os.path.join(files_folder,dir_name),file) if not os.path.exists(file_path): res = dict( state_code=1, error_msg='文件不存在' ) else: os.remove(file_path) res = dict( state_code=0, error_msg='ok' ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') @api_check def download_file(request): req = json.loads(request.body) dir_name = req.get('dir_name') file_name = req.get('file_name') file_type = req.get('file_type') file = file_name+'.'+file_type if file_type != '未知' else file_name file_path = os.path.join(os.path.join(files_folder,dir_name),file) if not os.path.exists(file_path): res = dict( state_code=1, error_msg='文件不存在' ) return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json') from django.http import StreamingHttpResponse file_size = os.path.getsize(file_path) def file_iterator(file_name, chunk_size=512): # 用于形成二进制数据 with open(file_name, 'rb') as f: while True: c = f.read(chunk_size) if c: yield c else: break the_file_name = file_path # 要下载的文件路径 res = file_iterator(the_file_name) response = StreamingHttpResponse(res) # 这里创建返回 response['Content-Type'] = 'application/octet-stream; charset=UTF-8' # 注意格式 response['Content-Length'] = file_size response['Content-Disposition'] = 'attachment;filename="{}"'.format(escape_uri_path(file)) # 注意filename 这个是下载后的名字 return response
[ "import os\nimport shutil\nimport json\nfrom django.shortcuts import render, HttpResponse\nfrom django.utils.encoding import escape_uri_path\nfrom django.db import transaction\nfrom web_pan.settings import files_folder\nfrom disk import models\n\n\n# Create your views here.\n\n\ndef logined(func):\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n return render(request, 'login.html')\n else:\n return func(request, *args, **kwargs)\n\n return wrapper\n\n\ndef api_check(func):\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n res = dict(\n state_code=-3,\n error_msg=\"登陆过期\"\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n else:\n return func(request, *args, **kwargs)\n\n return wrapper\n\n\ndef login(request):\n if request.method == 'GET':\n if request.session.get('user'):\n return render(request, 'index.html')\n return render(request, 'login.html')\n else:\n req = json.loads(request.body)\n user = req.get('username')\n pwd = req.get('pwd')\n obj_user = models.Users.objects.filter(user_name=user).all()\n if not obj_user:\n res = dict(\n state_code=1,\n error_msg=\"用户不存在\"\n )\n else:\n password = obj_user.first().password\n if str(pwd) != str(password):\n res = dict(\n state_code=2,\n error_msg=\"密码错误\"\n )\n else:\n request.session['user'] = user\n request.session.set_expiry(60*60*4)\n res = dict(\n state_code=0,\n error_msg=\"密码错误\"\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n\n\ndef logout(request):\n if request.session.get('user'):\n del request.session['user']\n return render(request, 'login.html')\n\n\n@logined\ndef index(request):\n return render(request, 'index.html')\n\n\n@api_check\ndef get_dir_list(request):\n user = request.session.get('user')\n obj_dir = models.Dirs.objects.filter(user_name=user).all()\n dir_list = []\n for dirs in obj_dir:\n user_dir = dirs.dir\n dir_list.append(user_dir)\n res = dict(\n state_code=0,\n error_msg='ok',\n data={\n \"dir_list\": dir_list\n }\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n\n\n@api_check\ndef user_mkdir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(\n state_code=-2,\n error_msg='参数错误'\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if os.path.exists(dir_path):\n res = dict(\n state_code=1,\n error_msg=\"该目录已被使用\"\n )\n else:\n user = request.session.get('user')\n if user:\n models.Dirs.objects.create(\n user_name=user,\n dir=dir_name\n )\n os.mkdir(dir_path)\n res = dict(\n state_code=0,\n error_msg='ok'\n )\n else:\n res = dict(\n state_code=-3,\n error_msg=\"登陆过期\"\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(\n state_code=-2,\n error_msg='参数错误'\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(\n state_code=1,\n error_msg='目录不存在'\n )\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(\n state_code=0,\n eror_msg='ok'\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(\n state_code=-2,\n error_msg='参数错误'\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(\n state_code=1,\n error_msg='目录不存在'\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n # 获取上传的文件,如果没有文件,则默认为None;\n File = request.FILES.get(\"file\", None)\n if File is None:\n res = dict(\n state_code=-2,\n error_msg='参数错误'\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n # 打开特定的文件进行二进制的写操作;\n with open(file_path, 'wb+') as f:\n # 分块写入文件;\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(\n state_code=0,\n error_msg='ok',\n )\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n@api_check\ndef query_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n dir_path = os.path.join(files_folder, dir_name)\n cmd_info = os.popen(\"ls -l -h {}\".format(dir_path)).read()\n file_list = cmd_info.split('\\n')[1:-1]\n file_list_data = []\n for file_info_cmd in file_list:\n file_info_list = file_info_cmd.split(' ')\n file_info = list(filter(None, file_info_list))\n file = file_info[-1]\n file_size = file_info[4]\n name_type = file.rsplit('.', 1)\n if len(name_type) < 2:\n name_type.append('未知')\n file_name, file_type = name_type\n file_list_data.append({\n 'file_name': file_name,\n 'file_type': file_type,\n 'file_size': file_size\n })\n res = dict(\n state_code=0,\n error_msg='ok',\n data={\n 'file_list': file_list_data\n }\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n\n\n@api_check\ndef del_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder,dir_name),file)\n if not os.path.exists(file_path):\n res = dict(\n state_code=1,\n error_msg='文件不存在'\n )\n else:\n os.remove(file_path)\n res = dict(\n state_code=0,\n error_msg='ok'\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name+'.'+file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder,dir_name),file)\n if not os.path.exists(file_path):\n res = dict(\n state_code=1,\n error_msg='文件不存在'\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n def file_iterator(file_name, chunk_size=512): # 用于形成二进制数据\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path # 要下载的文件路径\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res) # 这里创建返回\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8' # 注意格式\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(escape_uri_path(file)) # 注意filename 这个是下载后的名字\n return response\n", "import os\nimport shutil\nimport json\nfrom django.shortcuts import render, HttpResponse\nfrom django.utils.encoding import escape_uri_path\nfrom django.db import transaction\nfrom web_pan.settings import files_folder\nfrom disk import models\n\n\ndef logined(func):\n\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n return render(request, 'login.html')\n else:\n return func(request, *args, **kwargs)\n return wrapper\n\n\ndef api_check(func):\n\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n res = dict(state_code=-3, error_msg='登陆过期')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n else:\n return func(request, *args, **kwargs)\n return wrapper\n\n\ndef login(request):\n if request.method == 'GET':\n if request.session.get('user'):\n return render(request, 'index.html')\n return render(request, 'login.html')\n else:\n req = json.loads(request.body)\n user = req.get('username')\n pwd = req.get('pwd')\n obj_user = models.Users.objects.filter(user_name=user).all()\n if not obj_user:\n res = dict(state_code=1, error_msg='用户不存在')\n else:\n password = obj_user.first().password\n if str(pwd) != str(password):\n res = dict(state_code=2, error_msg='密码错误')\n else:\n request.session['user'] = user\n request.session.set_expiry(60 * 60 * 4)\n res = dict(state_code=0, error_msg='密码错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n\n\ndef logout(request):\n if request.session.get('user'):\n del request.session['user']\n return render(request, 'login.html')\n\n\n@logined\ndef index(request):\n return render(request, 'index.html')\n\n\n@api_check\ndef get_dir_list(request):\n user = request.session.get('user')\n obj_dir = models.Dirs.objects.filter(user_name=user).all()\n dir_list = []\n for dirs in obj_dir:\n user_dir = dirs.dir\n dir_list.append(user_dir)\n res = dict(state_code=0, error_msg='ok', data={'dir_list': dir_list})\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef user_mkdir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='该目录已被使用')\n else:\n user = request.session.get('user')\n if user:\n models.Dirs.objects.create(user_name=user, dir=dir_name)\n os.mkdir(dir_path)\n res = dict(state_code=0, error_msg='ok')\n else:\n res = dict(state_code=-3, error_msg='登陆过期')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n@api_check\ndef query_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n dir_path = os.path.join(files_folder, dir_name)\n cmd_info = os.popen('ls -l -h {}'.format(dir_path)).read()\n file_list = cmd_info.split('\\n')[1:-1]\n file_list_data = []\n for file_info_cmd in file_list:\n file_info_list = file_info_cmd.split(' ')\n file_info = list(filter(None, file_info_list))\n file = file_info[-1]\n file_size = file_info[4]\n name_type = file.rsplit('.', 1)\n if len(name_type) < 2:\n name_type.append('未知')\n file_name, file_type = name_type\n file_list_data.append({'file_name': file_name, 'file_type':\n file_type, 'file_size': file_size})\n res = dict(state_code=0, error_msg='ok', data={'file_list': file_list_data}\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef del_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n else:\n os.remove(file_path)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n\n def file_iterator(file_name, chunk_size=512):\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res)\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8'\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(\n escape_uri_path(file))\n return response\n", "<import token>\n\n\ndef logined(func):\n\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n return render(request, 'login.html')\n else:\n return func(request, *args, **kwargs)\n return wrapper\n\n\ndef api_check(func):\n\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n res = dict(state_code=-3, error_msg='登陆过期')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n else:\n return func(request, *args, **kwargs)\n return wrapper\n\n\ndef login(request):\n if request.method == 'GET':\n if request.session.get('user'):\n return render(request, 'index.html')\n return render(request, 'login.html')\n else:\n req = json.loads(request.body)\n user = req.get('username')\n pwd = req.get('pwd')\n obj_user = models.Users.objects.filter(user_name=user).all()\n if not obj_user:\n res = dict(state_code=1, error_msg='用户不存在')\n else:\n password = obj_user.first().password\n if str(pwd) != str(password):\n res = dict(state_code=2, error_msg='密码错误')\n else:\n request.session['user'] = user\n request.session.set_expiry(60 * 60 * 4)\n res = dict(state_code=0, error_msg='密码错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n\n\ndef logout(request):\n if request.session.get('user'):\n del request.session['user']\n return render(request, 'login.html')\n\n\n@logined\ndef index(request):\n return render(request, 'index.html')\n\n\n@api_check\ndef get_dir_list(request):\n user = request.session.get('user')\n obj_dir = models.Dirs.objects.filter(user_name=user).all()\n dir_list = []\n for dirs in obj_dir:\n user_dir = dirs.dir\n dir_list.append(user_dir)\n res = dict(state_code=0, error_msg='ok', data={'dir_list': dir_list})\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef user_mkdir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='该目录已被使用')\n else:\n user = request.session.get('user')\n if user:\n models.Dirs.objects.create(user_name=user, dir=dir_name)\n os.mkdir(dir_path)\n res = dict(state_code=0, error_msg='ok')\n else:\n res = dict(state_code=-3, error_msg='登陆过期')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n@api_check\ndef query_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n dir_path = os.path.join(files_folder, dir_name)\n cmd_info = os.popen('ls -l -h {}'.format(dir_path)).read()\n file_list = cmd_info.split('\\n')[1:-1]\n file_list_data = []\n for file_info_cmd in file_list:\n file_info_list = file_info_cmd.split(' ')\n file_info = list(filter(None, file_info_list))\n file = file_info[-1]\n file_size = file_info[4]\n name_type = file.rsplit('.', 1)\n if len(name_type) < 2:\n name_type.append('未知')\n file_name, file_type = name_type\n file_list_data.append({'file_name': file_name, 'file_type':\n file_type, 'file_size': file_size})\n res = dict(state_code=0, error_msg='ok', data={'file_list': file_list_data}\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef del_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n else:\n os.remove(file_path)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n\n def file_iterator(file_name, chunk_size=512):\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res)\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8'\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(\n escape_uri_path(file))\n return response\n", "<import token>\n\n\ndef logined(func):\n\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n return render(request, 'login.html')\n else:\n return func(request, *args, **kwargs)\n return wrapper\n\n\ndef api_check(func):\n\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n res = dict(state_code=-3, error_msg='登陆过期')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n else:\n return func(request, *args, **kwargs)\n return wrapper\n\n\ndef login(request):\n if request.method == 'GET':\n if request.session.get('user'):\n return render(request, 'index.html')\n return render(request, 'login.html')\n else:\n req = json.loads(request.body)\n user = req.get('username')\n pwd = req.get('pwd')\n obj_user = models.Users.objects.filter(user_name=user).all()\n if not obj_user:\n res = dict(state_code=1, error_msg='用户不存在')\n else:\n password = obj_user.first().password\n if str(pwd) != str(password):\n res = dict(state_code=2, error_msg='密码错误')\n else:\n request.session['user'] = user\n request.session.set_expiry(60 * 60 * 4)\n res = dict(state_code=0, error_msg='密码错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n\n\ndef logout(request):\n if request.session.get('user'):\n del request.session['user']\n return render(request, 'login.html')\n\n\n@logined\ndef index(request):\n return render(request, 'index.html')\n\n\n@api_check\ndef get_dir_list(request):\n user = request.session.get('user')\n obj_dir = models.Dirs.objects.filter(user_name=user).all()\n dir_list = []\n for dirs in obj_dir:\n user_dir = dirs.dir\n dir_list.append(user_dir)\n res = dict(state_code=0, error_msg='ok', data={'dir_list': dir_list})\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n<function token>\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n@api_check\ndef query_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n dir_path = os.path.join(files_folder, dir_name)\n cmd_info = os.popen('ls -l -h {}'.format(dir_path)).read()\n file_list = cmd_info.split('\\n')[1:-1]\n file_list_data = []\n for file_info_cmd in file_list:\n file_info_list = file_info_cmd.split(' ')\n file_info = list(filter(None, file_info_list))\n file = file_info[-1]\n file_size = file_info[4]\n name_type = file.rsplit('.', 1)\n if len(name_type) < 2:\n name_type.append('未知')\n file_name, file_type = name_type\n file_list_data.append({'file_name': file_name, 'file_type':\n file_type, 'file_size': file_size})\n res = dict(state_code=0, error_msg='ok', data={'file_list': file_list_data}\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef del_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n else:\n os.remove(file_path)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n\n def file_iterator(file_name, chunk_size=512):\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res)\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8'\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(\n escape_uri_path(file))\n return response\n", "<import token>\n<function token>\n\n\ndef api_check(func):\n\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n res = dict(state_code=-3, error_msg='登陆过期')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n else:\n return func(request, *args, **kwargs)\n return wrapper\n\n\ndef login(request):\n if request.method == 'GET':\n if request.session.get('user'):\n return render(request, 'index.html')\n return render(request, 'login.html')\n else:\n req = json.loads(request.body)\n user = req.get('username')\n pwd = req.get('pwd')\n obj_user = models.Users.objects.filter(user_name=user).all()\n if not obj_user:\n res = dict(state_code=1, error_msg='用户不存在')\n else:\n password = obj_user.first().password\n if str(pwd) != str(password):\n res = dict(state_code=2, error_msg='密码错误')\n else:\n request.session['user'] = user\n request.session.set_expiry(60 * 60 * 4)\n res = dict(state_code=0, error_msg='密码错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n\n\ndef logout(request):\n if request.session.get('user'):\n del request.session['user']\n return render(request, 'login.html')\n\n\n@logined\ndef index(request):\n return render(request, 'index.html')\n\n\n@api_check\ndef get_dir_list(request):\n user = request.session.get('user')\n obj_dir = models.Dirs.objects.filter(user_name=user).all()\n dir_list = []\n for dirs in obj_dir:\n user_dir = dirs.dir\n dir_list.append(user_dir)\n res = dict(state_code=0, error_msg='ok', data={'dir_list': dir_list})\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n<function token>\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n@api_check\ndef query_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n dir_path = os.path.join(files_folder, dir_name)\n cmd_info = os.popen('ls -l -h {}'.format(dir_path)).read()\n file_list = cmd_info.split('\\n')[1:-1]\n file_list_data = []\n for file_info_cmd in file_list:\n file_info_list = file_info_cmd.split(' ')\n file_info = list(filter(None, file_info_list))\n file = file_info[-1]\n file_size = file_info[4]\n name_type = file.rsplit('.', 1)\n if len(name_type) < 2:\n name_type.append('未知')\n file_name, file_type = name_type\n file_list_data.append({'file_name': file_name, 'file_type':\n file_type, 'file_size': file_size})\n res = dict(state_code=0, error_msg='ok', data={'file_list': file_list_data}\n )\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef del_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n else:\n os.remove(file_path)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n\n def file_iterator(file_name, chunk_size=512):\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res)\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8'\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(\n escape_uri_path(file))\n return response\n", "<import token>\n<function token>\n\n\ndef api_check(func):\n\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n res = dict(state_code=-3, error_msg='登陆过期')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n else:\n return func(request, *args, **kwargs)\n return wrapper\n\n\ndef login(request):\n if request.method == 'GET':\n if request.session.get('user'):\n return render(request, 'index.html')\n return render(request, 'login.html')\n else:\n req = json.loads(request.body)\n user = req.get('username')\n pwd = req.get('pwd')\n obj_user = models.Users.objects.filter(user_name=user).all()\n if not obj_user:\n res = dict(state_code=1, error_msg='用户不存在')\n else:\n password = obj_user.first().password\n if str(pwd) != str(password):\n res = dict(state_code=2, error_msg='密码错误')\n else:\n request.session['user'] = user\n request.session.set_expiry(60 * 60 * 4)\n res = dict(state_code=0, error_msg='密码错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n\n\ndef logout(request):\n if request.session.get('user'):\n del request.session['user']\n return render(request, 'login.html')\n\n\n@logined\ndef index(request):\n return render(request, 'index.html')\n\n\n@api_check\ndef get_dir_list(request):\n user = request.session.get('user')\n obj_dir = models.Dirs.objects.filter(user_name=user).all()\n dir_list = []\n for dirs in obj_dir:\n user_dir = dirs.dir\n dir_list.append(user_dir)\n res = dict(state_code=0, error_msg='ok', data={'dir_list': dir_list})\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n<function token>\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n<function token>\n\n\n@api_check\ndef del_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n else:\n os.remove(file_path)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n\n def file_iterator(file_name, chunk_size=512):\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res)\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8'\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(\n escape_uri_path(file))\n return response\n", "<import token>\n<function token>\n\n\ndef api_check(func):\n\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n res = dict(state_code=-3, error_msg='登陆过期')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n else:\n return func(request, *args, **kwargs)\n return wrapper\n\n\ndef login(request):\n if request.method == 'GET':\n if request.session.get('user'):\n return render(request, 'index.html')\n return render(request, 'login.html')\n else:\n req = json.loads(request.body)\n user = req.get('username')\n pwd = req.get('pwd')\n obj_user = models.Users.objects.filter(user_name=user).all()\n if not obj_user:\n res = dict(state_code=1, error_msg='用户不存在')\n else:\n password = obj_user.first().password\n if str(pwd) != str(password):\n res = dict(state_code=2, error_msg='密码错误')\n else:\n request.session['user'] = user\n request.session.set_expiry(60 * 60 * 4)\n res = dict(state_code=0, error_msg='密码错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n\n\ndef logout(request):\n if request.session.get('user'):\n del request.session['user']\n return render(request, 'login.html')\n\n\n<function token>\n\n\n@api_check\ndef get_dir_list(request):\n user = request.session.get('user')\n obj_dir = models.Dirs.objects.filter(user_name=user).all()\n dir_list = []\n for dirs in obj_dir:\n user_dir = dirs.dir\n dir_list.append(user_dir)\n res = dict(state_code=0, error_msg='ok', data={'dir_list': dir_list})\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n<function token>\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n<function token>\n\n\n@api_check\ndef del_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n else:\n os.remove(file_path)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n\n def file_iterator(file_name, chunk_size=512):\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res)\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8'\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(\n escape_uri_path(file))\n return response\n", "<import token>\n<function token>\n\n\ndef api_check(func):\n\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n res = dict(state_code=-3, error_msg='登陆过期')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n else:\n return func(request, *args, **kwargs)\n return wrapper\n\n\ndef login(request):\n if request.method == 'GET':\n if request.session.get('user'):\n return render(request, 'index.html')\n return render(request, 'login.html')\n else:\n req = json.loads(request.body)\n user = req.get('username')\n pwd = req.get('pwd')\n obj_user = models.Users.objects.filter(user_name=user).all()\n if not obj_user:\n res = dict(state_code=1, error_msg='用户不存在')\n else:\n password = obj_user.first().password\n if str(pwd) != str(password):\n res = dict(state_code=2, error_msg='密码错误')\n else:\n request.session['user'] = user\n request.session.set_expiry(60 * 60 * 4)\n res = dict(state_code=0, error_msg='密码错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n\n\ndef logout(request):\n if request.session.get('user'):\n del request.session['user']\n return render(request, 'login.html')\n\n\n<function token>\n<function token>\n<function token>\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n<function token>\n\n\n@api_check\ndef del_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n else:\n os.remove(file_path)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n\n def file_iterator(file_name, chunk_size=512):\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res)\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8'\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(\n escape_uri_path(file))\n return response\n", "<import token>\n<function token>\n\n\ndef api_check(func):\n\n def wrapper(request, *args, **kwargs):\n session = request.session.get('user')\n if not session:\n res = dict(state_code=-3, error_msg='登陆过期')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n else:\n return func(request, *args, **kwargs)\n return wrapper\n\n\n<function token>\n\n\ndef logout(request):\n if request.session.get('user'):\n del request.session['user']\n return render(request, 'login.html')\n\n\n<function token>\n<function token>\n<function token>\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n<function token>\n\n\n@api_check\ndef del_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n else:\n os.remove(file_path)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n\n def file_iterator(file_name, chunk_size=512):\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res)\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8'\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(\n escape_uri_path(file))\n return response\n", "<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef logout(request):\n if request.session.get('user'):\n del request.session['user']\n return render(request, 'login.html')\n\n\n<function token>\n<function token>\n<function token>\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n<function token>\n\n\n@api_check\ndef del_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n else:\n os.remove(file_path)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n\n def file_iterator(file_name, chunk_size=512):\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res)\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8'\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(\n escape_uri_path(file))\n return response\n", "<import token>\n<function token>\n<function token>\n<function token>\n\n\ndef logout(request):\n if request.session.get('user'):\n del request.session['user']\n return render(request, 'login.html')\n\n\n<function token>\n<function token>\n<function token>\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n<function token>\n<function token>\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n\n def file_iterator(file_name, chunk_size=512):\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res)\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8'\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(\n escape_uri_path(file))\n return response\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n<function token>\n<function token>\n\n\n@api_check\ndef download_file(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n file_name = req.get('file_name')\n file_type = req.get('file_type')\n file = file_name + '.' + file_type if file_type != '未知' else file_name\n file_path = os.path.join(os.path.join(files_folder, dir_name), file)\n if not os.path.exists(file_path):\n res = dict(state_code=1, error_msg='文件不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n from django.http import StreamingHttpResponse\n file_size = os.path.getsize(file_path)\n\n def file_iterator(file_name, chunk_size=512):\n with open(file_name, 'rb') as f:\n while True:\n c = f.read(chunk_size)\n if c:\n yield c\n else:\n break\n the_file_name = file_path\n res = file_iterator(the_file_name)\n response = StreamingHttpResponse(res)\n response['Content-Type'] = 'application/octet-stream; charset=UTF-8'\n response['Content-Length'] = file_size\n response['Content-Disposition'] = 'attachment;filename=\"{}\"'.format(\n escape_uri_path(file))\n return response\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n@api_check\ndef upload_file(request):\n dir_name = request.POST.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n File = request.FILES.get('file', None)\n if File is None:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n file_name = File.name\n file_path = os.path.join(dir_path, file_name)\n with open(file_path, 'wb+') as f:\n for chunk in File.chunks():\n f.write(chunk)\n res = dict(state_code=0, error_msg='ok')\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\n@api_check\ndef del_dir(request):\n req = json.loads(request.body)\n dir_name = req.get('dir_name')\n if not dir_name:\n res = dict(state_code=-2, error_msg='参数错误')\n return HttpResponse(json.dumps(res, ensure_ascii=False),\n content_type='application/json')\n dir_path = os.path.join(files_folder, dir_name)\n if not os.path.exists(dir_path):\n res = dict(state_code=1, error_msg='目录不存在')\n else:\n with transaction.atomic():\n obj_dir = models.Dirs.objects.filter(dir=dir_name).all()\n if obj_dir:\n obj_dir.delete()\n shutil.rmtree(dir_path)\n res = dict(state_code=0, eror_msg='ok')\n return HttpResponse(json.dumps(res, ensure_ascii=False), content_type=\n 'application/json')\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
706
1b529d8bafc81ef4dd9ff355de6abbd6f4ebddf1
import logging from xdcs.app import xdcs logger = logging.getLogger(__name__) def asynchronous(func): def task(*args, **kwargs): try: func(*args, **kwargs) except Exception as e: logger.exception('Exception during asynchronous execution: ' + str(e)) raise e def replacement(*args, **kwargs): return xdcs().executor() \ .submit(lambda: task(*args, **kwargs)) return replacement def lazy(func): class Lazy: def __init__(self, original) -> None: self._value_computed = False self._value = None self._original = [original] def get_value(self, *args, **kwargs): if self._value_computed: return self._value else: self._value = func(*args, **kwargs) self._value_computed = True return self._value _lazy = Lazy(func) def replacement(*args, **kwargs): return _lazy.get_value(*args, **kwargs) return replacement
[ "import logging\n\nfrom xdcs.app import xdcs\n\nlogger = logging.getLogger(__name__)\n\n\ndef asynchronous(func):\n def task(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except Exception as e:\n logger.exception('Exception during asynchronous execution: ' + str(e))\n raise e\n\n def replacement(*args, **kwargs):\n return xdcs().executor() \\\n .submit(lambda: task(*args, **kwargs))\n\n return replacement\n\n\ndef lazy(func):\n class Lazy:\n def __init__(self, original) -> None:\n self._value_computed = False\n self._value = None\n self._original = [original]\n\n def get_value(self, *args, **kwargs):\n if self._value_computed:\n return self._value\n else:\n self._value = func(*args, **kwargs)\n self._value_computed = True\n return self._value\n\n _lazy = Lazy(func)\n\n def replacement(*args, **kwargs):\n return _lazy.get_value(*args, **kwargs)\n\n return replacement\n", "import logging\nfrom xdcs.app import xdcs\nlogger = logging.getLogger(__name__)\n\n\ndef asynchronous(func):\n\n def task(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except Exception as e:\n logger.exception('Exception during asynchronous execution: ' +\n str(e))\n raise e\n\n def replacement(*args, **kwargs):\n return xdcs().executor().submit(lambda : task(*args, **kwargs))\n return replacement\n\n\ndef lazy(func):\n\n\n class Lazy:\n\n def __init__(self, original) ->None:\n self._value_computed = False\n self._value = None\n self._original = [original]\n\n def get_value(self, *args, **kwargs):\n if self._value_computed:\n return self._value\n else:\n self._value = func(*args, **kwargs)\n self._value_computed = True\n return self._value\n _lazy = Lazy(func)\n\n def replacement(*args, **kwargs):\n return _lazy.get_value(*args, **kwargs)\n return replacement\n", "<import token>\nlogger = logging.getLogger(__name__)\n\n\ndef asynchronous(func):\n\n def task(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except Exception as e:\n logger.exception('Exception during asynchronous execution: ' +\n str(e))\n raise e\n\n def replacement(*args, **kwargs):\n return xdcs().executor().submit(lambda : task(*args, **kwargs))\n return replacement\n\n\ndef lazy(func):\n\n\n class Lazy:\n\n def __init__(self, original) ->None:\n self._value_computed = False\n self._value = None\n self._original = [original]\n\n def get_value(self, *args, **kwargs):\n if self._value_computed:\n return self._value\n else:\n self._value = func(*args, **kwargs)\n self._value_computed = True\n return self._value\n _lazy = Lazy(func)\n\n def replacement(*args, **kwargs):\n return _lazy.get_value(*args, **kwargs)\n return replacement\n", "<import token>\n<assignment token>\n\n\ndef asynchronous(func):\n\n def task(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except Exception as e:\n logger.exception('Exception during asynchronous execution: ' +\n str(e))\n raise e\n\n def replacement(*args, **kwargs):\n return xdcs().executor().submit(lambda : task(*args, **kwargs))\n return replacement\n\n\ndef lazy(func):\n\n\n class Lazy:\n\n def __init__(self, original) ->None:\n self._value_computed = False\n self._value = None\n self._original = [original]\n\n def get_value(self, *args, **kwargs):\n if self._value_computed:\n return self._value\n else:\n self._value = func(*args, **kwargs)\n self._value_computed = True\n return self._value\n _lazy = Lazy(func)\n\n def replacement(*args, **kwargs):\n return _lazy.get_value(*args, **kwargs)\n return replacement\n", "<import token>\n<assignment token>\n<function token>\n\n\ndef lazy(func):\n\n\n class Lazy:\n\n def __init__(self, original) ->None:\n self._value_computed = False\n self._value = None\n self._original = [original]\n\n def get_value(self, *args, **kwargs):\n if self._value_computed:\n return self._value\n else:\n self._value = func(*args, **kwargs)\n self._value_computed = True\n return self._value\n _lazy = Lazy(func)\n\n def replacement(*args, **kwargs):\n return _lazy.get_value(*args, **kwargs)\n return replacement\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n" ]
false
707
cb48a1601798f72f9cf3759d3c13969bc824a0f6
from pyplasm import * import random as r def gen_windows(plan_grid, n, m, window_model): return STRUCT([ T([1,2])([j,i])( gen_cube_windows(plan_grid, window_model)(i, j, n, m)) for i in range(n) for j in range(m) if plan_grid[i][j]]) def gen_cube_windows(plan_grid, window_model): w = window_model hpcs = [CUBE(0.00001)] def gen_cube0(i, j, n, m): if j+1 == m or not plan_grid[i][j+1]: hpcs.append(T([1, 2])([1, .5])(MAP([S2, S1, S3])(w))) if j-1 < 0 or not plan_grid[i][j-1]: hpcs.append(T(2)(.5)(MAP([S2, S1, S3])(w))) if i+1 == n or not plan_grid[i+1][j]: hpcs.append(T([1, 2])([.5, 1])(w)) if i-1 < 0 or not plan_grid[i-1][j]: hpcs.append(T(1)(.5)(w)) return STRUCT(hpcs) return gen_cube0 def gen_body(plan_grid, n, m): c = CUBE(1) return STRUCT([ T([1,2])([j,i])(c) for i in range(n) for j in range(m) if plan_grid[i][j]]) def gen_house( box, plan_grid, door_model, window_model, roof_model): n = len(plan_grid) m = len(plan_grid[0]) body = STRUCT([ gen_body(plan_grid, n, m), T(3)(1), roof_model]) l2s_scale = map(lambda x,y: x/y, SIZE([1,2,3])(body), box) s2l_scale = [1/elem for elem in l2s_scale] scaled_win = S([1,2,3])(l2s_scale)(window_model) windows = gen_windows(plan_grid, n, m, scaled_win) house = STRUCT([body, windows]) return TEXTURE(['wood.jpg',True, True, 300,300, r.random()*3.1415, .1,.1, 0,0])( S([1,2,3])(s2l_scale)(house)) def l_shaped_house(box): grid = [ [False, False, True], [True, True, True]] roof = MKPOL([ [ [ 2, 0, 0], [2.5, 0, .5], [ 3, 0, 0], [ 3, 2, 0], [ 0, 2, 0], [ 0, 1.5, .5], [ 0, 1, 0], [ 2, 1, 0], [2.5, 1.5, .5] ], [ [3,2,1], [9,2,3,4], [5,6,9,4], [7,6,5], [7,8,9,6], [9,8,1,2] ], [1]]) window = T([1,2,3])([-.75, -.1, 1.2])(CUBOID([1.5, .2, 2])) return gen_house(box, grid, None, window, roof) def q_shaped_house(box): grid = [ [True, True, True], [True, True, True], [True, False, False]] roof = MKPOL([ [ [0,0,0], #1 [3,0,0], #2 [3,2,0], #3 [1,2,0], #4 [1,3,0], #5 [.5,3,.5], #6 [0,3,0], #7 [.5,.5,.5], #8 [2.5,.5,.5], #9 [2.5,1.5,.5], #10 [.5,1.5,.5] #11 ], [ [1,8,6,7], [1,2,9,8], [2,3,10,9], [10,3,4,11], [4,5,6,11], [6,5,7], [8,9,10,11] ], [1]]) window = T([1,2,3])([-.75, -.1, 1.2])(CUBOID([1.5, .2, 2])) return gen_house(box, grid, None, window, roof) def rectangular_house(box): grid = [ [True, True], [True, True], [True, True]] roof = MKPOL([ [ [0,0,0], #1 [1,0,1], #2 [2,0,0], #3 [2,3,0], #4 [1,3,1], #5 [0,3,0] #6 ], [ [1,2,5,6], [2,3,4,5], [1,3,2], [5,4,6] ], [1]]) window = T([1,2,3])([-.75, -.1, 1.2])(CUBOID([1.5, .2, 2])) return gen_house(box, grid, None, window, roof) def squared_house(box): grid = [ [True, True, True], [True, True, True], [True, True, True]] roof = MKPOL([ [ [0,0,0], #1 [3,0,0], #2 [3,3,0], #3 [0,3,0], #4 [1.5,1.5,1] #5 ], [ [5,1,2], [5,2,3], [5,3,4], [5,4,1] ], [1]]) window = T([1,2,3])([-.75, -.1, 1.2])(CUBOID([1.5, .2, 2])) return gen_house(box, grid, None, window, roof) if __name__=='__main__': VIEW(squared_house([15, 15, 8]))
[ "from pyplasm import *\nimport random as r\n\ndef gen_windows(plan_grid, n, m, window_model):\n return STRUCT([\n T([1,2])([j,i])(\n gen_cube_windows(plan_grid, window_model)(i, j, n, m))\n for i in range(n) \n for j in range(m) \n if plan_grid[i][j]])\n\ndef gen_cube_windows(plan_grid, window_model):\n w = window_model\n hpcs = [CUBE(0.00001)]\n \n def gen_cube0(i, j, n, m):\n if j+1 == m or not plan_grid[i][j+1]:\n hpcs.append(T([1, 2])([1, .5])(MAP([S2, S1, S3])(w)))\n \n if j-1 < 0 or not plan_grid[i][j-1]:\n hpcs.append(T(2)(.5)(MAP([S2, S1, S3])(w)))\n \n if i+1 == n or not plan_grid[i+1][j]:\n hpcs.append(T([1, 2])([.5, 1])(w))\n \n if i-1 < 0 or not plan_grid[i-1][j]:\n hpcs.append(T(1)(.5)(w))\n \n return STRUCT(hpcs)\n \n return gen_cube0\n \n\ndef gen_body(plan_grid, n, m):\n c = CUBE(1)\n return STRUCT([\n T([1,2])([j,i])(c)\n for i in range(n) \n for j in range(m) \n if plan_grid[i][j]])\n\n\ndef gen_house(\n box,\n plan_grid,\n door_model,\n window_model,\n roof_model):\n \n n = len(plan_grid)\n m = len(plan_grid[0])\n \n body = STRUCT([\n gen_body(plan_grid, n, m),\n T(3)(1),\n roof_model])\n \n l2s_scale = map(lambda x,y: x/y, SIZE([1,2,3])(body), box)\n s2l_scale = [1/elem for elem in l2s_scale]\n \n scaled_win = S([1,2,3])(l2s_scale)(window_model)\n \n windows = gen_windows(plan_grid, n, m, scaled_win)\n \n house = STRUCT([body, windows])\n \n return TEXTURE(['wood.jpg',True, True, 300,300, r.random()*3.1415, .1,.1, 0,0])(\n S([1,2,3])(s2l_scale)(house))\n\n\ndef l_shaped_house(box):\n \n grid = [\n [False, False, True],\n [True, True, True]]\n \n roof = MKPOL([\n [\n [ 2, 0, 0],\n [2.5, 0, .5],\n [ 3, 0, 0],\n [ 3, 2, 0],\n [ 0, 2, 0],\n [ 0, 1.5, .5],\n [ 0, 1, 0],\n [ 2, 1, 0],\n [2.5, 1.5, .5]\n ],\n [\n [3,2,1],\n [9,2,3,4],\n [5,6,9,4],\n [7,6,5],\n [7,8,9,6],\n [9,8,1,2]\n ],\n [1]])\n \n window = T([1,2,3])([-.75, -.1, 1.2])(CUBOID([1.5, .2, 2]))\n return gen_house(box, grid, None, window, roof)\n \ndef q_shaped_house(box):\n\n grid = [\n [True, True, True],\n [True, True, True],\n [True, False, False]]\n roof = MKPOL([\n [\n [0,0,0], #1\n [3,0,0], #2\n [3,2,0], #3\n [1,2,0], #4\n [1,3,0], #5\n [.5,3,.5], #6\n [0,3,0], #7\n [.5,.5,.5], #8\n [2.5,.5,.5], #9\n [2.5,1.5,.5], #10\n [.5,1.5,.5] #11\n ],\n [\n [1,8,6,7],\n [1,2,9,8],\n [2,3,10,9],\n [10,3,4,11],\n [4,5,6,11],\n [6,5,7],\n [8,9,10,11]\n ],\n [1]])\n \n window = T([1,2,3])([-.75, -.1, 1.2])(CUBOID([1.5, .2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef rectangular_house(box):\n\n grid = [\n [True, True],\n [True, True],\n [True, True]]\n roof = MKPOL([\n [\n [0,0,0], #1\n [1,0,1], #2\n [2,0,0], #3\n [2,3,0], #4\n [1,3,1], #5\n [0,3,0] #6\n ],\n [\n [1,2,5,6],\n [2,3,4,5],\n [1,3,2],\n [5,4,6]\n ],\n [1]])\n \n window = T([1,2,3])([-.75, -.1, 1.2])(CUBOID([1.5, .2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef squared_house(box):\n \n grid = [\n [True, True, True],\n [True, True, True],\n [True, True, True]]\n roof = MKPOL([\n [\n [0,0,0], #1\n [3,0,0], #2\n [3,3,0], #3\n [0,3,0], #4\n [1.5,1.5,1] #5\n ],\n [\n [5,1,2],\n [5,2,3],\n [5,3,4],\n [5,4,1]\n ],\n [1]])\n \n window = T([1,2,3])([-.75, -.1, 1.2])(CUBOID([1.5, .2, 2]))\n return gen_house(box, grid, None, window, roof)\n \n\nif __name__=='__main__':\n VIEW(squared_house([15, 15, 8]))\n\n", "from pyplasm import *\nimport random as r\n\n\ndef gen_windows(plan_grid, n, m, window_model):\n return STRUCT([T([1, 2])([j, i])(gen_cube_windows(plan_grid,\n window_model)(i, j, n, m)) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\ndef gen_cube_windows(plan_grid, window_model):\n w = window_model\n hpcs = [CUBE(1e-05)]\n\n def gen_cube0(i, j, n, m):\n if j + 1 == m or not plan_grid[i][j + 1]:\n hpcs.append(T([1, 2])([1, 0.5])(MAP([S2, S1, S3])(w)))\n if j - 1 < 0 or not plan_grid[i][j - 1]:\n hpcs.append(T(2)(0.5)(MAP([S2, S1, S3])(w)))\n if i + 1 == n or not plan_grid[i + 1][j]:\n hpcs.append(T([1, 2])([0.5, 1])(w))\n if i - 1 < 0 or not plan_grid[i - 1][j]:\n hpcs.append(T(1)(0.5)(w))\n return STRUCT(hpcs)\n return gen_cube0\n\n\ndef gen_body(plan_grid, n, m):\n c = CUBE(1)\n return STRUCT([T([1, 2])([j, i])(c) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\ndef gen_house(box, plan_grid, door_model, window_model, roof_model):\n n = len(plan_grid)\n m = len(plan_grid[0])\n body = STRUCT([gen_body(plan_grid, n, m), T(3)(1), roof_model])\n l2s_scale = map(lambda x, y: x / y, SIZE([1, 2, 3])(body), box)\n s2l_scale = [(1 / elem) for elem in l2s_scale]\n scaled_win = S([1, 2, 3])(l2s_scale)(window_model)\n windows = gen_windows(plan_grid, n, m, scaled_win)\n house = STRUCT([body, windows])\n return TEXTURE(['wood.jpg', True, True, 300, 300, r.random() * 3.1415, \n 0.1, 0.1, 0, 0])(S([1, 2, 3])(s2l_scale)(house))\n\n\ndef l_shaped_house(box):\n grid = [[False, False, True], [True, True, True]]\n roof = MKPOL([[[2, 0, 0], [2.5, 0, 0.5], [3, 0, 0], [3, 2, 0], [0, 2, 0\n ], [0, 1.5, 0.5], [0, 1, 0], [2, 1, 0], [2.5, 1.5, 0.5]], [[3, 2, 1\n ], [9, 2, 3, 4], [5, 6, 9, 4], [7, 6, 5], [7, 8, 9, 6], [9, 8, 1, 2\n ]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef q_shaped_house(box):\n grid = [[True, True, True], [True, True, True], [True, False, False]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 2, 0], [1, 2, 0], [1, 3, 0], [\n 0.5, 3, 0.5], [0, 3, 0], [0.5, 0.5, 0.5], [2.5, 0.5, 0.5], [2.5, \n 1.5, 0.5], [0.5, 1.5, 0.5]], [[1, 8, 6, 7], [1, 2, 9, 8], [2, 3, 10,\n 9], [10, 3, 4, 11], [4, 5, 6, 11], [6, 5, 7], [8, 9, 10, 11]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef rectangular_house(box):\n grid = [[True, True], [True, True], [True, True]]\n roof = MKPOL([[[0, 0, 0], [1, 0, 1], [2, 0, 0], [2, 3, 0], [1, 3, 1], [\n 0, 3, 0]], [[1, 2, 5, 6], [2, 3, 4, 5], [1, 3, 2], [5, 4, 6]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef squared_house(box):\n grid = [[True, True, True], [True, True, True], [True, True, True]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 3, 0], [0, 3, 0], [1.5, 1.5, 1\n ]], [[5, 1, 2], [5, 2, 3], [5, 3, 4], [5, 4, 1]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\nif __name__ == '__main__':\n VIEW(squared_house([15, 15, 8]))\n", "<import token>\n\n\ndef gen_windows(plan_grid, n, m, window_model):\n return STRUCT([T([1, 2])([j, i])(gen_cube_windows(plan_grid,\n window_model)(i, j, n, m)) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\ndef gen_cube_windows(plan_grid, window_model):\n w = window_model\n hpcs = [CUBE(1e-05)]\n\n def gen_cube0(i, j, n, m):\n if j + 1 == m or not plan_grid[i][j + 1]:\n hpcs.append(T([1, 2])([1, 0.5])(MAP([S2, S1, S3])(w)))\n if j - 1 < 0 or not plan_grid[i][j - 1]:\n hpcs.append(T(2)(0.5)(MAP([S2, S1, S3])(w)))\n if i + 1 == n or not plan_grid[i + 1][j]:\n hpcs.append(T([1, 2])([0.5, 1])(w))\n if i - 1 < 0 or not plan_grid[i - 1][j]:\n hpcs.append(T(1)(0.5)(w))\n return STRUCT(hpcs)\n return gen_cube0\n\n\ndef gen_body(plan_grid, n, m):\n c = CUBE(1)\n return STRUCT([T([1, 2])([j, i])(c) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\ndef gen_house(box, plan_grid, door_model, window_model, roof_model):\n n = len(plan_grid)\n m = len(plan_grid[0])\n body = STRUCT([gen_body(plan_grid, n, m), T(3)(1), roof_model])\n l2s_scale = map(lambda x, y: x / y, SIZE([1, 2, 3])(body), box)\n s2l_scale = [(1 / elem) for elem in l2s_scale]\n scaled_win = S([1, 2, 3])(l2s_scale)(window_model)\n windows = gen_windows(plan_grid, n, m, scaled_win)\n house = STRUCT([body, windows])\n return TEXTURE(['wood.jpg', True, True, 300, 300, r.random() * 3.1415, \n 0.1, 0.1, 0, 0])(S([1, 2, 3])(s2l_scale)(house))\n\n\ndef l_shaped_house(box):\n grid = [[False, False, True], [True, True, True]]\n roof = MKPOL([[[2, 0, 0], [2.5, 0, 0.5], [3, 0, 0], [3, 2, 0], [0, 2, 0\n ], [0, 1.5, 0.5], [0, 1, 0], [2, 1, 0], [2.5, 1.5, 0.5]], [[3, 2, 1\n ], [9, 2, 3, 4], [5, 6, 9, 4], [7, 6, 5], [7, 8, 9, 6], [9, 8, 1, 2\n ]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef q_shaped_house(box):\n grid = [[True, True, True], [True, True, True], [True, False, False]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 2, 0], [1, 2, 0], [1, 3, 0], [\n 0.5, 3, 0.5], [0, 3, 0], [0.5, 0.5, 0.5], [2.5, 0.5, 0.5], [2.5, \n 1.5, 0.5], [0.5, 1.5, 0.5]], [[1, 8, 6, 7], [1, 2, 9, 8], [2, 3, 10,\n 9], [10, 3, 4, 11], [4, 5, 6, 11], [6, 5, 7], [8, 9, 10, 11]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef rectangular_house(box):\n grid = [[True, True], [True, True], [True, True]]\n roof = MKPOL([[[0, 0, 0], [1, 0, 1], [2, 0, 0], [2, 3, 0], [1, 3, 1], [\n 0, 3, 0]], [[1, 2, 5, 6], [2, 3, 4, 5], [1, 3, 2], [5, 4, 6]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef squared_house(box):\n grid = [[True, True, True], [True, True, True], [True, True, True]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 3, 0], [0, 3, 0], [1.5, 1.5, 1\n ]], [[5, 1, 2], [5, 2, 3], [5, 3, 4], [5, 4, 1]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\nif __name__ == '__main__':\n VIEW(squared_house([15, 15, 8]))\n", "<import token>\n\n\ndef gen_windows(plan_grid, n, m, window_model):\n return STRUCT([T([1, 2])([j, i])(gen_cube_windows(plan_grid,\n window_model)(i, j, n, m)) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\ndef gen_cube_windows(plan_grid, window_model):\n w = window_model\n hpcs = [CUBE(1e-05)]\n\n def gen_cube0(i, j, n, m):\n if j + 1 == m or not plan_grid[i][j + 1]:\n hpcs.append(T([1, 2])([1, 0.5])(MAP([S2, S1, S3])(w)))\n if j - 1 < 0 or not plan_grid[i][j - 1]:\n hpcs.append(T(2)(0.5)(MAP([S2, S1, S3])(w)))\n if i + 1 == n or not plan_grid[i + 1][j]:\n hpcs.append(T([1, 2])([0.5, 1])(w))\n if i - 1 < 0 or not plan_grid[i - 1][j]:\n hpcs.append(T(1)(0.5)(w))\n return STRUCT(hpcs)\n return gen_cube0\n\n\ndef gen_body(plan_grid, n, m):\n c = CUBE(1)\n return STRUCT([T([1, 2])([j, i])(c) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\ndef gen_house(box, plan_grid, door_model, window_model, roof_model):\n n = len(plan_grid)\n m = len(plan_grid[0])\n body = STRUCT([gen_body(plan_grid, n, m), T(3)(1), roof_model])\n l2s_scale = map(lambda x, y: x / y, SIZE([1, 2, 3])(body), box)\n s2l_scale = [(1 / elem) for elem in l2s_scale]\n scaled_win = S([1, 2, 3])(l2s_scale)(window_model)\n windows = gen_windows(plan_grid, n, m, scaled_win)\n house = STRUCT([body, windows])\n return TEXTURE(['wood.jpg', True, True, 300, 300, r.random() * 3.1415, \n 0.1, 0.1, 0, 0])(S([1, 2, 3])(s2l_scale)(house))\n\n\ndef l_shaped_house(box):\n grid = [[False, False, True], [True, True, True]]\n roof = MKPOL([[[2, 0, 0], [2.5, 0, 0.5], [3, 0, 0], [3, 2, 0], [0, 2, 0\n ], [0, 1.5, 0.5], [0, 1, 0], [2, 1, 0], [2.5, 1.5, 0.5]], [[3, 2, 1\n ], [9, 2, 3, 4], [5, 6, 9, 4], [7, 6, 5], [7, 8, 9, 6], [9, 8, 1, 2\n ]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef q_shaped_house(box):\n grid = [[True, True, True], [True, True, True], [True, False, False]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 2, 0], [1, 2, 0], [1, 3, 0], [\n 0.5, 3, 0.5], [0, 3, 0], [0.5, 0.5, 0.5], [2.5, 0.5, 0.5], [2.5, \n 1.5, 0.5], [0.5, 1.5, 0.5]], [[1, 8, 6, 7], [1, 2, 9, 8], [2, 3, 10,\n 9], [10, 3, 4, 11], [4, 5, 6, 11], [6, 5, 7], [8, 9, 10, 11]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef rectangular_house(box):\n grid = [[True, True], [True, True], [True, True]]\n roof = MKPOL([[[0, 0, 0], [1, 0, 1], [2, 0, 0], [2, 3, 0], [1, 3, 1], [\n 0, 3, 0]], [[1, 2, 5, 6], [2, 3, 4, 5], [1, 3, 2], [5, 4, 6]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef squared_house(box):\n grid = [[True, True, True], [True, True, True], [True, True, True]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 3, 0], [0, 3, 0], [1.5, 1.5, 1\n ]], [[5, 1, 2], [5, 2, 3], [5, 3, 4], [5, 4, 1]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\n<code token>\n", "<import token>\n\n\ndef gen_windows(plan_grid, n, m, window_model):\n return STRUCT([T([1, 2])([j, i])(gen_cube_windows(plan_grid,\n window_model)(i, j, n, m)) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\n<function token>\n\n\ndef gen_body(plan_grid, n, m):\n c = CUBE(1)\n return STRUCT([T([1, 2])([j, i])(c) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\ndef gen_house(box, plan_grid, door_model, window_model, roof_model):\n n = len(plan_grid)\n m = len(plan_grid[0])\n body = STRUCT([gen_body(plan_grid, n, m), T(3)(1), roof_model])\n l2s_scale = map(lambda x, y: x / y, SIZE([1, 2, 3])(body), box)\n s2l_scale = [(1 / elem) for elem in l2s_scale]\n scaled_win = S([1, 2, 3])(l2s_scale)(window_model)\n windows = gen_windows(plan_grid, n, m, scaled_win)\n house = STRUCT([body, windows])\n return TEXTURE(['wood.jpg', True, True, 300, 300, r.random() * 3.1415, \n 0.1, 0.1, 0, 0])(S([1, 2, 3])(s2l_scale)(house))\n\n\ndef l_shaped_house(box):\n grid = [[False, False, True], [True, True, True]]\n roof = MKPOL([[[2, 0, 0], [2.5, 0, 0.5], [3, 0, 0], [3, 2, 0], [0, 2, 0\n ], [0, 1.5, 0.5], [0, 1, 0], [2, 1, 0], [2.5, 1.5, 0.5]], [[3, 2, 1\n ], [9, 2, 3, 4], [5, 6, 9, 4], [7, 6, 5], [7, 8, 9, 6], [9, 8, 1, 2\n ]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef q_shaped_house(box):\n grid = [[True, True, True], [True, True, True], [True, False, False]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 2, 0], [1, 2, 0], [1, 3, 0], [\n 0.5, 3, 0.5], [0, 3, 0], [0.5, 0.5, 0.5], [2.5, 0.5, 0.5], [2.5, \n 1.5, 0.5], [0.5, 1.5, 0.5]], [[1, 8, 6, 7], [1, 2, 9, 8], [2, 3, 10,\n 9], [10, 3, 4, 11], [4, 5, 6, 11], [6, 5, 7], [8, 9, 10, 11]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef rectangular_house(box):\n grid = [[True, True], [True, True], [True, True]]\n roof = MKPOL([[[0, 0, 0], [1, 0, 1], [2, 0, 0], [2, 3, 0], [1, 3, 1], [\n 0, 3, 0]], [[1, 2, 5, 6], [2, 3, 4, 5], [1, 3, 2], [5, 4, 6]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef squared_house(box):\n grid = [[True, True, True], [True, True, True], [True, True, True]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 3, 0], [0, 3, 0], [1.5, 1.5, 1\n ]], [[5, 1, 2], [5, 2, 3], [5, 3, 4], [5, 4, 1]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\n<code token>\n", "<import token>\n\n\ndef gen_windows(plan_grid, n, m, window_model):\n return STRUCT([T([1, 2])([j, i])(gen_cube_windows(plan_grid,\n window_model)(i, j, n, m)) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\n<function token>\n<function token>\n\n\ndef gen_house(box, plan_grid, door_model, window_model, roof_model):\n n = len(plan_grid)\n m = len(plan_grid[0])\n body = STRUCT([gen_body(plan_grid, n, m), T(3)(1), roof_model])\n l2s_scale = map(lambda x, y: x / y, SIZE([1, 2, 3])(body), box)\n s2l_scale = [(1 / elem) for elem in l2s_scale]\n scaled_win = S([1, 2, 3])(l2s_scale)(window_model)\n windows = gen_windows(plan_grid, n, m, scaled_win)\n house = STRUCT([body, windows])\n return TEXTURE(['wood.jpg', True, True, 300, 300, r.random() * 3.1415, \n 0.1, 0.1, 0, 0])(S([1, 2, 3])(s2l_scale)(house))\n\n\ndef l_shaped_house(box):\n grid = [[False, False, True], [True, True, True]]\n roof = MKPOL([[[2, 0, 0], [2.5, 0, 0.5], [3, 0, 0], [3, 2, 0], [0, 2, 0\n ], [0, 1.5, 0.5], [0, 1, 0], [2, 1, 0], [2.5, 1.5, 0.5]], [[3, 2, 1\n ], [9, 2, 3, 4], [5, 6, 9, 4], [7, 6, 5], [7, 8, 9, 6], [9, 8, 1, 2\n ]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef q_shaped_house(box):\n grid = [[True, True, True], [True, True, True], [True, False, False]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 2, 0], [1, 2, 0], [1, 3, 0], [\n 0.5, 3, 0.5], [0, 3, 0], [0.5, 0.5, 0.5], [2.5, 0.5, 0.5], [2.5, \n 1.5, 0.5], [0.5, 1.5, 0.5]], [[1, 8, 6, 7], [1, 2, 9, 8], [2, 3, 10,\n 9], [10, 3, 4, 11], [4, 5, 6, 11], [6, 5, 7], [8, 9, 10, 11]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef rectangular_house(box):\n grid = [[True, True], [True, True], [True, True]]\n roof = MKPOL([[[0, 0, 0], [1, 0, 1], [2, 0, 0], [2, 3, 0], [1, 3, 1], [\n 0, 3, 0]], [[1, 2, 5, 6], [2, 3, 4, 5], [1, 3, 2], [5, 4, 6]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef squared_house(box):\n grid = [[True, True, True], [True, True, True], [True, True, True]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 3, 0], [0, 3, 0], [1.5, 1.5, 1\n ]], [[5, 1, 2], [5, 2, 3], [5, 3, 4], [5, 4, 1]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\n<code token>\n", "<import token>\n\n\ndef gen_windows(plan_grid, n, m, window_model):\n return STRUCT([T([1, 2])([j, i])(gen_cube_windows(plan_grid,\n window_model)(i, j, n, m)) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\n<function token>\n<function token>\n\n\ndef gen_house(box, plan_grid, door_model, window_model, roof_model):\n n = len(plan_grid)\n m = len(plan_grid[0])\n body = STRUCT([gen_body(plan_grid, n, m), T(3)(1), roof_model])\n l2s_scale = map(lambda x, y: x / y, SIZE([1, 2, 3])(body), box)\n s2l_scale = [(1 / elem) for elem in l2s_scale]\n scaled_win = S([1, 2, 3])(l2s_scale)(window_model)\n windows = gen_windows(plan_grid, n, m, scaled_win)\n house = STRUCT([body, windows])\n return TEXTURE(['wood.jpg', True, True, 300, 300, r.random() * 3.1415, \n 0.1, 0.1, 0, 0])(S([1, 2, 3])(s2l_scale)(house))\n\n\ndef l_shaped_house(box):\n grid = [[False, False, True], [True, True, True]]\n roof = MKPOL([[[2, 0, 0], [2.5, 0, 0.5], [3, 0, 0], [3, 2, 0], [0, 2, 0\n ], [0, 1.5, 0.5], [0, 1, 0], [2, 1, 0], [2.5, 1.5, 0.5]], [[3, 2, 1\n ], [9, 2, 3, 4], [5, 6, 9, 4], [7, 6, 5], [7, 8, 9, 6], [9, 8, 1, 2\n ]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\n<function token>\n\n\ndef rectangular_house(box):\n grid = [[True, True], [True, True], [True, True]]\n roof = MKPOL([[[0, 0, 0], [1, 0, 1], [2, 0, 0], [2, 3, 0], [1, 3, 1], [\n 0, 3, 0]], [[1, 2, 5, 6], [2, 3, 4, 5], [1, 3, 2], [5, 4, 6]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef squared_house(box):\n grid = [[True, True, True], [True, True, True], [True, True, True]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 3, 0], [0, 3, 0], [1.5, 1.5, 1\n ]], [[5, 1, 2], [5, 2, 3], [5, 3, 4], [5, 4, 1]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\n<code token>\n", "<import token>\n\n\ndef gen_windows(plan_grid, n, m, window_model):\n return STRUCT([T([1, 2])([j, i])(gen_cube_windows(plan_grid,\n window_model)(i, j, n, m)) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef l_shaped_house(box):\n grid = [[False, False, True], [True, True, True]]\n roof = MKPOL([[[2, 0, 0], [2.5, 0, 0.5], [3, 0, 0], [3, 2, 0], [0, 2, 0\n ], [0, 1.5, 0.5], [0, 1, 0], [2, 1, 0], [2.5, 1.5, 0.5]], [[3, 2, 1\n ], [9, 2, 3, 4], [5, 6, 9, 4], [7, 6, 5], [7, 8, 9, 6], [9, 8, 1, 2\n ]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\n<function token>\n\n\ndef rectangular_house(box):\n grid = [[True, True], [True, True], [True, True]]\n roof = MKPOL([[[0, 0, 0], [1, 0, 1], [2, 0, 0], [2, 3, 0], [1, 3, 1], [\n 0, 3, 0]], [[1, 2, 5, 6], [2, 3, 4, 5], [1, 3, 2], [5, 4, 6]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\ndef squared_house(box):\n grid = [[True, True, True], [True, True, True], [True, True, True]]\n roof = MKPOL([[[0, 0, 0], [3, 0, 0], [3, 3, 0], [0, 3, 0], [1.5, 1.5, 1\n ]], [[5, 1, 2], [5, 2, 3], [5, 3, 4], [5, 4, 1]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\n<code token>\n", "<import token>\n\n\ndef gen_windows(plan_grid, n, m, window_model):\n return STRUCT([T([1, 2])([j, i])(gen_cube_windows(plan_grid,\n window_model)(i, j, n, m)) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef l_shaped_house(box):\n grid = [[False, False, True], [True, True, True]]\n roof = MKPOL([[[2, 0, 0], [2.5, 0, 0.5], [3, 0, 0], [3, 2, 0], [0, 2, 0\n ], [0, 1.5, 0.5], [0, 1, 0], [2, 1, 0], [2.5, 1.5, 0.5]], [[3, 2, 1\n ], [9, 2, 3, 4], [5, 6, 9, 4], [7, 6, 5], [7, 8, 9, 6], [9, 8, 1, 2\n ]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\n<function token>\n\n\ndef rectangular_house(box):\n grid = [[True, True], [True, True], [True, True]]\n roof = MKPOL([[[0, 0, 0], [1, 0, 1], [2, 0, 0], [2, 3, 0], [1, 3, 1], [\n 0, 3, 0]], [[1, 2, 5, 6], [2, 3, 4, 5], [1, 3, 2], [5, 4, 6]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\n<function token>\n<code token>\n", "<import token>\n\n\ndef gen_windows(plan_grid, n, m, window_model):\n return STRUCT([T([1, 2])([j, i])(gen_cube_windows(plan_grid,\n window_model)(i, j, n, m)) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef l_shaped_house(box):\n grid = [[False, False, True], [True, True, True]]\n roof = MKPOL([[[2, 0, 0], [2.5, 0, 0.5], [3, 0, 0], [3, 2, 0], [0, 2, 0\n ], [0, 1.5, 0.5], [0, 1, 0], [2, 1, 0], [2.5, 1.5, 0.5]], [[3, 2, 1\n ], [9, 2, 3, 4], [5, 6, 9, 4], [7, 6, 5], [7, 8, 9, 6], [9, 8, 1, 2\n ]], [1]])\n window = T([1, 2, 3])([-0.75, -0.1, 1.2])(CUBOID([1.5, 0.2, 2]))\n return gen_house(box, grid, None, window, roof)\n\n\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n\n\ndef gen_windows(plan_grid, n, m, window_model):\n return STRUCT([T([1, 2])([j, i])(gen_cube_windows(plan_grid,\n window_model)(i, j, n, m)) for i in range(n) for j in range(m) if\n plan_grid[i][j]])\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
708
7d3355ee775f759412308ab68a7aa409b9c74b20
''' 使用random模块,如何产生 50~150之间的数? ''' import random num1 = random.randint(50,151) print(num1)
[ "'''\r\n使用random模块,如何产生 50~150之间的数?\r\n'''\r\n\r\n\r\nimport random\r\n\r\nnum1 = random.randint(50,151)\r\nprint(num1)", "<docstring token>\nimport random\nnum1 = random.randint(50, 151)\nprint(num1)\n", "<docstring token>\n<import token>\nnum1 = random.randint(50, 151)\nprint(num1)\n", "<docstring token>\n<import token>\n<assignment token>\nprint(num1)\n", "<docstring token>\n<import token>\n<assignment token>\n<code token>\n" ]
false
709
7554b00f8c4d40f1d3ee2341f118048ca7ad10ea
import datetime class Event(object): def __init__(self): self.id = None self.raw = None self.create_dt = datetime.datetime.now() self.device_id = None self.collector_id = None self.device_hostname = None self.device_domain_name = None self.device_ip_address = None self.types = [] def to_dict(self): d = {} for item in self.__dict__: val = getattr(self, item) if val != None: d[item] = val return d
[ "import datetime\n\nclass Event(object):\n\n def __init__(self):\n self.id = None\n self.raw = None\n self.create_dt = datetime.datetime.now()\n self.device_id = None\n self.collector_id = None\n self.device_hostname = None\n self.device_domain_name = None\n self.device_ip_address = None\n self.types = []\n\n def to_dict(self):\n d = {}\n for item in self.__dict__:\n val = getattr(self, item)\n if val != None:\n d[item] = val\n\n return d\n\n", "import datetime\n\n\nclass Event(object):\n\n def __init__(self):\n self.id = None\n self.raw = None\n self.create_dt = datetime.datetime.now()\n self.device_id = None\n self.collector_id = None\n self.device_hostname = None\n self.device_domain_name = None\n self.device_ip_address = None\n self.types = []\n\n def to_dict(self):\n d = {}\n for item in self.__dict__:\n val = getattr(self, item)\n if val != None:\n d[item] = val\n return d\n", "<import token>\n\n\nclass Event(object):\n\n def __init__(self):\n self.id = None\n self.raw = None\n self.create_dt = datetime.datetime.now()\n self.device_id = None\n self.collector_id = None\n self.device_hostname = None\n self.device_domain_name = None\n self.device_ip_address = None\n self.types = []\n\n def to_dict(self):\n d = {}\n for item in self.__dict__:\n val = getattr(self, item)\n if val != None:\n d[item] = val\n return d\n", "<import token>\n\n\nclass Event(object):\n <function token>\n\n def to_dict(self):\n d = {}\n for item in self.__dict__:\n val = getattr(self, item)\n if val != None:\n d[item] = val\n return d\n", "<import token>\n\n\nclass Event(object):\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
710
f9db3c96bc3fd4911640d0428672c87072564b0d
"""Access IP Camera in Python OpenCV""" import cv2 #stream = cv2.VideoCapture('protocol://IP:port/1') # Use the next line if your camera has a username and password stream = cv2.VideoCapture('rtsp://SeniorDesign:[email protected]:554/video') while True: r, f = stream.read() cv2.imshow('IP Camera stream',f) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows()
[ "\"\"\"Access IP Camera in Python OpenCV\"\"\"\r\n\r\nimport cv2\r\n\r\n#stream = cv2.VideoCapture('protocol://IP:port/1')\r\n\r\n# Use the next line if your camera has a username and password\r\nstream = cv2.VideoCapture('rtsp://SeniorDesign:[email protected]:554/video') \r\n\r\nwhile True:\r\n\r\n r, f = stream.read()\r\n cv2.imshow('IP Camera stream',f)\r\n\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\ncv2.destroyAllWindows()", "<docstring token>\nimport cv2\nstream = cv2.VideoCapture('rtsp://SeniorDesign:[email protected]:554/video')\nwhile True:\n r, f = stream.read()\n cv2.imshow('IP Camera stream', f)\n if cv2.waitKey(1) & 255 == ord('q'):\n break\ncv2.destroyAllWindows()\n", "<docstring token>\n<import token>\nstream = cv2.VideoCapture('rtsp://SeniorDesign:[email protected]:554/video')\nwhile True:\n r, f = stream.read()\n cv2.imshow('IP Camera stream', f)\n if cv2.waitKey(1) & 255 == ord('q'):\n break\ncv2.destroyAllWindows()\n", "<docstring token>\n<import token>\n<assignment token>\nwhile True:\n r, f = stream.read()\n cv2.imshow('IP Camera stream', f)\n if cv2.waitKey(1) & 255 == ord('q'):\n break\ncv2.destroyAllWindows()\n", "<docstring token>\n<import token>\n<assignment token>\n<code token>\n" ]
false
711
7da2be1b530faa8ce9a8570247887e8e0d74c310
import pandas as pd #1. 读入数据 #从本地读入“wheat.csv”文件,指定index_col参数为00,即将第一列作为每行的索引。用head()函数查看前几行数据。 data = pd.read_csv("wheat.csv",index_col=0) print(data.head(6)) #2. 缺失值处理 #该数据集中包含部分缺失值,在模型训练时会遇到特征值为空的问题,故对缺失值进行处理, ## 用DataFrame的fillna方法进行缺失值填充,填充值为用mean方法得到的该列平均值。 data = data.fillna(data.mean()) print(data) #3. 划分数据集从sklearn.model_selection模块导入train_test_split函数, # 并将返回值放入变量X_train、X_test、y_train和y_test之中,指定参数test_size=0.3, # 即将70%的数据样本作为训练集,将30%的数据样本作为测试集。输出训练集和测试集大小。 from sklearn.model_selection import train_test_split X = data.iloc[:,:7] y = data.iloc[:,7] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=300) print(X_train.shape) print(y_train.shape) print(X_test.shape) print(y_test.shape) #4.构建随机森林模型并训练 #从sklearn.ensemble模块中导入RandomForestClassifier函数, ## 并用其构建随机森林分类模型,指定n_estimators参数为1010, # 即使用1010棵决策树构建模型。将训练集传入模型进行模型训练。 from sklearn.ensemble import RandomForestClassifier model= RandomForestClassifier(n_estimators=10) model.fit(X_train, y_train) #5.利用随机森林模型预测分类 #运用predict方法预测测试集中样本的分类,该方法返回一个预测结果数组,输出预测的分类结果。 y_pred = model.predict(X_test) print("Predictions of test set:\n%s"%y_pred) #6. 查看各特征重要性 #用feature_importances_属性查看每个特征的重要性,相对而言第11、22、55、77个特征在随机森林分类中的重要性强一些。 print(model.feature_importances_) #7. 评估模型准确率 #利用score方法计算模型在测试集上的预测准确率。 print(model.score(X_test,y_test)) #8. 调整随机森林中的树木数量 #随机森林中的数目数量是模型中较为重要的参数, #通过指定n_estimators参数进行设置,设置为30时模型的性能较10时有所提升, #但设置为100时,其准确度不但没有提升已不明显,甚至可能下降,可能已经过拟合。 model= RandomForestClassifier(n_estimators=30) model.fit(X_train, y_train) print(model.score(X_test,y_test)) #9. 与决策树分类进行比较 #决策树与随机森林在分类效果上进行比较, # 决策树模型的分类准确率与仅含单棵决策树的随机森林类似, # 但是总体上随机森林的准确度要高于决策树,但其模型的解释性较差,无法轻易得到树的基本结构。 from sklearn import tree clf = tree.DecisionTreeClassifier() clf = clf.fit(X_train, y_train) print(clf.score(X_test,y_test)) model= RandomForestClassifier(n_estimators=1) model.fit(X_train, y_train) print(model.score(X_test,y_test))
[ "import pandas as pd\n#1. 读入数据\n#从本地读入“wheat.csv”文件,指定index_col参数为00,即将第一列作为每行的索引。用head()函数查看前几行数据。\ndata = pd.read_csv(\"wheat.csv\",index_col=0)\nprint(data.head(6))\n\n#2. 缺失值处理\n#该数据集中包含部分缺失值,在模型训练时会遇到特征值为空的问题,故对缺失值进行处理,\n## 用DataFrame的fillna方法进行缺失值填充,填充值为用mean方法得到的该列平均值。\ndata = data.fillna(data.mean())\nprint(data)\n\n\n#3. 划分数据集从sklearn.model_selection模块导入train_test_split函数,\n# 并将返回值放入变量X_train、X_test、y_train和y_test之中,指定参数test_size=0.3,\n# 即将70%的数据样本作为训练集,将30%的数据样本作为测试集。输出训练集和测试集大小。\nfrom sklearn.model_selection import train_test_split\nX = data.iloc[:,:7]\ny = data.iloc[:,7]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=300)\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n\n#4.构建随机森林模型并训练\n#从sklearn.ensemble模块中导入RandomForestClassifier函数,\n## 并用其构建随机森林分类模型,指定n_estimators参数为1010,\n# 即使用1010棵决策树构建模型。将训练集传入模型进行模型训练。\nfrom sklearn.ensemble import RandomForestClassifier\nmodel= RandomForestClassifier(n_estimators=10)\nmodel.fit(X_train, y_train)\n\n#5.利用随机森林模型预测分类\n#运用predict方法预测测试集中样本的分类,该方法返回一个预测结果数组,输出预测的分类结果。\ny_pred = model.predict(X_test)\nprint(\"Predictions of test set:\\n%s\"%y_pred)\n\n#6. 查看各特征重要性\n#用feature_importances_属性查看每个特征的重要性,相对而言第11、22、55、77个特征在随机森林分类中的重要性强一些。\nprint(model.feature_importances_)\n\n#7. 评估模型准确率\n#利用score方法计算模型在测试集上的预测准确率。\nprint(model.score(X_test,y_test))\n\n#8. 调整随机森林中的树木数量\n#随机森林中的数目数量是模型中较为重要的参数,\n#通过指定n_estimators参数进行设置,设置为30时模型的性能较10时有所提升,\n#但设置为100时,其准确度不但没有提升已不明显,甚至可能下降,可能已经过拟合。\nmodel= RandomForestClassifier(n_estimators=30)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test,y_test))\n\n#9. 与决策树分类进行比较\n#决策树与随机森林在分类效果上进行比较,\n# 决策树模型的分类准确率与仅含单棵决策树的随机森林类似,\n# 但是总体上随机森林的准确度要高于决策树,但其模型的解释性较差,无法轻易得到树的基本结构。\nfrom sklearn import tree\nclf = tree.DecisionTreeClassifier()\nclf = clf.fit(X_train, y_train)\nprint(clf.score(X_test,y_test))\n\nmodel= RandomForestClassifier(n_estimators=1)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test,y_test))", "import pandas as pd\ndata = pd.read_csv('wheat.csv', index_col=0)\nprint(data.head(6))\ndata = data.fillna(data.mean())\nprint(data)\nfrom sklearn.model_selection import train_test_split\nX = data.iloc[:, :7]\ny = data.iloc[:, 7]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,\n random_state=300)\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\nfrom sklearn.ensemble import RandomForestClassifier\nmodel = RandomForestClassifier(n_estimators=10)\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\nprint(\"\"\"Predictions of test set:\n%s\"\"\" % y_pred)\nprint(model.feature_importances_)\nprint(model.score(X_test, y_test))\nmodel = RandomForestClassifier(n_estimators=30)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\nfrom sklearn import tree\nclf = tree.DecisionTreeClassifier()\nclf = clf.fit(X_train, y_train)\nprint(clf.score(X_test, y_test))\nmodel = RandomForestClassifier(n_estimators=1)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\n", "<import token>\ndata = pd.read_csv('wheat.csv', index_col=0)\nprint(data.head(6))\ndata = data.fillna(data.mean())\nprint(data)\n<import token>\nX = data.iloc[:, :7]\ny = data.iloc[:, 7]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,\n random_state=300)\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n<import token>\nmodel = RandomForestClassifier(n_estimators=10)\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\nprint(\"\"\"Predictions of test set:\n%s\"\"\" % y_pred)\nprint(model.feature_importances_)\nprint(model.score(X_test, y_test))\nmodel = RandomForestClassifier(n_estimators=30)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\n<import token>\nclf = tree.DecisionTreeClassifier()\nclf = clf.fit(X_train, y_train)\nprint(clf.score(X_test, y_test))\nmodel = RandomForestClassifier(n_estimators=1)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\n", "<import token>\n<assignment token>\nprint(data.head(6))\n<assignment token>\nprint(data)\n<import token>\n<assignment token>\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n<import token>\n<assignment token>\nmodel.fit(X_train, y_train)\n<assignment token>\nprint(\"\"\"Predictions of test set:\n%s\"\"\" % y_pred)\nprint(model.feature_importances_)\nprint(model.score(X_test, y_test))\n<assignment token>\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\n<import token>\n<assignment token>\nprint(clf.score(X_test, y_test))\n<assignment token>\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<import token>\n<assignment token>\n<code token>\n<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
712
7036ae5f74e6cb04518c20bb52122a1dfae76f23
import json from bokeh.plotting import figure, output_file from bokeh.io import show from bokeh.palettes import inferno from bokeh.models import ColumnDataSource, FactorRange from bokeh.transform import factor_cmap from bokeh.models import HoverTool # from bokeh.io import export_svgs def read_summary(summary_file): return json.loads(open(summary_file, "r").read()) def get_descriptions(summary): d = {} for o in summary["ontology_events"]: print(o) d[o] = summary["ontology_events"][o].get( 'description', summary["ontology_events"][o]['method']) + '_' + str(o) return(d) def plot_totals(summary): descriptions = get_descriptions(summary) totals = {} for event in summary['ontology_events'].keys(): totals[str(event)] = {'genes': [], 'rxns': [], 'terms': []} # genes for gene in summary['genes']: for term in summary['genes'][gene]['terms']: for event in summary['genes'][gene]['terms'][term]: totals[str(event)]['genes'].append(gene) # terms for term in summary['terms']: for event in summary['terms'][term]: totals[str(event)]['terms'].append(term) # rxns for rxn in summary['rxns']: for event in summary['rxns'][rxn]: totals[str(event)]['rxns'].append(rxn) # sums events = [] types = ['genes', 'terms', 'rxns'] gene_counts = [] rxn_counts = [] term_counts = [] for event in totals: events.append(descriptions[event]) gene_counts.append(len(set(totals[event]['genes']))) rxn_counts.append(len(set(totals[event]['rxns']))) term_counts.append(len(set(totals[event]['terms']))) data = {'events': events, 'genes': gene_counts, 'terms': term_counts, 'rxns': rxn_counts } x = [(event, type) for event in events for type in types] counts = sum(zip(data['genes'], data['terms'], data['rxns']), ()) source = ColumnDataSource(data=dict(x=x, counts=counts)) p = figure(y_range=FactorRange(*x), plot_height=400, plot_width=1000, title="Unique Counts per Annotation Event", tools="wheel_zoom,box_zoom,reset,save") p.hbar(y='x', right='counts', height=0.9, source=source, line_color="black", fill_color=factor_cmap('x', palette=inferno(len(types)), factors=types, start=1, end=2)) p.x_range.start = 0 p.y_range.range_padding = 0.1 p.yaxis.major_label_orientation = "horizontal" p.yaxis.subgroup_label_orientation = "horizontal" p.yaxis.group_label_orientation = "horizontal" p.ygrid.grid_line_color = None p.title.text_font_size = '12pt' p.xaxis.major_label_text_font_size = "12pt" p.yaxis.major_label_text_font_size = "12pt" p.yaxis.group_text_font_size = "12pt" p.add_tools(HoverTool(tooltips=[("Type", "@x"), ("Count", "@counts")])) return(p) #summary = read_summary("PT19DW.5.json") summary = read_summary("PT19DW.7.json") output_file("totals.html", title="Totals") totals = plot_totals(summary) show(totals)
[ "import json\n\nfrom bokeh.plotting import figure, output_file\nfrom bokeh.io import show\nfrom bokeh.palettes import inferno\nfrom bokeh.models import ColumnDataSource, FactorRange\nfrom bokeh.transform import factor_cmap\nfrom bokeh.models import HoverTool\n# from bokeh.io import export_svgs\n\n\ndef read_summary(summary_file):\n return json.loads(open(summary_file, \"r\").read())\n\n\ndef get_descriptions(summary):\n d = {}\n for o in summary[\"ontology_events\"]:\n print(o)\n d[o] = summary[\"ontology_events\"][o].get(\n 'description', summary[\"ontology_events\"][o]['method']) + '_' + str(o)\n return(d)\n\n\ndef plot_totals(summary):\n descriptions = get_descriptions(summary)\n totals = {}\n for event in summary['ontology_events'].keys():\n totals[str(event)] = {'genes': [],\n 'rxns': [],\n 'terms': []}\n\n # genes\n for gene in summary['genes']:\n for term in summary['genes'][gene]['terms']:\n for event in summary['genes'][gene]['terms'][term]:\n totals[str(event)]['genes'].append(gene)\n\n # terms\n for term in summary['terms']:\n for event in summary['terms'][term]:\n totals[str(event)]['terms'].append(term)\n\n # rxns\n for rxn in summary['rxns']:\n for event in summary['rxns'][rxn]:\n totals[str(event)]['rxns'].append(rxn)\n\n # sums\n events = []\n types = ['genes', 'terms', 'rxns']\n\n gene_counts = []\n rxn_counts = []\n term_counts = []\n\n for event in totals:\n events.append(descriptions[event])\n gene_counts.append(len(set(totals[event]['genes'])))\n rxn_counts.append(len(set(totals[event]['rxns'])))\n term_counts.append(len(set(totals[event]['terms'])))\n\n data = {'events': events,\n 'genes': gene_counts,\n 'terms': term_counts,\n 'rxns': rxn_counts\n }\n\n x = [(event, type) for event in events for type in types]\n\n counts = sum(zip(data['genes'], data['terms'], data['rxns']), ())\n source = ColumnDataSource(data=dict(x=x, counts=counts))\n\n p = figure(y_range=FactorRange(*x),\n plot_height=400,\n plot_width=1000,\n title=\"Unique Counts per Annotation Event\",\n tools=\"wheel_zoom,box_zoom,reset,save\")\n\n p.hbar(y='x',\n right='counts',\n height=0.9,\n source=source,\n line_color=\"black\",\n fill_color=factor_cmap('x',\n palette=inferno(len(types)),\n factors=types,\n start=1,\n end=2))\n\n p.x_range.start = 0\n p.y_range.range_padding = 0.1\n p.yaxis.major_label_orientation = \"horizontal\"\n p.yaxis.subgroup_label_orientation = \"horizontal\"\n p.yaxis.group_label_orientation = \"horizontal\"\n p.ygrid.grid_line_color = None\n p.title.text_font_size = '12pt'\n p.xaxis.major_label_text_font_size = \"12pt\"\n p.yaxis.major_label_text_font_size = \"12pt\"\n p.yaxis.group_text_font_size = \"12pt\"\n p.add_tools(HoverTool(tooltips=[(\"Type\", \"@x\"), (\"Count\", \"@counts\")]))\n\n return(p)\n\n\n#summary = read_summary(\"PT19DW.5.json\")\nsummary = read_summary(\"PT19DW.7.json\")\n\noutput_file(\"totals.html\", title=\"Totals\")\ntotals = plot_totals(summary)\n\nshow(totals)\n", "import json\nfrom bokeh.plotting import figure, output_file\nfrom bokeh.io import show\nfrom bokeh.palettes import inferno\nfrom bokeh.models import ColumnDataSource, FactorRange\nfrom bokeh.transform import factor_cmap\nfrom bokeh.models import HoverTool\n\n\ndef read_summary(summary_file):\n return json.loads(open(summary_file, 'r').read())\n\n\ndef get_descriptions(summary):\n d = {}\n for o in summary['ontology_events']:\n print(o)\n d[o] = summary['ontology_events'][o].get('description', summary[\n 'ontology_events'][o]['method']) + '_' + str(o)\n return d\n\n\ndef plot_totals(summary):\n descriptions = get_descriptions(summary)\n totals = {}\n for event in summary['ontology_events'].keys():\n totals[str(event)] = {'genes': [], 'rxns': [], 'terms': []}\n for gene in summary['genes']:\n for term in summary['genes'][gene]['terms']:\n for event in summary['genes'][gene]['terms'][term]:\n totals[str(event)]['genes'].append(gene)\n for term in summary['terms']:\n for event in summary['terms'][term]:\n totals[str(event)]['terms'].append(term)\n for rxn in summary['rxns']:\n for event in summary['rxns'][rxn]:\n totals[str(event)]['rxns'].append(rxn)\n events = []\n types = ['genes', 'terms', 'rxns']\n gene_counts = []\n rxn_counts = []\n term_counts = []\n for event in totals:\n events.append(descriptions[event])\n gene_counts.append(len(set(totals[event]['genes'])))\n rxn_counts.append(len(set(totals[event]['rxns'])))\n term_counts.append(len(set(totals[event]['terms'])))\n data = {'events': events, 'genes': gene_counts, 'terms': term_counts,\n 'rxns': rxn_counts}\n x = [(event, type) for event in events for type in types]\n counts = sum(zip(data['genes'], data['terms'], data['rxns']), ())\n source = ColumnDataSource(data=dict(x=x, counts=counts))\n p = figure(y_range=FactorRange(*x), plot_height=400, plot_width=1000,\n title='Unique Counts per Annotation Event', tools=\n 'wheel_zoom,box_zoom,reset,save')\n p.hbar(y='x', right='counts', height=0.9, source=source, line_color=\n 'black', fill_color=factor_cmap('x', palette=inferno(len(types)),\n factors=types, start=1, end=2))\n p.x_range.start = 0\n p.y_range.range_padding = 0.1\n p.yaxis.major_label_orientation = 'horizontal'\n p.yaxis.subgroup_label_orientation = 'horizontal'\n p.yaxis.group_label_orientation = 'horizontal'\n p.ygrid.grid_line_color = None\n p.title.text_font_size = '12pt'\n p.xaxis.major_label_text_font_size = '12pt'\n p.yaxis.major_label_text_font_size = '12pt'\n p.yaxis.group_text_font_size = '12pt'\n p.add_tools(HoverTool(tooltips=[('Type', '@x'), ('Count', '@counts')]))\n return p\n\n\nsummary = read_summary('PT19DW.7.json')\noutput_file('totals.html', title='Totals')\ntotals = plot_totals(summary)\nshow(totals)\n", "<import token>\n\n\ndef read_summary(summary_file):\n return json.loads(open(summary_file, 'r').read())\n\n\ndef get_descriptions(summary):\n d = {}\n for o in summary['ontology_events']:\n print(o)\n d[o] = summary['ontology_events'][o].get('description', summary[\n 'ontology_events'][o]['method']) + '_' + str(o)\n return d\n\n\ndef plot_totals(summary):\n descriptions = get_descriptions(summary)\n totals = {}\n for event in summary['ontology_events'].keys():\n totals[str(event)] = {'genes': [], 'rxns': [], 'terms': []}\n for gene in summary['genes']:\n for term in summary['genes'][gene]['terms']:\n for event in summary['genes'][gene]['terms'][term]:\n totals[str(event)]['genes'].append(gene)\n for term in summary['terms']:\n for event in summary['terms'][term]:\n totals[str(event)]['terms'].append(term)\n for rxn in summary['rxns']:\n for event in summary['rxns'][rxn]:\n totals[str(event)]['rxns'].append(rxn)\n events = []\n types = ['genes', 'terms', 'rxns']\n gene_counts = []\n rxn_counts = []\n term_counts = []\n for event in totals:\n events.append(descriptions[event])\n gene_counts.append(len(set(totals[event]['genes'])))\n rxn_counts.append(len(set(totals[event]['rxns'])))\n term_counts.append(len(set(totals[event]['terms'])))\n data = {'events': events, 'genes': gene_counts, 'terms': term_counts,\n 'rxns': rxn_counts}\n x = [(event, type) for event in events for type in types]\n counts = sum(zip(data['genes'], data['terms'], data['rxns']), ())\n source = ColumnDataSource(data=dict(x=x, counts=counts))\n p = figure(y_range=FactorRange(*x), plot_height=400, plot_width=1000,\n title='Unique Counts per Annotation Event', tools=\n 'wheel_zoom,box_zoom,reset,save')\n p.hbar(y='x', right='counts', height=0.9, source=source, line_color=\n 'black', fill_color=factor_cmap('x', palette=inferno(len(types)),\n factors=types, start=1, end=2))\n p.x_range.start = 0\n p.y_range.range_padding = 0.1\n p.yaxis.major_label_orientation = 'horizontal'\n p.yaxis.subgroup_label_orientation = 'horizontal'\n p.yaxis.group_label_orientation = 'horizontal'\n p.ygrid.grid_line_color = None\n p.title.text_font_size = '12pt'\n p.xaxis.major_label_text_font_size = '12pt'\n p.yaxis.major_label_text_font_size = '12pt'\n p.yaxis.group_text_font_size = '12pt'\n p.add_tools(HoverTool(tooltips=[('Type', '@x'), ('Count', '@counts')]))\n return p\n\n\nsummary = read_summary('PT19DW.7.json')\noutput_file('totals.html', title='Totals')\ntotals = plot_totals(summary)\nshow(totals)\n", "<import token>\n\n\ndef read_summary(summary_file):\n return json.loads(open(summary_file, 'r').read())\n\n\ndef get_descriptions(summary):\n d = {}\n for o in summary['ontology_events']:\n print(o)\n d[o] = summary['ontology_events'][o].get('description', summary[\n 'ontology_events'][o]['method']) + '_' + str(o)\n return d\n\n\ndef plot_totals(summary):\n descriptions = get_descriptions(summary)\n totals = {}\n for event in summary['ontology_events'].keys():\n totals[str(event)] = {'genes': [], 'rxns': [], 'terms': []}\n for gene in summary['genes']:\n for term in summary['genes'][gene]['terms']:\n for event in summary['genes'][gene]['terms'][term]:\n totals[str(event)]['genes'].append(gene)\n for term in summary['terms']:\n for event in summary['terms'][term]:\n totals[str(event)]['terms'].append(term)\n for rxn in summary['rxns']:\n for event in summary['rxns'][rxn]:\n totals[str(event)]['rxns'].append(rxn)\n events = []\n types = ['genes', 'terms', 'rxns']\n gene_counts = []\n rxn_counts = []\n term_counts = []\n for event in totals:\n events.append(descriptions[event])\n gene_counts.append(len(set(totals[event]['genes'])))\n rxn_counts.append(len(set(totals[event]['rxns'])))\n term_counts.append(len(set(totals[event]['terms'])))\n data = {'events': events, 'genes': gene_counts, 'terms': term_counts,\n 'rxns': rxn_counts}\n x = [(event, type) for event in events for type in types]\n counts = sum(zip(data['genes'], data['terms'], data['rxns']), ())\n source = ColumnDataSource(data=dict(x=x, counts=counts))\n p = figure(y_range=FactorRange(*x), plot_height=400, plot_width=1000,\n title='Unique Counts per Annotation Event', tools=\n 'wheel_zoom,box_zoom,reset,save')\n p.hbar(y='x', right='counts', height=0.9, source=source, line_color=\n 'black', fill_color=factor_cmap('x', palette=inferno(len(types)),\n factors=types, start=1, end=2))\n p.x_range.start = 0\n p.y_range.range_padding = 0.1\n p.yaxis.major_label_orientation = 'horizontal'\n p.yaxis.subgroup_label_orientation = 'horizontal'\n p.yaxis.group_label_orientation = 'horizontal'\n p.ygrid.grid_line_color = None\n p.title.text_font_size = '12pt'\n p.xaxis.major_label_text_font_size = '12pt'\n p.yaxis.major_label_text_font_size = '12pt'\n p.yaxis.group_text_font_size = '12pt'\n p.add_tools(HoverTool(tooltips=[('Type', '@x'), ('Count', '@counts')]))\n return p\n\n\n<assignment token>\noutput_file('totals.html', title='Totals')\n<assignment token>\nshow(totals)\n", "<import token>\n\n\ndef read_summary(summary_file):\n return json.loads(open(summary_file, 'r').read())\n\n\ndef get_descriptions(summary):\n d = {}\n for o in summary['ontology_events']:\n print(o)\n d[o] = summary['ontology_events'][o].get('description', summary[\n 'ontology_events'][o]['method']) + '_' + str(o)\n return d\n\n\ndef plot_totals(summary):\n descriptions = get_descriptions(summary)\n totals = {}\n for event in summary['ontology_events'].keys():\n totals[str(event)] = {'genes': [], 'rxns': [], 'terms': []}\n for gene in summary['genes']:\n for term in summary['genes'][gene]['terms']:\n for event in summary['genes'][gene]['terms'][term]:\n totals[str(event)]['genes'].append(gene)\n for term in summary['terms']:\n for event in summary['terms'][term]:\n totals[str(event)]['terms'].append(term)\n for rxn in summary['rxns']:\n for event in summary['rxns'][rxn]:\n totals[str(event)]['rxns'].append(rxn)\n events = []\n types = ['genes', 'terms', 'rxns']\n gene_counts = []\n rxn_counts = []\n term_counts = []\n for event in totals:\n events.append(descriptions[event])\n gene_counts.append(len(set(totals[event]['genes'])))\n rxn_counts.append(len(set(totals[event]['rxns'])))\n term_counts.append(len(set(totals[event]['terms'])))\n data = {'events': events, 'genes': gene_counts, 'terms': term_counts,\n 'rxns': rxn_counts}\n x = [(event, type) for event in events for type in types]\n counts = sum(zip(data['genes'], data['terms'], data['rxns']), ())\n source = ColumnDataSource(data=dict(x=x, counts=counts))\n p = figure(y_range=FactorRange(*x), plot_height=400, plot_width=1000,\n title='Unique Counts per Annotation Event', tools=\n 'wheel_zoom,box_zoom,reset,save')\n p.hbar(y='x', right='counts', height=0.9, source=source, line_color=\n 'black', fill_color=factor_cmap('x', palette=inferno(len(types)),\n factors=types, start=1, end=2))\n p.x_range.start = 0\n p.y_range.range_padding = 0.1\n p.yaxis.major_label_orientation = 'horizontal'\n p.yaxis.subgroup_label_orientation = 'horizontal'\n p.yaxis.group_label_orientation = 'horizontal'\n p.ygrid.grid_line_color = None\n p.title.text_font_size = '12pt'\n p.xaxis.major_label_text_font_size = '12pt'\n p.yaxis.major_label_text_font_size = '12pt'\n p.yaxis.group_text_font_size = '12pt'\n p.add_tools(HoverTool(tooltips=[('Type', '@x'), ('Count', '@counts')]))\n return p\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<function token>\n\n\ndef get_descriptions(summary):\n d = {}\n for o in summary['ontology_events']:\n print(o)\n d[o] = summary['ontology_events'][o].get('description', summary[\n 'ontology_events'][o]['method']) + '_' + str(o)\n return d\n\n\ndef plot_totals(summary):\n descriptions = get_descriptions(summary)\n totals = {}\n for event in summary['ontology_events'].keys():\n totals[str(event)] = {'genes': [], 'rxns': [], 'terms': []}\n for gene in summary['genes']:\n for term in summary['genes'][gene]['terms']:\n for event in summary['genes'][gene]['terms'][term]:\n totals[str(event)]['genes'].append(gene)\n for term in summary['terms']:\n for event in summary['terms'][term]:\n totals[str(event)]['terms'].append(term)\n for rxn in summary['rxns']:\n for event in summary['rxns'][rxn]:\n totals[str(event)]['rxns'].append(rxn)\n events = []\n types = ['genes', 'terms', 'rxns']\n gene_counts = []\n rxn_counts = []\n term_counts = []\n for event in totals:\n events.append(descriptions[event])\n gene_counts.append(len(set(totals[event]['genes'])))\n rxn_counts.append(len(set(totals[event]['rxns'])))\n term_counts.append(len(set(totals[event]['terms'])))\n data = {'events': events, 'genes': gene_counts, 'terms': term_counts,\n 'rxns': rxn_counts}\n x = [(event, type) for event in events for type in types]\n counts = sum(zip(data['genes'], data['terms'], data['rxns']), ())\n source = ColumnDataSource(data=dict(x=x, counts=counts))\n p = figure(y_range=FactorRange(*x), plot_height=400, plot_width=1000,\n title='Unique Counts per Annotation Event', tools=\n 'wheel_zoom,box_zoom,reset,save')\n p.hbar(y='x', right='counts', height=0.9, source=source, line_color=\n 'black', fill_color=factor_cmap('x', palette=inferno(len(types)),\n factors=types, start=1, end=2))\n p.x_range.start = 0\n p.y_range.range_padding = 0.1\n p.yaxis.major_label_orientation = 'horizontal'\n p.yaxis.subgroup_label_orientation = 'horizontal'\n p.yaxis.group_label_orientation = 'horizontal'\n p.ygrid.grid_line_color = None\n p.title.text_font_size = '12pt'\n p.xaxis.major_label_text_font_size = '12pt'\n p.yaxis.major_label_text_font_size = '12pt'\n p.yaxis.group_text_font_size = '12pt'\n p.add_tools(HoverTool(tooltips=[('Type', '@x'), ('Count', '@counts')]))\n return p\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<function token>\n\n\ndef get_descriptions(summary):\n d = {}\n for o in summary['ontology_events']:\n print(o)\n d[o] = summary['ontology_events'][o].get('description', summary[\n 'ontology_events'][o]['method']) + '_' + str(o)\n return d\n\n\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
713
5eb5388ffe7a7c880d8fcfaa137c2c9a133a0636
import wikipedia input_ = input("Type in your question ") print(wikipedia.summary(input_))
[ "import wikipedia\ninput_ = input(\"Type in your question \")\nprint(wikipedia.summary(input_))\n", "import wikipedia\ninput_ = input('Type in your question ')\nprint(wikipedia.summary(input_))\n", "<import token>\ninput_ = input('Type in your question ')\nprint(wikipedia.summary(input_))\n", "<import token>\n<assignment token>\nprint(wikipedia.summary(input_))\n", "<import token>\n<assignment token>\n<code token>\n" ]
false
714
51540a80c7b29dc0bbb6342ee45008108d54b6f2
# -*- coding: utf-8 -*- import numpy as np def gauss_seidel(relax, est, stop): """ Método iterativo de Gauss-Seidel para o sistema linear do trabalho. Onde relax é o fator de relaxação, est é o valor inicial, stop é o critério de parada, n é a quantidade de linhas do sistema e k é o número de iterações. """ k = 0 dif = 10000 n = len(est) diff = np.zeros(n) while dif > stop: k += 1 est[0] = ((1 - relax) * est[0]) + relax * (1.50 - est[1]) for i in range(1, int(n/2)): est[i] = ((1 - relax) * est[i]) + relax * \ ((1.0 - est[i-1] - est[i+1] - est[i+25])/4) for j in range(int(n/2), n-1): est[j] = ((1 - relax) * est[j]) + relax * \ ((2.0 - est[j-25] - est[j-1] - est[j+1])/5) est[n-1] = ((1 - relax) * est[n-1]) + relax * (3.00 - est[n-2]) dif = max(abs(np.subtract(est, diff))) diff = np.copy(est) return [est, k]
[ "# -*- coding: utf-8 -*-\nimport numpy as np\n\n\ndef gauss_seidel(relax, est, stop):\n \"\"\"\n Método iterativo de Gauss-Seidel para o sistema linear do trabalho.\n Onde relax é o fator de relaxação, est é o valor inicial, stop é o\n critério de parada, n é a quantidade de linhas do sistema e k é o\n número de iterações.\n \"\"\"\n\n k = 0\n dif = 10000\n n = len(est)\n diff = np.zeros(n)\n\n while dif > stop:\n k += 1\n\n est[0] = ((1 - relax) * est[0]) + relax * (1.50 - est[1])\n\n for i in range(1, int(n/2)):\n est[i] = ((1 - relax) * est[i]) + relax * \\\n ((1.0 - est[i-1] - est[i+1] - est[i+25])/4)\n\n for j in range(int(n/2), n-1):\n est[j] = ((1 - relax) * est[j]) + relax * \\\n ((2.0 - est[j-25] - est[j-1] - est[j+1])/5)\n\n est[n-1] = ((1 - relax) * est[n-1]) + relax * (3.00 - est[n-2])\n\n dif = max(abs(np.subtract(est, diff)))\n diff = np.copy(est)\n\n return [est, k]\n", "import numpy as np\n\n\ndef gauss_seidel(relax, est, stop):\n \"\"\"\n Método iterativo de Gauss-Seidel para o sistema linear do trabalho.\n Onde relax é o fator de relaxação, est é o valor inicial, stop é o\n critério de parada, n é a quantidade de linhas do sistema e k é o\n número de iterações.\n \"\"\"\n k = 0\n dif = 10000\n n = len(est)\n diff = np.zeros(n)\n while dif > stop:\n k += 1\n est[0] = (1 - relax) * est[0] + relax * (1.5 - est[1])\n for i in range(1, int(n / 2)):\n est[i] = (1 - relax) * est[i] + relax * ((1.0 - est[i - 1] -\n est[i + 1] - est[i + 25]) / 4)\n for j in range(int(n / 2), n - 1):\n est[j] = (1 - relax) * est[j] + relax * ((2.0 - est[j - 25] -\n est[j - 1] - est[j + 1]) / 5)\n est[n - 1] = (1 - relax) * est[n - 1] + relax * (3.0 - est[n - 2])\n dif = max(abs(np.subtract(est, diff)))\n diff = np.copy(est)\n return [est, k]\n", "<import token>\n\n\ndef gauss_seidel(relax, est, stop):\n \"\"\"\n Método iterativo de Gauss-Seidel para o sistema linear do trabalho.\n Onde relax é o fator de relaxação, est é o valor inicial, stop é o\n critério de parada, n é a quantidade de linhas do sistema e k é o\n número de iterações.\n \"\"\"\n k = 0\n dif = 10000\n n = len(est)\n diff = np.zeros(n)\n while dif > stop:\n k += 1\n est[0] = (1 - relax) * est[0] + relax * (1.5 - est[1])\n for i in range(1, int(n / 2)):\n est[i] = (1 - relax) * est[i] + relax * ((1.0 - est[i - 1] -\n est[i + 1] - est[i + 25]) / 4)\n for j in range(int(n / 2), n - 1):\n est[j] = (1 - relax) * est[j] + relax * ((2.0 - est[j - 25] -\n est[j - 1] - est[j + 1]) / 5)\n est[n - 1] = (1 - relax) * est[n - 1] + relax * (3.0 - est[n - 2])\n dif = max(abs(np.subtract(est, diff)))\n diff = np.copy(est)\n return [est, k]\n", "<import token>\n<function token>\n" ]
false
715
eb981a2d7f0ff5e6cc4a4a76f269c93c547965ba
from typing import Any, Dict, List import numpy as np from kedro.io import AbstractDataSet from msrest.exceptions import HttpOperationError from azureml.core import Workspace, Datastore from azureml.data.data_reference import DataReference class AZblob_datastore_data(AbstractDataSet): """``ImageDataSet`` loads / save image data from a given filepath as `numpy` array using Pillow. Example: :: >>> ImageDataSet(filepath='/img/file/path.png') """ def __init__(self, container_path: str, local_path : str, credentials: Dict[str, Any] = None): """Creates a new instance of ImageDataSet to load / save image data at the given filepath. Args: filepath: The location of the image file to load / save data. """ self._container_path = container_path self._local_path = local_path self._credentials = credentials def _load(self) -> np.ndarray: """Loads data from the image file. Returns: Data from the image file as a numpy array. """ # Initialis Workspace ws = Workspace.from_config() blob_datastore_name = self._credentials['storage_name'] account_name = self._credentials['storage_name'] # Storage account name container_name = self._credentials['container_name'] # Name of Azure blob container account_key = self._credentials['key'] # Storage account key # Register a new datastore try: blob_datastore = blob_datastore = Datastore.get(ws, blob_datastore_name) print("Found Blob Datastore with name: %s" % blob_datastore_name) except HttpOperationError: blob_datastore = Datastore.register_azure_blob_container(workspace = ws, datastore_name = blob_datastore_name, container_name = container_name, account_name = account_name, blob_datastore.download(target_path=self._local_path, prefix=self._container_path, show_progress=False) ... def _save(self, data: np.ndarray) -> None: """Saves image data to the specified filepath""" ... def _describe(self) -> Dict[str, Any]: """Returns a dict that describes the attributes of the dataset"""
[ "from typing import Any, Dict, List\n\nimport numpy as np\n\nfrom kedro.io import AbstractDataSet\nfrom msrest.exceptions import HttpOperationError\nfrom azureml.core import Workspace, Datastore\nfrom azureml.data.data_reference import DataReference\n\nclass AZblob_datastore_data(AbstractDataSet):\n \"\"\"``ImageDataSet`` loads / save image data from a given filepath as `numpy` array using Pillow.\n\n Example:\n ::\n\n >>> ImageDataSet(filepath='/img/file/path.png')\n \"\"\"\n\n def __init__(self,\n container_path: str,\n local_path : str,\n credentials: Dict[str, Any] = None):\n \"\"\"Creates a new instance of ImageDataSet to load / save image data at the given filepath.\n\n Args:\n filepath: The location of the image file to load / save data.\n \"\"\"\n self._container_path = container_path\n self._local_path = local_path\n self._credentials = credentials\n\n def _load(self) -> np.ndarray:\n \"\"\"Loads data from the image file.\n\n Returns:\n Data from the image file as a numpy array.\n \"\"\"\n # Initialis Workspace\n\n ws = Workspace.from_config()\n\n blob_datastore_name = self._credentials['storage_name']\n account_name = self._credentials['storage_name'] # Storage account name\n container_name = self._credentials['container_name'] # Name of Azure blob container\n account_key = self._credentials['key'] # Storage account key\n\n # Register a new datastore\n try:\n blob_datastore = blob_datastore = Datastore.get(ws, blob_datastore_name)\n print(\"Found Blob Datastore with name: %s\" % blob_datastore_name)\n\n except HttpOperationError:\n blob_datastore = Datastore.register_azure_blob_container(workspace = ws, \n datastore_name = blob_datastore_name, \n container_name = container_name,\n account_name = account_name,\n blob_datastore.download(target_path=self._local_path,\n prefix=self._container_path,\n show_progress=False) \n ...\n\n def _save(self, data: np.ndarray) -> None:\n \"\"\"Saves image data to the specified filepath\"\"\"\n ...\n\n def _describe(self) -> Dict[str, Any]:\n \n \"\"\"Returns a dict that describes the attributes of the dataset\"\"\"" ]
true
716
0beb5c5c5db9247d66a5a49cfff7282ead52a9b7
#!/usr/bin/env python import h5py class HDF5_Parser(object): # noqa: N801 """ Examples -------- >>> import h5py >>> indata = h5py.File('test.hdf5') >>> dataset = indata.create_dataset("mydataset", (10,), dtype='i') >>> indata.close() >>> with open('test.hdf5') as f: ... data = HDF5_Parser().read_file(f) >>> data['mydataset'][:] array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32) >>> import os >>> os.remove('test.hdf5') """ plugin_name = 'hdf5.read' plugin_descript = 'read *.hdf5 (in read mode) files using h5py' file_regex = '*.hdf5' def read_file(self, file_obj, **kwargs): return h5py.File(file_obj.name, mode='r')
[ "#!/usr/bin/env python\n\nimport h5py\n\n\nclass HDF5_Parser(object): # noqa: N801\n \"\"\"\n\n Examples\n --------\n\n >>> import h5py\n >>> indata = h5py.File('test.hdf5')\n >>> dataset = indata.create_dataset(\"mydataset\", (10,), dtype='i')\n >>> indata.close()\n\n >>> with open('test.hdf5') as f:\n ... data = HDF5_Parser().read_file(f)\n >>> data['mydataset'][:]\n array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)\n\n >>> import os\n >>> os.remove('test.hdf5')\n\n \"\"\"\n\n plugin_name = 'hdf5.read'\n plugin_descript = 'read *.hdf5 (in read mode) files using h5py'\n file_regex = '*.hdf5'\n\n def read_file(self, file_obj, **kwargs):\n return h5py.File(file_obj.name, mode='r')\n", "import h5py\n\n\nclass HDF5_Parser(object):\n \"\"\"\n\n Examples\n --------\n\n >>> import h5py\n >>> indata = h5py.File('test.hdf5')\n >>> dataset = indata.create_dataset(\"mydataset\", (10,), dtype='i')\n >>> indata.close()\n\n >>> with open('test.hdf5') as f:\n ... data = HDF5_Parser().read_file(f)\n >>> data['mydataset'][:]\n array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)\n\n >>> import os\n >>> os.remove('test.hdf5')\n\n \"\"\"\n plugin_name = 'hdf5.read'\n plugin_descript = 'read *.hdf5 (in read mode) files using h5py'\n file_regex = '*.hdf5'\n\n def read_file(self, file_obj, **kwargs):\n return h5py.File(file_obj.name, mode='r')\n", "<import token>\n\n\nclass HDF5_Parser(object):\n \"\"\"\n\n Examples\n --------\n\n >>> import h5py\n >>> indata = h5py.File('test.hdf5')\n >>> dataset = indata.create_dataset(\"mydataset\", (10,), dtype='i')\n >>> indata.close()\n\n >>> with open('test.hdf5') as f:\n ... data = HDF5_Parser().read_file(f)\n >>> data['mydataset'][:]\n array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32)\n\n >>> import os\n >>> os.remove('test.hdf5')\n\n \"\"\"\n plugin_name = 'hdf5.read'\n plugin_descript = 'read *.hdf5 (in read mode) files using h5py'\n file_regex = '*.hdf5'\n\n def read_file(self, file_obj, **kwargs):\n return h5py.File(file_obj.name, mode='r')\n", "<import token>\n\n\nclass HDF5_Parser(object):\n <docstring token>\n plugin_name = 'hdf5.read'\n plugin_descript = 'read *.hdf5 (in read mode) files using h5py'\n file_regex = '*.hdf5'\n\n def read_file(self, file_obj, **kwargs):\n return h5py.File(file_obj.name, mode='r')\n", "<import token>\n\n\nclass HDF5_Parser(object):\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def read_file(self, file_obj, **kwargs):\n return h5py.File(file_obj.name, mode='r')\n", "<import token>\n\n\nclass HDF5_Parser(object):\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
717
93d4c6b6aef827d6746afc684c32a9cf1d0229e4
# 가위, 바위, 보 게임 # 컴퓨터 가위, 바위, 보 리스트에서 랜덤하게 뽑기 위해 random 함수 호출 import random # 컴퓨터 가위, 바위, 보 리스트 list_b = ["가위", "바위", "보"] # 이긴횟수, 진 횟수 카운팅 하기 위한 변수 person_win_count = 0 person_lose_count = 0 while person_win_count < 4 or person_lose_count < 4: # 가위, 바위, 보 입력 받기 player = input("가위, 바위, 보 중 어떤 것을 낼래요? ") if player != "가위" and player != "바위" and player != "보": player = input("다시 입력해 주세요.(예: 가위, 바위, 보)") # 컴퓨터 가위, 바위, 보 임의 추출 computer = random.choice(list_b) print("컴퓨터:", computer) # 사람과 컴퓨터간 가위, 바위, 보 비교 및 카운팅 if player == computer: print("비겼습니다.") elif player == "가위": if computer == "바위": person_lose_count = person_lose_count + 1 print("컴퓨터가 이겼습니다.") if computer == "보": person_win_count = person_win_count + 1 print("당신이 이겼습니다.") elif player == "바위": if computer == "가위": person_win_count = person_win_count + 1 print("당신이 이겼습니다.") if computer == "보": person_lose_count = person_lose_count + 1 print("컴퓨터가 이겼습니다.") elif player == "보": if computer == "바위": person_win_count = person_win_count + 1 print("당신이 이겼습니다.") if computer == "가위": person_lose_count = person_lose_count + 1 print("컴퓨터가 이겼습니다.") # 3번 이겼는지, 3번 졌는지 조건비교, 최종결과, 게임종료 if person_win_count == 3: print("당신이 3번을 이겼습니다.^^; 가위바위보 게임을 종료합니다.") break elif person_lose_count == 3: print("당신이 3번을 졌습니다.-_-; 가위바위보 게임을 종료합니다.") break
[ "# 가위, 바위, 보 게임\n\n\n# 컴퓨터 가위, 바위, 보 리스트에서 랜덤하게 뽑기 위해 random 함수 호출\nimport random\n\n# 컴퓨터 가위, 바위, 보 리스트\nlist_b = [\"가위\", \"바위\", \"보\"]\n\n# 이긴횟수, 진 횟수 카운팅 하기 위한 변수\nperson_win_count = 0\nperson_lose_count = 0\n\nwhile person_win_count < 4 or person_lose_count < 4:\n # 가위, 바위, 보 입력 받기\n player = input(\"가위, 바위, 보 중 어떤 것을 낼래요? \")\n if player != \"가위\" and player != \"바위\" and player != \"보\":\n player = input(\"다시 입력해 주세요.(예: 가위, 바위, 보)\")\n\n # 컴퓨터 가위, 바위, 보 임의 추출\n computer = random.choice(list_b)\n print(\"컴퓨터:\", computer)\n\n # 사람과 컴퓨터간 가위, 바위, 보 비교 및 카운팅\n if player == computer:\n print(\"비겼습니다.\")\n elif player == \"가위\":\n if computer == \"바위\":\n person_lose_count = person_lose_count + 1\n print(\"컴퓨터가 이겼습니다.\")\n if computer == \"보\":\n person_win_count = person_win_count + 1\n print(\"당신이 이겼습니다.\")\n\n elif player == \"바위\":\n if computer == \"가위\":\n person_win_count = person_win_count + 1\n print(\"당신이 이겼습니다.\")\n if computer == \"보\":\n person_lose_count = person_lose_count + 1\n print(\"컴퓨터가 이겼습니다.\")\n\n elif player == \"보\":\n if computer == \"바위\":\n person_win_count = person_win_count + 1\n print(\"당신이 이겼습니다.\")\n if computer == \"가위\":\n person_lose_count = person_lose_count + 1\n print(\"컴퓨터가 이겼습니다.\")\n\n # 3번 이겼는지, 3번 졌는지 조건비교, 최종결과, 게임종료\n if person_win_count == 3:\n print(\"당신이 3번을 이겼습니다.^^; 가위바위보 게임을 종료합니다.\")\n break\n elif person_lose_count == 3:\n print(\"당신이 3번을 졌습니다.-_-; 가위바위보 게임을 종료합니다.\")\n break\n", "import random\nlist_b = ['가위', '바위', '보']\nperson_win_count = 0\nperson_lose_count = 0\nwhile person_win_count < 4 or person_lose_count < 4:\n player = input('가위, 바위, 보 중 어떤 것을 낼래요? ')\n if player != '가위' and player != '바위' and player != '보':\n player = input('다시 입력해 주세요.(예: 가위, 바위, 보)')\n computer = random.choice(list_b)\n print('컴퓨터:', computer)\n if player == computer:\n print('비겼습니다.')\n elif player == '가위':\n if computer == '바위':\n person_lose_count = person_lose_count + 1\n print('컴퓨터가 이겼습니다.')\n if computer == '보':\n person_win_count = person_win_count + 1\n print('당신이 이겼습니다.')\n elif player == '바위':\n if computer == '가위':\n person_win_count = person_win_count + 1\n print('당신이 이겼습니다.')\n if computer == '보':\n person_lose_count = person_lose_count + 1\n print('컴퓨터가 이겼습니다.')\n elif player == '보':\n if computer == '바위':\n person_win_count = person_win_count + 1\n print('당신이 이겼습니다.')\n if computer == '가위':\n person_lose_count = person_lose_count + 1\n print('컴퓨터가 이겼습니다.')\n if person_win_count == 3:\n print('당신이 3번을 이겼습니다.^^; 가위바위보 게임을 종료합니다.')\n break\n elif person_lose_count == 3:\n print('당신이 3번을 졌습니다.-_-; 가위바위보 게임을 종료합니다.')\n break\n", "<import token>\nlist_b = ['가위', '바위', '보']\nperson_win_count = 0\nperson_lose_count = 0\nwhile person_win_count < 4 or person_lose_count < 4:\n player = input('가위, 바위, 보 중 어떤 것을 낼래요? ')\n if player != '가위' and player != '바위' and player != '보':\n player = input('다시 입력해 주세요.(예: 가위, 바위, 보)')\n computer = random.choice(list_b)\n print('컴퓨터:', computer)\n if player == computer:\n print('비겼습니다.')\n elif player == '가위':\n if computer == '바위':\n person_lose_count = person_lose_count + 1\n print('컴퓨터가 이겼습니다.')\n if computer == '보':\n person_win_count = person_win_count + 1\n print('당신이 이겼습니다.')\n elif player == '바위':\n if computer == '가위':\n person_win_count = person_win_count + 1\n print('당신이 이겼습니다.')\n if computer == '보':\n person_lose_count = person_lose_count + 1\n print('컴퓨터가 이겼습니다.')\n elif player == '보':\n if computer == '바위':\n person_win_count = person_win_count + 1\n print('당신이 이겼습니다.')\n if computer == '가위':\n person_lose_count = person_lose_count + 1\n print('컴퓨터가 이겼습니다.')\n if person_win_count == 3:\n print('당신이 3번을 이겼습니다.^^; 가위바위보 게임을 종료합니다.')\n break\n elif person_lose_count == 3:\n print('당신이 3번을 졌습니다.-_-; 가위바위보 게임을 종료합니다.')\n break\n", "<import token>\n<assignment token>\nwhile person_win_count < 4 or person_lose_count < 4:\n player = input('가위, 바위, 보 중 어떤 것을 낼래요? ')\n if player != '가위' and player != '바위' and player != '보':\n player = input('다시 입력해 주세요.(예: 가위, 바위, 보)')\n computer = random.choice(list_b)\n print('컴퓨터:', computer)\n if player == computer:\n print('비겼습니다.')\n elif player == '가위':\n if computer == '바위':\n person_lose_count = person_lose_count + 1\n print('컴퓨터가 이겼습니다.')\n if computer == '보':\n person_win_count = person_win_count + 1\n print('당신이 이겼습니다.')\n elif player == '바위':\n if computer == '가위':\n person_win_count = person_win_count + 1\n print('당신이 이겼습니다.')\n if computer == '보':\n person_lose_count = person_lose_count + 1\n print('컴퓨터가 이겼습니다.')\n elif player == '보':\n if computer == '바위':\n person_win_count = person_win_count + 1\n print('당신이 이겼습니다.')\n if computer == '가위':\n person_lose_count = person_lose_count + 1\n print('컴퓨터가 이겼습니다.')\n if person_win_count == 3:\n print('당신이 3번을 이겼습니다.^^; 가위바위보 게임을 종료합니다.')\n break\n elif person_lose_count == 3:\n print('당신이 3번을 졌습니다.-_-; 가위바위보 게임을 종료합니다.')\n break\n", "<import token>\n<assignment token>\n<code token>\n" ]
false
718
d7d94cfed0b819297069c3434c70359a327403cd
from django.contrib import admin from . import models admin.site.register(models.Comentario) # Register your models here.
[ "from django.contrib import admin\nfrom . import models\n\nadmin.site.register(models.Comentario)\n\n# Register your models here.\n", "from django.contrib import admin\nfrom . import models\nadmin.site.register(models.Comentario)\n", "<import token>\nadmin.site.register(models.Comentario)\n", "<import token>\n<code token>\n" ]
false
719
32f9b5c32acbb6411fe6ab99616d8459acfd7c74
import os import pubmed_parser as pp nlpPath = "/Users/kapmayn/Desktop/nlp" articlesFolderPath = nlpPath + "/articles" abstractsFilePath = nlpPath + "/abstracts.txt" articlesFileNameList = os.listdir(articlesFolderPath) articlesFileNameList(reverse = True) resultFile = open(abstractsFilePath, 'w') for fileName in articlesFileNameList: print(fileName) dictOut = pp.parse_medline_xml(articlesFolderPath + "/" + fileName) for item in dictOut: resultFile.write((item['abstract'] + '\n'))
[ "import os\nimport pubmed_parser as pp\n\nnlpPath = \"/Users/kapmayn/Desktop/nlp\"\narticlesFolderPath = nlpPath + \"/articles\"\nabstractsFilePath = nlpPath + \"/abstracts.txt\"\n\narticlesFileNameList = os.listdir(articlesFolderPath)\narticlesFileNameList(reverse = True)\nresultFile = open(abstractsFilePath, 'w')\n\nfor fileName in articlesFileNameList:\n\tprint(fileName)\n\tdictOut = pp.parse_medline_xml(articlesFolderPath + \"/\" + fileName)\n\tfor item in dictOut:\n\t\tresultFile.write((item['abstract'] + '\\n'))", "import os\nimport pubmed_parser as pp\nnlpPath = '/Users/kapmayn/Desktop/nlp'\narticlesFolderPath = nlpPath + '/articles'\nabstractsFilePath = nlpPath + '/abstracts.txt'\narticlesFileNameList = os.listdir(articlesFolderPath)\narticlesFileNameList(reverse=True)\nresultFile = open(abstractsFilePath, 'w')\nfor fileName in articlesFileNameList:\n print(fileName)\n dictOut = pp.parse_medline_xml(articlesFolderPath + '/' + fileName)\n for item in dictOut:\n resultFile.write(item['abstract'] + '\\n')\n", "<import token>\nnlpPath = '/Users/kapmayn/Desktop/nlp'\narticlesFolderPath = nlpPath + '/articles'\nabstractsFilePath = nlpPath + '/abstracts.txt'\narticlesFileNameList = os.listdir(articlesFolderPath)\narticlesFileNameList(reverse=True)\nresultFile = open(abstractsFilePath, 'w')\nfor fileName in articlesFileNameList:\n print(fileName)\n dictOut = pp.parse_medline_xml(articlesFolderPath + '/' + fileName)\n for item in dictOut:\n resultFile.write(item['abstract'] + '\\n')\n", "<import token>\n<assignment token>\narticlesFileNameList(reverse=True)\n<assignment token>\nfor fileName in articlesFileNameList:\n print(fileName)\n dictOut = pp.parse_medline_xml(articlesFolderPath + '/' + fileName)\n for item in dictOut:\n resultFile.write(item['abstract'] + '\\n')\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
720
373c102018fdcc5211263304c368c2e8beef3257
# -- coding: utf-8 -- from django.conf.urls import url from myapp.view import views from myapp.view import story from myapp.view import img # 添加 from myapp.view import login from myapp.view import tuling from myapp.view import utilView from myapp.view.wechat import wechat_modules from myapp.view import router urlpatterns = [ url(r'get_img_api$', router.get_img_api), url(r'add_book$', views.add_book, ), url(r'show_books$', views.show_books, ), url(r'add_story$', story.add_story), url(r'show_storys$', story.show_storys), url(r'add_comment$', story.add_comment), url(r'show_comments$', story.show_comments), url(r'uploadImg$', img.uploadImg), url(r'showImg$', img.showImg), url(r'uploadImgForUs$', img.uploadImgForUs), url(r'showImgForUs', img.showImgForUs), url(r'add_user', login.add_user), url(r'login', login.login), url(r'get_username', login.get_username), url(r'send_register_email', login.send_register_email), url(r'check_username', login.check_username), url(r'chat_with_tuling', tuling.chat_with_tuling), url(r'utilView_getLive2d', utilView.get_live2d), url(r'utilView_getRandJson', utilView.get_rand_json), url(r'get_wechat', wechat_modules.on_get), url(r'', login.other_request), ]
[ "# -- coding: utf-8 --\nfrom django.conf.urls import url\nfrom myapp.view import views\nfrom myapp.view import story\nfrom myapp.view import img # 添加\nfrom myapp.view import login\nfrom myapp.view import tuling\nfrom myapp.view import utilView\nfrom myapp.view.wechat import wechat_modules\nfrom myapp.view import router\n\nurlpatterns = [\n url(r'get_img_api$', router.get_img_api),\n url(r'add_book$', views.add_book, ),\n url(r'show_books$', views.show_books, ),\n\n url(r'add_story$', story.add_story),\n url(r'show_storys$', story.show_storys),\n\n url(r'add_comment$', story.add_comment),\n url(r'show_comments$', story.show_comments),\n\n url(r'uploadImg$', img.uploadImg),\n url(r'showImg$', img.showImg),\n url(r'uploadImgForUs$', img.uploadImgForUs),\n url(r'showImgForUs', img.showImgForUs),\n\n url(r'add_user', login.add_user),\n url(r'login', login.login),\n url(r'get_username', login.get_username),\n url(r'send_register_email', login.send_register_email),\n url(r'check_username', login.check_username),\n\n url(r'chat_with_tuling', tuling.chat_with_tuling),\n url(r'utilView_getLive2d', utilView.get_live2d),\n url(r'utilView_getRandJson', utilView.get_rand_json),\n\n url(r'get_wechat', wechat_modules.on_get),\n\n url(r'', login.other_request),\n]\n", "from django.conf.urls import url\nfrom myapp.view import views\nfrom myapp.view import story\nfrom myapp.view import img\nfrom myapp.view import login\nfrom myapp.view import tuling\nfrom myapp.view import utilView\nfrom myapp.view.wechat import wechat_modules\nfrom myapp.view import router\nurlpatterns = [url('get_img_api$', router.get_img_api), url('add_book$',\n views.add_book), url('show_books$', views.show_books), url('add_story$',\n story.add_story), url('show_storys$', story.show_storys), url(\n 'add_comment$', story.add_comment), url('show_comments$', story.\n show_comments), url('uploadImg$', img.uploadImg), url('showImg$', img.\n showImg), url('uploadImgForUs$', img.uploadImgForUs), url(\n 'showImgForUs', img.showImgForUs), url('add_user', login.add_user), url\n ('login', login.login), url('get_username', login.get_username), url(\n 'send_register_email', login.send_register_email), url('check_username',\n login.check_username), url('chat_with_tuling', tuling.chat_with_tuling),\n url('utilView_getLive2d', utilView.get_live2d), url(\n 'utilView_getRandJson', utilView.get_rand_json), url('get_wechat',\n wechat_modules.on_get), url('', login.other_request)]\n", "<import token>\nurlpatterns = [url('get_img_api$', router.get_img_api), url('add_book$',\n views.add_book), url('show_books$', views.show_books), url('add_story$',\n story.add_story), url('show_storys$', story.show_storys), url(\n 'add_comment$', story.add_comment), url('show_comments$', story.\n show_comments), url('uploadImg$', img.uploadImg), url('showImg$', img.\n showImg), url('uploadImgForUs$', img.uploadImgForUs), url(\n 'showImgForUs', img.showImgForUs), url('add_user', login.add_user), url\n ('login', login.login), url('get_username', login.get_username), url(\n 'send_register_email', login.send_register_email), url('check_username',\n login.check_username), url('chat_with_tuling', tuling.chat_with_tuling),\n url('utilView_getLive2d', utilView.get_live2d), url(\n 'utilView_getRandJson', utilView.get_rand_json), url('get_wechat',\n wechat_modules.on_get), url('', login.other_request)]\n", "<import token>\n<assignment token>\n" ]
false
721
622b388beb56eba85bbb08510c2bcea55f23da9a
data = " Ramya , Deepa,LIRIL ,amma, dad, Kiran, 12321 , Suresh, Jayesh, Ramesh,Balu" lst = data.split(",") for name in lst: name = name.strip().upper() rname = name[::-1] if name == rname: print(name) girlsdata = "Tanvi,Dhatri,Haadya,Deepthi,Deepa,Ramya" # Name which start with DEE get those name print("-"*20) names = girlsdata.split(",") for name in names: name = name.upper() if "D" in name: print(name)
[ "data = \" Ramya , Deepa,LIRIL ,amma, dad, Kiran, 12321 , Suresh, Jayesh, Ramesh,Balu\"\n\nlst = data.split(\",\")\n\nfor name in lst:\n name = name.strip().upper()\n rname = name[::-1]\n if name == rname:\n print(name)\n\ngirlsdata = \"Tanvi,Dhatri,Haadya,Deepthi,Deepa,Ramya\"\n# Name which start with DEE get those name\nprint(\"-\"*20)\nnames = girlsdata.split(\",\")\nfor name in names:\n name = name.upper()\n if \"D\" in name:\n print(name)", "data = (\n ' Ramya , Deepa,LIRIL ,amma, dad, Kiran, 12321 , Suresh, Jayesh, Ramesh,Balu'\n )\nlst = data.split(',')\nfor name in lst:\n name = name.strip().upper()\n rname = name[::-1]\n if name == rname:\n print(name)\ngirlsdata = 'Tanvi,Dhatri,Haadya,Deepthi,Deepa,Ramya'\nprint('-' * 20)\nnames = girlsdata.split(',')\nfor name in names:\n name = name.upper()\n if 'D' in name:\n print(name)\n", "<assignment token>\nfor name in lst:\n name = name.strip().upper()\n rname = name[::-1]\n if name == rname:\n print(name)\n<assignment token>\nprint('-' * 20)\n<assignment token>\nfor name in names:\n name = name.upper()\n if 'D' in name:\n print(name)\n", "<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
722
e1787fd4be66d19ab83ece44eacfd96cb488b504
with expression [as var] #...BODY... #object is the result of the expression and must have __enter__ and __exit__ methods #result of the expression must be context manager - implements context management protocol #https://www.python.org/dev/peps/pep-0343/ # This PEP adds a new statement "with" to the Python language to make # it possible to factor out standard uses of try/finally statements. # In this PEP, context managers provide __enter__() and __exit__() # methods that are invoked on entry to and exit from the body of the # with statement.
[ "with expression [as var]\n\t#...BODY...\n\n#object is the result of the expression and must have __enter__ and __exit__ methods\n#result of the expression must be context manager - implements context management protocol\n\n#https://www.python.org/dev/peps/pep-0343/\n# This PEP adds a new statement \"with\" to the Python language to make\n# it possible to factor out standard uses of try/finally statements.\n\n# In this PEP, context managers provide __enter__() and __exit__()\n# methods that are invoked on entry to and exit from the body of the\n# with statement." ]
true
723
f3167d8f1a806c38fb10672605d8e94265d2fc9c
from database import db from database import ma from datetime import datetime from sqlalchemy import ForeignKeyConstraint from models.admin import Admin, admin_limited_schema from models.event_status import EventStatus, event_status_schema from models.org_unit import org_unit_schema class Event(db.Model): # class corresponding to the event table in the database __tablename__ = 'event' __table_args__ = ( ForeignKeyConstraint(['status_id'], ['event_status.id']), ForeignKeyConstraint(['org_id'], ['org_unit.id']), ForeignKeyConstraint(['created_by'], ['admin.id']), ) id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(45), nullable=False) venue = db.Column(db.String(45), nullable=False) location_lat = db.Column(db.Float, nullable=False) location_long = db.Column(db.Float, nullable=False) date_created = db.Column(db.DateTime, nullable=False, default=datetime.now) start_time = db.Column(db.DateTime, nullable=False) duration = db.Column(db.Float, nullable=False) coordinator_name = db.Column(db.String(45), nullable=False) coordinator_contact = db.Column(db.Integer, nullable=False) status_id = db.Column(db.Integer, nullable=False) org_id = db.Column(db.Integer, nullable=False) created_by = db.Column(db.Integer, nullable=False) description = db.Column(db.String(500), nullable=False) def __init__(self, name, venue, location_lat, location_long, start_time, duration, coordinator_name, coordinator_contact, status_id, org_id, created_by, description): self.name = name self.venue = venue self.location_lat = location_lat self.location_long = location_long self.start_time = start_time self.duration = duration self.coordinator_name = coordinator_name self.coordinator_contact = coordinator_contact self.status_id = status_id self.org_id = org_id self.created_by = created_by self.description = description class EventSchema(ma.Schema): class Meta: fields = ('id', 'name', 'venue', 'location_lat', 'location_long', 'date_created', 'start_time', 'duration', 'coordinator_name', 'coordinator_contact', 'status_id', 'org_id', 'description') # init schema event_schema = EventSchema() events_schema = EventSchema(many=True) class EventFullInfoSchema(ma.Schema): event = ma.Nested(event_schema) admin = ma.Nested(admin_limited_schema) status = ma.Nested(event_status_schema) org_unit = ma.Nested(org_unit_schema) event_with_full_schema = EventFullInfoSchema() events_with_full_schema = EventFullInfoSchema(many=True)
[ "from database import db\nfrom database import ma\nfrom datetime import datetime\nfrom sqlalchemy import ForeignKeyConstraint\nfrom models.admin import Admin, admin_limited_schema\nfrom models.event_status import EventStatus, event_status_schema\nfrom models.org_unit import org_unit_schema\n\nclass Event(db.Model):\n # class corresponding to the event table in the database\n __tablename__ = 'event'\n __table_args__ = (\n ForeignKeyConstraint(['status_id'], ['event_status.id']),\n ForeignKeyConstraint(['org_id'], ['org_unit.id']),\n ForeignKeyConstraint(['created_by'], ['admin.id']),\n )\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(45), nullable=False)\n venue = db.Column(db.String(45), nullable=False)\n location_lat = db.Column(db.Float, nullable=False)\n location_long = db.Column(db.Float, nullable=False)\n date_created = db.Column(db.DateTime, nullable=False, default=datetime.now)\n start_time = db.Column(db.DateTime, nullable=False)\n duration = db.Column(db.Float, nullable=False)\n coordinator_name = db.Column(db.String(45), nullable=False)\n coordinator_contact = db.Column(db.Integer, nullable=False)\n status_id = db.Column(db.Integer, nullable=False)\n org_id = db.Column(db.Integer, nullable=False)\n created_by = db.Column(db.Integer, nullable=False)\n description = db.Column(db.String(500), nullable=False)\n\n def __init__(self, name, venue, location_lat, location_long, start_time, duration, coordinator_name, coordinator_contact, status_id, org_id, created_by, description):\n self.name = name\n self.venue = venue\n self.location_lat = location_lat\n self.location_long = location_long\n self.start_time = start_time\n self.duration = duration\n self.coordinator_name = coordinator_name\n self.coordinator_contact = coordinator_contact\n self.status_id = status_id\n self.org_id = org_id\n self.created_by = created_by\n self.description = description\n\n\nclass EventSchema(ma.Schema):\n class Meta:\n fields = ('id', 'name', 'venue', 'location_lat', 'location_long', 'date_created', 'start_time',\n 'duration', 'coordinator_name', 'coordinator_contact', 'status_id', 'org_id', 'description')\n\n\n# init schema\nevent_schema = EventSchema()\nevents_schema = EventSchema(many=True)\n\n\nclass EventFullInfoSchema(ma.Schema):\n event = ma.Nested(event_schema)\n admin = ma.Nested(admin_limited_schema)\n status = ma.Nested(event_status_schema)\n org_unit = ma.Nested(org_unit_schema)\n\n\n\nevent_with_full_schema = EventFullInfoSchema()\nevents_with_full_schema = EventFullInfoSchema(many=True)", "from database import db\nfrom database import ma\nfrom datetime import datetime\nfrom sqlalchemy import ForeignKeyConstraint\nfrom models.admin import Admin, admin_limited_schema\nfrom models.event_status import EventStatus, event_status_schema\nfrom models.org_unit import org_unit_schema\n\n\nclass Event(db.Model):\n __tablename__ = 'event'\n __table_args__ = ForeignKeyConstraint(['status_id'], ['event_status.id']\n ), ForeignKeyConstraint(['org_id'], ['org_unit.id']\n ), ForeignKeyConstraint(['created_by'], ['admin.id'])\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(45), nullable=False)\n venue = db.Column(db.String(45), nullable=False)\n location_lat = db.Column(db.Float, nullable=False)\n location_long = db.Column(db.Float, nullable=False)\n date_created = db.Column(db.DateTime, nullable=False, default=datetime.now)\n start_time = db.Column(db.DateTime, nullable=False)\n duration = db.Column(db.Float, nullable=False)\n coordinator_name = db.Column(db.String(45), nullable=False)\n coordinator_contact = db.Column(db.Integer, nullable=False)\n status_id = db.Column(db.Integer, nullable=False)\n org_id = db.Column(db.Integer, nullable=False)\n created_by = db.Column(db.Integer, nullable=False)\n description = db.Column(db.String(500), nullable=False)\n\n def __init__(self, name, venue, location_lat, location_long, start_time,\n duration, coordinator_name, coordinator_contact, status_id, org_id,\n created_by, description):\n self.name = name\n self.venue = venue\n self.location_lat = location_lat\n self.location_long = location_long\n self.start_time = start_time\n self.duration = duration\n self.coordinator_name = coordinator_name\n self.coordinator_contact = coordinator_contact\n self.status_id = status_id\n self.org_id = org_id\n self.created_by = created_by\n self.description = description\n\n\nclass EventSchema(ma.Schema):\n\n\n class Meta:\n fields = ('id', 'name', 'venue', 'location_lat', 'location_long',\n 'date_created', 'start_time', 'duration', 'coordinator_name',\n 'coordinator_contact', 'status_id', 'org_id', 'description')\n\n\nevent_schema = EventSchema()\nevents_schema = EventSchema(many=True)\n\n\nclass EventFullInfoSchema(ma.Schema):\n event = ma.Nested(event_schema)\n admin = ma.Nested(admin_limited_schema)\n status = ma.Nested(event_status_schema)\n org_unit = ma.Nested(org_unit_schema)\n\n\nevent_with_full_schema = EventFullInfoSchema()\nevents_with_full_schema = EventFullInfoSchema(many=True)\n", "<import token>\n\n\nclass Event(db.Model):\n __tablename__ = 'event'\n __table_args__ = ForeignKeyConstraint(['status_id'], ['event_status.id']\n ), ForeignKeyConstraint(['org_id'], ['org_unit.id']\n ), ForeignKeyConstraint(['created_by'], ['admin.id'])\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(45), nullable=False)\n venue = db.Column(db.String(45), nullable=False)\n location_lat = db.Column(db.Float, nullable=False)\n location_long = db.Column(db.Float, nullable=False)\n date_created = db.Column(db.DateTime, nullable=False, default=datetime.now)\n start_time = db.Column(db.DateTime, nullable=False)\n duration = db.Column(db.Float, nullable=False)\n coordinator_name = db.Column(db.String(45), nullable=False)\n coordinator_contact = db.Column(db.Integer, nullable=False)\n status_id = db.Column(db.Integer, nullable=False)\n org_id = db.Column(db.Integer, nullable=False)\n created_by = db.Column(db.Integer, nullable=False)\n description = db.Column(db.String(500), nullable=False)\n\n def __init__(self, name, venue, location_lat, location_long, start_time,\n duration, coordinator_name, coordinator_contact, status_id, org_id,\n created_by, description):\n self.name = name\n self.venue = venue\n self.location_lat = location_lat\n self.location_long = location_long\n self.start_time = start_time\n self.duration = duration\n self.coordinator_name = coordinator_name\n self.coordinator_contact = coordinator_contact\n self.status_id = status_id\n self.org_id = org_id\n self.created_by = created_by\n self.description = description\n\n\nclass EventSchema(ma.Schema):\n\n\n class Meta:\n fields = ('id', 'name', 'venue', 'location_lat', 'location_long',\n 'date_created', 'start_time', 'duration', 'coordinator_name',\n 'coordinator_contact', 'status_id', 'org_id', 'description')\n\n\nevent_schema = EventSchema()\nevents_schema = EventSchema(many=True)\n\n\nclass EventFullInfoSchema(ma.Schema):\n event = ma.Nested(event_schema)\n admin = ma.Nested(admin_limited_schema)\n status = ma.Nested(event_status_schema)\n org_unit = ma.Nested(org_unit_schema)\n\n\nevent_with_full_schema = EventFullInfoSchema()\nevents_with_full_schema = EventFullInfoSchema(many=True)\n", "<import token>\n\n\nclass Event(db.Model):\n __tablename__ = 'event'\n __table_args__ = ForeignKeyConstraint(['status_id'], ['event_status.id']\n ), ForeignKeyConstraint(['org_id'], ['org_unit.id']\n ), ForeignKeyConstraint(['created_by'], ['admin.id'])\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(45), nullable=False)\n venue = db.Column(db.String(45), nullable=False)\n location_lat = db.Column(db.Float, nullable=False)\n location_long = db.Column(db.Float, nullable=False)\n date_created = db.Column(db.DateTime, nullable=False, default=datetime.now)\n start_time = db.Column(db.DateTime, nullable=False)\n duration = db.Column(db.Float, nullable=False)\n coordinator_name = db.Column(db.String(45), nullable=False)\n coordinator_contact = db.Column(db.Integer, nullable=False)\n status_id = db.Column(db.Integer, nullable=False)\n org_id = db.Column(db.Integer, nullable=False)\n created_by = db.Column(db.Integer, nullable=False)\n description = db.Column(db.String(500), nullable=False)\n\n def __init__(self, name, venue, location_lat, location_long, start_time,\n duration, coordinator_name, coordinator_contact, status_id, org_id,\n created_by, description):\n self.name = name\n self.venue = venue\n self.location_lat = location_lat\n self.location_long = location_long\n self.start_time = start_time\n self.duration = duration\n self.coordinator_name = coordinator_name\n self.coordinator_contact = coordinator_contact\n self.status_id = status_id\n self.org_id = org_id\n self.created_by = created_by\n self.description = description\n\n\nclass EventSchema(ma.Schema):\n\n\n class Meta:\n fields = ('id', 'name', 'venue', 'location_lat', 'location_long',\n 'date_created', 'start_time', 'duration', 'coordinator_name',\n 'coordinator_contact', 'status_id', 'org_id', 'description')\n\n\n<assignment token>\n\n\nclass EventFullInfoSchema(ma.Schema):\n event = ma.Nested(event_schema)\n admin = ma.Nested(admin_limited_schema)\n status = ma.Nested(event_status_schema)\n org_unit = ma.Nested(org_unit_schema)\n\n\n<assignment token>\n", "<import token>\n\n\nclass Event(db.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, name, venue, location_lat, location_long, start_time,\n duration, coordinator_name, coordinator_contact, status_id, org_id,\n created_by, description):\n self.name = name\n self.venue = venue\n self.location_lat = location_lat\n self.location_long = location_long\n self.start_time = start_time\n self.duration = duration\n self.coordinator_name = coordinator_name\n self.coordinator_contact = coordinator_contact\n self.status_id = status_id\n self.org_id = org_id\n self.created_by = created_by\n self.description = description\n\n\nclass EventSchema(ma.Schema):\n\n\n class Meta:\n fields = ('id', 'name', 'venue', 'location_lat', 'location_long',\n 'date_created', 'start_time', 'duration', 'coordinator_name',\n 'coordinator_contact', 'status_id', 'org_id', 'description')\n\n\n<assignment token>\n\n\nclass EventFullInfoSchema(ma.Schema):\n event = ma.Nested(event_schema)\n admin = ma.Nested(admin_limited_schema)\n status = ma.Nested(event_status_schema)\n org_unit = ma.Nested(org_unit_schema)\n\n\n<assignment token>\n", "<import token>\n\n\nclass Event(db.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass EventSchema(ma.Schema):\n\n\n class Meta:\n fields = ('id', 'name', 'venue', 'location_lat', 'location_long',\n 'date_created', 'start_time', 'duration', 'coordinator_name',\n 'coordinator_contact', 'status_id', 'org_id', 'description')\n\n\n<assignment token>\n\n\nclass EventFullInfoSchema(ma.Schema):\n event = ma.Nested(event_schema)\n admin = ma.Nested(admin_limited_schema)\n status = ma.Nested(event_status_schema)\n org_unit = ma.Nested(org_unit_schema)\n\n\n<assignment token>\n", "<import token>\n<class token>\n\n\nclass EventSchema(ma.Schema):\n\n\n class Meta:\n fields = ('id', 'name', 'venue', 'location_lat', 'location_long',\n 'date_created', 'start_time', 'duration', 'coordinator_name',\n 'coordinator_contact', 'status_id', 'org_id', 'description')\n\n\n<assignment token>\n\n\nclass EventFullInfoSchema(ma.Schema):\n event = ma.Nested(event_schema)\n admin = ma.Nested(admin_limited_schema)\n status = ma.Nested(event_status_schema)\n org_unit = ma.Nested(org_unit_schema)\n\n\n<assignment token>\n", "<import token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass EventFullInfoSchema(ma.Schema):\n event = ma.Nested(event_schema)\n admin = ma.Nested(admin_limited_schema)\n status = ma.Nested(event_status_schema)\n org_unit = ma.Nested(org_unit_schema)\n\n\n<assignment token>\n", "<import token>\n<class token>\n<class token>\n<assignment token>\n\n\nclass EventFullInfoSchema(ma.Schema):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n\n<assignment token>\n", "<import token>\n<class token>\n<class token>\n<assignment token>\n<class token>\n<assignment token>\n" ]
false
724
a26cab29f0777764f014eeff13745be60e55b62d
import requests #try make the request try: r = requests.get('http://skitter.com') print(r) # see the results # catch a failue except (requests.ConnectionError, requests.Timeout) as x: pass
[ "import requests\n\n#try make the request\ntry:\n\tr = requests.get('http://skitter.com')\n\tprint(r)\t# see the results\n\n# catch a failue\nexcept (requests.ConnectionError, requests.Timeout) as x:\n\tpass", "import requests\ntry:\n r = requests.get('http://skitter.com')\n print(r)\nexcept (requests.ConnectionError, requests.Timeout) as x:\n pass\n", "<import token>\ntry:\n r = requests.get('http://skitter.com')\n print(r)\nexcept (requests.ConnectionError, requests.Timeout) as x:\n pass\n", "<import token>\n<code token>\n" ]
false
725
de77edaccdaada785f41828135ad2da4ae2b403e
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.core.mail import EmailMultiAlternatives from django.template import loader from django.conf import settings from django.contrib.sites.shortcuts import get_current_site class Blog(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,) class Post(models.Model): blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING) user = models.ForeignKey(User,on_delete=models.CASCADE,) header = models.CharField(max_length=50) text = models.CharField(max_length=2048) create_date = models.DateTimeField(auto_now=True) @receiver(post_save, sender=Post) def send_email(sender, **kwargs): post = Post.objects.get(id=kwargs.get('instance').id) template = loader.get_template('post2email.html') subject = "Post in blog " + post.blog.user.username context = { "header": post.header, "text": post.text, "id": post.id, "host": getattr(settings, 'MY_DJANGO_URL_PATH', ''), } html_content = template.render(context) msg = EmailMultiAlternatives(subject, "", "", [post.user.email]) msg.attach_alternative(html_content, "text/html") msg.send() class ReadPost(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,) post = models.ForeignKey(Post, on_delete=models.DO_NOTHING) class Subscription(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,) blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)
[ "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template import loader\nfrom django.conf import settings\nfrom django.contrib.sites.shortcuts import get_current_site\n\nclass Blog(models.Model):\n user = models.ForeignKey(User,on_delete=models.CASCADE,)\n\nclass Post(models.Model):\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n user = models.ForeignKey(User,on_delete=models.CASCADE,)\n header = models.CharField(max_length=50)\n text = models.CharField(max_length=2048)\n create_date = models.DateTimeField(auto_now=True)\n\n@receiver(post_save, sender=Post)\ndef send_email(sender, **kwargs):\n post = Post.objects.get(id=kwargs.get('instance').id)\n template = loader.get_template('post2email.html')\n subject = \"Post in blog \" + post.blog.user.username\n context = { \"header\": post.header,\n \"text\": post.text,\n \"id\": post.id,\n \"host\": getattr(settings, 'MY_DJANGO_URL_PATH', ''),\n }\n html_content = template.render(context)\n msg = EmailMultiAlternatives(subject, \"\", \"\", [post.user.email])\n msg.attach_alternative(html_content, \"text/html\")\n msg.send() \n \nclass ReadPost(models.Model):\n user = models.ForeignKey(User,on_delete=models.CASCADE,)\n post = models.ForeignKey(Post, on_delete=models.DO_NOTHING)\n\nclass Subscription(models.Model):\n user = models.ForeignKey(User,on_delete=models.CASCADE,)\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)", "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template import loader\nfrom django.conf import settings\nfrom django.contrib.sites.shortcuts import get_current_site\n\n\nclass Blog(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n\n\nclass Post(models.Model):\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n header = models.CharField(max_length=50)\n text = models.CharField(max_length=2048)\n create_date = models.DateTimeField(auto_now=True)\n\n\n@receiver(post_save, sender=Post)\ndef send_email(sender, **kwargs):\n post = Post.objects.get(id=kwargs.get('instance').id)\n template = loader.get_template('post2email.html')\n subject = 'Post in blog ' + post.blog.user.username\n context = {'header': post.header, 'text': post.text, 'id': post.id,\n 'host': getattr(settings, 'MY_DJANGO_URL_PATH', '')}\n html_content = template.render(context)\n msg = EmailMultiAlternatives(subject, '', '', [post.user.email])\n msg.attach_alternative(html_content, 'text/html')\n msg.send()\n\n\nclass ReadPost(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n post = models.ForeignKey(Post, on_delete=models.DO_NOTHING)\n\n\nclass Subscription(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n", "<import token>\n\n\nclass Blog(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n\n\nclass Post(models.Model):\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n header = models.CharField(max_length=50)\n text = models.CharField(max_length=2048)\n create_date = models.DateTimeField(auto_now=True)\n\n\n@receiver(post_save, sender=Post)\ndef send_email(sender, **kwargs):\n post = Post.objects.get(id=kwargs.get('instance').id)\n template = loader.get_template('post2email.html')\n subject = 'Post in blog ' + post.blog.user.username\n context = {'header': post.header, 'text': post.text, 'id': post.id,\n 'host': getattr(settings, 'MY_DJANGO_URL_PATH', '')}\n html_content = template.render(context)\n msg = EmailMultiAlternatives(subject, '', '', [post.user.email])\n msg.attach_alternative(html_content, 'text/html')\n msg.send()\n\n\nclass ReadPost(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n post = models.ForeignKey(Post, on_delete=models.DO_NOTHING)\n\n\nclass Subscription(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n", "<import token>\n\n\nclass Blog(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n\n\nclass Post(models.Model):\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n header = models.CharField(max_length=50)\n text = models.CharField(max_length=2048)\n create_date = models.DateTimeField(auto_now=True)\n\n\n<function token>\n\n\nclass ReadPost(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n post = models.ForeignKey(Post, on_delete=models.DO_NOTHING)\n\n\nclass Subscription(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n", "<import token>\n\n\nclass Blog(models.Model):\n <assignment token>\n\n\nclass Post(models.Model):\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n header = models.CharField(max_length=50)\n text = models.CharField(max_length=2048)\n create_date = models.DateTimeField(auto_now=True)\n\n\n<function token>\n\n\nclass ReadPost(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n post = models.ForeignKey(Post, on_delete=models.DO_NOTHING)\n\n\nclass Subscription(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n", "<import token>\n<class token>\n\n\nclass Post(models.Model):\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n header = models.CharField(max_length=50)\n text = models.CharField(max_length=2048)\n create_date = models.DateTimeField(auto_now=True)\n\n\n<function token>\n\n\nclass ReadPost(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n post = models.ForeignKey(Post, on_delete=models.DO_NOTHING)\n\n\nclass Subscription(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n", "<import token>\n<class token>\n\n\nclass Post(models.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n\n<function token>\n\n\nclass ReadPost(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n post = models.ForeignKey(Post, on_delete=models.DO_NOTHING)\n\n\nclass Subscription(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n", "<import token>\n<class token>\n<class token>\n<function token>\n\n\nclass ReadPost(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n post = models.ForeignKey(Post, on_delete=models.DO_NOTHING)\n\n\nclass Subscription(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n", "<import token>\n<class token>\n<class token>\n<function token>\n\n\nclass ReadPost(models.Model):\n <assignment token>\n <assignment token>\n\n\nclass Subscription(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n", "<import token>\n<class token>\n<class token>\n<function token>\n<class token>\n\n\nclass Subscription(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n blog = models.ForeignKey(Blog, on_delete=models.DO_NOTHING)\n", "<import token>\n<class token>\n<class token>\n<function token>\n<class token>\n\n\nclass Subscription(models.Model):\n <assignment token>\n <assignment token>\n", "<import token>\n<class token>\n<class token>\n<function token>\n<class token>\n<class token>\n" ]
false
726
c3efaeab600ec9a7a9fffdfad5c9dc1faad8fee7
try: from LoggerPlugin import LoggerPlugin except ImportError: from RTOC.LoggerPlugin import LoggerPlugin from .holdPeak_VC820.vc820py.vc820 import MultimeterMessage import serial import sys import traceback from PyQt5 import uic from PyQt5 import QtWidgets import logging as log log.basicConfig(level=log.INFO) logging = log.getLogger(__name__) devicename = "HoldPeak" default_device = 'COM7' SERIAL_BAUDRATE = 2400 SERIAL_BYTESIZE = 8 SERIAL_TIMEOUT = 1 SAMPLERATE = 1 class Plugin(LoggerPlugin): """ Zeichnet die Messdaten eines HoldPeak VC820 Multimeters auf """ def __init__(self, *args, **kwargs): # Plugin setup super(Plugin, self).__init__(*args, **kwargs) self.setDeviceName(devicename) self.smallGUI = True self._last_value = 0 self._jump_allowed = True # Data-logger thread self.setPerpetualTimer(self._updateT, samplerate=SAMPLERATE) # self.updater.start() def __openPort(self, portname=default_device): # Communication setup #self.portname = "/dev/ttyUSB0" #self.portname = "COM7" self.portname = portname ################################################################################# # os.system("sudo chmod a+rw /dev/ttyUSB0") # ####### # uncomment this line if you do not set device rules: # > sudo nano /etc/udev/rules.d/50-myusb.rules # > * SUBSYSTEMS=="usb", ATTRS{idVendor}=="067b", ATTRS{idProduct}=="2303", GROUP="users", MODE="0666" # > [Strg+O, Strg+X] # > sudo udevadm control --reload # Ref: http://ask.xmodulo.com/change-usb-device-permission-linux.html ################################################################################# try: self._serial_port = serial.Serial( self.portname, baudrate=SERIAL_BAUDRATE, parity='N', bytesize=SERIAL_BYTESIZE, timeout=SERIAL_TIMEOUT, rtscts=1, dsrdtr=1) # dtr and rts settings required for adapter self._serial_port.dtr = True self._serial_port.rts = False # ------------- return True except Exception: tb = traceback.format_exc() logging.debug(tb) return False # THIS IS YOUR THREAD def _updateT(self): valid, value, unit = self._get_data() if unit == "V": datanames = ["Spannung"] elif unit == "A": datanames = ["Strom"] elif unit == "Ohm": datanames = ["Widerstand"] elif unit == "°C": datanames = ["Temperatur"] elif unit == "F": datanames = ["Kapazität"] elif unit == "Hz": datanames = ["Frequenz"] else: datanames = [unit] if valid: if abs(self._last_value-value) >= 2 and not self._jump_allowed: self._jump_allowed = True else: self.stream(y=[value], snames=datanames, unit=unit) self._jump_allowed = False self._last_value = value def loadGUI(self): self.widget = QtWidgets.QWidget() packagedir = self.getDir(__file__) uic.loadUi(packagedir+"/holdPeak_VC820/portSelectWidget.ui", self.widget) # self.setCallbacks() self.widget.pushButton.clicked.connect(self.__openPortCallback) self.__openPortCallback() return self.widget def __openPortCallback(self): if self.run: self.cancel() self.widget.pushButton.setText("Verbinden") else: port = self.widget.comboBox.currentText() if self.__openPort(port): self.start() self.widget.pushButton.setText("Beenden") else: self.cancel() self.widget.pushButton.setText("Fehler") def _get_data(self): test = self._serial_port.read(1) if len(test) != 1: logging.error("recieved incomplete data, skipping...", file=sys.stderr) return False, None, None if MultimeterMessage.check_first_byte(test[0]): data = test + self._serial_port.read(MultimeterMessage.MESSAGE_LENGTH-1) else: logging.error("received incorrect data (%s), skipping..." % test.hex(), file=sys.stderr) return False, None, None if len(data) != MultimeterMessage.MESSAGE_LENGTH: logging.error("received incomplete message (%s), skipping..." % data.hex(), file=sys.stderr) return False, None, None try: message = MultimeterMessage(data) #message.value = message.get_base_reading() except ValueError as e: logging.debug(e) logging.error("Error decoding: %s on message %s" % (str(e), data.hex())) return False, None, None # logging.debug(str(message)) # return True, message.value, message.unit return True, round(message.value*message.multiplier, 10), message.base_unit if __name__ == "__main__": standalone = Plugin() standalone.setup()
[ "try:\n from LoggerPlugin import LoggerPlugin\nexcept ImportError:\n from RTOC.LoggerPlugin import LoggerPlugin\n\nfrom .holdPeak_VC820.vc820py.vc820 import MultimeterMessage\nimport serial\nimport sys\nimport traceback\n\nfrom PyQt5 import uic\nfrom PyQt5 import QtWidgets\nimport logging as log\nlog.basicConfig(level=log.INFO)\nlogging = log.getLogger(__name__)\n\ndevicename = \"HoldPeak\"\ndefault_device = 'COM7'\nSERIAL_BAUDRATE = 2400\nSERIAL_BYTESIZE = 8\nSERIAL_TIMEOUT = 1\nSAMPLERATE = 1\n\nclass Plugin(LoggerPlugin):\n \"\"\"\nZeichnet die Messdaten eines HoldPeak VC820 Multimeters auf\n \"\"\"\n def __init__(self, *args, **kwargs):\n # Plugin setup\n super(Plugin, self).__init__(*args, **kwargs)\n self.setDeviceName(devicename)\n self.smallGUI = True\n\n self._last_value = 0\n self._jump_allowed = True\n # Data-logger thread\n self.setPerpetualTimer(self._updateT, samplerate=SAMPLERATE)\n # self.updater.start()\n\n def __openPort(self, portname=default_device):\n # Communication setup\n #self.portname = \"/dev/ttyUSB0\"\n #self.portname = \"COM7\"\n self.portname = portname\n #################################################################################\n # os.system(\"sudo chmod a+rw /dev/ttyUSB0\")\n # #######\n # uncomment this line if you do not set device rules:\n # > sudo nano /etc/udev/rules.d/50-myusb.rules\n # > * SUBSYSTEMS==\"usb\", ATTRS{idVendor}==\"067b\", ATTRS{idProduct}==\"2303\", GROUP=\"users\", MODE=\"0666\"\n # > [Strg+O, Strg+X]\n # > sudo udevadm control --reload\n # Ref: http://ask.xmodulo.com/change-usb-device-permission-linux.html\n #################################################################################\n try:\n self._serial_port = serial.Serial(\n self.portname, baudrate=SERIAL_BAUDRATE, parity='N', bytesize=SERIAL_BYTESIZE, timeout=SERIAL_TIMEOUT, rtscts=1, dsrdtr=1)\n # dtr and rts settings required for adapter\n self._serial_port.dtr = True\n self._serial_port.rts = False\n # -------------\n return True\n except Exception:\n tb = traceback.format_exc()\n logging.debug(tb)\n return False\n\n # THIS IS YOUR THREAD\n def _updateT(self):\n valid, value, unit = self._get_data()\n if unit == \"V\":\n datanames = [\"Spannung\"]\n elif unit == \"A\":\n datanames = [\"Strom\"]\n elif unit == \"Ohm\":\n datanames = [\"Widerstand\"]\n elif unit == \"°C\":\n datanames = [\"Temperatur\"]\n elif unit == \"F\":\n datanames = [\"Kapazität\"]\n elif unit == \"Hz\":\n datanames = [\"Frequenz\"]\n else:\n datanames = [unit]\n if valid:\n if abs(self._last_value-value) >= 2 and not self._jump_allowed:\n self._jump_allowed = True\n else:\n self.stream(y=[value], snames=datanames, unit=unit)\n self._jump_allowed = False\n self._last_value = value\n\n def loadGUI(self):\n self.widget = QtWidgets.QWidget()\n packagedir = self.getDir(__file__)\n uic.loadUi(packagedir+\"/holdPeak_VC820/portSelectWidget.ui\", self.widget)\n # self.setCallbacks()\n self.widget.pushButton.clicked.connect(self.__openPortCallback)\n self.__openPortCallback()\n return self.widget\n\n def __openPortCallback(self):\n if self.run:\n self.cancel()\n self.widget.pushButton.setText(\"Verbinden\")\n else:\n port = self.widget.comboBox.currentText()\n if self.__openPort(port):\n self.start()\n self.widget.pushButton.setText(\"Beenden\")\n else:\n self.cancel()\n self.widget.pushButton.setText(\"Fehler\")\n\n def _get_data(self):\n test = self._serial_port.read(1)\n if len(test) != 1:\n logging.error(\"recieved incomplete data, skipping...\", file=sys.stderr)\n return False, None, None\n if MultimeterMessage.check_first_byte(test[0]):\n data = test + self._serial_port.read(MultimeterMessage.MESSAGE_LENGTH-1)\n else:\n logging.error(\"received incorrect data (%s), skipping...\" % test.hex(), file=sys.stderr)\n return False, None, None\n if len(data) != MultimeterMessage.MESSAGE_LENGTH:\n logging.error(\"received incomplete message (%s), skipping...\" %\n data.hex(), file=sys.stderr)\n return False, None, None\n try:\n message = MultimeterMessage(data)\n #message.value = message.get_base_reading()\n except ValueError as e:\n logging.debug(e)\n logging.error(\"Error decoding: %s on message %s\" % (str(e), data.hex()))\n return False, None, None\n # logging.debug(str(message))\n # return True, message.value, message.unit\n return True, round(message.value*message.multiplier, 10), message.base_unit\n\n\nif __name__ == \"__main__\":\n standalone = Plugin()\n standalone.setup()\n", "try:\n from LoggerPlugin import LoggerPlugin\nexcept ImportError:\n from RTOC.LoggerPlugin import LoggerPlugin\nfrom .holdPeak_VC820.vc820py.vc820 import MultimeterMessage\nimport serial\nimport sys\nimport traceback\nfrom PyQt5 import uic\nfrom PyQt5 import QtWidgets\nimport logging as log\nlog.basicConfig(level=log.INFO)\nlogging = log.getLogger(__name__)\ndevicename = 'HoldPeak'\ndefault_device = 'COM7'\nSERIAL_BAUDRATE = 2400\nSERIAL_BYTESIZE = 8\nSERIAL_TIMEOUT = 1\nSAMPLERATE = 1\n\n\nclass Plugin(LoggerPlugin):\n \"\"\"\nZeichnet die Messdaten eines HoldPeak VC820 Multimeters auf\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(Plugin, self).__init__(*args, **kwargs)\n self.setDeviceName(devicename)\n self.smallGUI = True\n self._last_value = 0\n self._jump_allowed = True\n self.setPerpetualTimer(self._updateT, samplerate=SAMPLERATE)\n\n def __openPort(self, portname=default_device):\n self.portname = portname\n try:\n self._serial_port = serial.Serial(self.portname, baudrate=\n SERIAL_BAUDRATE, parity='N', bytesize=SERIAL_BYTESIZE,\n timeout=SERIAL_TIMEOUT, rtscts=1, dsrdtr=1)\n self._serial_port.dtr = True\n self._serial_port.rts = False\n return True\n except Exception:\n tb = traceback.format_exc()\n logging.debug(tb)\n return False\n\n def _updateT(self):\n valid, value, unit = self._get_data()\n if unit == 'V':\n datanames = ['Spannung']\n elif unit == 'A':\n datanames = ['Strom']\n elif unit == 'Ohm':\n datanames = ['Widerstand']\n elif unit == '°C':\n datanames = ['Temperatur']\n elif unit == 'F':\n datanames = ['Kapazität']\n elif unit == 'Hz':\n datanames = ['Frequenz']\n else:\n datanames = [unit]\n if valid:\n if abs(self._last_value - value) >= 2 and not self._jump_allowed:\n self._jump_allowed = True\n else:\n self.stream(y=[value], snames=datanames, unit=unit)\n self._jump_allowed = False\n self._last_value = value\n\n def loadGUI(self):\n self.widget = QtWidgets.QWidget()\n packagedir = self.getDir(__file__)\n uic.loadUi(packagedir + '/holdPeak_VC820/portSelectWidget.ui', self\n .widget)\n self.widget.pushButton.clicked.connect(self.__openPortCallback)\n self.__openPortCallback()\n return self.widget\n\n def __openPortCallback(self):\n if self.run:\n self.cancel()\n self.widget.pushButton.setText('Verbinden')\n else:\n port = self.widget.comboBox.currentText()\n if self.__openPort(port):\n self.start()\n self.widget.pushButton.setText('Beenden')\n else:\n self.cancel()\n self.widget.pushButton.setText('Fehler')\n\n def _get_data(self):\n test = self._serial_port.read(1)\n if len(test) != 1:\n logging.error('recieved incomplete data, skipping...', file=sys\n .stderr)\n return False, None, None\n if MultimeterMessage.check_first_byte(test[0]):\n data = test + self._serial_port.read(MultimeterMessage.\n MESSAGE_LENGTH - 1)\n else:\n logging.error('received incorrect data (%s), skipping...' %\n test.hex(), file=sys.stderr)\n return False, None, None\n if len(data) != MultimeterMessage.MESSAGE_LENGTH:\n logging.error('received incomplete message (%s), skipping...' %\n data.hex(), file=sys.stderr)\n return False, None, None\n try:\n message = MultimeterMessage(data)\n except ValueError as e:\n logging.debug(e)\n logging.error('Error decoding: %s on message %s' % (str(e),\n data.hex()))\n return False, None, None\n return True, round(message.value * message.multiplier, 10\n ), message.base_unit\n\n\nif __name__ == '__main__':\n standalone = Plugin()\n standalone.setup()\n", "try:\n from LoggerPlugin import LoggerPlugin\nexcept ImportError:\n from RTOC.LoggerPlugin import LoggerPlugin\n<import token>\nlog.basicConfig(level=log.INFO)\nlogging = log.getLogger(__name__)\ndevicename = 'HoldPeak'\ndefault_device = 'COM7'\nSERIAL_BAUDRATE = 2400\nSERIAL_BYTESIZE = 8\nSERIAL_TIMEOUT = 1\nSAMPLERATE = 1\n\n\nclass Plugin(LoggerPlugin):\n \"\"\"\nZeichnet die Messdaten eines HoldPeak VC820 Multimeters auf\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(Plugin, self).__init__(*args, **kwargs)\n self.setDeviceName(devicename)\n self.smallGUI = True\n self._last_value = 0\n self._jump_allowed = True\n self.setPerpetualTimer(self._updateT, samplerate=SAMPLERATE)\n\n def __openPort(self, portname=default_device):\n self.portname = portname\n try:\n self._serial_port = serial.Serial(self.portname, baudrate=\n SERIAL_BAUDRATE, parity='N', bytesize=SERIAL_BYTESIZE,\n timeout=SERIAL_TIMEOUT, rtscts=1, dsrdtr=1)\n self._serial_port.dtr = True\n self._serial_port.rts = False\n return True\n except Exception:\n tb = traceback.format_exc()\n logging.debug(tb)\n return False\n\n def _updateT(self):\n valid, value, unit = self._get_data()\n if unit == 'V':\n datanames = ['Spannung']\n elif unit == 'A':\n datanames = ['Strom']\n elif unit == 'Ohm':\n datanames = ['Widerstand']\n elif unit == '°C':\n datanames = ['Temperatur']\n elif unit == 'F':\n datanames = ['Kapazität']\n elif unit == 'Hz':\n datanames = ['Frequenz']\n else:\n datanames = [unit]\n if valid:\n if abs(self._last_value - value) >= 2 and not self._jump_allowed:\n self._jump_allowed = True\n else:\n self.stream(y=[value], snames=datanames, unit=unit)\n self._jump_allowed = False\n self._last_value = value\n\n def loadGUI(self):\n self.widget = QtWidgets.QWidget()\n packagedir = self.getDir(__file__)\n uic.loadUi(packagedir + '/holdPeak_VC820/portSelectWidget.ui', self\n .widget)\n self.widget.pushButton.clicked.connect(self.__openPortCallback)\n self.__openPortCallback()\n return self.widget\n\n def __openPortCallback(self):\n if self.run:\n self.cancel()\n self.widget.pushButton.setText('Verbinden')\n else:\n port = self.widget.comboBox.currentText()\n if self.__openPort(port):\n self.start()\n self.widget.pushButton.setText('Beenden')\n else:\n self.cancel()\n self.widget.pushButton.setText('Fehler')\n\n def _get_data(self):\n test = self._serial_port.read(1)\n if len(test) != 1:\n logging.error('recieved incomplete data, skipping...', file=sys\n .stderr)\n return False, None, None\n if MultimeterMessage.check_first_byte(test[0]):\n data = test + self._serial_port.read(MultimeterMessage.\n MESSAGE_LENGTH - 1)\n else:\n logging.error('received incorrect data (%s), skipping...' %\n test.hex(), file=sys.stderr)\n return False, None, None\n if len(data) != MultimeterMessage.MESSAGE_LENGTH:\n logging.error('received incomplete message (%s), skipping...' %\n data.hex(), file=sys.stderr)\n return False, None, None\n try:\n message = MultimeterMessage(data)\n except ValueError as e:\n logging.debug(e)\n logging.error('Error decoding: %s on message %s' % (str(e),\n data.hex()))\n return False, None, None\n return True, round(message.value * message.multiplier, 10\n ), message.base_unit\n\n\nif __name__ == '__main__':\n standalone = Plugin()\n standalone.setup()\n", "try:\n from LoggerPlugin import LoggerPlugin\nexcept ImportError:\n from RTOC.LoggerPlugin import LoggerPlugin\n<import token>\nlog.basicConfig(level=log.INFO)\n<assignment token>\n\n\nclass Plugin(LoggerPlugin):\n \"\"\"\nZeichnet die Messdaten eines HoldPeak VC820 Multimeters auf\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(Plugin, self).__init__(*args, **kwargs)\n self.setDeviceName(devicename)\n self.smallGUI = True\n self._last_value = 0\n self._jump_allowed = True\n self.setPerpetualTimer(self._updateT, samplerate=SAMPLERATE)\n\n def __openPort(self, portname=default_device):\n self.portname = portname\n try:\n self._serial_port = serial.Serial(self.portname, baudrate=\n SERIAL_BAUDRATE, parity='N', bytesize=SERIAL_BYTESIZE,\n timeout=SERIAL_TIMEOUT, rtscts=1, dsrdtr=1)\n self._serial_port.dtr = True\n self._serial_port.rts = False\n return True\n except Exception:\n tb = traceback.format_exc()\n logging.debug(tb)\n return False\n\n def _updateT(self):\n valid, value, unit = self._get_data()\n if unit == 'V':\n datanames = ['Spannung']\n elif unit == 'A':\n datanames = ['Strom']\n elif unit == 'Ohm':\n datanames = ['Widerstand']\n elif unit == '°C':\n datanames = ['Temperatur']\n elif unit == 'F':\n datanames = ['Kapazität']\n elif unit == 'Hz':\n datanames = ['Frequenz']\n else:\n datanames = [unit]\n if valid:\n if abs(self._last_value - value) >= 2 and not self._jump_allowed:\n self._jump_allowed = True\n else:\n self.stream(y=[value], snames=datanames, unit=unit)\n self._jump_allowed = False\n self._last_value = value\n\n def loadGUI(self):\n self.widget = QtWidgets.QWidget()\n packagedir = self.getDir(__file__)\n uic.loadUi(packagedir + '/holdPeak_VC820/portSelectWidget.ui', self\n .widget)\n self.widget.pushButton.clicked.connect(self.__openPortCallback)\n self.__openPortCallback()\n return self.widget\n\n def __openPortCallback(self):\n if self.run:\n self.cancel()\n self.widget.pushButton.setText('Verbinden')\n else:\n port = self.widget.comboBox.currentText()\n if self.__openPort(port):\n self.start()\n self.widget.pushButton.setText('Beenden')\n else:\n self.cancel()\n self.widget.pushButton.setText('Fehler')\n\n def _get_data(self):\n test = self._serial_port.read(1)\n if len(test) != 1:\n logging.error('recieved incomplete data, skipping...', file=sys\n .stderr)\n return False, None, None\n if MultimeterMessage.check_first_byte(test[0]):\n data = test + self._serial_port.read(MultimeterMessage.\n MESSAGE_LENGTH - 1)\n else:\n logging.error('received incorrect data (%s), skipping...' %\n test.hex(), file=sys.stderr)\n return False, None, None\n if len(data) != MultimeterMessage.MESSAGE_LENGTH:\n logging.error('received incomplete message (%s), skipping...' %\n data.hex(), file=sys.stderr)\n return False, None, None\n try:\n message = MultimeterMessage(data)\n except ValueError as e:\n logging.debug(e)\n logging.error('Error decoding: %s on message %s' % (str(e),\n data.hex()))\n return False, None, None\n return True, round(message.value * message.multiplier, 10\n ), message.base_unit\n\n\nif __name__ == '__main__':\n standalone = Plugin()\n standalone.setup()\n", "<code token>\n<import token>\n<code token>\n<assignment token>\n\n\nclass Plugin(LoggerPlugin):\n \"\"\"\nZeichnet die Messdaten eines HoldPeak VC820 Multimeters auf\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(Plugin, self).__init__(*args, **kwargs)\n self.setDeviceName(devicename)\n self.smallGUI = True\n self._last_value = 0\n self._jump_allowed = True\n self.setPerpetualTimer(self._updateT, samplerate=SAMPLERATE)\n\n def __openPort(self, portname=default_device):\n self.portname = portname\n try:\n self._serial_port = serial.Serial(self.portname, baudrate=\n SERIAL_BAUDRATE, parity='N', bytesize=SERIAL_BYTESIZE,\n timeout=SERIAL_TIMEOUT, rtscts=1, dsrdtr=1)\n self._serial_port.dtr = True\n self._serial_port.rts = False\n return True\n except Exception:\n tb = traceback.format_exc()\n logging.debug(tb)\n return False\n\n def _updateT(self):\n valid, value, unit = self._get_data()\n if unit == 'V':\n datanames = ['Spannung']\n elif unit == 'A':\n datanames = ['Strom']\n elif unit == 'Ohm':\n datanames = ['Widerstand']\n elif unit == '°C':\n datanames = ['Temperatur']\n elif unit == 'F':\n datanames = ['Kapazität']\n elif unit == 'Hz':\n datanames = ['Frequenz']\n else:\n datanames = [unit]\n if valid:\n if abs(self._last_value - value) >= 2 and not self._jump_allowed:\n self._jump_allowed = True\n else:\n self.stream(y=[value], snames=datanames, unit=unit)\n self._jump_allowed = False\n self._last_value = value\n\n def loadGUI(self):\n self.widget = QtWidgets.QWidget()\n packagedir = self.getDir(__file__)\n uic.loadUi(packagedir + '/holdPeak_VC820/portSelectWidget.ui', self\n .widget)\n self.widget.pushButton.clicked.connect(self.__openPortCallback)\n self.__openPortCallback()\n return self.widget\n\n def __openPortCallback(self):\n if self.run:\n self.cancel()\n self.widget.pushButton.setText('Verbinden')\n else:\n port = self.widget.comboBox.currentText()\n if self.__openPort(port):\n self.start()\n self.widget.pushButton.setText('Beenden')\n else:\n self.cancel()\n self.widget.pushButton.setText('Fehler')\n\n def _get_data(self):\n test = self._serial_port.read(1)\n if len(test) != 1:\n logging.error('recieved incomplete data, skipping...', file=sys\n .stderr)\n return False, None, None\n if MultimeterMessage.check_first_byte(test[0]):\n data = test + self._serial_port.read(MultimeterMessage.\n MESSAGE_LENGTH - 1)\n else:\n logging.error('received incorrect data (%s), skipping...' %\n test.hex(), file=sys.stderr)\n return False, None, None\n if len(data) != MultimeterMessage.MESSAGE_LENGTH:\n logging.error('received incomplete message (%s), skipping...' %\n data.hex(), file=sys.stderr)\n return False, None, None\n try:\n message = MultimeterMessage(data)\n except ValueError as e:\n logging.debug(e)\n logging.error('Error decoding: %s on message %s' % (str(e),\n data.hex()))\n return False, None, None\n return True, round(message.value * message.multiplier, 10\n ), message.base_unit\n\n\n<code token>\n", "<code token>\n<import token>\n<code token>\n<assignment token>\n\n\nclass Plugin(LoggerPlugin):\n <docstring token>\n\n def __init__(self, *args, **kwargs):\n super(Plugin, self).__init__(*args, **kwargs)\n self.setDeviceName(devicename)\n self.smallGUI = True\n self._last_value = 0\n self._jump_allowed = True\n self.setPerpetualTimer(self._updateT, samplerate=SAMPLERATE)\n\n def __openPort(self, portname=default_device):\n self.portname = portname\n try:\n self._serial_port = serial.Serial(self.portname, baudrate=\n SERIAL_BAUDRATE, parity='N', bytesize=SERIAL_BYTESIZE,\n timeout=SERIAL_TIMEOUT, rtscts=1, dsrdtr=1)\n self._serial_port.dtr = True\n self._serial_port.rts = False\n return True\n except Exception:\n tb = traceback.format_exc()\n logging.debug(tb)\n return False\n\n def _updateT(self):\n valid, value, unit = self._get_data()\n if unit == 'V':\n datanames = ['Spannung']\n elif unit == 'A':\n datanames = ['Strom']\n elif unit == 'Ohm':\n datanames = ['Widerstand']\n elif unit == '°C':\n datanames = ['Temperatur']\n elif unit == 'F':\n datanames = ['Kapazität']\n elif unit == 'Hz':\n datanames = ['Frequenz']\n else:\n datanames = [unit]\n if valid:\n if abs(self._last_value - value) >= 2 and not self._jump_allowed:\n self._jump_allowed = True\n else:\n self.stream(y=[value], snames=datanames, unit=unit)\n self._jump_allowed = False\n self._last_value = value\n\n def loadGUI(self):\n self.widget = QtWidgets.QWidget()\n packagedir = self.getDir(__file__)\n uic.loadUi(packagedir + '/holdPeak_VC820/portSelectWidget.ui', self\n .widget)\n self.widget.pushButton.clicked.connect(self.__openPortCallback)\n self.__openPortCallback()\n return self.widget\n\n def __openPortCallback(self):\n if self.run:\n self.cancel()\n self.widget.pushButton.setText('Verbinden')\n else:\n port = self.widget.comboBox.currentText()\n if self.__openPort(port):\n self.start()\n self.widget.pushButton.setText('Beenden')\n else:\n self.cancel()\n self.widget.pushButton.setText('Fehler')\n\n def _get_data(self):\n test = self._serial_port.read(1)\n if len(test) != 1:\n logging.error('recieved incomplete data, skipping...', file=sys\n .stderr)\n return False, None, None\n if MultimeterMessage.check_first_byte(test[0]):\n data = test + self._serial_port.read(MultimeterMessage.\n MESSAGE_LENGTH - 1)\n else:\n logging.error('received incorrect data (%s), skipping...' %\n test.hex(), file=sys.stderr)\n return False, None, None\n if len(data) != MultimeterMessage.MESSAGE_LENGTH:\n logging.error('received incomplete message (%s), skipping...' %\n data.hex(), file=sys.stderr)\n return False, None, None\n try:\n message = MultimeterMessage(data)\n except ValueError as e:\n logging.debug(e)\n logging.error('Error decoding: %s on message %s' % (str(e),\n data.hex()))\n return False, None, None\n return True, round(message.value * message.multiplier, 10\n ), message.base_unit\n\n\n<code token>\n", "<code token>\n<import token>\n<code token>\n<assignment token>\n\n\nclass Plugin(LoggerPlugin):\n <docstring token>\n\n def __init__(self, *args, **kwargs):\n super(Plugin, self).__init__(*args, **kwargs)\n self.setDeviceName(devicename)\n self.smallGUI = True\n self._last_value = 0\n self._jump_allowed = True\n self.setPerpetualTimer(self._updateT, samplerate=SAMPLERATE)\n <function token>\n\n def _updateT(self):\n valid, value, unit = self._get_data()\n if unit == 'V':\n datanames = ['Spannung']\n elif unit == 'A':\n datanames = ['Strom']\n elif unit == 'Ohm':\n datanames = ['Widerstand']\n elif unit == '°C':\n datanames = ['Temperatur']\n elif unit == 'F':\n datanames = ['Kapazität']\n elif unit == 'Hz':\n datanames = ['Frequenz']\n else:\n datanames = [unit]\n if valid:\n if abs(self._last_value - value) >= 2 and not self._jump_allowed:\n self._jump_allowed = True\n else:\n self.stream(y=[value], snames=datanames, unit=unit)\n self._jump_allowed = False\n self._last_value = value\n\n def loadGUI(self):\n self.widget = QtWidgets.QWidget()\n packagedir = self.getDir(__file__)\n uic.loadUi(packagedir + '/holdPeak_VC820/portSelectWidget.ui', self\n .widget)\n self.widget.pushButton.clicked.connect(self.__openPortCallback)\n self.__openPortCallback()\n return self.widget\n\n def __openPortCallback(self):\n if self.run:\n self.cancel()\n self.widget.pushButton.setText('Verbinden')\n else:\n port = self.widget.comboBox.currentText()\n if self.__openPort(port):\n self.start()\n self.widget.pushButton.setText('Beenden')\n else:\n self.cancel()\n self.widget.pushButton.setText('Fehler')\n\n def _get_data(self):\n test = self._serial_port.read(1)\n if len(test) != 1:\n logging.error('recieved incomplete data, skipping...', file=sys\n .stderr)\n return False, None, None\n if MultimeterMessage.check_first_byte(test[0]):\n data = test + self._serial_port.read(MultimeterMessage.\n MESSAGE_LENGTH - 1)\n else:\n logging.error('received incorrect data (%s), skipping...' %\n test.hex(), file=sys.stderr)\n return False, None, None\n if len(data) != MultimeterMessage.MESSAGE_LENGTH:\n logging.error('received incomplete message (%s), skipping...' %\n data.hex(), file=sys.stderr)\n return False, None, None\n try:\n message = MultimeterMessage(data)\n except ValueError as e:\n logging.debug(e)\n logging.error('Error decoding: %s on message %s' % (str(e),\n data.hex()))\n return False, None, None\n return True, round(message.value * message.multiplier, 10\n ), message.base_unit\n\n\n<code token>\n", "<code token>\n<import token>\n<code token>\n<assignment token>\n\n\nclass Plugin(LoggerPlugin):\n <docstring token>\n\n def __init__(self, *args, **kwargs):\n super(Plugin, self).__init__(*args, **kwargs)\n self.setDeviceName(devicename)\n self.smallGUI = True\n self._last_value = 0\n self._jump_allowed = True\n self.setPerpetualTimer(self._updateT, samplerate=SAMPLERATE)\n <function token>\n <function token>\n\n def loadGUI(self):\n self.widget = QtWidgets.QWidget()\n packagedir = self.getDir(__file__)\n uic.loadUi(packagedir + '/holdPeak_VC820/portSelectWidget.ui', self\n .widget)\n self.widget.pushButton.clicked.connect(self.__openPortCallback)\n self.__openPortCallback()\n return self.widget\n\n def __openPortCallback(self):\n if self.run:\n self.cancel()\n self.widget.pushButton.setText('Verbinden')\n else:\n port = self.widget.comboBox.currentText()\n if self.__openPort(port):\n self.start()\n self.widget.pushButton.setText('Beenden')\n else:\n self.cancel()\n self.widget.pushButton.setText('Fehler')\n\n def _get_data(self):\n test = self._serial_port.read(1)\n if len(test) != 1:\n logging.error('recieved incomplete data, skipping...', file=sys\n .stderr)\n return False, None, None\n if MultimeterMessage.check_first_byte(test[0]):\n data = test + self._serial_port.read(MultimeterMessage.\n MESSAGE_LENGTH - 1)\n else:\n logging.error('received incorrect data (%s), skipping...' %\n test.hex(), file=sys.stderr)\n return False, None, None\n if len(data) != MultimeterMessage.MESSAGE_LENGTH:\n logging.error('received incomplete message (%s), skipping...' %\n data.hex(), file=sys.stderr)\n return False, None, None\n try:\n message = MultimeterMessage(data)\n except ValueError as e:\n logging.debug(e)\n logging.error('Error decoding: %s on message %s' % (str(e),\n data.hex()))\n return False, None, None\n return True, round(message.value * message.multiplier, 10\n ), message.base_unit\n\n\n<code token>\n", "<code token>\n<import token>\n<code token>\n<assignment token>\n\n\nclass Plugin(LoggerPlugin):\n <docstring token>\n\n def __init__(self, *args, **kwargs):\n super(Plugin, self).__init__(*args, **kwargs)\n self.setDeviceName(devicename)\n self.smallGUI = True\n self._last_value = 0\n self._jump_allowed = True\n self.setPerpetualTimer(self._updateT, samplerate=SAMPLERATE)\n <function token>\n <function token>\n\n def loadGUI(self):\n self.widget = QtWidgets.QWidget()\n packagedir = self.getDir(__file__)\n uic.loadUi(packagedir + '/holdPeak_VC820/portSelectWidget.ui', self\n .widget)\n self.widget.pushButton.clicked.connect(self.__openPortCallback)\n self.__openPortCallback()\n return self.widget\n <function token>\n\n def _get_data(self):\n test = self._serial_port.read(1)\n if len(test) != 1:\n logging.error('recieved incomplete data, skipping...', file=sys\n .stderr)\n return False, None, None\n if MultimeterMessage.check_first_byte(test[0]):\n data = test + self._serial_port.read(MultimeterMessage.\n MESSAGE_LENGTH - 1)\n else:\n logging.error('received incorrect data (%s), skipping...' %\n test.hex(), file=sys.stderr)\n return False, None, None\n if len(data) != MultimeterMessage.MESSAGE_LENGTH:\n logging.error('received incomplete message (%s), skipping...' %\n data.hex(), file=sys.stderr)\n return False, None, None\n try:\n message = MultimeterMessage(data)\n except ValueError as e:\n logging.debug(e)\n logging.error('Error decoding: %s on message %s' % (str(e),\n data.hex()))\n return False, None, None\n return True, round(message.value * message.multiplier, 10\n ), message.base_unit\n\n\n<code token>\n", "<code token>\n<import token>\n<code token>\n<assignment token>\n\n\nclass Plugin(LoggerPlugin):\n <docstring token>\n\n def __init__(self, *args, **kwargs):\n super(Plugin, self).__init__(*args, **kwargs)\n self.setDeviceName(devicename)\n self.smallGUI = True\n self._last_value = 0\n self._jump_allowed = True\n self.setPerpetualTimer(self._updateT, samplerate=SAMPLERATE)\n <function token>\n <function token>\n\n def loadGUI(self):\n self.widget = QtWidgets.QWidget()\n packagedir = self.getDir(__file__)\n uic.loadUi(packagedir + '/holdPeak_VC820/portSelectWidget.ui', self\n .widget)\n self.widget.pushButton.clicked.connect(self.__openPortCallback)\n self.__openPortCallback()\n return self.widget\n <function token>\n <function token>\n\n\n<code token>\n", "<code token>\n<import token>\n<code token>\n<assignment token>\n\n\nclass Plugin(LoggerPlugin):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def loadGUI(self):\n self.widget = QtWidgets.QWidget()\n packagedir = self.getDir(__file__)\n uic.loadUi(packagedir + '/holdPeak_VC820/portSelectWidget.ui', self\n .widget)\n self.widget.pushButton.clicked.connect(self.__openPortCallback)\n self.__openPortCallback()\n return self.widget\n <function token>\n <function token>\n\n\n<code token>\n", "<code token>\n<import token>\n<code token>\n<assignment token>\n\n\nclass Plugin(LoggerPlugin):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<code token>\n", "<code token>\n<import token>\n<code token>\n<assignment token>\n<class token>\n<code token>\n" ]
false
727
776470546585257bf06073e2d894e8a04cf2376d
""" Duck typing Ref: http://www.voidspace.org.uk/python/articles/duck_typing.shtml """ ########## # mathmatic operator (syntactic sugar) print 3 + 3 # same as >>> print int.__add__(3, 3) # <<< # overload '+' operator class Klass1(object): def __init__(self, a, b): self.a = a self.b = b def __add__(self, other): return self.a - other.b class Klass2(object): def __init__(self, a, b): self.a = a self.b = b def __add__(self, other): return self.b - other.a obj1 = Klass1(1, 2) obj2 = Klass2(10, 20) print obj1 + obj2 # same as >>> print obj1.__add__(obj2) # <<< ########## # data access for sequence type objects(list, tuple) and mapping type object(dict) # (syntactic sugar) a = [0,1,2] print a[0] # same as >>> print list.__getitem__(a, 0) # <<< b = {'a':0, 'b':1} print b['a'] # same as >>> print dict.__getitem__(b, 'a') # <<< ########## # function call # callable checks where a var has __call__ attr. def f(arg): print arg f(123) # >>> 123 # same as >>> f.__call__(123) # >>> 123 # <<< \ # 'Duck typing' happens because when we do var['member'] Python doesn't care what type object var is. # All it cares is whether the call to its __getitem__ method returns anything sensible. If not - an error will be raised. Something like TypeError: Unsubscriptable object.. # This means you can create your own classes that have their own internal data structures - but are accessed using normal Python syntax. This is awfully convenient. # isinstance(object, dict) returns True if object is a dictionary - or an instance of a subclass of dict. # Instead of: # # if isinstance(object, dict): # value = object[member] # # it is considered more pythonic to do : # # try: # value = object[member] # except TypeError: # # do something else # # Our example above could become : # # if hasattr(object, 'keys'): # value = object[member] #
[ "\"\"\"\nDuck typing\nRef: http://www.voidspace.org.uk/python/articles/duck_typing.shtml\n\"\"\"\n\n##########\n# mathmatic operator (syntactic sugar)\nprint 3 + 3\n# same as >>>\nprint int.__add__(3, 3)\n# <<<\n\n# overload '+' operator\nclass Klass1(object):\n def __init__(self, a, b):\n self.a = a\n self.b = b\n def __add__(self, other):\n return self.a - other.b\n\nclass Klass2(object):\n def __init__(self, a, b):\n self.a = a\n self.b = b\n def __add__(self, other):\n return self.b - other.a\n\nobj1 = Klass1(1, 2)\nobj2 = Klass2(10, 20)\nprint obj1 + obj2\n# same as >>>\nprint obj1.__add__(obj2)\n# <<<\n\n\n##########\n# data access for sequence type objects(list, tuple) and mapping type object(dict)\n# (syntactic sugar)\na = [0,1,2]\nprint a[0]\n# same as >>>\nprint list.__getitem__(a, 0)\n# <<<\n\nb = {'a':0, 'b':1}\nprint b['a']\n# same as >>>\nprint dict.__getitem__(b, 'a')\n# <<<\n\n##########\n# function call\n# callable checks where a var has __call__ attr.\ndef f(arg):\n print arg\n\nf(123)\n# >>> 123\n# same as >>>\nf.__call__(123)\n# >>> 123\n# <<<\n\\\n\n\n# 'Duck typing' happens because when we do var['member'] Python doesn't care what type object var is.\n# All it cares is whether the call to its __getitem__ method returns anything sensible. If not - an error will be raised. Something like TypeError: Unsubscriptable object..\n# This means you can create your own classes that have their own internal data structures - but are accessed using normal Python syntax. This is awfully convenient.\n\n# isinstance(object, dict) returns True if object is a dictionary - or an instance of a subclass of dict.\n# Instead of:\n#\n# if isinstance(object, dict):\n# value = object[member]\n#\n# it is considered more pythonic to do :\n#\n# try:\n# value = object[member]\n# except TypeError:\n# # do something else\n#\n# Our example above could become :\n#\n# if hasattr(object, 'keys'):\n# value = object[member]\n#\n" ]
true
728
60b5e515c7275bfa0f79e22f54302a578c2f7b79
def find_happy_number(num): slow, fast = num, num while True: slow = find_square_sum(slow) # move one step fast = find_square_sum(find_square_sum(fast)) # move two steps if slow == fast: # found the cycle break return slow == 1 # see if the cycle is stuck on the number '1' def find_square_sum(num): _sum = 0 while (num > 0): digit = num % 10 _sum += digit * digit num //= 10 return _sum print(find_happy_number(23)) print(find_happy_number(12))
[ "def find_happy_number(num):\n slow, fast = num, num\n while True:\n slow = find_square_sum(slow) # move one step\n fast = find_square_sum(find_square_sum(fast)) # move two steps\n if slow == fast: # found the cycle\n break\n return slow == 1 # see if the cycle is stuck on the number '1'\n\n\ndef find_square_sum(num):\n _sum = 0\n while (num > 0):\n digit = num % 10\n _sum += digit * digit\n num //= 10\n return _sum\n\nprint(find_happy_number(23)) \nprint(find_happy_number(12))", "def find_happy_number(num):\n slow, fast = num, num\n while True:\n slow = find_square_sum(slow)\n fast = find_square_sum(find_square_sum(fast))\n if slow == fast:\n break\n return slow == 1\n\n\ndef find_square_sum(num):\n _sum = 0\n while num > 0:\n digit = num % 10\n _sum += digit * digit\n num //= 10\n return _sum\n\n\nprint(find_happy_number(23))\nprint(find_happy_number(12))\n", "def find_happy_number(num):\n slow, fast = num, num\n while True:\n slow = find_square_sum(slow)\n fast = find_square_sum(find_square_sum(fast))\n if slow == fast:\n break\n return slow == 1\n\n\ndef find_square_sum(num):\n _sum = 0\n while num > 0:\n digit = num % 10\n _sum += digit * digit\n num //= 10\n return _sum\n\n\n<code token>\n", "<function token>\n\n\ndef find_square_sum(num):\n _sum = 0\n while num > 0:\n digit = num % 10\n _sum += digit * digit\n num //= 10\n return _sum\n\n\n<code token>\n", "<function token>\n<function token>\n<code token>\n" ]
false
729
af1a6c6009b21962228fbe737f27c22bf9460762
from gevent.event import Event from gevent.queue import Queue from ping_pong_chat.aio_queue import AGQueue received_event = Event() leave_rooms_event = Event() exit_event = Event() output_message_queue = AGQueue() input_message_queue = AGQueue() matrix_to_aio_queue = AGQueue() aio_to_matrix_queue = AGQueue() sync_to_matrix_queue = Queue() SERVER_URL = "https://transport.transport01.raiden.network"
[ "from gevent.event import Event\nfrom gevent.queue import Queue\nfrom ping_pong_chat.aio_queue import AGQueue\n\nreceived_event = Event()\nleave_rooms_event = Event()\nexit_event = Event()\noutput_message_queue = AGQueue()\ninput_message_queue = AGQueue()\n\nmatrix_to_aio_queue = AGQueue()\naio_to_matrix_queue = AGQueue()\nsync_to_matrix_queue = Queue()\n\nSERVER_URL = \"https://transport.transport01.raiden.network\"\n", "from gevent.event import Event\nfrom gevent.queue import Queue\nfrom ping_pong_chat.aio_queue import AGQueue\nreceived_event = Event()\nleave_rooms_event = Event()\nexit_event = Event()\noutput_message_queue = AGQueue()\ninput_message_queue = AGQueue()\nmatrix_to_aio_queue = AGQueue()\naio_to_matrix_queue = AGQueue()\nsync_to_matrix_queue = Queue()\nSERVER_URL = 'https://transport.transport01.raiden.network'\n", "<import token>\nreceived_event = Event()\nleave_rooms_event = Event()\nexit_event = Event()\noutput_message_queue = AGQueue()\ninput_message_queue = AGQueue()\nmatrix_to_aio_queue = AGQueue()\naio_to_matrix_queue = AGQueue()\nsync_to_matrix_queue = Queue()\nSERVER_URL = 'https://transport.transport01.raiden.network'\n", "<import token>\n<assignment token>\n" ]
false
730
ed80f5f898548ca012779543051ccff5b34e4fcc
from django.shortcuts import render import requests from bs4 import BeautifulSoup import json from rest_framework.response import Response from rest_framework.decorators import api_view,authentication_classes,permission_classes from rest_framework import status from django.contrib.staticfiles.storage import staticfiles_storage from user.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated # Create your views here. def getdata(url): data = requests.get(url) return data.text def get_json(): file_path = staticfiles_storage.path('coordinates.json') with open(file_path,'r') as f: data = json.load(f) html_doc = getdata("https://www.mygov.in/covid-19") soup = BeautifulSoup(html_doc, 'html.parser') k = soup.tbody.get_text() k = (("\n"+k).split("\n\n"))[1:-1] datarow = {} for index,item in enumerate(k): value = item.split("\n") datarow[value[1].lower()] = { 'coordinates':list(data.values())[index], 'confirmed':value[2], 'active':value[3], 'recovered':value[4], 'deceased':value[5] } return datarow @api_view(['GET']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def get_map_josn(request): """ List all code snippets, or create a new snippet. """ if request.method == 'GET': data = get_json() print('Responsed') return Response(data,status=status.HTTP_200_OK) @api_view(['GET']) def coordinates(request): url = 'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json' resp = requests.get(url) data = json.loads(resp.text) return Response(data,status=status.HTTP_200_OK)
[ "from django.shortcuts import render\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view,authentication_classes,permission_classes\nfrom rest_framework import status\nfrom django.contrib.staticfiles.storage import staticfiles_storage\nfrom user.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\n\n# Create your views here.\n\ndef getdata(url):\n data = requests.get(url)\n return data.text\n\ndef get_json():\n file_path = staticfiles_storage.path('coordinates.json')\n with open(file_path,'r') as f:\n data = json.load(f)\n\n html_doc = getdata(\"https://www.mygov.in/covid-19\")\n soup = BeautifulSoup(html_doc, 'html.parser')\n k = soup.tbody.get_text()\n k = ((\"\\n\"+k).split(\"\\n\\n\"))[1:-1]\n\n datarow = {}\n for index,item in enumerate(k):\n value = item.split(\"\\n\")\n datarow[value[1].lower()] = {\n 'coordinates':list(data.values())[index],\n 'confirmed':value[2],\n 'active':value[3],\n 'recovered':value[4],\n 'deceased':value[5]\n }\n return datarow\n\n@api_view(['GET'])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef get_map_josn(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n data = get_json()\n print('Responsed')\n return Response(data,status=status.HTTP_200_OK)\n\n@api_view(['GET'])\ndef coordinates(request):\n url = 'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'\n resp = requests.get(url)\n data = json.loads(resp.text)\n return Response(data,status=status.HTTP_200_OK)", "from django.shortcuts import render\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view, authentication_classes, permission_classes\nfrom rest_framework import status\nfrom django.contrib.staticfiles.storage import staticfiles_storage\nfrom user.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\n\n\ndef getdata(url):\n data = requests.get(url)\n return data.text\n\n\ndef get_json():\n file_path = staticfiles_storage.path('coordinates.json')\n with open(file_path, 'r') as f:\n data = json.load(f)\n html_doc = getdata('https://www.mygov.in/covid-19')\n soup = BeautifulSoup(html_doc, 'html.parser')\n k = soup.tbody.get_text()\n k = ('\\n' + k).split('\\n\\n')[1:-1]\n datarow = {}\n for index, item in enumerate(k):\n value = item.split('\\n')\n datarow[value[1].lower()] = {'coordinates': list(data.values())[\n index], 'confirmed': value[2], 'active': value[3], 'recovered':\n value[4], 'deceased': value[5]}\n return datarow\n\n\n@api_view(['GET'])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef get_map_josn(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n data = get_json()\n print('Responsed')\n return Response(data, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef coordinates(request):\n url = (\n 'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'\n )\n resp = requests.get(url)\n data = json.loads(resp.text)\n return Response(data, status=status.HTTP_200_OK)\n", "<import token>\n\n\ndef getdata(url):\n data = requests.get(url)\n return data.text\n\n\ndef get_json():\n file_path = staticfiles_storage.path('coordinates.json')\n with open(file_path, 'r') as f:\n data = json.load(f)\n html_doc = getdata('https://www.mygov.in/covid-19')\n soup = BeautifulSoup(html_doc, 'html.parser')\n k = soup.tbody.get_text()\n k = ('\\n' + k).split('\\n\\n')[1:-1]\n datarow = {}\n for index, item in enumerate(k):\n value = item.split('\\n')\n datarow[value[1].lower()] = {'coordinates': list(data.values())[\n index], 'confirmed': value[2], 'active': value[3], 'recovered':\n value[4], 'deceased': value[5]}\n return datarow\n\n\n@api_view(['GET'])\n@authentication_classes([TokenAuthentication])\n@permission_classes([IsAuthenticated])\ndef get_map_josn(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n data = get_json()\n print('Responsed')\n return Response(data, status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\ndef coordinates(request):\n url = (\n 'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'\n )\n resp = requests.get(url)\n data = json.loads(resp.text)\n return Response(data, status=status.HTTP_200_OK)\n", "<import token>\n\n\ndef getdata(url):\n data = requests.get(url)\n return data.text\n\n\ndef get_json():\n file_path = staticfiles_storage.path('coordinates.json')\n with open(file_path, 'r') as f:\n data = json.load(f)\n html_doc = getdata('https://www.mygov.in/covid-19')\n soup = BeautifulSoup(html_doc, 'html.parser')\n k = soup.tbody.get_text()\n k = ('\\n' + k).split('\\n\\n')[1:-1]\n datarow = {}\n for index, item in enumerate(k):\n value = item.split('\\n')\n datarow[value[1].lower()] = {'coordinates': list(data.values())[\n index], 'confirmed': value[2], 'active': value[3], 'recovered':\n value[4], 'deceased': value[5]}\n return datarow\n\n\n<function token>\n\n\n@api_view(['GET'])\ndef coordinates(request):\n url = (\n 'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'\n )\n resp = requests.get(url)\n data = json.loads(resp.text)\n return Response(data, status=status.HTTP_200_OK)\n", "<import token>\n\n\ndef getdata(url):\n data = requests.get(url)\n return data.text\n\n\n<function token>\n<function token>\n\n\n@api_view(['GET'])\ndef coordinates(request):\n url = (\n 'https://raw.githubusercontent.com/namantam1/indian_coordinated/master/india.json'\n )\n resp = requests.get(url)\n data = json.loads(resp.text)\n return Response(data, status=status.HTTP_200_OK)\n", "<import token>\n\n\ndef getdata(url):\n data = requests.get(url)\n return data.text\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
731
53fae0103168f4074ba0645c33e4640fcefdfc96
from urllib.error import URLError from urllib.request import urlopen from bs4 import BeautifulSoup import re import pymysql import ssl from pymysql import Error def decode_page(page_bytes, charsets=('utf-8',)): """通过指定的字符集对页面进行解码(不是每个网站都将字符集设置为utf-8)""" page_html = None for charset in charsets: try: page_html = page_bytes.decode(charset) break except UnicodeDecodeError: pass # logging.error('Decode:', error) return page_html def get_page_html(seed_url, *, retry_times=3, charsets=('utf-8',)): """获取页面的HTML代码(通过递归实现指定次数的重试操作)""" page_html = None try: page_html = decode_page(urlopen(seed_url).read(), charsets) except URLError: # logging.error('URL:', error) if retry_times > 0: return get_page_html(seed_url, retry_times=retry_times - 1, charsets=charsets) return page_html def get_matched_parts(page_html, pattern_str, pattern_ignore_case=re.I): """从页面中提取需要的部分(通常是链接也可以通过正则表达式进行指定)""" soup = BeautifulSoup(page_html, 'html.parser') for h1 in soup.find_all('h1'): return h1.get_text() def get_link_list(page_html): soup = BeautifulSoup(page_html, 'html.parser') list = [] for a_link in soup.find_all('a'): link = a_link['href'] if ('https://' in link) or ('http://' in link): list.append(link) # print(page_html) #print(list) return list def start_crawl(seed_url, match_pattern, *, max_depth=-1): """开始执行爬虫程序并对指定的数据进行持久化操作""" # conn = pymysql.connect(host='localhost', port=3306, # database='crawler', user='root', # password='Huhaohao@123', charset='utf8') conn = pymysql.connect(host='localhost', port=3306, user='root', password='Huhaohao@123', charset='utf8') with conn.cursor() as cursor: #cursor.execute("create database crawler if not exists;") cursor.execute('use crawler') cursor.execute( "CREATE TABLE IF NOT EXISTS tb_result " + "(" + "title TEXT NOT NULL," + "link TEXT NOT NULL" + ")" ) try: with conn.cursor() as cursor: url_list = [seed_url] # 通过下面的字典避免重复抓取并控制抓取深度 visited_url_list = {seed_url: 0} while url_list: current_url = url_list.pop(0) depth = visited_url_list[current_url] if depth != max_depth: # 尝试用utf-8/gbk/gb2312三种字符集进行页面解码 page_html = get_page_html(current_url, charsets=('utf-8', 'gbk', 'gb2312')) links_list = get_link_list(page_html) param_list = [] for link in links_list: if link not in visited_url_list: visited_url_list[link] = depth + 1 page_html = get_page_html(link, charsets=('utf-8', 'gbk', 'gb2312')) headings = get_matched_parts(page_html, r'<h1>(.*)<span') if headings: param_list.append((headings, link)) cursor.executemany('insert into tb_result(title, link) values(%s, %s)', param_list) conn.commit() except Error: pass # logging.error('SQL:', error) finally: conn.close() def main(): """主函数""" ssl._create_default_https_context = ssl._create_unverified_context start_crawl('http://sports.sohu.com/nba_a.shtml', r'<a[^>]*href=["\'](.*?)["\']', max_depth=2) if __name__ == '__main__': main()
[ "from urllib.error import URLError\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\nimport pymysql\nimport ssl\nfrom pymysql import Error\n\ndef decode_page(page_bytes, charsets=('utf-8',)):\n \"\"\"通过指定的字符集对页面进行解码(不是每个网站都将字符集设置为utf-8)\"\"\"\n page_html = None\n for charset in charsets:\n try:\n page_html = page_bytes.decode(charset)\n break\n except UnicodeDecodeError:\n pass\n # logging.error('Decode:', error)\n return page_html\n\n\ndef get_page_html(seed_url, *, retry_times=3, charsets=('utf-8',)):\n \"\"\"获取页面的HTML代码(通过递归实现指定次数的重试操作)\"\"\"\n page_html = None\n try:\n page_html = decode_page(urlopen(seed_url).read(), charsets)\n except URLError:\n # logging.error('URL:', error)\n if retry_times > 0:\n return get_page_html(seed_url, retry_times=retry_times - 1,\n charsets=charsets)\n return page_html\n\n\ndef get_matched_parts(page_html, pattern_str, pattern_ignore_case=re.I):\n \"\"\"从页面中提取需要的部分(通常是链接也可以通过正则表达式进行指定)\"\"\"\n soup = BeautifulSoup(page_html, 'html.parser')\n for h1 in soup.find_all('h1'):\n return h1.get_text()\n\n\ndef get_link_list(page_html):\n soup = BeautifulSoup(page_html, 'html.parser')\n list = []\n for a_link in soup.find_all('a'):\n link = a_link['href']\n if ('https://' in link) or ('http://' in link):\n list.append(link)\n # print(page_html)\n #print(list)\n return list\n\n\ndef start_crawl(seed_url, match_pattern, *, max_depth=-1):\n \"\"\"开始执行爬虫程序并对指定的数据进行持久化操作\"\"\"\n # conn = pymysql.connect(host='localhost', port=3306,\n # database='crawler', user='root',\n # password='Huhaohao@123', charset='utf8')\n\n conn = pymysql.connect(host='localhost', port=3306,\n user='root', password='Huhaohao@123', charset='utf8')\n\n with conn.cursor() as cursor:\n #cursor.execute(\"create database crawler if not exists;\")\n cursor.execute('use crawler')\n cursor.execute(\n \"CREATE TABLE IF NOT EXISTS tb_result \" +\n \"(\" +\n \"title TEXT NOT NULL,\" +\n \"link TEXT NOT NULL\" +\n \")\"\n )\n\n\n\n\n try:\n with conn.cursor() as cursor:\n url_list = [seed_url]\n # 通过下面的字典避免重复抓取并控制抓取深度\n visited_url_list = {seed_url: 0}\n while url_list:\n current_url = url_list.pop(0)\n depth = visited_url_list[current_url]\n if depth != max_depth:\n # 尝试用utf-8/gbk/gb2312三种字符集进行页面解码\n page_html = get_page_html(current_url, charsets=('utf-8', 'gbk', 'gb2312'))\n links_list = get_link_list(page_html)\n param_list = []\n for link in links_list:\n if link not in visited_url_list:\n visited_url_list[link] = depth + 1\n page_html = get_page_html(link, charsets=('utf-8', 'gbk', 'gb2312'))\n headings = get_matched_parts(page_html, r'<h1>(.*)<span')\n if headings:\n param_list.append((headings, link))\n cursor.executemany('insert into tb_result(title, link) values(%s, %s)',\n param_list)\n conn.commit()\n except Error:\n pass\n # logging.error('SQL:', error)\n finally:\n conn.close()\n\ndef main():\n \"\"\"主函数\"\"\"\n ssl._create_default_https_context = ssl._create_unverified_context\n start_crawl('http://sports.sohu.com/nba_a.shtml',\n r'<a[^>]*href=[\"\\'](.*?)[\"\\']',\n max_depth=2)\n\n\nif __name__ == '__main__':\n main()\n", "from urllib.error import URLError\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\nimport pymysql\nimport ssl\nfrom pymysql import Error\n\n\ndef decode_page(page_bytes, charsets=('utf-8',)):\n \"\"\"通过指定的字符集对页面进行解码(不是每个网站都将字符集设置为utf-8)\"\"\"\n page_html = None\n for charset in charsets:\n try:\n page_html = page_bytes.decode(charset)\n break\n except UnicodeDecodeError:\n pass\n return page_html\n\n\ndef get_page_html(seed_url, *, retry_times=3, charsets=('utf-8',)):\n \"\"\"获取页面的HTML代码(通过递归实现指定次数的重试操作)\"\"\"\n page_html = None\n try:\n page_html = decode_page(urlopen(seed_url).read(), charsets)\n except URLError:\n if retry_times > 0:\n return get_page_html(seed_url, retry_times=retry_times - 1,\n charsets=charsets)\n return page_html\n\n\ndef get_matched_parts(page_html, pattern_str, pattern_ignore_case=re.I):\n \"\"\"从页面中提取需要的部分(通常是链接也可以通过正则表达式进行指定)\"\"\"\n soup = BeautifulSoup(page_html, 'html.parser')\n for h1 in soup.find_all('h1'):\n return h1.get_text()\n\n\ndef get_link_list(page_html):\n soup = BeautifulSoup(page_html, 'html.parser')\n list = []\n for a_link in soup.find_all('a'):\n link = a_link['href']\n if 'https://' in link or 'http://' in link:\n list.append(link)\n return list\n\n\ndef start_crawl(seed_url, match_pattern, *, max_depth=-1):\n \"\"\"开始执行爬虫程序并对指定的数据进行持久化操作\"\"\"\n conn = pymysql.connect(host='localhost', port=3306, user='root',\n password='Huhaohao@123', charset='utf8')\n with conn.cursor() as cursor:\n cursor.execute('use crawler')\n cursor.execute('CREATE TABLE IF NOT EXISTS tb_result ' + '(' +\n 'title TEXT NOT NULL,' + 'link TEXT NOT NULL' + ')')\n try:\n with conn.cursor() as cursor:\n url_list = [seed_url]\n visited_url_list = {seed_url: 0}\n while url_list:\n current_url = url_list.pop(0)\n depth = visited_url_list[current_url]\n if depth != max_depth:\n page_html = get_page_html(current_url, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n links_list = get_link_list(page_html)\n param_list = []\n for link in links_list:\n if link not in visited_url_list:\n visited_url_list[link] = depth + 1\n page_html = get_page_html(link, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n headings = get_matched_parts(page_html,\n '<h1>(.*)<span')\n if headings:\n param_list.append((headings, link))\n cursor.executemany(\n 'insert into tb_result(title, link) values(%s, %s)',\n param_list)\n conn.commit()\n except Error:\n pass\n finally:\n conn.close()\n\n\ndef main():\n \"\"\"主函数\"\"\"\n ssl._create_default_https_context = ssl._create_unverified_context\n start_crawl('http://sports.sohu.com/nba_a.shtml',\n '<a[^>]*href=[\"\\\\\\'](.*?)[\"\\\\\\']', max_depth=2)\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n\n\ndef decode_page(page_bytes, charsets=('utf-8',)):\n \"\"\"通过指定的字符集对页面进行解码(不是每个网站都将字符集设置为utf-8)\"\"\"\n page_html = None\n for charset in charsets:\n try:\n page_html = page_bytes.decode(charset)\n break\n except UnicodeDecodeError:\n pass\n return page_html\n\n\ndef get_page_html(seed_url, *, retry_times=3, charsets=('utf-8',)):\n \"\"\"获取页面的HTML代码(通过递归实现指定次数的重试操作)\"\"\"\n page_html = None\n try:\n page_html = decode_page(urlopen(seed_url).read(), charsets)\n except URLError:\n if retry_times > 0:\n return get_page_html(seed_url, retry_times=retry_times - 1,\n charsets=charsets)\n return page_html\n\n\ndef get_matched_parts(page_html, pattern_str, pattern_ignore_case=re.I):\n \"\"\"从页面中提取需要的部分(通常是链接也可以通过正则表达式进行指定)\"\"\"\n soup = BeautifulSoup(page_html, 'html.parser')\n for h1 in soup.find_all('h1'):\n return h1.get_text()\n\n\ndef get_link_list(page_html):\n soup = BeautifulSoup(page_html, 'html.parser')\n list = []\n for a_link in soup.find_all('a'):\n link = a_link['href']\n if 'https://' in link or 'http://' in link:\n list.append(link)\n return list\n\n\ndef start_crawl(seed_url, match_pattern, *, max_depth=-1):\n \"\"\"开始执行爬虫程序并对指定的数据进行持久化操作\"\"\"\n conn = pymysql.connect(host='localhost', port=3306, user='root',\n password='Huhaohao@123', charset='utf8')\n with conn.cursor() as cursor:\n cursor.execute('use crawler')\n cursor.execute('CREATE TABLE IF NOT EXISTS tb_result ' + '(' +\n 'title TEXT NOT NULL,' + 'link TEXT NOT NULL' + ')')\n try:\n with conn.cursor() as cursor:\n url_list = [seed_url]\n visited_url_list = {seed_url: 0}\n while url_list:\n current_url = url_list.pop(0)\n depth = visited_url_list[current_url]\n if depth != max_depth:\n page_html = get_page_html(current_url, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n links_list = get_link_list(page_html)\n param_list = []\n for link in links_list:\n if link not in visited_url_list:\n visited_url_list[link] = depth + 1\n page_html = get_page_html(link, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n headings = get_matched_parts(page_html,\n '<h1>(.*)<span')\n if headings:\n param_list.append((headings, link))\n cursor.executemany(\n 'insert into tb_result(title, link) values(%s, %s)',\n param_list)\n conn.commit()\n except Error:\n pass\n finally:\n conn.close()\n\n\ndef main():\n \"\"\"主函数\"\"\"\n ssl._create_default_https_context = ssl._create_unverified_context\n start_crawl('http://sports.sohu.com/nba_a.shtml',\n '<a[^>]*href=[\"\\\\\\'](.*?)[\"\\\\\\']', max_depth=2)\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n\n\ndef decode_page(page_bytes, charsets=('utf-8',)):\n \"\"\"通过指定的字符集对页面进行解码(不是每个网站都将字符集设置为utf-8)\"\"\"\n page_html = None\n for charset in charsets:\n try:\n page_html = page_bytes.decode(charset)\n break\n except UnicodeDecodeError:\n pass\n return page_html\n\n\ndef get_page_html(seed_url, *, retry_times=3, charsets=('utf-8',)):\n \"\"\"获取页面的HTML代码(通过递归实现指定次数的重试操作)\"\"\"\n page_html = None\n try:\n page_html = decode_page(urlopen(seed_url).read(), charsets)\n except URLError:\n if retry_times > 0:\n return get_page_html(seed_url, retry_times=retry_times - 1,\n charsets=charsets)\n return page_html\n\n\ndef get_matched_parts(page_html, pattern_str, pattern_ignore_case=re.I):\n \"\"\"从页面中提取需要的部分(通常是链接也可以通过正则表达式进行指定)\"\"\"\n soup = BeautifulSoup(page_html, 'html.parser')\n for h1 in soup.find_all('h1'):\n return h1.get_text()\n\n\ndef get_link_list(page_html):\n soup = BeautifulSoup(page_html, 'html.parser')\n list = []\n for a_link in soup.find_all('a'):\n link = a_link['href']\n if 'https://' in link or 'http://' in link:\n list.append(link)\n return list\n\n\ndef start_crawl(seed_url, match_pattern, *, max_depth=-1):\n \"\"\"开始执行爬虫程序并对指定的数据进行持久化操作\"\"\"\n conn = pymysql.connect(host='localhost', port=3306, user='root',\n password='Huhaohao@123', charset='utf8')\n with conn.cursor() as cursor:\n cursor.execute('use crawler')\n cursor.execute('CREATE TABLE IF NOT EXISTS tb_result ' + '(' +\n 'title TEXT NOT NULL,' + 'link TEXT NOT NULL' + ')')\n try:\n with conn.cursor() as cursor:\n url_list = [seed_url]\n visited_url_list = {seed_url: 0}\n while url_list:\n current_url = url_list.pop(0)\n depth = visited_url_list[current_url]\n if depth != max_depth:\n page_html = get_page_html(current_url, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n links_list = get_link_list(page_html)\n param_list = []\n for link in links_list:\n if link not in visited_url_list:\n visited_url_list[link] = depth + 1\n page_html = get_page_html(link, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n headings = get_matched_parts(page_html,\n '<h1>(.*)<span')\n if headings:\n param_list.append((headings, link))\n cursor.executemany(\n 'insert into tb_result(title, link) values(%s, %s)',\n param_list)\n conn.commit()\n except Error:\n pass\n finally:\n conn.close()\n\n\ndef main():\n \"\"\"主函数\"\"\"\n ssl._create_default_https_context = ssl._create_unverified_context\n start_crawl('http://sports.sohu.com/nba_a.shtml',\n '<a[^>]*href=[\"\\\\\\'](.*?)[\"\\\\\\']', max_depth=2)\n\n\n<code token>\n", "<import token>\n\n\ndef decode_page(page_bytes, charsets=('utf-8',)):\n \"\"\"通过指定的字符集对页面进行解码(不是每个网站都将字符集设置为utf-8)\"\"\"\n page_html = None\n for charset in charsets:\n try:\n page_html = page_bytes.decode(charset)\n break\n except UnicodeDecodeError:\n pass\n return page_html\n\n\ndef get_page_html(seed_url, *, retry_times=3, charsets=('utf-8',)):\n \"\"\"获取页面的HTML代码(通过递归实现指定次数的重试操作)\"\"\"\n page_html = None\n try:\n page_html = decode_page(urlopen(seed_url).read(), charsets)\n except URLError:\n if retry_times > 0:\n return get_page_html(seed_url, retry_times=retry_times - 1,\n charsets=charsets)\n return page_html\n\n\n<function token>\n\n\ndef get_link_list(page_html):\n soup = BeautifulSoup(page_html, 'html.parser')\n list = []\n for a_link in soup.find_all('a'):\n link = a_link['href']\n if 'https://' in link or 'http://' in link:\n list.append(link)\n return list\n\n\ndef start_crawl(seed_url, match_pattern, *, max_depth=-1):\n \"\"\"开始执行爬虫程序并对指定的数据进行持久化操作\"\"\"\n conn = pymysql.connect(host='localhost', port=3306, user='root',\n password='Huhaohao@123', charset='utf8')\n with conn.cursor() as cursor:\n cursor.execute('use crawler')\n cursor.execute('CREATE TABLE IF NOT EXISTS tb_result ' + '(' +\n 'title TEXT NOT NULL,' + 'link TEXT NOT NULL' + ')')\n try:\n with conn.cursor() as cursor:\n url_list = [seed_url]\n visited_url_list = {seed_url: 0}\n while url_list:\n current_url = url_list.pop(0)\n depth = visited_url_list[current_url]\n if depth != max_depth:\n page_html = get_page_html(current_url, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n links_list = get_link_list(page_html)\n param_list = []\n for link in links_list:\n if link not in visited_url_list:\n visited_url_list[link] = depth + 1\n page_html = get_page_html(link, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n headings = get_matched_parts(page_html,\n '<h1>(.*)<span')\n if headings:\n param_list.append((headings, link))\n cursor.executemany(\n 'insert into tb_result(title, link) values(%s, %s)',\n param_list)\n conn.commit()\n except Error:\n pass\n finally:\n conn.close()\n\n\ndef main():\n \"\"\"主函数\"\"\"\n ssl._create_default_https_context = ssl._create_unverified_context\n start_crawl('http://sports.sohu.com/nba_a.shtml',\n '<a[^>]*href=[\"\\\\\\'](.*?)[\"\\\\\\']', max_depth=2)\n\n\n<code token>\n", "<import token>\n\n\ndef decode_page(page_bytes, charsets=('utf-8',)):\n \"\"\"通过指定的字符集对页面进行解码(不是每个网站都将字符集设置为utf-8)\"\"\"\n page_html = None\n for charset in charsets:\n try:\n page_html = page_bytes.decode(charset)\n break\n except UnicodeDecodeError:\n pass\n return page_html\n\n\ndef get_page_html(seed_url, *, retry_times=3, charsets=('utf-8',)):\n \"\"\"获取页面的HTML代码(通过递归实现指定次数的重试操作)\"\"\"\n page_html = None\n try:\n page_html = decode_page(urlopen(seed_url).read(), charsets)\n except URLError:\n if retry_times > 0:\n return get_page_html(seed_url, retry_times=retry_times - 1,\n charsets=charsets)\n return page_html\n\n\n<function token>\n<function token>\n\n\ndef start_crawl(seed_url, match_pattern, *, max_depth=-1):\n \"\"\"开始执行爬虫程序并对指定的数据进行持久化操作\"\"\"\n conn = pymysql.connect(host='localhost', port=3306, user='root',\n password='Huhaohao@123', charset='utf8')\n with conn.cursor() as cursor:\n cursor.execute('use crawler')\n cursor.execute('CREATE TABLE IF NOT EXISTS tb_result ' + '(' +\n 'title TEXT NOT NULL,' + 'link TEXT NOT NULL' + ')')\n try:\n with conn.cursor() as cursor:\n url_list = [seed_url]\n visited_url_list = {seed_url: 0}\n while url_list:\n current_url = url_list.pop(0)\n depth = visited_url_list[current_url]\n if depth != max_depth:\n page_html = get_page_html(current_url, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n links_list = get_link_list(page_html)\n param_list = []\n for link in links_list:\n if link not in visited_url_list:\n visited_url_list[link] = depth + 1\n page_html = get_page_html(link, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n headings = get_matched_parts(page_html,\n '<h1>(.*)<span')\n if headings:\n param_list.append((headings, link))\n cursor.executemany(\n 'insert into tb_result(title, link) values(%s, %s)',\n param_list)\n conn.commit()\n except Error:\n pass\n finally:\n conn.close()\n\n\ndef main():\n \"\"\"主函数\"\"\"\n ssl._create_default_https_context = ssl._create_unverified_context\n start_crawl('http://sports.sohu.com/nba_a.shtml',\n '<a[^>]*href=[\"\\\\\\'](.*?)[\"\\\\\\']', max_depth=2)\n\n\n<code token>\n", "<import token>\n\n\ndef decode_page(page_bytes, charsets=('utf-8',)):\n \"\"\"通过指定的字符集对页面进行解码(不是每个网站都将字符集设置为utf-8)\"\"\"\n page_html = None\n for charset in charsets:\n try:\n page_html = page_bytes.decode(charset)\n break\n except UnicodeDecodeError:\n pass\n return page_html\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef start_crawl(seed_url, match_pattern, *, max_depth=-1):\n \"\"\"开始执行爬虫程序并对指定的数据进行持久化操作\"\"\"\n conn = pymysql.connect(host='localhost', port=3306, user='root',\n password='Huhaohao@123', charset='utf8')\n with conn.cursor() as cursor:\n cursor.execute('use crawler')\n cursor.execute('CREATE TABLE IF NOT EXISTS tb_result ' + '(' +\n 'title TEXT NOT NULL,' + 'link TEXT NOT NULL' + ')')\n try:\n with conn.cursor() as cursor:\n url_list = [seed_url]\n visited_url_list = {seed_url: 0}\n while url_list:\n current_url = url_list.pop(0)\n depth = visited_url_list[current_url]\n if depth != max_depth:\n page_html = get_page_html(current_url, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n links_list = get_link_list(page_html)\n param_list = []\n for link in links_list:\n if link not in visited_url_list:\n visited_url_list[link] = depth + 1\n page_html = get_page_html(link, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n headings = get_matched_parts(page_html,\n '<h1>(.*)<span')\n if headings:\n param_list.append((headings, link))\n cursor.executemany(\n 'insert into tb_result(title, link) values(%s, %s)',\n param_list)\n conn.commit()\n except Error:\n pass\n finally:\n conn.close()\n\n\ndef main():\n \"\"\"主函数\"\"\"\n ssl._create_default_https_context = ssl._create_unverified_context\n start_crawl('http://sports.sohu.com/nba_a.shtml',\n '<a[^>]*href=[\"\\\\\\'](.*?)[\"\\\\\\']', max_depth=2)\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef start_crawl(seed_url, match_pattern, *, max_depth=-1):\n \"\"\"开始执行爬虫程序并对指定的数据进行持久化操作\"\"\"\n conn = pymysql.connect(host='localhost', port=3306, user='root',\n password='Huhaohao@123', charset='utf8')\n with conn.cursor() as cursor:\n cursor.execute('use crawler')\n cursor.execute('CREATE TABLE IF NOT EXISTS tb_result ' + '(' +\n 'title TEXT NOT NULL,' + 'link TEXT NOT NULL' + ')')\n try:\n with conn.cursor() as cursor:\n url_list = [seed_url]\n visited_url_list = {seed_url: 0}\n while url_list:\n current_url = url_list.pop(0)\n depth = visited_url_list[current_url]\n if depth != max_depth:\n page_html = get_page_html(current_url, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n links_list = get_link_list(page_html)\n param_list = []\n for link in links_list:\n if link not in visited_url_list:\n visited_url_list[link] = depth + 1\n page_html = get_page_html(link, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n headings = get_matched_parts(page_html,\n '<h1>(.*)<span')\n if headings:\n param_list.append((headings, link))\n cursor.executemany(\n 'insert into tb_result(title, link) values(%s, %s)',\n param_list)\n conn.commit()\n except Error:\n pass\n finally:\n conn.close()\n\n\ndef main():\n \"\"\"主函数\"\"\"\n ssl._create_default_https_context = ssl._create_unverified_context\n start_crawl('http://sports.sohu.com/nba_a.shtml',\n '<a[^>]*href=[\"\\\\\\'](.*?)[\"\\\\\\']', max_depth=2)\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n\n\ndef start_crawl(seed_url, match_pattern, *, max_depth=-1):\n \"\"\"开始执行爬虫程序并对指定的数据进行持久化操作\"\"\"\n conn = pymysql.connect(host='localhost', port=3306, user='root',\n password='Huhaohao@123', charset='utf8')\n with conn.cursor() as cursor:\n cursor.execute('use crawler')\n cursor.execute('CREATE TABLE IF NOT EXISTS tb_result ' + '(' +\n 'title TEXT NOT NULL,' + 'link TEXT NOT NULL' + ')')\n try:\n with conn.cursor() as cursor:\n url_list = [seed_url]\n visited_url_list = {seed_url: 0}\n while url_list:\n current_url = url_list.pop(0)\n depth = visited_url_list[current_url]\n if depth != max_depth:\n page_html = get_page_html(current_url, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n links_list = get_link_list(page_html)\n param_list = []\n for link in links_list:\n if link not in visited_url_list:\n visited_url_list[link] = depth + 1\n page_html = get_page_html(link, charsets=(\n 'utf-8', 'gbk', 'gb2312'))\n headings = get_matched_parts(page_html,\n '<h1>(.*)<span')\n if headings:\n param_list.append((headings, link))\n cursor.executemany(\n 'insert into tb_result(title, link) values(%s, %s)',\n param_list)\n conn.commit()\n except Error:\n pass\n finally:\n conn.close()\n\n\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
732
45fcafdd30f890ddf5eaa090152fde2e2da4dbef
# 튜플(tuple) - 리스트와 구조가 비슷함 #변경, 삭제 할 수 없다. t = ('코스모스', '민들레', '국화') print(t) print(t[:2]) print(t[1:]) #del t[0] - 삭제 안됨 #t[2] ="매화" - 수정 안됨 t2 = (1, 2, 3) t3 = (4,) # 1개 추가하기 (쉼표를 붙임) print(t2) print(t3) print(t2 + t3) # 요소 더하기
[ "# 튜플(tuple) - 리스트와 구조가 비슷함\n#변경, 삭제 할 수 없다.\n\nt = ('코스모스', '민들레', '국화')\nprint(t)\nprint(t[:2])\nprint(t[1:])\n#del t[0] - 삭제 안됨\n#t[2] =\"매화\" - 수정 안됨\n\nt2 = (1, 2, 3)\nt3 = (4,) # 1개 추가하기 (쉼표를 붙임)\nprint(t2)\nprint(t3)\nprint(t2 + t3) # 요소 더하기\n", "t = '코스모스', '민들레', '국화'\nprint(t)\nprint(t[:2])\nprint(t[1:])\nt2 = 1, 2, 3\nt3 = 4,\nprint(t2)\nprint(t3)\nprint(t2 + t3)\n", "<assignment token>\nprint(t)\nprint(t[:2])\nprint(t[1:])\n<assignment token>\nprint(t2)\nprint(t3)\nprint(t2 + t3)\n", "<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
733
73e7e43e9cfb3c0884480809bc03ade687d641d6
from os import wait import cv2 import numpy as np import math import sys import types import operator ## orb 및 bf matcher 선언 orb = cv2.cv2.ORB_create( nfeatures=5000, scaleFactor=1.2, nlevels=8, edgeThreshold=31, firstLevel=0, WTA_K=2, scoreType=cv2.ORB_FAST_SCORE, patchSize=31, fastThreshold=25, ) bf = cv2.BFMatcher(cv2.NORM_HAMMING) def getScale(NumFrame, t_gt, seq_num): txt_file = open('/media/cordin/새 볼륨/rosbag/dataset/poses/{0:02d}.txt'.format(seq_num)) x_prev = float(t_gt[0]) y_prev = float(t_gt[1]) z_prev = float(t_gt[2]) line = txt_file.readlines() line_sp = line[NumFrame].split(' ') x = float(line_sp[3]) y = float(line_sp[7]) z = float(line_sp[11]) t_gt[0] = x t_gt[1] = y t_gt[2] = z txt_file.close() scale = math.sqrt((x-x_prev)**2 + (y-y_prev)**2 + (z-z_prev)**2) return scale, t_gt if __name__ == "__main__": MAX_FRAME = 1000 SEQ_NUM = 2 #Camera intrinsic parameter focal = 718.8560 pp = (607.1928, 185.2157) textOrg1 = (10,30) textOrg2 = (10,80) textOrg3 = (10,130) img_1_c = cv2.imread("/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/000000.png".format(SEQ_NUM)) img_2_c = cv2.imread("/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/000001.png".format(SEQ_NUM)) img_1 = cv2.cvtColor(img_1_c,cv2.COLOR_BGR2GRAY) img_2 = cv2.cvtColor(img_2_c,cv2.COLOR_BGR2GRAY) kp1, des1 = orb.detectAndCompute(img_1,None) kp2, des2 = orb.detectAndCompute(img_2,None) matches = bf.match(des1,des2) matches = sorted(matches, key = lambda x:x.distance) idx = matches[0:1500] pts1 = [] pts2 = [] for i in idx: pts1.append(kp1[i.queryIdx].pt) pts2.append(kp2[i.trainIdx].pt) pts1 = np.array(pts1) pts2 = np.array(pts2) E, mask = cv2.findEssentialMat(pts1,pts2,focal = focal, pp = pp, method=cv2.RANSAC, prob = 0.999, threshold=1.0) _, R_f, t_f, _ = cv2.recoverPose(E, pts1, pts2, focal = focal, pp = pp) R_f_seg = R_f t_f_seg = t_f t_gt = np.zeros((3,1),dtype=np.float64) prevImage = img_2 kp_prev = kp2 des_prev = des2 traj = np.zeros((1000,2000),dtype=np.uint8) traj = cv2.cvtColor(traj,cv2.COLOR_GRAY2BGR) rmse_total = 0 for numFrame in range(2, MAX_FRAME): filename = '/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/{1:06d}.png'.format(SEQ_NUM,numFrame) currImage_c = cv2.imread(filename) currImage = cv2.cvtColor(currImage_c,cv2.COLOR_BGR2GRAY) # feature extraction kp_curr, des_curr = orb.detectAndCompute(currImage,None) # feature matching matches = bf.match(des_prev,des_curr) matches = sorted(matches, key = lambda x:x.distance) idx = matches[0:1500] pts1 = [] pts2 = [] for i in idx: pts1.append(kp_prev[i.queryIdx].pt) pts2.append(kp_curr[i.trainIdx].pt) pts1 = np.array(pts1) pts2 = np.array(pts2) # caculate R, t E_mat, mask_n = cv2.findEssentialMat(pts2, pts1, focal = focal, pp = pp, method=cv2.RANSAC, prob = 0.999, threshold=1.0) _, R, t, _ = cv2.recoverPose(E_mat, pts2, pts1, focal = focal, pp = pp) # get scale abs_scale, t_gt = getScale(numFrame, t_gt, SEQ_NUM) # update trajectory t_f = t_f + abs_scale*R_f.dot(t) R_f = R.dot(R_f) # caculate Error error = map(operator.sub,t_gt,t_f) error_sum_square = sum(map(lambda x:x*x,error)) rmse = math.sqrt(error_sum_square/3) rmse_total = rmse_total + rmse print("rmse = ",rmse_total/numFrame) prevImage = currImage kp_prev = kp_curr des_prev = des_curr # visualization x_gt = int(t_gt[0]) + 1000 y_gt = int(t_gt[2]) + 100 x = int(t_f[0]) + 1000 y = int(t_f[2]) + 100 cv2.circle(traj, (x,y), 1 , (0,0,255), 2) cv2.circle(traj, (x_gt,y_gt), 1 , (0,255,0), 2) cv2.rectangle(traj, (10,10), (700,150), (0,0,0), -1) text1 = 'orb Coordinates: x = {0:02f}m y = {1:02f}m z = {2:02f}m'.format(float(t_f[0]),float(t_f[1]),float(t_f[2])) cv2.putText(traj, text1, textOrg1, cv2.FONT_HERSHEY_PLAIN,1,(255,255,255),1,8) text3 = 'gt Coordinates: x = {0:02f}m y = {1:02f}m z = {2:02f}m'.format(float(t_gt[0]),float(t_gt[1]),float(t_gt[2])) cv2.putText(traj, text3, textOrg3, cv2.FONT_HERSHEY_PLAIN,1,(255,255,255),1,8) feature_img = cv2.drawKeypoints(currImage_c, kp_curr, None) cv2.imshow("trajectory", traj) cv2.imshow("feat_img", feature_img) cv2.waitKey(1) cv2.imwrite("result_{0:02d}.png".format(SEQ_NUM),traj)
[ "from os import wait\nimport cv2\nimport numpy as np\nimport math\nimport sys\nimport types\nimport operator\n\n## orb 및 bf matcher 선언\norb = cv2.cv2.ORB_create(\n nfeatures=5000,\n scaleFactor=1.2,\n nlevels=8,\n edgeThreshold=31,\n firstLevel=0,\n WTA_K=2,\n scoreType=cv2.ORB_FAST_SCORE,\n patchSize=31,\n fastThreshold=25,\n )\n\nbf = cv2.BFMatcher(cv2.NORM_HAMMING)\n\n\ndef getScale(NumFrame, t_gt, seq_num):\n\n txt_file = open('/media/cordin/새 볼륨/rosbag/dataset/poses/{0:02d}.txt'.format(seq_num))\n \n x_prev = float(t_gt[0])\n y_prev = float(t_gt[1])\n z_prev = float(t_gt[2])\n\n line = txt_file.readlines()\n line_sp = line[NumFrame].split(' ')\n\n x = float(line_sp[3])\n y = float(line_sp[7])\n z = float(line_sp[11])\n\n t_gt[0] = x\n t_gt[1] = y\n t_gt[2] = z\n\n txt_file.close()\n\n scale = math.sqrt((x-x_prev)**2 + (y-y_prev)**2 + (z-z_prev)**2)\n return scale, t_gt\n\n\nif __name__ == \"__main__\":\n MAX_FRAME = 1000\n SEQ_NUM = 2\n\n #Camera intrinsic parameter\n focal = 718.8560\n pp = (607.1928, 185.2157)\n\n textOrg1 = (10,30)\n textOrg2 = (10,80)\n textOrg3 = (10,130)\n\n img_1_c = cv2.imread(\"/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/000000.png\".format(SEQ_NUM))\n img_2_c = cv2.imread(\"/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/000001.png\".format(SEQ_NUM))\n img_1 = cv2.cvtColor(img_1_c,cv2.COLOR_BGR2GRAY)\n img_2 = cv2.cvtColor(img_2_c,cv2.COLOR_BGR2GRAY)\n\n kp1, des1 = orb.detectAndCompute(img_1,None)\n kp2, des2 = orb.detectAndCompute(img_2,None)\n\n matches = bf.match(des1,des2)\n matches = sorted(matches, key = lambda x:x.distance)\n\n idx = matches[0:1500]\n\n pts1 = []\n pts2 = []\n\n for i in idx:\n pts1.append(kp1[i.queryIdx].pt)\n pts2.append(kp2[i.trainIdx].pt)\n\n\n pts1 = np.array(pts1)\n pts2 = np.array(pts2)\n\n E, mask = cv2.findEssentialMat(pts1,pts2,focal = focal, pp = pp, method=cv2.RANSAC, prob = 0.999, threshold=1.0)\n _, R_f, t_f, _ = cv2.recoverPose(E, pts1, pts2, focal = focal, pp = pp)\n\n R_f_seg = R_f\n t_f_seg = t_f\n\n t_gt = np.zeros((3,1),dtype=np.float64)\n\n prevImage = img_2\n kp_prev = kp2\n des_prev = des2\n\n traj = np.zeros((1000,2000),dtype=np.uint8)\n traj = cv2.cvtColor(traj,cv2.COLOR_GRAY2BGR)\n\n rmse_total = 0\n \n for numFrame in range(2, MAX_FRAME):\n filename = '/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/{1:06d}.png'.format(SEQ_NUM,numFrame)\n \n currImage_c = cv2.imread(filename)\n currImage = cv2.cvtColor(currImage_c,cv2.COLOR_BGR2GRAY)\n\n # feature extraction\n kp_curr, des_curr = orb.detectAndCompute(currImage,None)\n\n # feature matching\n matches = bf.match(des_prev,des_curr)\n matches = sorted(matches, key = lambda x:x.distance)\n idx = matches[0:1500]\n\n pts1 = []\n pts2 = []\n\n for i in idx:\n pts1.append(kp_prev[i.queryIdx].pt)\n pts2.append(kp_curr[i.trainIdx].pt)\n\n pts1 = np.array(pts1)\n pts2 = np.array(pts2)\n\n # caculate R, t\n E_mat, mask_n = cv2.findEssentialMat(pts2, pts1, focal = focal, pp = pp, method=cv2.RANSAC, prob = 0.999, threshold=1.0)\n _, R, t, _ = cv2.recoverPose(E_mat, pts2, pts1, focal = focal, pp = pp)\n\n # get scale\n abs_scale, t_gt = getScale(numFrame, t_gt, SEQ_NUM)\n \n # update trajectory\n t_f = t_f + abs_scale*R_f.dot(t)\n R_f = R.dot(R_f)\n\n # caculate Error\n error = map(operator.sub,t_gt,t_f)\n error_sum_square = sum(map(lambda x:x*x,error))\n rmse = math.sqrt(error_sum_square/3)\n rmse_total = rmse_total + rmse\n\n print(\"rmse = \",rmse_total/numFrame)\n\n prevImage = currImage\n kp_prev = kp_curr\n des_prev = des_curr\n\n # visualization\n x_gt = int(t_gt[0]) + 1000\n y_gt = int(t_gt[2]) + 100\n\n x = int(t_f[0]) + 1000\n y = int(t_f[2]) + 100\n\n cv2.circle(traj, (x,y), 1 , (0,0,255), 2)\n cv2.circle(traj, (x_gt,y_gt), 1 , (0,255,0), 2)\n \n\n cv2.rectangle(traj, (10,10), (700,150), (0,0,0), -1)\n text1 = 'orb Coordinates: x = {0:02f}m y = {1:02f}m z = {2:02f}m'.format(float(t_f[0]),float(t_f[1]),float(t_f[2]))\n cv2.putText(traj, text1, textOrg1, cv2.FONT_HERSHEY_PLAIN,1,(255,255,255),1,8)\n\n text3 = 'gt Coordinates: x = {0:02f}m y = {1:02f}m z = {2:02f}m'.format(float(t_gt[0]),float(t_gt[1]),float(t_gt[2]))\n cv2.putText(traj, text3, textOrg3, cv2.FONT_HERSHEY_PLAIN,1,(255,255,255),1,8)\n\n feature_img = cv2.drawKeypoints(currImage_c, kp_curr, None)\n\n cv2.imshow(\"trajectory\", traj)\n cv2.imshow(\"feat_img\", feature_img)\n\n cv2.waitKey(1)\n \n cv2.imwrite(\"result_{0:02d}.png\".format(SEQ_NUM),traj)", "from os import wait\nimport cv2\nimport numpy as np\nimport math\nimport sys\nimport types\nimport operator\norb = cv2.cv2.ORB_create(nfeatures=5000, scaleFactor=1.2, nlevels=8,\n edgeThreshold=31, firstLevel=0, WTA_K=2, scoreType=cv2.ORB_FAST_SCORE,\n patchSize=31, fastThreshold=25)\nbf = cv2.BFMatcher(cv2.NORM_HAMMING)\n\n\ndef getScale(NumFrame, t_gt, seq_num):\n txt_file = open('/media/cordin/새 볼륨/rosbag/dataset/poses/{0:02d}.txt'.\n format(seq_num))\n x_prev = float(t_gt[0])\n y_prev = float(t_gt[1])\n z_prev = float(t_gt[2])\n line = txt_file.readlines()\n line_sp = line[NumFrame].split(' ')\n x = float(line_sp[3])\n y = float(line_sp[7])\n z = float(line_sp[11])\n t_gt[0] = x\n t_gt[1] = y\n t_gt[2] = z\n txt_file.close()\n scale = math.sqrt((x - x_prev) ** 2 + (y - y_prev) ** 2 + (z - z_prev) ** 2\n )\n return scale, t_gt\n\n\nif __name__ == '__main__':\n MAX_FRAME = 1000\n SEQ_NUM = 2\n focal = 718.856\n pp = 607.1928, 185.2157\n textOrg1 = 10, 30\n textOrg2 = 10, 80\n textOrg3 = 10, 130\n img_1_c = cv2.imread(\n '/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/000000.png'\n .format(SEQ_NUM))\n img_2_c = cv2.imread(\n '/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/000001.png'\n .format(SEQ_NUM))\n img_1 = cv2.cvtColor(img_1_c, cv2.COLOR_BGR2GRAY)\n img_2 = cv2.cvtColor(img_2_c, cv2.COLOR_BGR2GRAY)\n kp1, des1 = orb.detectAndCompute(img_1, None)\n kp2, des2 = orb.detectAndCompute(img_2, None)\n matches = bf.match(des1, des2)\n matches = sorted(matches, key=lambda x: x.distance)\n idx = matches[0:1500]\n pts1 = []\n pts2 = []\n for i in idx:\n pts1.append(kp1[i.queryIdx].pt)\n pts2.append(kp2[i.trainIdx].pt)\n pts1 = np.array(pts1)\n pts2 = np.array(pts2)\n E, mask = cv2.findEssentialMat(pts1, pts2, focal=focal, pp=pp, method=\n cv2.RANSAC, prob=0.999, threshold=1.0)\n _, R_f, t_f, _ = cv2.recoverPose(E, pts1, pts2, focal=focal, pp=pp)\n R_f_seg = R_f\n t_f_seg = t_f\n t_gt = np.zeros((3, 1), dtype=np.float64)\n prevImage = img_2\n kp_prev = kp2\n des_prev = des2\n traj = np.zeros((1000, 2000), dtype=np.uint8)\n traj = cv2.cvtColor(traj, cv2.COLOR_GRAY2BGR)\n rmse_total = 0\n for numFrame in range(2, MAX_FRAME):\n filename = (\n '/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/{1:06d}.png'\n .format(SEQ_NUM, numFrame))\n currImage_c = cv2.imread(filename)\n currImage = cv2.cvtColor(currImage_c, cv2.COLOR_BGR2GRAY)\n kp_curr, des_curr = orb.detectAndCompute(currImage, None)\n matches = bf.match(des_prev, des_curr)\n matches = sorted(matches, key=lambda x: x.distance)\n idx = matches[0:1500]\n pts1 = []\n pts2 = []\n for i in idx:\n pts1.append(kp_prev[i.queryIdx].pt)\n pts2.append(kp_curr[i.trainIdx].pt)\n pts1 = np.array(pts1)\n pts2 = np.array(pts2)\n E_mat, mask_n = cv2.findEssentialMat(pts2, pts1, focal=focal, pp=pp,\n method=cv2.RANSAC, prob=0.999, threshold=1.0)\n _, R, t, _ = cv2.recoverPose(E_mat, pts2, pts1, focal=focal, pp=pp)\n abs_scale, t_gt = getScale(numFrame, t_gt, SEQ_NUM)\n t_f = t_f + abs_scale * R_f.dot(t)\n R_f = R.dot(R_f)\n error = map(operator.sub, t_gt, t_f)\n error_sum_square = sum(map(lambda x: x * x, error))\n rmse = math.sqrt(error_sum_square / 3)\n rmse_total = rmse_total + rmse\n print('rmse = ', rmse_total / numFrame)\n prevImage = currImage\n kp_prev = kp_curr\n des_prev = des_curr\n x_gt = int(t_gt[0]) + 1000\n y_gt = int(t_gt[2]) + 100\n x = int(t_f[0]) + 1000\n y = int(t_f[2]) + 100\n cv2.circle(traj, (x, y), 1, (0, 0, 255), 2)\n cv2.circle(traj, (x_gt, y_gt), 1, (0, 255, 0), 2)\n cv2.rectangle(traj, (10, 10), (700, 150), (0, 0, 0), -1)\n text1 = ('orb Coordinates: x = {0:02f}m y = {1:02f}m z = {2:02f}m'.\n format(float(t_f[0]), float(t_f[1]), float(t_f[2])))\n cv2.putText(traj, text1, textOrg1, cv2.FONT_HERSHEY_PLAIN, 1, (255,\n 255, 255), 1, 8)\n text3 = ('gt Coordinates: x = {0:02f}m y = {1:02f}m z = {2:02f}m'.\n format(float(t_gt[0]), float(t_gt[1]), float(t_gt[2])))\n cv2.putText(traj, text3, textOrg3, cv2.FONT_HERSHEY_PLAIN, 1, (255,\n 255, 255), 1, 8)\n feature_img = cv2.drawKeypoints(currImage_c, kp_curr, None)\n cv2.imshow('trajectory', traj)\n cv2.imshow('feat_img', feature_img)\n cv2.waitKey(1)\n cv2.imwrite('result_{0:02d}.png'.format(SEQ_NUM), traj)\n", "<import token>\norb = cv2.cv2.ORB_create(nfeatures=5000, scaleFactor=1.2, nlevels=8,\n edgeThreshold=31, firstLevel=0, WTA_K=2, scoreType=cv2.ORB_FAST_SCORE,\n patchSize=31, fastThreshold=25)\nbf = cv2.BFMatcher(cv2.NORM_HAMMING)\n\n\ndef getScale(NumFrame, t_gt, seq_num):\n txt_file = open('/media/cordin/새 볼륨/rosbag/dataset/poses/{0:02d}.txt'.\n format(seq_num))\n x_prev = float(t_gt[0])\n y_prev = float(t_gt[1])\n z_prev = float(t_gt[2])\n line = txt_file.readlines()\n line_sp = line[NumFrame].split(' ')\n x = float(line_sp[3])\n y = float(line_sp[7])\n z = float(line_sp[11])\n t_gt[0] = x\n t_gt[1] = y\n t_gt[2] = z\n txt_file.close()\n scale = math.sqrt((x - x_prev) ** 2 + (y - y_prev) ** 2 + (z - z_prev) ** 2\n )\n return scale, t_gt\n\n\nif __name__ == '__main__':\n MAX_FRAME = 1000\n SEQ_NUM = 2\n focal = 718.856\n pp = 607.1928, 185.2157\n textOrg1 = 10, 30\n textOrg2 = 10, 80\n textOrg3 = 10, 130\n img_1_c = cv2.imread(\n '/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/000000.png'\n .format(SEQ_NUM))\n img_2_c = cv2.imread(\n '/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/000001.png'\n .format(SEQ_NUM))\n img_1 = cv2.cvtColor(img_1_c, cv2.COLOR_BGR2GRAY)\n img_2 = cv2.cvtColor(img_2_c, cv2.COLOR_BGR2GRAY)\n kp1, des1 = orb.detectAndCompute(img_1, None)\n kp2, des2 = orb.detectAndCompute(img_2, None)\n matches = bf.match(des1, des2)\n matches = sorted(matches, key=lambda x: x.distance)\n idx = matches[0:1500]\n pts1 = []\n pts2 = []\n for i in idx:\n pts1.append(kp1[i.queryIdx].pt)\n pts2.append(kp2[i.trainIdx].pt)\n pts1 = np.array(pts1)\n pts2 = np.array(pts2)\n E, mask = cv2.findEssentialMat(pts1, pts2, focal=focal, pp=pp, method=\n cv2.RANSAC, prob=0.999, threshold=1.0)\n _, R_f, t_f, _ = cv2.recoverPose(E, pts1, pts2, focal=focal, pp=pp)\n R_f_seg = R_f\n t_f_seg = t_f\n t_gt = np.zeros((3, 1), dtype=np.float64)\n prevImage = img_2\n kp_prev = kp2\n des_prev = des2\n traj = np.zeros((1000, 2000), dtype=np.uint8)\n traj = cv2.cvtColor(traj, cv2.COLOR_GRAY2BGR)\n rmse_total = 0\n for numFrame in range(2, MAX_FRAME):\n filename = (\n '/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/{1:06d}.png'\n .format(SEQ_NUM, numFrame))\n currImage_c = cv2.imread(filename)\n currImage = cv2.cvtColor(currImage_c, cv2.COLOR_BGR2GRAY)\n kp_curr, des_curr = orb.detectAndCompute(currImage, None)\n matches = bf.match(des_prev, des_curr)\n matches = sorted(matches, key=lambda x: x.distance)\n idx = matches[0:1500]\n pts1 = []\n pts2 = []\n for i in idx:\n pts1.append(kp_prev[i.queryIdx].pt)\n pts2.append(kp_curr[i.trainIdx].pt)\n pts1 = np.array(pts1)\n pts2 = np.array(pts2)\n E_mat, mask_n = cv2.findEssentialMat(pts2, pts1, focal=focal, pp=pp,\n method=cv2.RANSAC, prob=0.999, threshold=1.0)\n _, R, t, _ = cv2.recoverPose(E_mat, pts2, pts1, focal=focal, pp=pp)\n abs_scale, t_gt = getScale(numFrame, t_gt, SEQ_NUM)\n t_f = t_f + abs_scale * R_f.dot(t)\n R_f = R.dot(R_f)\n error = map(operator.sub, t_gt, t_f)\n error_sum_square = sum(map(lambda x: x * x, error))\n rmse = math.sqrt(error_sum_square / 3)\n rmse_total = rmse_total + rmse\n print('rmse = ', rmse_total / numFrame)\n prevImage = currImage\n kp_prev = kp_curr\n des_prev = des_curr\n x_gt = int(t_gt[0]) + 1000\n y_gt = int(t_gt[2]) + 100\n x = int(t_f[0]) + 1000\n y = int(t_f[2]) + 100\n cv2.circle(traj, (x, y), 1, (0, 0, 255), 2)\n cv2.circle(traj, (x_gt, y_gt), 1, (0, 255, 0), 2)\n cv2.rectangle(traj, (10, 10), (700, 150), (0, 0, 0), -1)\n text1 = ('orb Coordinates: x = {0:02f}m y = {1:02f}m z = {2:02f}m'.\n format(float(t_f[0]), float(t_f[1]), float(t_f[2])))\n cv2.putText(traj, text1, textOrg1, cv2.FONT_HERSHEY_PLAIN, 1, (255,\n 255, 255), 1, 8)\n text3 = ('gt Coordinates: x = {0:02f}m y = {1:02f}m z = {2:02f}m'.\n format(float(t_gt[0]), float(t_gt[1]), float(t_gt[2])))\n cv2.putText(traj, text3, textOrg3, cv2.FONT_HERSHEY_PLAIN, 1, (255,\n 255, 255), 1, 8)\n feature_img = cv2.drawKeypoints(currImage_c, kp_curr, None)\n cv2.imshow('trajectory', traj)\n cv2.imshow('feat_img', feature_img)\n cv2.waitKey(1)\n cv2.imwrite('result_{0:02d}.png'.format(SEQ_NUM), traj)\n", "<import token>\n<assignment token>\n\n\ndef getScale(NumFrame, t_gt, seq_num):\n txt_file = open('/media/cordin/새 볼륨/rosbag/dataset/poses/{0:02d}.txt'.\n format(seq_num))\n x_prev = float(t_gt[0])\n y_prev = float(t_gt[1])\n z_prev = float(t_gt[2])\n line = txt_file.readlines()\n line_sp = line[NumFrame].split(' ')\n x = float(line_sp[3])\n y = float(line_sp[7])\n z = float(line_sp[11])\n t_gt[0] = x\n t_gt[1] = y\n t_gt[2] = z\n txt_file.close()\n scale = math.sqrt((x - x_prev) ** 2 + (y - y_prev) ** 2 + (z - z_prev) ** 2\n )\n return scale, t_gt\n\n\nif __name__ == '__main__':\n MAX_FRAME = 1000\n SEQ_NUM = 2\n focal = 718.856\n pp = 607.1928, 185.2157\n textOrg1 = 10, 30\n textOrg2 = 10, 80\n textOrg3 = 10, 130\n img_1_c = cv2.imread(\n '/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/000000.png'\n .format(SEQ_NUM))\n img_2_c = cv2.imread(\n '/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/000001.png'\n .format(SEQ_NUM))\n img_1 = cv2.cvtColor(img_1_c, cv2.COLOR_BGR2GRAY)\n img_2 = cv2.cvtColor(img_2_c, cv2.COLOR_BGR2GRAY)\n kp1, des1 = orb.detectAndCompute(img_1, None)\n kp2, des2 = orb.detectAndCompute(img_2, None)\n matches = bf.match(des1, des2)\n matches = sorted(matches, key=lambda x: x.distance)\n idx = matches[0:1500]\n pts1 = []\n pts2 = []\n for i in idx:\n pts1.append(kp1[i.queryIdx].pt)\n pts2.append(kp2[i.trainIdx].pt)\n pts1 = np.array(pts1)\n pts2 = np.array(pts2)\n E, mask = cv2.findEssentialMat(pts1, pts2, focal=focal, pp=pp, method=\n cv2.RANSAC, prob=0.999, threshold=1.0)\n _, R_f, t_f, _ = cv2.recoverPose(E, pts1, pts2, focal=focal, pp=pp)\n R_f_seg = R_f\n t_f_seg = t_f\n t_gt = np.zeros((3, 1), dtype=np.float64)\n prevImage = img_2\n kp_prev = kp2\n des_prev = des2\n traj = np.zeros((1000, 2000), dtype=np.uint8)\n traj = cv2.cvtColor(traj, cv2.COLOR_GRAY2BGR)\n rmse_total = 0\n for numFrame in range(2, MAX_FRAME):\n filename = (\n '/media/cordin/새 볼륨/rosbag/dataset/sequences/{0:02d}/image_0/{1:06d}.png'\n .format(SEQ_NUM, numFrame))\n currImage_c = cv2.imread(filename)\n currImage = cv2.cvtColor(currImage_c, cv2.COLOR_BGR2GRAY)\n kp_curr, des_curr = orb.detectAndCompute(currImage, None)\n matches = bf.match(des_prev, des_curr)\n matches = sorted(matches, key=lambda x: x.distance)\n idx = matches[0:1500]\n pts1 = []\n pts2 = []\n for i in idx:\n pts1.append(kp_prev[i.queryIdx].pt)\n pts2.append(kp_curr[i.trainIdx].pt)\n pts1 = np.array(pts1)\n pts2 = np.array(pts2)\n E_mat, mask_n = cv2.findEssentialMat(pts2, pts1, focal=focal, pp=pp,\n method=cv2.RANSAC, prob=0.999, threshold=1.0)\n _, R, t, _ = cv2.recoverPose(E_mat, pts2, pts1, focal=focal, pp=pp)\n abs_scale, t_gt = getScale(numFrame, t_gt, SEQ_NUM)\n t_f = t_f + abs_scale * R_f.dot(t)\n R_f = R.dot(R_f)\n error = map(operator.sub, t_gt, t_f)\n error_sum_square = sum(map(lambda x: x * x, error))\n rmse = math.sqrt(error_sum_square / 3)\n rmse_total = rmse_total + rmse\n print('rmse = ', rmse_total / numFrame)\n prevImage = currImage\n kp_prev = kp_curr\n des_prev = des_curr\n x_gt = int(t_gt[0]) + 1000\n y_gt = int(t_gt[2]) + 100\n x = int(t_f[0]) + 1000\n y = int(t_f[2]) + 100\n cv2.circle(traj, (x, y), 1, (0, 0, 255), 2)\n cv2.circle(traj, (x_gt, y_gt), 1, (0, 255, 0), 2)\n cv2.rectangle(traj, (10, 10), (700, 150), (0, 0, 0), -1)\n text1 = ('orb Coordinates: x = {0:02f}m y = {1:02f}m z = {2:02f}m'.\n format(float(t_f[0]), float(t_f[1]), float(t_f[2])))\n cv2.putText(traj, text1, textOrg1, cv2.FONT_HERSHEY_PLAIN, 1, (255,\n 255, 255), 1, 8)\n text3 = ('gt Coordinates: x = {0:02f}m y = {1:02f}m z = {2:02f}m'.\n format(float(t_gt[0]), float(t_gt[1]), float(t_gt[2])))\n cv2.putText(traj, text3, textOrg3, cv2.FONT_HERSHEY_PLAIN, 1, (255,\n 255, 255), 1, 8)\n feature_img = cv2.drawKeypoints(currImage_c, kp_curr, None)\n cv2.imshow('trajectory', traj)\n cv2.imshow('feat_img', feature_img)\n cv2.waitKey(1)\n cv2.imwrite('result_{0:02d}.png'.format(SEQ_NUM), traj)\n", "<import token>\n<assignment token>\n\n\ndef getScale(NumFrame, t_gt, seq_num):\n txt_file = open('/media/cordin/새 볼륨/rosbag/dataset/poses/{0:02d}.txt'.\n format(seq_num))\n x_prev = float(t_gt[0])\n y_prev = float(t_gt[1])\n z_prev = float(t_gt[2])\n line = txt_file.readlines()\n line_sp = line[NumFrame].split(' ')\n x = float(line_sp[3])\n y = float(line_sp[7])\n z = float(line_sp[11])\n t_gt[0] = x\n t_gt[1] = y\n t_gt[2] = z\n txt_file.close()\n scale = math.sqrt((x - x_prev) ** 2 + (y - y_prev) ** 2 + (z - z_prev) ** 2\n )\n return scale, t_gt\n\n\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<code token>\n" ]
false
734
d9538c030c0225c4255100da70d6bf23f550a64f
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>) # Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## from osv import osv, fields class SaleOrder(osv.osv): ''' Sale Order ''' _inherit = 'sale.order' _columns = { 'coupon_code':fields.char('Promo Coupon Code', size=20), } def apply_promotions(self, cursor, user, ids, context=None): """ Applies the promotions to the given records @param cursor: Database Cursor @param user: ID of User @param ids: ID of current record. @param context: Context(no direct use). """ promotions_obj = self.pool.get('promos.rules') for order_id in ids: promotions_obj.apply_promotions(cursor, user, order_id, context=None) return True SaleOrder() class SaleOrderLine(osv.osv): ''' Sale Order Line ''' _inherit = "sale.order.line" _columns = { 'promotion_line':fields.boolean( "Promotion Line", help="Indicates if the line was created by promotions" ) } SaleOrderLine() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
[ "# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>)\n# Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>\n#\n##############################################################################\nfrom osv import osv, fields\n\nclass SaleOrder(osv.osv):\n '''\n Sale Order\n '''\n _inherit = 'sale.order'\n \n _columns = {\n 'coupon_code':fields.char('Promo Coupon Code', size=20),\n }\n \n def apply_promotions(self, cursor, user, ids, context=None):\n \"\"\"\n Applies the promotions to the given records\n @param cursor: Database Cursor\n @param user: ID of User\n @param ids: ID of current record.\n @param context: Context(no direct use).\n \"\"\"\n promotions_obj = self.pool.get('promos.rules')\n for order_id in ids:\n promotions_obj.apply_promotions(cursor, user, \n order_id, context=None)\n \n return True\n \nSaleOrder()\n\n\nclass SaleOrderLine(osv.osv):\n '''\n Sale Order Line\n '''\n _inherit = \"sale.order.line\"\n \n _columns = {\n 'promotion_line':fields.boolean(\n \"Promotion Line\",\n help=\"Indicates if the line was created by promotions\"\n )\n }\nSaleOrderLine()\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:", "from osv import osv, fields\n\n\nclass SaleOrder(osv.osv):\n \"\"\"\n Sale Order\n \"\"\"\n _inherit = 'sale.order'\n _columns = {'coupon_code': fields.char('Promo Coupon Code', size=20)}\n\n def apply_promotions(self, cursor, user, ids, context=None):\n \"\"\"\n Applies the promotions to the given records\n @param cursor: Database Cursor\n @param user: ID of User\n @param ids: ID of current record.\n @param context: Context(no direct use).\n \"\"\"\n promotions_obj = self.pool.get('promos.rules')\n for order_id in ids:\n promotions_obj.apply_promotions(cursor, user, order_id, context\n =None)\n return True\n\n\nSaleOrder()\n\n\nclass SaleOrderLine(osv.osv):\n \"\"\"\n Sale Order Line\n \"\"\"\n _inherit = 'sale.order.line'\n _columns = {'promotion_line': fields.boolean('Promotion Line', help=\n 'Indicates if the line was created by promotions')}\n\n\nSaleOrderLine()\n", "<import token>\n\n\nclass SaleOrder(osv.osv):\n \"\"\"\n Sale Order\n \"\"\"\n _inherit = 'sale.order'\n _columns = {'coupon_code': fields.char('Promo Coupon Code', size=20)}\n\n def apply_promotions(self, cursor, user, ids, context=None):\n \"\"\"\n Applies the promotions to the given records\n @param cursor: Database Cursor\n @param user: ID of User\n @param ids: ID of current record.\n @param context: Context(no direct use).\n \"\"\"\n promotions_obj = self.pool.get('promos.rules')\n for order_id in ids:\n promotions_obj.apply_promotions(cursor, user, order_id, context\n =None)\n return True\n\n\nSaleOrder()\n\n\nclass SaleOrderLine(osv.osv):\n \"\"\"\n Sale Order Line\n \"\"\"\n _inherit = 'sale.order.line'\n _columns = {'promotion_line': fields.boolean('Promotion Line', help=\n 'Indicates if the line was created by promotions')}\n\n\nSaleOrderLine()\n", "<import token>\n\n\nclass SaleOrder(osv.osv):\n \"\"\"\n Sale Order\n \"\"\"\n _inherit = 'sale.order'\n _columns = {'coupon_code': fields.char('Promo Coupon Code', size=20)}\n\n def apply_promotions(self, cursor, user, ids, context=None):\n \"\"\"\n Applies the promotions to the given records\n @param cursor: Database Cursor\n @param user: ID of User\n @param ids: ID of current record.\n @param context: Context(no direct use).\n \"\"\"\n promotions_obj = self.pool.get('promos.rules')\n for order_id in ids:\n promotions_obj.apply_promotions(cursor, user, order_id, context\n =None)\n return True\n\n\n<code token>\n\n\nclass SaleOrderLine(osv.osv):\n \"\"\"\n Sale Order Line\n \"\"\"\n _inherit = 'sale.order.line'\n _columns = {'promotion_line': fields.boolean('Promotion Line', help=\n 'Indicates if the line was created by promotions')}\n\n\n<code token>\n", "<import token>\n\n\nclass SaleOrder(osv.osv):\n <docstring token>\n _inherit = 'sale.order'\n _columns = {'coupon_code': fields.char('Promo Coupon Code', size=20)}\n\n def apply_promotions(self, cursor, user, ids, context=None):\n \"\"\"\n Applies the promotions to the given records\n @param cursor: Database Cursor\n @param user: ID of User\n @param ids: ID of current record.\n @param context: Context(no direct use).\n \"\"\"\n promotions_obj = self.pool.get('promos.rules')\n for order_id in ids:\n promotions_obj.apply_promotions(cursor, user, order_id, context\n =None)\n return True\n\n\n<code token>\n\n\nclass SaleOrderLine(osv.osv):\n \"\"\"\n Sale Order Line\n \"\"\"\n _inherit = 'sale.order.line'\n _columns = {'promotion_line': fields.boolean('Promotion Line', help=\n 'Indicates if the line was created by promotions')}\n\n\n<code token>\n", "<import token>\n\n\nclass SaleOrder(osv.osv):\n <docstring token>\n <assignment token>\n <assignment token>\n\n def apply_promotions(self, cursor, user, ids, context=None):\n \"\"\"\n Applies the promotions to the given records\n @param cursor: Database Cursor\n @param user: ID of User\n @param ids: ID of current record.\n @param context: Context(no direct use).\n \"\"\"\n promotions_obj = self.pool.get('promos.rules')\n for order_id in ids:\n promotions_obj.apply_promotions(cursor, user, order_id, context\n =None)\n return True\n\n\n<code token>\n\n\nclass SaleOrderLine(osv.osv):\n \"\"\"\n Sale Order Line\n \"\"\"\n _inherit = 'sale.order.line'\n _columns = {'promotion_line': fields.boolean('Promotion Line', help=\n 'Indicates if the line was created by promotions')}\n\n\n<code token>\n", "<import token>\n\n\nclass SaleOrder(osv.osv):\n <docstring token>\n <assignment token>\n <assignment token>\n <function token>\n\n\n<code token>\n\n\nclass SaleOrderLine(osv.osv):\n \"\"\"\n Sale Order Line\n \"\"\"\n _inherit = 'sale.order.line'\n _columns = {'promotion_line': fields.boolean('Promotion Line', help=\n 'Indicates if the line was created by promotions')}\n\n\n<code token>\n", "<import token>\n<class token>\n<code token>\n\n\nclass SaleOrderLine(osv.osv):\n \"\"\"\n Sale Order Line\n \"\"\"\n _inherit = 'sale.order.line'\n _columns = {'promotion_line': fields.boolean('Promotion Line', help=\n 'Indicates if the line was created by promotions')}\n\n\n<code token>\n", "<import token>\n<class token>\n<code token>\n\n\nclass SaleOrderLine(osv.osv):\n <docstring token>\n _inherit = 'sale.order.line'\n _columns = {'promotion_line': fields.boolean('Promotion Line', help=\n 'Indicates if the line was created by promotions')}\n\n\n<code token>\n", "<import token>\n<class token>\n<code token>\n\n\nclass SaleOrderLine(osv.osv):\n <docstring token>\n <assignment token>\n <assignment token>\n\n\n<code token>\n", "<import token>\n<class token>\n<code token>\n<class token>\n<code token>\n" ]
false
735
eb558644283d992af2c324d457dbe674b714235f
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import JsonResponse from knowdb.models import Knowledge import random # Create your views here. def answer(request): ret = {} data = Knowledge.objects.all() num = random.choice(range(1,int(data.count())+1)) ret['name'] = data[num-1].name ret['answer'] = data[num-1].answer print ret return JsonResponse({'exec':'true','ret':ret}) def edit(request): name = request.POST.get('name') answer = request.POST.get('answer') print name,answer try: adddata = Knowledge(name=name,answer=answer) adddata.save() return JsonResponse({'exec':'true','ret':'提交成功'}) except Exception as e: return JsonResponse({'exec':'false','ret':'提交失败'})
[ "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\nfrom django.http import JsonResponse\nfrom knowdb.models import Knowledge\n\nimport random\n# Create your views here.\n\ndef answer(request):\n ret = {}\n data = Knowledge.objects.all()\n num = random.choice(range(1,int(data.count())+1))\n ret['name'] = data[num-1].name\n ret['answer'] = data[num-1].answer\n print ret\n return JsonResponse({'exec':'true','ret':ret})\n\n\n\ndef edit(request):\n name = request.POST.get('name')\n answer = request.POST.get('answer')\n print name,answer\n try:\n adddata = Knowledge(name=name,answer=answer)\n adddata.save()\n return JsonResponse({'exec':'true','ret':'提交成功'})\n except Exception as e:\n return JsonResponse({'exec':'false','ret':'提交失败'})\n" ]
true
736
40b6d62f1e360c0df19b7e98fcb67dbd578e709f
#!/usr/bin/python # -*- coding: utf-8 -*- import csv from collections import defaultdict from docopt import docopt __doc__ = """{f} Usage: {f} <used_file> {f} -h | --help Options: -h --help Show this screen and exit. """.format(f=__file__) args = docopt(__doc__) used_file = args['<used_file>'] exceed_list = [] user_limit_dict = defaultdict(float) user_limit_f = open('/opt/uge/Accounting_Statistics/etc/user_limit_py.csv', 'r') reader = csv.reader(user_limit_f) header = next(reader) for row in reader: user_limit_dict[row[0]] = float(row[1]) print user_limit_dict used_f = open(used_file, 'r') reader = csv.DictReader(used_f) for row in reader: print row
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport csv\nfrom collections import defaultdict\nfrom docopt import docopt\n\n__doc__ = \"\"\"{f}\n\nUsage:\n {f} <used_file>\n {f} -h | --help\n\nOptions:\n -h --help Show this screen and exit.\n\"\"\".format(f=__file__)\n\nargs = docopt(__doc__)\nused_file = args['<used_file>']\n\nexceed_list = []\n\nuser_limit_dict = defaultdict(float)\n\nuser_limit_f = open('/opt/uge/Accounting_Statistics/etc/user_limit_py.csv', 'r')\n\nreader = csv.reader(user_limit_f)\nheader = next(reader)\nfor row in reader:\n user_limit_dict[row[0]] = float(row[1])\n\nprint user_limit_dict\n\n\nused_f = open(used_file, 'r')\n\nreader = csv.DictReader(used_f)\nfor row in reader:\n print row\n" ]
true
737
4e8a5b0ba13921fb88d5d6371d50e7120ab01265
from metricsManager import MetricsManager def TestDrawGraphs(): manager = MetricsManager() manager.displayMetricsGraph() return def main(): TestDrawGraphs() if __name__ == "__main__": main()
[ "from metricsManager import MetricsManager\n\n\ndef TestDrawGraphs():\n manager = MetricsManager()\n manager.displayMetricsGraph()\n return\n\n\ndef main():\n TestDrawGraphs()\n\n\nif __name__ == \"__main__\":\n main()\n", "from metricsManager import MetricsManager\n\n\ndef TestDrawGraphs():\n manager = MetricsManager()\n manager.displayMetricsGraph()\n return\n\n\ndef main():\n TestDrawGraphs()\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n\n\ndef TestDrawGraphs():\n manager = MetricsManager()\n manager.displayMetricsGraph()\n return\n\n\ndef main():\n TestDrawGraphs()\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n\n\ndef TestDrawGraphs():\n manager = MetricsManager()\n manager.displayMetricsGraph()\n return\n\n\ndef main():\n TestDrawGraphs()\n\n\n<code token>\n", "<import token>\n\n\ndef TestDrawGraphs():\n manager = MetricsManager()\n manager.displayMetricsGraph()\n return\n\n\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<code token>\n" ]
false
738
f1f708f00e05941c9a18a24b9a7556558583c3c7
TRAIN_INPUT_PATH = "~/Projects/competitions/titanic/data/train.csv" TEST_INPUT_PATH = "~/Projects/competitions/titanic/data/test.csv" OUTPUT_PATH = "output/" TRAIN_VAL_SPLIT = 0.75 RANDOM_SEED = 42 MODEL = "LOGISTIC_REGRESSION" LOG_PATH = "logs/"
[ "TRAIN_INPUT_PATH = \"~/Projects/competitions/titanic/data/train.csv\"\nTEST_INPUT_PATH = \"~/Projects/competitions/titanic/data/test.csv\"\nOUTPUT_PATH = \"output/\"\nTRAIN_VAL_SPLIT = 0.75\nRANDOM_SEED = 42\nMODEL = \"LOGISTIC_REGRESSION\"\nLOG_PATH = \"logs/\"\n", "TRAIN_INPUT_PATH = '~/Projects/competitions/titanic/data/train.csv'\nTEST_INPUT_PATH = '~/Projects/competitions/titanic/data/test.csv'\nOUTPUT_PATH = 'output/'\nTRAIN_VAL_SPLIT = 0.75\nRANDOM_SEED = 42\nMODEL = 'LOGISTIC_REGRESSION'\nLOG_PATH = 'logs/'\n", "<assignment token>\n" ]
false
739
911631e96d21bdf22a219007f1bdc04a5e6965dc
__author__ = 'Administrator' # 抓取IP的主要逻辑 from urllib import request import urllib.parse import logging from multiprocessing import pool from time import sleep import random from lxml import etree def getRandomUserAgnet(): user_agents=[ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360S" ] userAgent=random.choice(user_agents) return userAgent def getProxies(): proxies=[] for i in range(1,10): url="http://www.xicidaili.com/nn/{0}".format(i) userAgent=getRandomUserAgnet() headers={"User-Agent":userAgent} opener=urllib.request.build_opener() opener.addheaders=[headers] try: data=opener.open(url,timeout=5).read() sleep(3) except Exception as e: logging.debug(e) selector=etree.HTML(data) ip_addr=selector.xpath("//tr[@class='odd']/td[2]/text()") port=selector.xpath("//tr[@class='odd']/td[3]/text()") sur_time=selector.xpath("//tr[@class='odd']/td[9]/text()") ver_time=selector.xpath("//tr[@class='odd']/td[10]/text()") for j in range(len(ip_addr)): ip=ip_addr[j]+":"+port[j] proxies.append(ip) return proxies def verify_ip(currentIp): tmp_proxies=[] testUrl="http://www.baidu.com" userAgent=getRandomUserAgnet() proxy_support=urllib.request.ProxyHandler({"http":currentIp}) opener=urllib.request.build_opener(proxy_support) opener.addheaders=[("User-Agent",userAgent)] urllib.request.install_opener(opener) try: res=urllib.request.urlopen(testUrl,timeout=5).read() if len(res)!=0: tmp_proxies.append(currentIp) except urllib.error.URLError as er2: if hasattr(er2,'code'): logging.debug("unvalid ipaddress"+currentIp+str(er2.code)) if hasattr(er2,"reason"): logging.debug("reason is the "+currentIp+str(er2.reason)) except Exception as er: logging.debug(er) sleep(2) return tmp_proxies if __name__=="__main__": getProxies()
[ "__author__ = 'Administrator'\n# 抓取IP的主要逻辑\nfrom urllib import request\nimport urllib.parse\nimport logging\nfrom multiprocessing import pool\nfrom time import sleep\nimport random\nfrom lxml import etree\ndef getRandomUserAgnet():\n user_agents=[\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360S\"\n ]\n userAgent=random.choice(user_agents)\n return userAgent\ndef getProxies():\n proxies=[]\n for i in range(1,10):\n url=\"http://www.xicidaili.com/nn/{0}\".format(i)\n userAgent=getRandomUserAgnet()\n headers={\"User-Agent\":userAgent}\n opener=urllib.request.build_opener()\n opener.addheaders=[headers]\n try:\n data=opener.open(url,timeout=5).read()\n sleep(3)\n except Exception as e:\n logging.debug(e)\n selector=etree.HTML(data)\n ip_addr=selector.xpath(\"//tr[@class='odd']/td[2]/text()\")\n port=selector.xpath(\"//tr[@class='odd']/td[3]/text()\")\n sur_time=selector.xpath(\"//tr[@class='odd']/td[9]/text()\")\n ver_time=selector.xpath(\"//tr[@class='odd']/td[10]/text()\")\n for j in range(len(ip_addr)):\n ip=ip_addr[j]+\":\"+port[j]\n proxies.append(ip)\n return proxies\ndef verify_ip(currentIp):\n tmp_proxies=[]\n testUrl=\"http://www.baidu.com\"\n userAgent=getRandomUserAgnet()\n proxy_support=urllib.request.ProxyHandler({\"http\":currentIp})\n opener=urllib.request.build_opener(proxy_support)\n opener.addheaders=[(\"User-Agent\",userAgent)]\n urllib.request.install_opener(opener)\n try:\n res=urllib.request.urlopen(testUrl,timeout=5).read()\n if len(res)!=0:\n tmp_proxies.append(currentIp)\n except urllib.error.URLError as er2:\n if hasattr(er2,'code'):\n logging.debug(\"unvalid ipaddress\"+currentIp+str(er2.code))\n if hasattr(er2,\"reason\"):\n logging.debug(\"reason is the \"+currentIp+str(er2.reason))\n except Exception as er:\n logging.debug(er)\n sleep(2)\n return tmp_proxies\nif __name__==\"__main__\":\n getProxies()\n", "__author__ = 'Administrator'\nfrom urllib import request\nimport urllib.parse\nimport logging\nfrom multiprocessing import pool\nfrom time import sleep\nimport random\nfrom lxml import etree\n\n\ndef getRandomUserAgnet():\n user_agents = [\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360S'\n ]\n userAgent = random.choice(user_agents)\n return userAgent\n\n\ndef getProxies():\n proxies = []\n for i in range(1, 10):\n url = 'http://www.xicidaili.com/nn/{0}'.format(i)\n userAgent = getRandomUserAgnet()\n headers = {'User-Agent': userAgent}\n opener = urllib.request.build_opener()\n opener.addheaders = [headers]\n try:\n data = opener.open(url, timeout=5).read()\n sleep(3)\n except Exception as e:\n logging.debug(e)\n selector = etree.HTML(data)\n ip_addr = selector.xpath(\"//tr[@class='odd']/td[2]/text()\")\n port = selector.xpath(\"//tr[@class='odd']/td[3]/text()\")\n sur_time = selector.xpath(\"//tr[@class='odd']/td[9]/text()\")\n ver_time = selector.xpath(\"//tr[@class='odd']/td[10]/text()\")\n for j in range(len(ip_addr)):\n ip = ip_addr[j] + ':' + port[j]\n proxies.append(ip)\n return proxies\n\n\ndef verify_ip(currentIp):\n tmp_proxies = []\n testUrl = 'http://www.baidu.com'\n userAgent = getRandomUserAgnet()\n proxy_support = urllib.request.ProxyHandler({'http': currentIp})\n opener = urllib.request.build_opener(proxy_support)\n opener.addheaders = [('User-Agent', userAgent)]\n urllib.request.install_opener(opener)\n try:\n res = urllib.request.urlopen(testUrl, timeout=5).read()\n if len(res) != 0:\n tmp_proxies.append(currentIp)\n except urllib.error.URLError as er2:\n if hasattr(er2, 'code'):\n logging.debug('unvalid ipaddress' + currentIp + str(er2.code))\n if hasattr(er2, 'reason'):\n logging.debug('reason is the ' + currentIp + str(er2.reason))\n except Exception as er:\n logging.debug(er)\n sleep(2)\n return tmp_proxies\n\n\nif __name__ == '__main__':\n getProxies()\n", "__author__ = 'Administrator'\n<import token>\n\n\ndef getRandomUserAgnet():\n user_agents = [\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360S'\n ]\n userAgent = random.choice(user_agents)\n return userAgent\n\n\ndef getProxies():\n proxies = []\n for i in range(1, 10):\n url = 'http://www.xicidaili.com/nn/{0}'.format(i)\n userAgent = getRandomUserAgnet()\n headers = {'User-Agent': userAgent}\n opener = urllib.request.build_opener()\n opener.addheaders = [headers]\n try:\n data = opener.open(url, timeout=5).read()\n sleep(3)\n except Exception as e:\n logging.debug(e)\n selector = etree.HTML(data)\n ip_addr = selector.xpath(\"//tr[@class='odd']/td[2]/text()\")\n port = selector.xpath(\"//tr[@class='odd']/td[3]/text()\")\n sur_time = selector.xpath(\"//tr[@class='odd']/td[9]/text()\")\n ver_time = selector.xpath(\"//tr[@class='odd']/td[10]/text()\")\n for j in range(len(ip_addr)):\n ip = ip_addr[j] + ':' + port[j]\n proxies.append(ip)\n return proxies\n\n\ndef verify_ip(currentIp):\n tmp_proxies = []\n testUrl = 'http://www.baidu.com'\n userAgent = getRandomUserAgnet()\n proxy_support = urllib.request.ProxyHandler({'http': currentIp})\n opener = urllib.request.build_opener(proxy_support)\n opener.addheaders = [('User-Agent', userAgent)]\n urllib.request.install_opener(opener)\n try:\n res = urllib.request.urlopen(testUrl, timeout=5).read()\n if len(res) != 0:\n tmp_proxies.append(currentIp)\n except urllib.error.URLError as er2:\n if hasattr(er2, 'code'):\n logging.debug('unvalid ipaddress' + currentIp + str(er2.code))\n if hasattr(er2, 'reason'):\n logging.debug('reason is the ' + currentIp + str(er2.reason))\n except Exception as er:\n logging.debug(er)\n sleep(2)\n return tmp_proxies\n\n\nif __name__ == '__main__':\n getProxies()\n", "<assignment token>\n<import token>\n\n\ndef getRandomUserAgnet():\n user_agents = [\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360S'\n ]\n userAgent = random.choice(user_agents)\n return userAgent\n\n\ndef getProxies():\n proxies = []\n for i in range(1, 10):\n url = 'http://www.xicidaili.com/nn/{0}'.format(i)\n userAgent = getRandomUserAgnet()\n headers = {'User-Agent': userAgent}\n opener = urllib.request.build_opener()\n opener.addheaders = [headers]\n try:\n data = opener.open(url, timeout=5).read()\n sleep(3)\n except Exception as e:\n logging.debug(e)\n selector = etree.HTML(data)\n ip_addr = selector.xpath(\"//tr[@class='odd']/td[2]/text()\")\n port = selector.xpath(\"//tr[@class='odd']/td[3]/text()\")\n sur_time = selector.xpath(\"//tr[@class='odd']/td[9]/text()\")\n ver_time = selector.xpath(\"//tr[@class='odd']/td[10]/text()\")\n for j in range(len(ip_addr)):\n ip = ip_addr[j] + ':' + port[j]\n proxies.append(ip)\n return proxies\n\n\ndef verify_ip(currentIp):\n tmp_proxies = []\n testUrl = 'http://www.baidu.com'\n userAgent = getRandomUserAgnet()\n proxy_support = urllib.request.ProxyHandler({'http': currentIp})\n opener = urllib.request.build_opener(proxy_support)\n opener.addheaders = [('User-Agent', userAgent)]\n urllib.request.install_opener(opener)\n try:\n res = urllib.request.urlopen(testUrl, timeout=5).read()\n if len(res) != 0:\n tmp_proxies.append(currentIp)\n except urllib.error.URLError as er2:\n if hasattr(er2, 'code'):\n logging.debug('unvalid ipaddress' + currentIp + str(er2.code))\n if hasattr(er2, 'reason'):\n logging.debug('reason is the ' + currentIp + str(er2.reason))\n except Exception as er:\n logging.debug(er)\n sleep(2)\n return tmp_proxies\n\n\nif __name__ == '__main__':\n getProxies()\n", "<assignment token>\n<import token>\n\n\ndef getRandomUserAgnet():\n user_agents = [\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360S'\n ]\n userAgent = random.choice(user_agents)\n return userAgent\n\n\ndef getProxies():\n proxies = []\n for i in range(1, 10):\n url = 'http://www.xicidaili.com/nn/{0}'.format(i)\n userAgent = getRandomUserAgnet()\n headers = {'User-Agent': userAgent}\n opener = urllib.request.build_opener()\n opener.addheaders = [headers]\n try:\n data = opener.open(url, timeout=5).read()\n sleep(3)\n except Exception as e:\n logging.debug(e)\n selector = etree.HTML(data)\n ip_addr = selector.xpath(\"//tr[@class='odd']/td[2]/text()\")\n port = selector.xpath(\"//tr[@class='odd']/td[3]/text()\")\n sur_time = selector.xpath(\"//tr[@class='odd']/td[9]/text()\")\n ver_time = selector.xpath(\"//tr[@class='odd']/td[10]/text()\")\n for j in range(len(ip_addr)):\n ip = ip_addr[j] + ':' + port[j]\n proxies.append(ip)\n return proxies\n\n\ndef verify_ip(currentIp):\n tmp_proxies = []\n testUrl = 'http://www.baidu.com'\n userAgent = getRandomUserAgnet()\n proxy_support = urllib.request.ProxyHandler({'http': currentIp})\n opener = urllib.request.build_opener(proxy_support)\n opener.addheaders = [('User-Agent', userAgent)]\n urllib.request.install_opener(opener)\n try:\n res = urllib.request.urlopen(testUrl, timeout=5).read()\n if len(res) != 0:\n tmp_proxies.append(currentIp)\n except urllib.error.URLError as er2:\n if hasattr(er2, 'code'):\n logging.debug('unvalid ipaddress' + currentIp + str(er2.code))\n if hasattr(er2, 'reason'):\n logging.debug('reason is the ' + currentIp + str(er2.reason))\n except Exception as er:\n logging.debug(er)\n sleep(2)\n return tmp_proxies\n\n\n<code token>\n", "<assignment token>\n<import token>\n\n\ndef getRandomUserAgnet():\n user_agents = [\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360S'\n ]\n userAgent = random.choice(user_agents)\n return userAgent\n\n\ndef getProxies():\n proxies = []\n for i in range(1, 10):\n url = 'http://www.xicidaili.com/nn/{0}'.format(i)\n userAgent = getRandomUserAgnet()\n headers = {'User-Agent': userAgent}\n opener = urllib.request.build_opener()\n opener.addheaders = [headers]\n try:\n data = opener.open(url, timeout=5).read()\n sleep(3)\n except Exception as e:\n logging.debug(e)\n selector = etree.HTML(data)\n ip_addr = selector.xpath(\"//tr[@class='odd']/td[2]/text()\")\n port = selector.xpath(\"//tr[@class='odd']/td[3]/text()\")\n sur_time = selector.xpath(\"//tr[@class='odd']/td[9]/text()\")\n ver_time = selector.xpath(\"//tr[@class='odd']/td[10]/text()\")\n for j in range(len(ip_addr)):\n ip = ip_addr[j] + ':' + port[j]\n proxies.append(ip)\n return proxies\n\n\n<function token>\n<code token>\n", "<assignment token>\n<import token>\n<function token>\n\n\ndef getProxies():\n proxies = []\n for i in range(1, 10):\n url = 'http://www.xicidaili.com/nn/{0}'.format(i)\n userAgent = getRandomUserAgnet()\n headers = {'User-Agent': userAgent}\n opener = urllib.request.build_opener()\n opener.addheaders = [headers]\n try:\n data = opener.open(url, timeout=5).read()\n sleep(3)\n except Exception as e:\n logging.debug(e)\n selector = etree.HTML(data)\n ip_addr = selector.xpath(\"//tr[@class='odd']/td[2]/text()\")\n port = selector.xpath(\"//tr[@class='odd']/td[3]/text()\")\n sur_time = selector.xpath(\"//tr[@class='odd']/td[9]/text()\")\n ver_time = selector.xpath(\"//tr[@class='odd']/td[10]/text()\")\n for j in range(len(ip_addr)):\n ip = ip_addr[j] + ':' + port[j]\n proxies.append(ip)\n return proxies\n\n\n<function token>\n<code token>\n", "<assignment token>\n<import token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
740
bc890f0f40a7e9c916628d491e473b5ecfa9bb9b
from random import random import numpy as np class TemperatureSensor: sensor_type = "temperature" unit="celsius" instance_id="283h62gsj" #initialisation def __init__(self, average_temperature, temperature_variation, min_temperature, max_temperature): self.average_temperature = average_temperature self.temperature_variation = temperature_variation self.min_temperature = min_temperature self.max_temperature= max_temperature self.value = 0.0 #initialise current temp value #sensing def sense(self): #self.value = self.value + self.simple_random() self.value = self.complex_random() + self.noise() return self.value #noise def noise(self): self.noise_value = np.random.normal(0,1) return self.noise_value #helper function for generating values with min temp as its base def simple_random(self): value = self.min_temperature + (random() * (self.max_temperature - self.min_temperature)) #so that it is in the range return value def complex_random(self): value = self.average_temperature * (1 + (self.temperature_variation/100) * (1 * random() -1)) value = max(value,self.min_temperature) value = min(value,self.max_temperature) return value #creating instance of sensor ts = TemperatureSensor(25,10,16,35)
[ "from random import random\r\n\r\nimport numpy as np\r\n\r\nclass TemperatureSensor:\r\n sensor_type = \"temperature\"\r\n unit=\"celsius\"\r\n instance_id=\"283h62gsj\"\r\n \r\n #initialisation\r\n \r\n def __init__(self, average_temperature, temperature_variation, min_temperature, max_temperature):\r\n self.average_temperature = average_temperature\r\n self.temperature_variation = temperature_variation\r\n self.min_temperature = min_temperature \r\n self.max_temperature= max_temperature\r\n self.value = 0.0 #initialise current temp value\r\n \r\n #sensing \r\n def sense(self):\r\n #self.value = self.value + self.simple_random()\r\n self.value = self.complex_random() + self.noise()\r\n return self.value\r\n \r\n #noise\r\n def noise(self):\r\n self.noise_value = np.random.normal(0,1)\r\n return self.noise_value\r\n \r\n #helper function for generating values with min temp as its base\r\n def simple_random(self):\r\n value = self.min_temperature + (random() * (self.max_temperature - self.min_temperature)) #so that it is in the range\r\n return value\r\n \r\n def complex_random(self):\r\n value = self.average_temperature * (1 + (self.temperature_variation/100) * (1 * random() -1))\r\n value = max(value,self.min_temperature)\r\n value = min(value,self.max_temperature)\r\n return value\r\n \r\n#creating instance of sensor\r\nts = TemperatureSensor(25,10,16,35)\r\n\r\n", "from random import random\nimport numpy as np\n\n\nclass TemperatureSensor:\n sensor_type = 'temperature'\n unit = 'celsius'\n instance_id = '283h62gsj'\n\n def __init__(self, average_temperature, temperature_variation,\n min_temperature, max_temperature):\n self.average_temperature = average_temperature\n self.temperature_variation = temperature_variation\n self.min_temperature = min_temperature\n self.max_temperature = max_temperature\n self.value = 0.0\n\n def sense(self):\n self.value = self.complex_random() + self.noise()\n return self.value\n\n def noise(self):\n self.noise_value = np.random.normal(0, 1)\n return self.noise_value\n\n def simple_random(self):\n value = self.min_temperature + random() * (self.max_temperature -\n self.min_temperature)\n return value\n\n def complex_random(self):\n value = self.average_temperature * (1 + self.temperature_variation /\n 100 * (1 * random() - 1))\n value = max(value, self.min_temperature)\n value = min(value, self.max_temperature)\n return value\n\n\nts = TemperatureSensor(25, 10, 16, 35)\n", "<import token>\n\n\nclass TemperatureSensor:\n sensor_type = 'temperature'\n unit = 'celsius'\n instance_id = '283h62gsj'\n\n def __init__(self, average_temperature, temperature_variation,\n min_temperature, max_temperature):\n self.average_temperature = average_temperature\n self.temperature_variation = temperature_variation\n self.min_temperature = min_temperature\n self.max_temperature = max_temperature\n self.value = 0.0\n\n def sense(self):\n self.value = self.complex_random() + self.noise()\n return self.value\n\n def noise(self):\n self.noise_value = np.random.normal(0, 1)\n return self.noise_value\n\n def simple_random(self):\n value = self.min_temperature + random() * (self.max_temperature -\n self.min_temperature)\n return value\n\n def complex_random(self):\n value = self.average_temperature * (1 + self.temperature_variation /\n 100 * (1 * random() - 1))\n value = max(value, self.min_temperature)\n value = min(value, self.max_temperature)\n return value\n\n\nts = TemperatureSensor(25, 10, 16, 35)\n", "<import token>\n\n\nclass TemperatureSensor:\n sensor_type = 'temperature'\n unit = 'celsius'\n instance_id = '283h62gsj'\n\n def __init__(self, average_temperature, temperature_variation,\n min_temperature, max_temperature):\n self.average_temperature = average_temperature\n self.temperature_variation = temperature_variation\n self.min_temperature = min_temperature\n self.max_temperature = max_temperature\n self.value = 0.0\n\n def sense(self):\n self.value = self.complex_random() + self.noise()\n return self.value\n\n def noise(self):\n self.noise_value = np.random.normal(0, 1)\n return self.noise_value\n\n def simple_random(self):\n value = self.min_temperature + random() * (self.max_temperature -\n self.min_temperature)\n return value\n\n def complex_random(self):\n value = self.average_temperature * (1 + self.temperature_variation /\n 100 * (1 * random() - 1))\n value = max(value, self.min_temperature)\n value = min(value, self.max_temperature)\n return value\n\n\n<assignment token>\n", "<import token>\n\n\nclass TemperatureSensor:\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, average_temperature, temperature_variation,\n min_temperature, max_temperature):\n self.average_temperature = average_temperature\n self.temperature_variation = temperature_variation\n self.min_temperature = min_temperature\n self.max_temperature = max_temperature\n self.value = 0.0\n\n def sense(self):\n self.value = self.complex_random() + self.noise()\n return self.value\n\n def noise(self):\n self.noise_value = np.random.normal(0, 1)\n return self.noise_value\n\n def simple_random(self):\n value = self.min_temperature + random() * (self.max_temperature -\n self.min_temperature)\n return value\n\n def complex_random(self):\n value = self.average_temperature * (1 + self.temperature_variation /\n 100 * (1 * random() - 1))\n value = max(value, self.min_temperature)\n value = min(value, self.max_temperature)\n return value\n\n\n<assignment token>\n", "<import token>\n\n\nclass TemperatureSensor:\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, average_temperature, temperature_variation,\n min_temperature, max_temperature):\n self.average_temperature = average_temperature\n self.temperature_variation = temperature_variation\n self.min_temperature = min_temperature\n self.max_temperature = max_temperature\n self.value = 0.0\n\n def sense(self):\n self.value = self.complex_random() + self.noise()\n return self.value\n <function token>\n\n def simple_random(self):\n value = self.min_temperature + random() * (self.max_temperature -\n self.min_temperature)\n return value\n\n def complex_random(self):\n value = self.average_temperature * (1 + self.temperature_variation /\n 100 * (1 * random() - 1))\n value = max(value, self.min_temperature)\n value = min(value, self.max_temperature)\n return value\n\n\n<assignment token>\n", "<import token>\n\n\nclass TemperatureSensor:\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n def sense(self):\n self.value = self.complex_random() + self.noise()\n return self.value\n <function token>\n\n def simple_random(self):\n value = self.min_temperature + random() * (self.max_temperature -\n self.min_temperature)\n return value\n\n def complex_random(self):\n value = self.average_temperature * (1 + self.temperature_variation /\n 100 * (1 * random() - 1))\n value = max(value, self.min_temperature)\n value = min(value, self.max_temperature)\n return value\n\n\n<assignment token>\n", "<import token>\n\n\nclass TemperatureSensor:\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n def sense(self):\n self.value = self.complex_random() + self.noise()\n return self.value\n <function token>\n <function token>\n\n def complex_random(self):\n value = self.average_temperature * (1 + self.temperature_variation /\n 100 * (1 * random() - 1))\n value = max(value, self.min_temperature)\n value = min(value, self.max_temperature)\n return value\n\n\n<assignment token>\n", "<import token>\n\n\nclass TemperatureSensor:\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def complex_random(self):\n value = self.average_temperature * (1 + self.temperature_variation /\n 100 * (1 * random() - 1))\n value = max(value, self.min_temperature)\n value = min(value, self.max_temperature)\n return value\n\n\n<assignment token>\n", "<import token>\n\n\nclass TemperatureSensor:\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<assignment token>\n", "<import token>\n<class token>\n<assignment token>\n" ]
false
741
fe597ad4462b1af3f3f99346c759c5fa8a7c14f4
def check_ip_or_mask(temp_str): IPv4_regex = (r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}') temp_list_ip_mask = re.findall(IPv4_regex, temp_str) binary_temp_list_ip_mask = [] temp_binary_ip_mask = '' for x in range(len(temp_list_ip_mask)): split_ip_address = re.split(r'\.', temp_list_ip_mask[x]) for y in range(len(split_ip_address)): temp_binary_ip_mask += str(bin(int(split_ip_address[y]))[2:].zfill(8)) binary_temp_list_ip_mask.append(temp_binary_ip_mask) temp_binary_ip_mask = '' ip_index_list = [] mask_index_list = [] for x in range(2): if not re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]): ip_index_list.append(x) if re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]): mask_index_list.append(x) if len(ip_index_list) == 1 and len(mask_index_list) == 1: ipv4 = temp_list_ip_mask[int(ip_index_list[0])] net_mask = temp_list_ip_mask[int(mask_index_list[0])] else: if (binary_temp_list_ip_mask[0].count('1')) < (binary_temp_list_ip_mask[0].count('1')): ipv4 = temp_list_ip_mask[0] net_mask = temp_list_ip_mask[1] else: ipv4 = temp_list_ip_mask[1] net_mask = temp_list_ip_mask[0] return "IPv4: " + ipv4 + "\n" + "Net mask: " + net_mask
[ "def check_ip_or_mask(temp_str):\n IPv4_regex = (r'(?:[0-9]{1,3}\\.){3}[0-9]{1,3}')\n temp_list_ip_mask = re.findall(IPv4_regex, temp_str)\n binary_temp_list_ip_mask = []\n temp_binary_ip_mask = ''\n for x in range(len(temp_list_ip_mask)):\n split_ip_address = re.split(r'\\.', temp_list_ip_mask[x])\n for y in range(len(split_ip_address)):\n temp_binary_ip_mask += str(bin(int(split_ip_address[y]))[2:].zfill(8))\n binary_temp_list_ip_mask.append(temp_binary_ip_mask)\n temp_binary_ip_mask = ''\n ip_index_list = []\n mask_index_list = []\n for x in range(2):\n if not re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n ip_index_list.append(x)\n if re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n mask_index_list.append(x)\n if len(ip_index_list) == 1 and len(mask_index_list) == 1:\n ipv4 = temp_list_ip_mask[int(ip_index_list[0])]\n net_mask = temp_list_ip_mask[int(mask_index_list[0])]\n else:\n if (binary_temp_list_ip_mask[0].count('1')) < (binary_temp_list_ip_mask[0].count('1')):\n ipv4 = temp_list_ip_mask[0]\n net_mask = temp_list_ip_mask[1]\n else:\n ipv4 = temp_list_ip_mask[1]\n net_mask = temp_list_ip_mask[0]\n\n return \"IPv4: \" + ipv4 + \"\\n\" + \"Net mask: \" + net_mask\n", "def check_ip_or_mask(temp_str):\n IPv4_regex = '(?:[0-9]{1,3}\\\\.){3}[0-9]{1,3}'\n temp_list_ip_mask = re.findall(IPv4_regex, temp_str)\n binary_temp_list_ip_mask = []\n temp_binary_ip_mask = ''\n for x in range(len(temp_list_ip_mask)):\n split_ip_address = re.split('\\\\.', temp_list_ip_mask[x])\n for y in range(len(split_ip_address)):\n temp_binary_ip_mask += str(bin(int(split_ip_address[y]))[2:].\n zfill(8))\n binary_temp_list_ip_mask.append(temp_binary_ip_mask)\n temp_binary_ip_mask = ''\n ip_index_list = []\n mask_index_list = []\n for x in range(2):\n if not re.match('^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n ip_index_list.append(x)\n if re.match('^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n mask_index_list.append(x)\n if len(ip_index_list) == 1 and len(mask_index_list) == 1:\n ipv4 = temp_list_ip_mask[int(ip_index_list[0])]\n net_mask = temp_list_ip_mask[int(mask_index_list[0])]\n elif binary_temp_list_ip_mask[0].count('1') < binary_temp_list_ip_mask[0\n ].count('1'):\n ipv4 = temp_list_ip_mask[0]\n net_mask = temp_list_ip_mask[1]\n else:\n ipv4 = temp_list_ip_mask[1]\n net_mask = temp_list_ip_mask[0]\n return 'IPv4: ' + ipv4 + '\\n' + 'Net mask: ' + net_mask\n", "<function token>\n" ]
false
742
0528d7761cbbf3dbe881ff05b81060f3d97e7f6c
import collections import copy import threading import typing as tp from ..decorators.decorators import wraps from ..typing import K, V, T class Monitor: """ Base utility class for creating monitors (the synchronization thingies!) These are NOT re-entrant! Use it like that: >>> class MyProtectedObject(Monitor): >>> def __init__(self, *args, **kwargs): >>> Monitor.__init__(self) >>> ... do your job .. >>> @Monitor.synchronized >>> def function_that_needs_mutual_exclusion(self): >>> .. do your threadsafe jobs .. >>> def function_that_partially_needs_protection(self): >>> .. do your jobs .. >>> with Monitor.acquire(self): >>> .. do your threadsafe jobs .. >>> .. do your jobs .. >>> with self: >>> .. do your threadsafe jobs .. """ def __enter__(self) -> 'Monitor': self._monitor_lock.acquire() return self def __exit__(self, exc_type, exc_val, exc_tb) -> bool: self._monitor_lock.release() return False def __init__(self): """You need to invoke this at your constructor You can also use it to release locks of other objects.""" self._monitor_lock = threading.Lock() # type: threading.Lock @staticmethod def synchronize_on_attribute(attr_name: str): """ When a Monitor is an attribute of a class, and you have a method instance that you would like secure by acquiring that monitor, use this. The first argument taken by that method instance must be self. :param attr_name: name of the attribute that is the monitor """ def outer(fun): @wraps(fun) def method(self, *args, **kwargs): # noinspection PyProtectedMember with getattr(self, attr_name)._monitor_lock: return fun(self, *args, **kwargs) return method return outer @staticmethod def synchronized(fun: tp.Callable) -> tp.Callable: """ This is a decorator. Class method decorated with that will lock the global lock of given instance, making it threadsafe. Depending on usage pattern of your class and it's data semantics, your performance may vary """ @wraps(fun) def monitored(*args, **kwargs): # noinspection PyProtectedMember with args[0]._monitor_lock: return fun(*args, **kwargs) return monitored class release: """ Returns a context manager object that can release another object as long as that object is a monitor. Consider foo, which is a monitor. You have a protected function, but you feel that you can release it for a while as it would improve parallelism. You can use it as such: >>> @Monitor.synchronized >>> def protected_function(self): >>> .. do some stuff that needs mutual exclusion .. >>> with Monitor.release(self): >>> .. do some I/O that does not need mutual exclusion .. >>> .. back to protected stuff .. """ __slots__ = ('foo',) def __init__(self, foo: 'Monitor'): self.foo = foo def __enter__(self) -> None: # noinspection PyProtectedMember self.foo._monitor_lock.release() def __exit__(self, e1, e2, e3) -> bool: # noinspection PyProtectedMember self.foo._monitor_lock.acquire() return False class acquire: """ Returns a context manager object that can lock another object, as long as that object is a monitor. Consider foo, which is a monitor. If you needed to lock it from outside, you would do: >>> with Monitor.acquire(foo): >>> .. do operations on foo that need mutual exclusion .. """ __slots__ = ('foo',) def __init__(self, foo: 'Monitor'): self.foo = foo def __enter__(self) -> None: # noinspection PyProtectedMember self.foo._monitor_lock.acquire() def __exit__(self, e1, e2, e3) -> bool: # noinspection PyProtectedMember self.foo._monitor_lock.release() return False @classmethod def synchronize_on(cls, monitor: 'Monitor') -> tp.Callable[[tp.Callable], tp.Callable]: """ A decorator for locking on non-self Monitor objects Use it like: >>> class MasterClass(Monitor): >>> def get_object(self): >>> class SlaveClass: >>> @Monitor.synchronize_on(self) >>> def get_object(self2): >>> ... >>> return SlaveClass """ def outer(fun): @wraps(fun) def inner(*args, **kwargs): with cls.acquire(monitor): return fun(*args, **kwargs) return inner return outer class RMonitor(Monitor): """ Monitor, but using an reentrant lock instead of a normal one """ def __init__(self): self._monitor_lock = threading.RLock() # type: threading.RLock class MonitorList(tp.Generic[T], collections.UserList, Monitor): """ A list that is also a monitor. Note that access to it's properties is not automatically synchronized, you got to invoke the monitor to implement an opportunistic locking of your own choice """ def __init__(self, *args): collections.UserList.__init__(self, *args) Monitor.__init__(self) def __copy__(self) -> 'MonitorList': return MonitorList(copy.copy(self.data)) def __deepcopy__(self, memo) -> 'MonitorList': return MonitorList(copy.deepcopy(self.data, memo=memo)) def __getitem__(self, item: tp.Union[slice, int]) -> T: return self.data[item] def __setitem__(self, key: int, value: T) -> None: self.data[key] = value def __delitem__(self, key: tp.Union[slice, int]) -> None: del self.data[key] class MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor): """ A dict that is also a monitor. Note that access to it's properties is not automatically synchronized, you got to invoke the monitor to implement an opportunistic locking of your own choice """ def __init__(self, *args, **kwargs): collections.UserDict.__init__(self, *args, **kwargs) Monitor.__init__(self) def __getitem__(self, item: K) -> V: return self.data[item] def __setitem__(self, key: K, value: V) -> None: self.data[key] = value def __delitem__(self, key: K) -> None: del self.data[key] def __copy__(self) -> 'MonitorDict': return MonitorDict(copy.copy(self.data)) def __deepcopy__(self, memo) -> 'MonitorDict': return MonitorDict(copy.deepcopy(self.data, memo=memo)) class MonitorSet(set, Monitor): """ A set that allows atomic insert-if-not-already-there operation """ def __init__(self, *args): super().__init__(*args) Monitor.__init__(self) def insert_and_check(self, item) -> bool: """ Perform an atomic insert if not already in set :param item: item to insert :return: whether the item was successfully inserted """ with Monitor.acquire(self): if item in self: return False self.add(item) return True
[ "import collections\nimport copy\nimport threading\nimport typing as tp\n\nfrom ..decorators.decorators import wraps\n\nfrom ..typing import K, V, T\n\n\nclass Monitor:\n \"\"\"\n Base utility class for creating monitors (the synchronization thingies!)\n\n These are NOT re-entrant!\n\n Use it like that:\n\n >>> class MyProtectedObject(Monitor):\n >>> def __init__(self, *args, **kwargs):\n >>> Monitor.__init__(self)\n >>> ... do your job ..\n\n >>> @Monitor.synchronized\n >>> def function_that_needs_mutual_exclusion(self):\n >>> .. do your threadsafe jobs ..\n\n >>> def function_that_partially_needs_protection(self):\n >>> .. do your jobs ..\n >>> with Monitor.acquire(self):\n >>> .. do your threadsafe jobs ..\n >>> .. do your jobs ..\n >>> with self:\n >>> .. do your threadsafe jobs ..\n \"\"\"\n\n def __enter__(self) -> 'Monitor':\n self._monitor_lock.acquire()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb) -> bool:\n self._monitor_lock.release()\n return False\n\n def __init__(self):\n \"\"\"You need to invoke this at your constructor\n You can also use it to release locks of other objects.\"\"\"\n self._monitor_lock = threading.Lock() # type: threading.Lock\n\n @staticmethod\n def synchronize_on_attribute(attr_name: str):\n \"\"\"\n When a Monitor is an attribute of a class, and you have a method instance\n that you would like secure by acquiring that monitor, use this.\n\n The first argument taken by that method instance must be self.\n\n :param attr_name: name of the attribute that is the monitor\n \"\"\"\n\n def outer(fun):\n @wraps(fun)\n def method(self, *args, **kwargs):\n # noinspection PyProtectedMember\n with getattr(self, attr_name)._monitor_lock:\n return fun(self, *args, **kwargs)\n\n return method\n\n return outer\n\n @staticmethod\n def synchronized(fun: tp.Callable) -> tp.Callable:\n \"\"\"\n This is a decorator. Class method decorated with that will lock the\n global lock of given instance, making it threadsafe. Depending on\n usage pattern of your class and it's data semantics, your performance\n may vary\n \"\"\"\n\n @wraps(fun)\n def monitored(*args, **kwargs):\n # noinspection PyProtectedMember\n with args[0]._monitor_lock:\n return fun(*args, **kwargs)\n\n return monitored\n\n class release:\n \"\"\"\n Returns a context manager object that can release another object\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. You have a protected function,\n but you feel that you can release it for a while as it would\n improve parallelism. You can use it as such:\n\n >>> @Monitor.synchronized\n >>> def protected_function(self):\n >>> .. do some stuff that needs mutual exclusion ..\n >>> with Monitor.release(self):\n >>> .. do some I/O that does not need mutual exclusion ..\n >>> .. back to protected stuff ..\n \"\"\"\n __slots__ = ('foo',)\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) -> None:\n # noinspection PyProtectedMember\n self.foo._monitor_lock.release()\n\n def __exit__(self, e1, e2, e3) -> bool:\n # noinspection PyProtectedMember\n self.foo._monitor_lock.acquire()\n return False\n\n class acquire:\n \"\"\"\n Returns a context manager object that can lock another object,\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. If you needed to lock it from\n outside, you would do:\n\n >>> with Monitor.acquire(foo):\n >>> .. do operations on foo that need mutual exclusion ..\n \"\"\"\n __slots__ = ('foo',)\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) -> None:\n # noinspection PyProtectedMember\n self.foo._monitor_lock.acquire()\n\n def __exit__(self, e1, e2, e3) -> bool:\n # noinspection PyProtectedMember\n self.foo._monitor_lock.release()\n return False\n\n @classmethod\n def synchronize_on(cls, monitor: 'Monitor') -> tp.Callable[[tp.Callable], tp.Callable]:\n \"\"\"\n A decorator for locking on non-self Monitor objects\n\n Use it like:\n\n >>> class MasterClass(Monitor):\n >>> def get_object(self):\n >>> class SlaveClass:\n >>> @Monitor.synchronize_on(self)\n >>> def get_object(self2):\n >>> ...\n >>> return SlaveClass\n \"\"\"\n\n def outer(fun):\n @wraps(fun)\n def inner(*args, **kwargs):\n with cls.acquire(monitor):\n return fun(*args, **kwargs)\n\n return inner\n\n return outer\n\n\nclass RMonitor(Monitor):\n \"\"\"\n Monitor, but using an reentrant lock instead of a normal one\n \"\"\"\n\n def __init__(self):\n self._monitor_lock = threading.RLock() # type: threading.RLock\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) -> 'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) -> 'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) -> T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) -> None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) -> None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) -> V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) -> None:\n self.data[key] = value\n\n def __delitem__(self, key: K) -> None:\n del self.data[key]\n\n def __copy__(self) -> 'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) -> 'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) -> bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "import collections\nimport copy\nimport threading\nimport typing as tp\nfrom ..decorators.decorators import wraps\nfrom ..typing import K, V, T\n\n\nclass Monitor:\n \"\"\"\n Base utility class for creating monitors (the synchronization thingies!)\n\n These are NOT re-entrant!\n\n Use it like that:\n\n >>> class MyProtectedObject(Monitor):\n >>> def __init__(self, *args, **kwargs):\n >>> Monitor.__init__(self)\n >>> ... do your job ..\n\n >>> @Monitor.synchronized\n >>> def function_that_needs_mutual_exclusion(self):\n >>> .. do your threadsafe jobs ..\n\n >>> def function_that_partially_needs_protection(self):\n >>> .. do your jobs ..\n >>> with Monitor.acquire(self):\n >>> .. do your threadsafe jobs ..\n >>> .. do your jobs ..\n >>> with self:\n >>> .. do your threadsafe jobs ..\n \"\"\"\n\n def __enter__(self) ->'Monitor':\n self._monitor_lock.acquire()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb) ->bool:\n self._monitor_lock.release()\n return False\n\n def __init__(self):\n \"\"\"You need to invoke this at your constructor\n You can also use it to release locks of other objects.\"\"\"\n self._monitor_lock = threading.Lock()\n\n @staticmethod\n def synchronize_on_attribute(attr_name: str):\n \"\"\"\n When a Monitor is an attribute of a class, and you have a method instance\n that you would like secure by acquiring that monitor, use this.\n\n The first argument taken by that method instance must be self.\n\n :param attr_name: name of the attribute that is the monitor\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def method(self, *args, **kwargs):\n with getattr(self, attr_name)._monitor_lock:\n return fun(self, *args, **kwargs)\n return method\n return outer\n\n @staticmethod\n def synchronized(fun: tp.Callable) ->tp.Callable:\n \"\"\"\n This is a decorator. Class method decorated with that will lock the\n global lock of given instance, making it threadsafe. Depending on\n usage pattern of your class and it's data semantics, your performance\n may vary\n \"\"\"\n\n @wraps(fun)\n def monitored(*args, **kwargs):\n with args[0]._monitor_lock:\n return fun(*args, **kwargs)\n return monitored\n\n\n class release:\n \"\"\"\n Returns a context manager object that can release another object\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. You have a protected function,\n but you feel that you can release it for a while as it would\n improve parallelism. You can use it as such:\n\n >>> @Monitor.synchronized\n >>> def protected_function(self):\n >>> .. do some stuff that needs mutual exclusion ..\n >>> with Monitor.release(self):\n >>> .. do some I/O that does not need mutual exclusion ..\n >>> .. back to protected stuff ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.release()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.acquire()\n return False\n\n\n class acquire:\n \"\"\"\n Returns a context manager object that can lock another object,\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. If you needed to lock it from\n outside, you would do:\n\n >>> with Monitor.acquire(foo):\n >>> .. do operations on foo that need mutual exclusion ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.acquire()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.release()\n return False\n\n @classmethod\n def synchronize_on(cls, monitor: 'Monitor') ->tp.Callable[[tp.Callable],\n tp.Callable]:\n \"\"\"\n A decorator for locking on non-self Monitor objects\n\n Use it like:\n\n >>> class MasterClass(Monitor):\n >>> def get_object(self):\n >>> class SlaveClass:\n >>> @Monitor.synchronize_on(self)\n >>> def get_object(self2):\n >>> ...\n >>> return SlaveClass\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def inner(*args, **kwargs):\n with cls.acquire(monitor):\n return fun(*args, **kwargs)\n return inner\n return outer\n\n\nclass RMonitor(Monitor):\n \"\"\"\n Monitor, but using an reentrant lock instead of a normal one\n \"\"\"\n\n def __init__(self):\n self._monitor_lock = threading.RLock()\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n\n\nclass Monitor:\n \"\"\"\n Base utility class for creating monitors (the synchronization thingies!)\n\n These are NOT re-entrant!\n\n Use it like that:\n\n >>> class MyProtectedObject(Monitor):\n >>> def __init__(self, *args, **kwargs):\n >>> Monitor.__init__(self)\n >>> ... do your job ..\n\n >>> @Monitor.synchronized\n >>> def function_that_needs_mutual_exclusion(self):\n >>> .. do your threadsafe jobs ..\n\n >>> def function_that_partially_needs_protection(self):\n >>> .. do your jobs ..\n >>> with Monitor.acquire(self):\n >>> .. do your threadsafe jobs ..\n >>> .. do your jobs ..\n >>> with self:\n >>> .. do your threadsafe jobs ..\n \"\"\"\n\n def __enter__(self) ->'Monitor':\n self._monitor_lock.acquire()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb) ->bool:\n self._monitor_lock.release()\n return False\n\n def __init__(self):\n \"\"\"You need to invoke this at your constructor\n You can also use it to release locks of other objects.\"\"\"\n self._monitor_lock = threading.Lock()\n\n @staticmethod\n def synchronize_on_attribute(attr_name: str):\n \"\"\"\n When a Monitor is an attribute of a class, and you have a method instance\n that you would like secure by acquiring that monitor, use this.\n\n The first argument taken by that method instance must be self.\n\n :param attr_name: name of the attribute that is the monitor\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def method(self, *args, **kwargs):\n with getattr(self, attr_name)._monitor_lock:\n return fun(self, *args, **kwargs)\n return method\n return outer\n\n @staticmethod\n def synchronized(fun: tp.Callable) ->tp.Callable:\n \"\"\"\n This is a decorator. Class method decorated with that will lock the\n global lock of given instance, making it threadsafe. Depending on\n usage pattern of your class and it's data semantics, your performance\n may vary\n \"\"\"\n\n @wraps(fun)\n def monitored(*args, **kwargs):\n with args[0]._monitor_lock:\n return fun(*args, **kwargs)\n return monitored\n\n\n class release:\n \"\"\"\n Returns a context manager object that can release another object\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. You have a protected function,\n but you feel that you can release it for a while as it would\n improve parallelism. You can use it as such:\n\n >>> @Monitor.synchronized\n >>> def protected_function(self):\n >>> .. do some stuff that needs mutual exclusion ..\n >>> with Monitor.release(self):\n >>> .. do some I/O that does not need mutual exclusion ..\n >>> .. back to protected stuff ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.release()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.acquire()\n return False\n\n\n class acquire:\n \"\"\"\n Returns a context manager object that can lock another object,\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. If you needed to lock it from\n outside, you would do:\n\n >>> with Monitor.acquire(foo):\n >>> .. do operations on foo that need mutual exclusion ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.acquire()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.release()\n return False\n\n @classmethod\n def synchronize_on(cls, monitor: 'Monitor') ->tp.Callable[[tp.Callable],\n tp.Callable]:\n \"\"\"\n A decorator for locking on non-self Monitor objects\n\n Use it like:\n\n >>> class MasterClass(Monitor):\n >>> def get_object(self):\n >>> class SlaveClass:\n >>> @Monitor.synchronize_on(self)\n >>> def get_object(self2):\n >>> ...\n >>> return SlaveClass\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def inner(*args, **kwargs):\n with cls.acquire(monitor):\n return fun(*args, **kwargs)\n return inner\n return outer\n\n\nclass RMonitor(Monitor):\n \"\"\"\n Monitor, but using an reentrant lock instead of a normal one\n \"\"\"\n\n def __init__(self):\n self._monitor_lock = threading.RLock()\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n\n\nclass Monitor:\n <docstring token>\n\n def __enter__(self) ->'Monitor':\n self._monitor_lock.acquire()\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb) ->bool:\n self._monitor_lock.release()\n return False\n\n def __init__(self):\n \"\"\"You need to invoke this at your constructor\n You can also use it to release locks of other objects.\"\"\"\n self._monitor_lock = threading.Lock()\n\n @staticmethod\n def synchronize_on_attribute(attr_name: str):\n \"\"\"\n When a Monitor is an attribute of a class, and you have a method instance\n that you would like secure by acquiring that monitor, use this.\n\n The first argument taken by that method instance must be self.\n\n :param attr_name: name of the attribute that is the monitor\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def method(self, *args, **kwargs):\n with getattr(self, attr_name)._monitor_lock:\n return fun(self, *args, **kwargs)\n return method\n return outer\n\n @staticmethod\n def synchronized(fun: tp.Callable) ->tp.Callable:\n \"\"\"\n This is a decorator. Class method decorated with that will lock the\n global lock of given instance, making it threadsafe. Depending on\n usage pattern of your class and it's data semantics, your performance\n may vary\n \"\"\"\n\n @wraps(fun)\n def monitored(*args, **kwargs):\n with args[0]._monitor_lock:\n return fun(*args, **kwargs)\n return monitored\n\n\n class release:\n \"\"\"\n Returns a context manager object that can release another object\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. You have a protected function,\n but you feel that you can release it for a while as it would\n improve parallelism. You can use it as such:\n\n >>> @Monitor.synchronized\n >>> def protected_function(self):\n >>> .. do some stuff that needs mutual exclusion ..\n >>> with Monitor.release(self):\n >>> .. do some I/O that does not need mutual exclusion ..\n >>> .. back to protected stuff ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.release()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.acquire()\n return False\n\n\n class acquire:\n \"\"\"\n Returns a context manager object that can lock another object,\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. If you needed to lock it from\n outside, you would do:\n\n >>> with Monitor.acquire(foo):\n >>> .. do operations on foo that need mutual exclusion ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.acquire()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.release()\n return False\n\n @classmethod\n def synchronize_on(cls, monitor: 'Monitor') ->tp.Callable[[tp.Callable],\n tp.Callable]:\n \"\"\"\n A decorator for locking on non-self Monitor objects\n\n Use it like:\n\n >>> class MasterClass(Monitor):\n >>> def get_object(self):\n >>> class SlaveClass:\n >>> @Monitor.synchronize_on(self)\n >>> def get_object(self2):\n >>> ...\n >>> return SlaveClass\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def inner(*args, **kwargs):\n with cls.acquire(monitor):\n return fun(*args, **kwargs)\n return inner\n return outer\n\n\nclass RMonitor(Monitor):\n \"\"\"\n Monitor, but using an reentrant lock instead of a normal one\n \"\"\"\n\n def __init__(self):\n self._monitor_lock = threading.RLock()\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n\n\nclass Monitor:\n <docstring token>\n\n def __enter__(self) ->'Monitor':\n self._monitor_lock.acquire()\n return self\n <function token>\n\n def __init__(self):\n \"\"\"You need to invoke this at your constructor\n You can also use it to release locks of other objects.\"\"\"\n self._monitor_lock = threading.Lock()\n\n @staticmethod\n def synchronize_on_attribute(attr_name: str):\n \"\"\"\n When a Monitor is an attribute of a class, and you have a method instance\n that you would like secure by acquiring that monitor, use this.\n\n The first argument taken by that method instance must be self.\n\n :param attr_name: name of the attribute that is the monitor\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def method(self, *args, **kwargs):\n with getattr(self, attr_name)._monitor_lock:\n return fun(self, *args, **kwargs)\n return method\n return outer\n\n @staticmethod\n def synchronized(fun: tp.Callable) ->tp.Callable:\n \"\"\"\n This is a decorator. Class method decorated with that will lock the\n global lock of given instance, making it threadsafe. Depending on\n usage pattern of your class and it's data semantics, your performance\n may vary\n \"\"\"\n\n @wraps(fun)\n def monitored(*args, **kwargs):\n with args[0]._monitor_lock:\n return fun(*args, **kwargs)\n return monitored\n\n\n class release:\n \"\"\"\n Returns a context manager object that can release another object\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. You have a protected function,\n but you feel that you can release it for a while as it would\n improve parallelism. You can use it as such:\n\n >>> @Monitor.synchronized\n >>> def protected_function(self):\n >>> .. do some stuff that needs mutual exclusion ..\n >>> with Monitor.release(self):\n >>> .. do some I/O that does not need mutual exclusion ..\n >>> .. back to protected stuff ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.release()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.acquire()\n return False\n\n\n class acquire:\n \"\"\"\n Returns a context manager object that can lock another object,\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. If you needed to lock it from\n outside, you would do:\n\n >>> with Monitor.acquire(foo):\n >>> .. do operations on foo that need mutual exclusion ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.acquire()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.release()\n return False\n\n @classmethod\n def synchronize_on(cls, monitor: 'Monitor') ->tp.Callable[[tp.Callable],\n tp.Callable]:\n \"\"\"\n A decorator for locking on non-self Monitor objects\n\n Use it like:\n\n >>> class MasterClass(Monitor):\n >>> def get_object(self):\n >>> class SlaveClass:\n >>> @Monitor.synchronize_on(self)\n >>> def get_object(self2):\n >>> ...\n >>> return SlaveClass\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def inner(*args, **kwargs):\n with cls.acquire(monitor):\n return fun(*args, **kwargs)\n return inner\n return outer\n\n\nclass RMonitor(Monitor):\n \"\"\"\n Monitor, but using an reentrant lock instead of a normal one\n \"\"\"\n\n def __init__(self):\n self._monitor_lock = threading.RLock()\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n\n\nclass Monitor:\n <docstring token>\n\n def __enter__(self) ->'Monitor':\n self._monitor_lock.acquire()\n return self\n <function token>\n <function token>\n\n @staticmethod\n def synchronize_on_attribute(attr_name: str):\n \"\"\"\n When a Monitor is an attribute of a class, and you have a method instance\n that you would like secure by acquiring that monitor, use this.\n\n The first argument taken by that method instance must be self.\n\n :param attr_name: name of the attribute that is the monitor\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def method(self, *args, **kwargs):\n with getattr(self, attr_name)._monitor_lock:\n return fun(self, *args, **kwargs)\n return method\n return outer\n\n @staticmethod\n def synchronized(fun: tp.Callable) ->tp.Callable:\n \"\"\"\n This is a decorator. Class method decorated with that will lock the\n global lock of given instance, making it threadsafe. Depending on\n usage pattern of your class and it's data semantics, your performance\n may vary\n \"\"\"\n\n @wraps(fun)\n def monitored(*args, **kwargs):\n with args[0]._monitor_lock:\n return fun(*args, **kwargs)\n return monitored\n\n\n class release:\n \"\"\"\n Returns a context manager object that can release another object\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. You have a protected function,\n but you feel that you can release it for a while as it would\n improve parallelism. You can use it as such:\n\n >>> @Monitor.synchronized\n >>> def protected_function(self):\n >>> .. do some stuff that needs mutual exclusion ..\n >>> with Monitor.release(self):\n >>> .. do some I/O that does not need mutual exclusion ..\n >>> .. back to protected stuff ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.release()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.acquire()\n return False\n\n\n class acquire:\n \"\"\"\n Returns a context manager object that can lock another object,\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. If you needed to lock it from\n outside, you would do:\n\n >>> with Monitor.acquire(foo):\n >>> .. do operations on foo that need mutual exclusion ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.acquire()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.release()\n return False\n\n @classmethod\n def synchronize_on(cls, monitor: 'Monitor') ->tp.Callable[[tp.Callable],\n tp.Callable]:\n \"\"\"\n A decorator for locking on non-self Monitor objects\n\n Use it like:\n\n >>> class MasterClass(Monitor):\n >>> def get_object(self):\n >>> class SlaveClass:\n >>> @Monitor.synchronize_on(self)\n >>> def get_object(self2):\n >>> ...\n >>> return SlaveClass\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def inner(*args, **kwargs):\n with cls.acquire(monitor):\n return fun(*args, **kwargs)\n return inner\n return outer\n\n\nclass RMonitor(Monitor):\n \"\"\"\n Monitor, but using an reentrant lock instead of a normal one\n \"\"\"\n\n def __init__(self):\n self._monitor_lock = threading.RLock()\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n\n\nclass Monitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n @staticmethod\n def synchronize_on_attribute(attr_name: str):\n \"\"\"\n When a Monitor is an attribute of a class, and you have a method instance\n that you would like secure by acquiring that monitor, use this.\n\n The first argument taken by that method instance must be self.\n\n :param attr_name: name of the attribute that is the monitor\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def method(self, *args, **kwargs):\n with getattr(self, attr_name)._monitor_lock:\n return fun(self, *args, **kwargs)\n return method\n return outer\n\n @staticmethod\n def synchronized(fun: tp.Callable) ->tp.Callable:\n \"\"\"\n This is a decorator. Class method decorated with that will lock the\n global lock of given instance, making it threadsafe. Depending on\n usage pattern of your class and it's data semantics, your performance\n may vary\n \"\"\"\n\n @wraps(fun)\n def monitored(*args, **kwargs):\n with args[0]._monitor_lock:\n return fun(*args, **kwargs)\n return monitored\n\n\n class release:\n \"\"\"\n Returns a context manager object that can release another object\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. You have a protected function,\n but you feel that you can release it for a while as it would\n improve parallelism. You can use it as such:\n\n >>> @Monitor.synchronized\n >>> def protected_function(self):\n >>> .. do some stuff that needs mutual exclusion ..\n >>> with Monitor.release(self):\n >>> .. do some I/O that does not need mutual exclusion ..\n >>> .. back to protected stuff ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.release()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.acquire()\n return False\n\n\n class acquire:\n \"\"\"\n Returns a context manager object that can lock another object,\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. If you needed to lock it from\n outside, you would do:\n\n >>> with Monitor.acquire(foo):\n >>> .. do operations on foo that need mutual exclusion ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.acquire()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.release()\n return False\n\n @classmethod\n def synchronize_on(cls, monitor: 'Monitor') ->tp.Callable[[tp.Callable],\n tp.Callable]:\n \"\"\"\n A decorator for locking on non-self Monitor objects\n\n Use it like:\n\n >>> class MasterClass(Monitor):\n >>> def get_object(self):\n >>> class SlaveClass:\n >>> @Monitor.synchronize_on(self)\n >>> def get_object(self2):\n >>> ...\n >>> return SlaveClass\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def inner(*args, **kwargs):\n with cls.acquire(monitor):\n return fun(*args, **kwargs)\n return inner\n return outer\n\n\nclass RMonitor(Monitor):\n \"\"\"\n Monitor, but using an reentrant lock instead of a normal one\n \"\"\"\n\n def __init__(self):\n self._monitor_lock = threading.RLock()\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n\n\nclass Monitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n @staticmethod\n def synchronize_on_attribute(attr_name: str):\n \"\"\"\n When a Monitor is an attribute of a class, and you have a method instance\n that you would like secure by acquiring that monitor, use this.\n\n The first argument taken by that method instance must be self.\n\n :param attr_name: name of the attribute that is the monitor\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def method(self, *args, **kwargs):\n with getattr(self, attr_name)._monitor_lock:\n return fun(self, *args, **kwargs)\n return method\n return outer\n\n @staticmethod\n def synchronized(fun: tp.Callable) ->tp.Callable:\n \"\"\"\n This is a decorator. Class method decorated with that will lock the\n global lock of given instance, making it threadsafe. Depending on\n usage pattern of your class and it's data semantics, your performance\n may vary\n \"\"\"\n\n @wraps(fun)\n def monitored(*args, **kwargs):\n with args[0]._monitor_lock:\n return fun(*args, **kwargs)\n return monitored\n\n\n class release:\n \"\"\"\n Returns a context manager object that can release another object\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. You have a protected function,\n but you feel that you can release it for a while as it would\n improve parallelism. You can use it as such:\n\n >>> @Monitor.synchronized\n >>> def protected_function(self):\n >>> .. do some stuff that needs mutual exclusion ..\n >>> with Monitor.release(self):\n >>> .. do some I/O that does not need mutual exclusion ..\n >>> .. back to protected stuff ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.release()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.acquire()\n return False\n\n\n class acquire:\n \"\"\"\n Returns a context manager object that can lock another object,\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. If you needed to lock it from\n outside, you would do:\n\n >>> with Monitor.acquire(foo):\n >>> .. do operations on foo that need mutual exclusion ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.acquire()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.release()\n return False\n <function token>\n\n\nclass RMonitor(Monitor):\n \"\"\"\n Monitor, but using an reentrant lock instead of a normal one\n \"\"\"\n\n def __init__(self):\n self._monitor_lock = threading.RLock()\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n\n\nclass Monitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n @staticmethod\n def synchronize_on_attribute(attr_name: str):\n \"\"\"\n When a Monitor is an attribute of a class, and you have a method instance\n that you would like secure by acquiring that monitor, use this.\n\n The first argument taken by that method instance must be self.\n\n :param attr_name: name of the attribute that is the monitor\n \"\"\"\n\n def outer(fun):\n\n @wraps(fun)\n def method(self, *args, **kwargs):\n with getattr(self, attr_name)._monitor_lock:\n return fun(self, *args, **kwargs)\n return method\n return outer\n <function token>\n\n\n class release:\n \"\"\"\n Returns a context manager object that can release another object\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. You have a protected function,\n but you feel that you can release it for a while as it would\n improve parallelism. You can use it as such:\n\n >>> @Monitor.synchronized\n >>> def protected_function(self):\n >>> .. do some stuff that needs mutual exclusion ..\n >>> with Monitor.release(self):\n >>> .. do some I/O that does not need mutual exclusion ..\n >>> .. back to protected stuff ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.release()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.acquire()\n return False\n\n\n class acquire:\n \"\"\"\n Returns a context manager object that can lock another object,\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. If you needed to lock it from\n outside, you would do:\n\n >>> with Monitor.acquire(foo):\n >>> .. do operations on foo that need mutual exclusion ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.acquire()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.release()\n return False\n <function token>\n\n\nclass RMonitor(Monitor):\n \"\"\"\n Monitor, but using an reentrant lock instead of a normal one\n \"\"\"\n\n def __init__(self):\n self._monitor_lock = threading.RLock()\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n\n\nclass Monitor:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n class release:\n \"\"\"\n Returns a context manager object that can release another object\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. You have a protected function,\n but you feel that you can release it for a while as it would\n improve parallelism. You can use it as such:\n\n >>> @Monitor.synchronized\n >>> def protected_function(self):\n >>> .. do some stuff that needs mutual exclusion ..\n >>> with Monitor.release(self):\n >>> .. do some I/O that does not need mutual exclusion ..\n >>> .. back to protected stuff ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.release()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.acquire()\n return False\n\n\n class acquire:\n \"\"\"\n Returns a context manager object that can lock another object,\n as long as that object is a monitor.\n\n Consider foo, which is a monitor. If you needed to lock it from\n outside, you would do:\n\n >>> with Monitor.acquire(foo):\n >>> .. do operations on foo that need mutual exclusion ..\n \"\"\"\n __slots__ = 'foo',\n\n def __init__(self, foo: 'Monitor'):\n self.foo = foo\n\n def __enter__(self) ->None:\n self.foo._monitor_lock.acquire()\n\n def __exit__(self, e1, e2, e3) ->bool:\n self.foo._monitor_lock.release()\n return False\n <function token>\n\n\nclass RMonitor(Monitor):\n \"\"\"\n Monitor, but using an reentrant lock instead of a normal one\n \"\"\"\n\n def __init__(self):\n self._monitor_lock = threading.RLock()\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n\n\nclass RMonitor(Monitor):\n \"\"\"\n Monitor, but using an reentrant lock instead of a normal one\n \"\"\"\n\n def __init__(self):\n self._monitor_lock = threading.RLock()\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n\n\nclass RMonitor(Monitor):\n <docstring token>\n\n def __init__(self):\n self._monitor_lock = threading.RLock()\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n\n\nclass RMonitor(Monitor):\n <docstring token>\n <function token>\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n \"\"\"\n A list that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n <docstring token>\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n\n def __getitem__(self, item: tp.Union[slice, int]) ->T:\n return self.data[item]\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n <docstring token>\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n <function token>\n\n def __setitem__(self, key: int, value: T) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n <docstring token>\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorList':\n return MonitorList(copy.deepcopy(self.data, memo=memo))\n <function token>\n <function token>\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n <docstring token>\n\n def __init__(self, *args):\n collections.UserList.__init__(self, *args)\n Monitor.__init__(self)\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n <function token>\n <function token>\n <function token>\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n <docstring token>\n <function token>\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n <function token>\n <function token>\n <function token>\n\n def __delitem__(self, key: tp.Union[slice, int]) ->None:\n del self.data[key]\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n <docstring token>\n <function token>\n\n def __copy__(self) ->'MonitorList':\n return MonitorList(copy.copy(self.data))\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n\n\nclass MonitorList(tp.Generic[T], collections.UserList, Monitor):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n \"\"\"\n A dict that is also a monitor.\n\n Note that access to it's properties is not automatically synchronized, you got to\n invoke the monitor to implement an opportunistic locking of your own choice\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n <docstring token>\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n\n def __getitem__(self, item: K) ->V:\n return self.data[item]\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n <docstring token>\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n <function token>\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n\n def __deepcopy__(self, memo) ->'MonitorDict':\n return MonitorDict(copy.deepcopy(self.data, memo=memo))\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n <docstring token>\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n <function token>\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n\n def __delitem__(self, key: K) ->None:\n del self.data[key]\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n <function token>\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n <docstring token>\n\n def __init__(self, *args, **kwargs):\n collections.UserDict.__init__(self, *args, **kwargs)\n Monitor.__init__(self)\n <function token>\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n <function token>\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n <function token>\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n <docstring token>\n <function token>\n <function token>\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n <function token>\n\n def __copy__(self) ->'MonitorDict':\n return MonitorDict(copy.copy(self.data))\n <function token>\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n <docstring token>\n <function token>\n <function token>\n\n def __setitem__(self, key: K, value: V) ->None:\n self.data[key] = value\n <function token>\n <function token>\n <function token>\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorDict(tp.Generic[K, V], collections.UserDict, Monitor):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorSet(set, Monitor):\n \"\"\"\n A set that allows atomic insert-if-not-already-there operation\n \"\"\"\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorSet(set, Monitor):\n <docstring token>\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n\n def insert_and_check(self, item) ->bool:\n \"\"\"\n Perform an atomic insert if not already in set\n\n :param item: item to insert\n :return: whether the item was successfully inserted\n \"\"\"\n with Monitor.acquire(self):\n if item in self:\n return False\n self.add(item)\n return True\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorSet(set, Monitor):\n <docstring token>\n\n def __init__(self, *args):\n super().__init__(*args)\n Monitor.__init__(self)\n <function token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass MonitorSet(set, Monitor):\n <docstring token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n" ]
false
743
8c336edddadbf4689721b474c254ded061ecf4b5
from . import scramsha1, scrammer
[ "from . import scramsha1, scrammer\n", "<import token>\n" ]
false
744
0fb288e3ab074e021ec726d71cbd5c8546a8455b
import shutil import tempfile import salt.runners.net as net from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock from tests.support.runtests import RUNTIME_VARS from tests.support.unit import TestCase, skipIf @skipIf(not net.HAS_NAPALM, "napalm module required for this test") class NetTest(TestCase, LoaderModuleMockMixin): """ Test the net runner """ def setup_loader_modules(self): mock_get = MagicMock(return_value={}) self.extmods_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP) self.addCleanup(shutil.rmtree, self.extmods_dir, ignore_errors=True) return { net: { "__opts__": { "optimization_order": [0, 1, 2], "renderer": "yaml", "renderer_blacklist": [], "renderer_whitelist": [], "extension_modules": self.extmods_dir, }, "__salt__": {"mine.get": mock_get}, } } def test_interfaces(self): ret = net.interfaces() self.assertEqual(None, ret) def test_findarp(self): ret = net.findarp() self.assertEqual(None, ret) def test_findmac(self): ret = net.findmac() self.assertEqual(None, ret) def test_lldp(self): ret = net.lldp() self.assertEqual(None, ret) def test_find(self): ret = net.find("") self.assertEqual({}, ret) def test_multi_find(self): ret = net.multi_find() self.assertEqual(None, ret)
[ "import shutil\nimport tempfile\n\nimport salt.runners.net as net\nfrom tests.support.mixins import LoaderModuleMockMixin\nfrom tests.support.mock import MagicMock\nfrom tests.support.runtests import RUNTIME_VARS\nfrom tests.support.unit import TestCase, skipIf\n\n\n@skipIf(not net.HAS_NAPALM, \"napalm module required for this test\")\nclass NetTest(TestCase, LoaderModuleMockMixin):\n \"\"\"\n Test the net runner\n \"\"\"\n\n def setup_loader_modules(self):\n mock_get = MagicMock(return_value={})\n self.extmods_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)\n self.addCleanup(shutil.rmtree, self.extmods_dir, ignore_errors=True)\n return {\n net: {\n \"__opts__\": {\n \"optimization_order\": [0, 1, 2],\n \"renderer\": \"yaml\",\n \"renderer_blacklist\": [],\n \"renderer_whitelist\": [],\n \"extension_modules\": self.extmods_dir,\n },\n \"__salt__\": {\"mine.get\": mock_get},\n }\n }\n\n def test_interfaces(self):\n ret = net.interfaces()\n self.assertEqual(None, ret)\n\n def test_findarp(self):\n ret = net.findarp()\n self.assertEqual(None, ret)\n\n def test_findmac(self):\n ret = net.findmac()\n self.assertEqual(None, ret)\n\n def test_lldp(self):\n ret = net.lldp()\n self.assertEqual(None, ret)\n\n def test_find(self):\n ret = net.find(\"\")\n self.assertEqual({}, ret)\n\n def test_multi_find(self):\n ret = net.multi_find()\n self.assertEqual(None, ret)\n", "import shutil\nimport tempfile\nimport salt.runners.net as net\nfrom tests.support.mixins import LoaderModuleMockMixin\nfrom tests.support.mock import MagicMock\nfrom tests.support.runtests import RUNTIME_VARS\nfrom tests.support.unit import TestCase, skipIf\n\n\n@skipIf(not net.HAS_NAPALM, 'napalm module required for this test')\nclass NetTest(TestCase, LoaderModuleMockMixin):\n \"\"\"\n Test the net runner\n \"\"\"\n\n def setup_loader_modules(self):\n mock_get = MagicMock(return_value={})\n self.extmods_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)\n self.addCleanup(shutil.rmtree, self.extmods_dir, ignore_errors=True)\n return {net: {'__opts__': {'optimization_order': [0, 1, 2],\n 'renderer': 'yaml', 'renderer_blacklist': [],\n 'renderer_whitelist': [], 'extension_modules': self.extmods_dir\n }, '__salt__': {'mine.get': mock_get}}}\n\n def test_interfaces(self):\n ret = net.interfaces()\n self.assertEqual(None, ret)\n\n def test_findarp(self):\n ret = net.findarp()\n self.assertEqual(None, ret)\n\n def test_findmac(self):\n ret = net.findmac()\n self.assertEqual(None, ret)\n\n def test_lldp(self):\n ret = net.lldp()\n self.assertEqual(None, ret)\n\n def test_find(self):\n ret = net.find('')\n self.assertEqual({}, ret)\n\n def test_multi_find(self):\n ret = net.multi_find()\n self.assertEqual(None, ret)\n", "<import token>\n\n\n@skipIf(not net.HAS_NAPALM, 'napalm module required for this test')\nclass NetTest(TestCase, LoaderModuleMockMixin):\n \"\"\"\n Test the net runner\n \"\"\"\n\n def setup_loader_modules(self):\n mock_get = MagicMock(return_value={})\n self.extmods_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)\n self.addCleanup(shutil.rmtree, self.extmods_dir, ignore_errors=True)\n return {net: {'__opts__': {'optimization_order': [0, 1, 2],\n 'renderer': 'yaml', 'renderer_blacklist': [],\n 'renderer_whitelist': [], 'extension_modules': self.extmods_dir\n }, '__salt__': {'mine.get': mock_get}}}\n\n def test_interfaces(self):\n ret = net.interfaces()\n self.assertEqual(None, ret)\n\n def test_findarp(self):\n ret = net.findarp()\n self.assertEqual(None, ret)\n\n def test_findmac(self):\n ret = net.findmac()\n self.assertEqual(None, ret)\n\n def test_lldp(self):\n ret = net.lldp()\n self.assertEqual(None, ret)\n\n def test_find(self):\n ret = net.find('')\n self.assertEqual({}, ret)\n\n def test_multi_find(self):\n ret = net.multi_find()\n self.assertEqual(None, ret)\n", "<import token>\n\n\n@skipIf(not net.HAS_NAPALM, 'napalm module required for this test')\nclass NetTest(TestCase, LoaderModuleMockMixin):\n <docstring token>\n\n def setup_loader_modules(self):\n mock_get = MagicMock(return_value={})\n self.extmods_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)\n self.addCleanup(shutil.rmtree, self.extmods_dir, ignore_errors=True)\n return {net: {'__opts__': {'optimization_order': [0, 1, 2],\n 'renderer': 'yaml', 'renderer_blacklist': [],\n 'renderer_whitelist': [], 'extension_modules': self.extmods_dir\n }, '__salt__': {'mine.get': mock_get}}}\n\n def test_interfaces(self):\n ret = net.interfaces()\n self.assertEqual(None, ret)\n\n def test_findarp(self):\n ret = net.findarp()\n self.assertEqual(None, ret)\n\n def test_findmac(self):\n ret = net.findmac()\n self.assertEqual(None, ret)\n\n def test_lldp(self):\n ret = net.lldp()\n self.assertEqual(None, ret)\n\n def test_find(self):\n ret = net.find('')\n self.assertEqual({}, ret)\n\n def test_multi_find(self):\n ret = net.multi_find()\n self.assertEqual(None, ret)\n", "<import token>\n\n\n@skipIf(not net.HAS_NAPALM, 'napalm module required for this test')\nclass NetTest(TestCase, LoaderModuleMockMixin):\n <docstring token>\n\n def setup_loader_modules(self):\n mock_get = MagicMock(return_value={})\n self.extmods_dir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)\n self.addCleanup(shutil.rmtree, self.extmods_dir, ignore_errors=True)\n return {net: {'__opts__': {'optimization_order': [0, 1, 2],\n 'renderer': 'yaml', 'renderer_blacklist': [],\n 'renderer_whitelist': [], 'extension_modules': self.extmods_dir\n }, '__salt__': {'mine.get': mock_get}}}\n\n def test_interfaces(self):\n ret = net.interfaces()\n self.assertEqual(None, ret)\n\n def test_findarp(self):\n ret = net.findarp()\n self.assertEqual(None, ret)\n\n def test_findmac(self):\n ret = net.findmac()\n self.assertEqual(None, ret)\n <function token>\n\n def test_find(self):\n ret = net.find('')\n self.assertEqual({}, ret)\n\n def test_multi_find(self):\n ret = net.multi_find()\n self.assertEqual(None, ret)\n", "<import token>\n\n\n@skipIf(not net.HAS_NAPALM, 'napalm module required for this test')\nclass NetTest(TestCase, LoaderModuleMockMixin):\n <docstring token>\n <function token>\n\n def test_interfaces(self):\n ret = net.interfaces()\n self.assertEqual(None, ret)\n\n def test_findarp(self):\n ret = net.findarp()\n self.assertEqual(None, ret)\n\n def test_findmac(self):\n ret = net.findmac()\n self.assertEqual(None, ret)\n <function token>\n\n def test_find(self):\n ret = net.find('')\n self.assertEqual({}, ret)\n\n def test_multi_find(self):\n ret = net.multi_find()\n self.assertEqual(None, ret)\n", "<import token>\n\n\n@skipIf(not net.HAS_NAPALM, 'napalm module required for this test')\nclass NetTest(TestCase, LoaderModuleMockMixin):\n <docstring token>\n <function token>\n\n def test_interfaces(self):\n ret = net.interfaces()\n self.assertEqual(None, ret)\n\n def test_findarp(self):\n ret = net.findarp()\n self.assertEqual(None, ret)\n <function token>\n <function token>\n\n def test_find(self):\n ret = net.find('')\n self.assertEqual({}, ret)\n\n def test_multi_find(self):\n ret = net.multi_find()\n self.assertEqual(None, ret)\n", "<import token>\n\n\n@skipIf(not net.HAS_NAPALM, 'napalm module required for this test')\nclass NetTest(TestCase, LoaderModuleMockMixin):\n <docstring token>\n <function token>\n\n def test_interfaces(self):\n ret = net.interfaces()\n self.assertEqual(None, ret)\n\n def test_findarp(self):\n ret = net.findarp()\n self.assertEqual(None, ret)\n <function token>\n <function token>\n <function token>\n\n def test_multi_find(self):\n ret = net.multi_find()\n self.assertEqual(None, ret)\n", "<import token>\n\n\n@skipIf(not net.HAS_NAPALM, 'napalm module required for this test')\nclass NetTest(TestCase, LoaderModuleMockMixin):\n <docstring token>\n <function token>\n\n def test_interfaces(self):\n ret = net.interfaces()\n self.assertEqual(None, ret)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_multi_find(self):\n ret = net.multi_find()\n self.assertEqual(None, ret)\n", "<import token>\n\n\n@skipIf(not net.HAS_NAPALM, 'napalm module required for this test')\nclass NetTest(TestCase, LoaderModuleMockMixin):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def test_multi_find(self):\n ret = net.multi_find()\n self.assertEqual(None, ret)\n", "<import token>\n\n\n@skipIf(not net.HAS_NAPALM, 'napalm module required for this test')\nclass NetTest(TestCase, LoaderModuleMockMixin):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
745
b12c8d0cb1cd1e48df6246fe3f16467b2db296e0
import sys def dir_slash(): slash = '/' if 'win' in sys.platform: slash = '\\' return slash
[ "import sys\n\ndef dir_slash():\n slash = '/'\n if 'win' in sys.platform: slash = '\\\\'\n return slash\n", "import sys\n\n\ndef dir_slash():\n slash = '/'\n if 'win' in sys.platform:\n slash = '\\\\'\n return slash\n", "<import token>\n\n\ndef dir_slash():\n slash = '/'\n if 'win' in sys.platform:\n slash = '\\\\'\n return slash\n", "<import token>\n<function token>\n" ]
false
746
a09bc84a14718422894127a519d67dc0c6b13bc9
#n = int(input()) #s = input() n, m = map(int, input().split()) #s, t = input().split() #n, m, l = map(int, input().split()) #s, t, r = input().split() #a = map(int, input().split()) #a = input().split() a = [int(input()) for _ in range(n)] #a = [input() for _ in range(n)] #t = input() #m = int(input()) #p, q = map(int, input().split()) #p, q = input().split() #p, q, r = map(int, input().split()) #p, q, r = input().split() #b = map(int, input().split()) #b = input().split() #b = [int(input()) for _ in range(m)] #b = [input() for _ in range(m)] cnt, ans, mx, mn = 0, m, 0, 100000000 for i in range(n - 1): if a[i + 1] - a[i] < m: ans += a[i + 1] - a[i] else: ans += m print(ans)
[ "#n = int(input())\n#s = input()\nn, m = map(int, input().split())\n#s, t = input().split()\n#n, m, l = map(int, input().split())\n#s, t, r = input().split()\n#a = map(int, input().split())\n#a = input().split()\na = [int(input()) for _ in range(n)]\n#a = [input() for _ in range(n)]\n\n#t = input()\n#m = int(input())\n#p, q = map(int, input().split())\n#p, q = input().split()\n#p, q, r = map(int, input().split())\n#p, q, r = input().split()\n#b = map(int, input().split())\n#b = input().split()\n#b = [int(input()) for _ in range(m)]\n#b = [input() for _ in range(m)]\ncnt, ans, mx, mn = 0, m, 0, 100000000\nfor i in range(n - 1):\n if a[i + 1] - a[i] < m:\n ans += a[i + 1] - a[i]\n else:\n ans += m\nprint(ans)\n", "n, m = map(int, input().split())\na = [int(input()) for _ in range(n)]\ncnt, ans, mx, mn = 0, m, 0, 100000000\nfor i in range(n - 1):\n if a[i + 1] - a[i] < m:\n ans += a[i + 1] - a[i]\n else:\n ans += m\nprint(ans)\n", "<assignment token>\nfor i in range(n - 1):\n if a[i + 1] - a[i] < m:\n ans += a[i + 1] - a[i]\n else:\n ans += m\nprint(ans)\n", "<assignment token>\n<code token>\n" ]
false
747
330b843501e0fdaff21cc4eff1ef930d54ab6e8d
''' Temperature Container ''' class TempHolder: range_start = 0 range_end = 0 star_count_lst = [0,0,0,0,0,0] counter = 0 def __init__(self, in_range_start, in_range_end): self.range_start = in_range_start self.range_end = in_range_end self.counter = 0 self.star_count_lst = [0,0,0,0,0,0] def is_in_temp_range(self, temp): if self.range_start <= temp and temp < self.range_end: return True else: return False def add_rating(self, rating): if int(rating) == 0: self.star_count_lst[0] += 1 if int(rating) == 1: self.star_count_lst[1] += 1 if int(rating) == 2: self.star_count_lst[2] += 1 if int(rating) == 3: self.star_count_lst[3] += 1 if int(rating) == 4: self.star_count_lst[4] += 1 if int(rating) == 5: self.star_count_lst[5] += 1 self.counter += 1 def __str__(self): return_str = "" return_str += "Temp: " + str(self.range_start) + "-" + str(self.range_end) + "\n" return_str += "Count: " + str(self.counter) + "\n" if self.star_count_lst[0] == 0: return_str += "0 Stars: 0.00%\n" else: return_str += "0 Stars: " + str(round((self.star_count_lst[0] / (self.counter * 1.0)), 4) * 100) + "%\n" if self.star_count_lst[1] == 0: return_str += "1 Stars: 0.00%\n" else: return_str += "1 Stars: " + str(round((self.star_count_lst[1] / (self.counter * 1.0)), 4) * 100) + "%\n" if self.star_count_lst[2] == 0: return_str += "2 Stars: 0.00%\n" else: return_str += "2 Stars: " + str(round((self.star_count_lst[2] / (self.counter * 1.0)), 4) * 100) + "%\n" if self.star_count_lst[3] == 0: return_str += "3 Stars: 0.00%\n" else: return_str += "3 Stars: " + str(round((self.star_count_lst[3] / (self.counter * 1.0)), 4) * 100) + "%\n" if self.star_count_lst[4] == 0: return_str += "4 Stars: 0.00%\n" else: return_str += "4 Stars: " + str(round((self.star_count_lst[4] / (self.counter * 1.0)), 4) * 100) + "%\n" if self.star_count_lst[5] == 0: return_str += "5 Stars: 0.00%\n" else: return_str += "5 Stars: " + str(round((self.star_count_lst[5] / (self.counter * 1.0)), 4) * 100) + "%\n" return return_str class TempAnalysis: temp_holder_lst = list() def __init__(self): temp_counter = 0 while temp_counter < 110: self.temp_holder_lst.append(TempHolder(temp_counter, temp_counter + 10)) temp_counter += 10 def add_rating(self, rating, temp): for temp_holder in self.temp_holder_lst: if temp_holder.is_in_temp_range(temp): temp_holder.add_rating(rating) return True return False def __str__(self): return_str = "Breakdown by Temperature:\n" return_str += "-------------------------\n" for temp_holder in self.temp_holder_lst: return_str += str(temp_holder) + "\n" return return_str ''' Temperature Container ''' class FRSHTTHolder: frshtt_code = "" star_count_lst = [0,0,0,0,0,0] counter = 0 def __init__(self, in_frshtt_code): self.frshtt_code = in_frshtt_code self.counter = 0 self.star_count_lst = [0,0,0,0,0,0] def is_in_code(self, in_frshtt_code): if self.frshtt_code == in_frshtt_code: return True else: return False def add_rating(self, rating): if int(rating) == 0: self.star_count_lst[0] += 1 if int(rating) == 1: self.star_count_lst[1] += 1 if int(rating) == 2: self.star_count_lst[2] += 1 if int(rating) == 3: self.star_count_lst[3] += 1 if int(rating) == 4: self.star_count_lst[4] += 1 if int(rating) == 5: self.star_count_lst[5] += 1 self.counter += 1 def __str__(self): return_str = "" return_str += "Code: " + str(self.frshtt_code) + "\n" return_str += "Count: " + str(self.counter) + "\n" if self.star_count_lst[0] == 0: return_str += "0 Stars: 0.00%\n" else: return_str += "0 Stars: " + str(round((self.star_count_lst[0] / (self.counter * 1.0)), 4) * 100) + "%\n" if self.star_count_lst[1] == 0: return_str += "1 Stars: 0.00%\n" else: return_str += "1 Stars: " + str(round((self.star_count_lst[1] / (self.counter * 1.0)), 4) * 100) + "%\n" if self.star_count_lst[2] == 0: return_str += "2 Stars: 0.00%\n" else: return_str += "2 Stars: " + str(round((self.star_count_lst[2] / (self.counter * 1.0)), 4) * 100) + "%\n" if self.star_count_lst[3] == 0: return_str += "3 Stars: 0.00%\n" else: return_str += "3 Stars: " + str(round((self.star_count_lst[3] / (self.counter * 1.0)), 4) * 100) + "%\n" if self.star_count_lst[4] == 0: return_str += "4 Stars: 0.00%\n" else: return_str += "4 Stars: " + str(round((self.star_count_lst[4] / (self.counter * 1.0)), 4) * 100) + "%\n" if self.star_count_lst[5] == 0: return_str += "5 Stars: 0.00%\n" else: return_str += "5 Stars: " + str(round((self.star_count_lst[5] / (self.counter * 1.0)), 4) * 100) + "%\n" return return_str class FRSHTTAnalysis: frshtt_holder_lst = list() def __init__(self): # no weather self.frshtt_holder_lst.append(FRSHTTHolder("000000")) # rain self.frshtt_holder_lst.append(FRSHTTHolder("010000")) # thunder strom self.frshtt_holder_lst.append(FRSHTTHolder("010010")) # fog self.frshtt_holder_lst.append(FRSHTTHolder("100000")) # snow self.frshtt_holder_lst.append(FRSHTTHolder("001000")) # mixed (snow/rain) self.frshtt_holder_lst.append(FRSHTTHolder("011000")) # dry thunder self.frshtt_holder_lst.append(FRSHTTHolder("000010")) # hail self.frshtt_holder_lst.append(FRSHTTHolder("000100")) def add_rating(self, rating, frshtt_code): for frshtt_holder in self.frshtt_holder_lst: if frshtt_holder.is_in_code(frshtt_code): frshtt_holder.add_rating(rating) return True return False def __str__(self): return_str = "Breakdown by Code:\n" return_str += "-------------------------\n" for frshtt_holder in self.frshtt_holder_lst: return_str += str(frshtt_holder) + "\n" return return_str
[ "'''\nTemperature Container\n'''\nclass TempHolder:\n range_start = 0\n range_end = 0\n \n star_count_lst = [0,0,0,0,0,0]\n counter = 0\n \n def __init__(self, in_range_start, in_range_end):\n self.range_start = in_range_start\n self.range_end = in_range_end\n self.counter = 0\n self.star_count_lst = [0,0,0,0,0,0]\n \n def is_in_temp_range(self, temp):\n if self.range_start <= temp and temp < self.range_end:\n return True\n else:\n return False\n \n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n \n self.counter += 1\n \n def __str__(self):\n return_str = \"\"\n \n return_str += \"Temp: \" + str(self.range_start) + \"-\" + str(self.range_end) + \"\\n\"\n return_str += \"Count: \" + str(self.counter) + \"\\n\"\n\n if self.star_count_lst[0] == 0:\n return_str += \"0 Stars: 0.00%\\n\" \n else:\n return_str += \"0 Stars: \" + str(round((self.star_count_lst[0] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n if self.star_count_lst[1] == 0:\n return_str += \"1 Stars: 0.00%\\n\"\n else:\n return_str += \"1 Stars: \" + str(round((self.star_count_lst[1] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n if self.star_count_lst[2] == 0:\n return_str += \"2 Stars: 0.00%\\n\"\n else:\n return_str += \"2 Stars: \" + str(round((self.star_count_lst[2] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n if self.star_count_lst[3] == 0:\n return_str += \"3 Stars: 0.00%\\n\"\n else:\n return_str += \"3 Stars: \" + str(round((self.star_count_lst[3] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n if self.star_count_lst[4] == 0:\n return_str += \"4 Stars: 0.00%\\n\"\n else:\n return_str += \"4 Stars: \" + str(round((self.star_count_lst[4] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n if self.star_count_lst[5] == 0:\n return_str += \"5 Stars: 0.00%\\n\"\n else:\n return_str += \"5 Stars: \" + str(round((self.star_count_lst[5] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n return return_str\n \nclass TempAnalysis:\n temp_holder_lst = list()\n \n def __init__(self):\n temp_counter = 0\n \n while temp_counter < 110:\n self.temp_holder_lst.append(TempHolder(temp_counter, temp_counter + 10))\n temp_counter += 10\n \n def add_rating(self, rating, temp):\n for temp_holder in self.temp_holder_lst:\n if temp_holder.is_in_temp_range(temp):\n temp_holder.add_rating(rating)\n return True\n \n return False\n \n def __str__(self):\n return_str = \"Breakdown by Temperature:\\n\"\n return_str += \"-------------------------\\n\"\n \n for temp_holder in self.temp_holder_lst:\n return_str += str(temp_holder) + \"\\n\"\n \n return return_str\n \n \n'''\nTemperature Container\n'''\nclass FRSHTTHolder:\n frshtt_code = \"\"\n \n star_count_lst = [0,0,0,0,0,0]\n counter = 0\n \n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0,0,0,0,0,0]\n \n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n \n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n \n self.counter += 1\n \n def __str__(self):\n return_str = \"\"\n \n return_str += \"Code: \" + str(self.frshtt_code) + \"\\n\"\n return_str += \"Count: \" + str(self.counter) + \"\\n\"\n\n if self.star_count_lst[0] == 0:\n return_str += \"0 Stars: 0.00%\\n\" \n else:\n return_str += \"0 Stars: \" + str(round((self.star_count_lst[0] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n if self.star_count_lst[1] == 0:\n return_str += \"1 Stars: 0.00%\\n\"\n else:\n return_str += \"1 Stars: \" + str(round((self.star_count_lst[1] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n if self.star_count_lst[2] == 0:\n return_str += \"2 Stars: 0.00%\\n\"\n else:\n return_str += \"2 Stars: \" + str(round((self.star_count_lst[2] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n if self.star_count_lst[3] == 0:\n return_str += \"3 Stars: 0.00%\\n\"\n else:\n return_str += \"3 Stars: \" + str(round((self.star_count_lst[3] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n if self.star_count_lst[4] == 0:\n return_str += \"4 Stars: 0.00%\\n\"\n else:\n return_str += \"4 Stars: \" + str(round((self.star_count_lst[4] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n if self.star_count_lst[5] == 0:\n return_str += \"5 Stars: 0.00%\\n\"\n else:\n return_str += \"5 Stars: \" + str(round((self.star_count_lst[5] / (self.counter * 1.0)), 4) * 100) + \"%\\n\"\n \n return return_str\n \nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n \n def __init__(self):\n # no weather\n self.frshtt_holder_lst.append(FRSHTTHolder(\"000000\"))\n # rain\n self.frshtt_holder_lst.append(FRSHTTHolder(\"010000\"))\n # thunder strom\n self.frshtt_holder_lst.append(FRSHTTHolder(\"010010\"))\n # fog\n self.frshtt_holder_lst.append(FRSHTTHolder(\"100000\"))\n # snow\n self.frshtt_holder_lst.append(FRSHTTHolder(\"001000\"))\n # mixed (snow/rain)\n self.frshtt_holder_lst.append(FRSHTTHolder(\"011000\"))\n # dry thunder\n self.frshtt_holder_lst.append(FRSHTTHolder(\"000010\"))\n # hail\n self.frshtt_holder_lst.append(FRSHTTHolder(\"000100\"))\n \n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n \n return False\n \n def __str__(self):\n return_str = \"Breakdown by Code:\\n\"\n return_str += \"-------------------------\\n\"\n \n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + \"\\n\"\n \n return return_str\n", "<docstring token>\n\n\nclass TempHolder:\n range_start = 0\n range_end = 0\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_range_start, in_range_end):\n self.range_start = in_range_start\n self.range_end = in_range_end\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_temp_range(self, temp):\n if self.range_start <= temp and temp < self.range_end:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Temp: ' + str(self.range_start) + '-' + str(self.\n range_end) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass TempAnalysis:\n temp_holder_lst = list()\n\n def __init__(self):\n temp_counter = 0\n while temp_counter < 110:\n self.temp_holder_lst.append(TempHolder(temp_counter, \n temp_counter + 10))\n temp_counter += 10\n\n def add_rating(self, rating, temp):\n for temp_holder in self.temp_holder_lst:\n if temp_holder.is_in_temp_range(temp):\n temp_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Temperature:\\n'\n return_str += '-------------------------\\n'\n for temp_holder in self.temp_holder_lst:\n return_str += str(temp_holder) + '\\n'\n return return_str\n\n\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n\n\nclass TempHolder:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, in_range_start, in_range_end):\n self.range_start = in_range_start\n self.range_end = in_range_end\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_temp_range(self, temp):\n if self.range_start <= temp and temp < self.range_end:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Temp: ' + str(self.range_start) + '-' + str(self.\n range_end) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass TempAnalysis:\n temp_holder_lst = list()\n\n def __init__(self):\n temp_counter = 0\n while temp_counter < 110:\n self.temp_holder_lst.append(TempHolder(temp_counter, \n temp_counter + 10))\n temp_counter += 10\n\n def add_rating(self, rating, temp):\n for temp_holder in self.temp_holder_lst:\n if temp_holder.is_in_temp_range(temp):\n temp_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Temperature:\\n'\n return_str += '-------------------------\\n'\n for temp_holder in self.temp_holder_lst:\n return_str += str(temp_holder) + '\\n'\n return return_str\n\n\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n\n\nclass TempHolder:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n def is_in_temp_range(self, temp):\n if self.range_start <= temp and temp < self.range_end:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Temp: ' + str(self.range_start) + '-' + str(self.\n range_end) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass TempAnalysis:\n temp_holder_lst = list()\n\n def __init__(self):\n temp_counter = 0\n while temp_counter < 110:\n self.temp_holder_lst.append(TempHolder(temp_counter, \n temp_counter + 10))\n temp_counter += 10\n\n def add_rating(self, rating, temp):\n for temp_holder in self.temp_holder_lst:\n if temp_holder.is_in_temp_range(temp):\n temp_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Temperature:\\n'\n return_str += '-------------------------\\n'\n for temp_holder in self.temp_holder_lst:\n return_str += str(temp_holder) + '\\n'\n return return_str\n\n\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n\n\nclass TempHolder:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Temp: ' + str(self.range_start) + '-' + str(self.\n range_end) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass TempAnalysis:\n temp_holder_lst = list()\n\n def __init__(self):\n temp_counter = 0\n while temp_counter < 110:\n self.temp_holder_lst.append(TempHolder(temp_counter, \n temp_counter + 10))\n temp_counter += 10\n\n def add_rating(self, rating, temp):\n for temp_holder in self.temp_holder_lst:\n if temp_holder.is_in_temp_range(temp):\n temp_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Temperature:\\n'\n return_str += '-------------------------\\n'\n for temp_holder in self.temp_holder_lst:\n return_str += str(temp_holder) + '\\n'\n return return_str\n\n\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n\n\nclass TempHolder:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n <function token>\n\n\nclass TempAnalysis:\n temp_holder_lst = list()\n\n def __init__(self):\n temp_counter = 0\n while temp_counter < 110:\n self.temp_holder_lst.append(TempHolder(temp_counter, \n temp_counter + 10))\n temp_counter += 10\n\n def add_rating(self, rating, temp):\n for temp_holder in self.temp_holder_lst:\n if temp_holder.is_in_temp_range(temp):\n temp_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Temperature:\\n'\n return_str += '-------------------------\\n'\n for temp_holder in self.temp_holder_lst:\n return_str += str(temp_holder) + '\\n'\n return return_str\n\n\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n\n\nclass TempHolder:\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TempAnalysis:\n temp_holder_lst = list()\n\n def __init__(self):\n temp_counter = 0\n while temp_counter < 110:\n self.temp_holder_lst.append(TempHolder(temp_counter, \n temp_counter + 10))\n temp_counter += 10\n\n def add_rating(self, rating, temp):\n for temp_holder in self.temp_holder_lst:\n if temp_holder.is_in_temp_range(temp):\n temp_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Temperature:\\n'\n return_str += '-------------------------\\n'\n for temp_holder in self.temp_holder_lst:\n return_str += str(temp_holder) + '\\n'\n return return_str\n\n\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n\n\nclass TempAnalysis:\n temp_holder_lst = list()\n\n def __init__(self):\n temp_counter = 0\n while temp_counter < 110:\n self.temp_holder_lst.append(TempHolder(temp_counter, \n temp_counter + 10))\n temp_counter += 10\n\n def add_rating(self, rating, temp):\n for temp_holder in self.temp_holder_lst:\n if temp_holder.is_in_temp_range(temp):\n temp_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Temperature:\\n'\n return_str += '-------------------------\\n'\n for temp_holder in self.temp_holder_lst:\n return_str += str(temp_holder) + '\\n'\n return return_str\n\n\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n\n\nclass TempAnalysis:\n <assignment token>\n\n def __init__(self):\n temp_counter = 0\n while temp_counter < 110:\n self.temp_holder_lst.append(TempHolder(temp_counter, \n temp_counter + 10))\n temp_counter += 10\n\n def add_rating(self, rating, temp):\n for temp_holder in self.temp_holder_lst:\n if temp_holder.is_in_temp_range(temp):\n temp_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Temperature:\\n'\n return_str += '-------------------------\\n'\n for temp_holder in self.temp_holder_lst:\n return_str += str(temp_holder) + '\\n'\n return return_str\n\n\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n\n\nclass TempAnalysis:\n <assignment token>\n\n def __init__(self):\n temp_counter = 0\n while temp_counter < 110:\n self.temp_holder_lst.append(TempHolder(temp_counter, \n temp_counter + 10))\n temp_counter += 10\n\n def add_rating(self, rating, temp):\n for temp_holder in self.temp_holder_lst:\n if temp_holder.is_in_temp_range(temp):\n temp_holder.add_rating(rating)\n return True\n return False\n <function token>\n\n\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n\n\nclass TempAnalysis:\n <assignment token>\n\n def __init__(self):\n temp_counter = 0\n while temp_counter < 110:\n self.temp_holder_lst.append(TempHolder(temp_counter, \n temp_counter + 10))\n temp_counter += 10\n <function token>\n <function token>\n\n\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n\n\nclass TempAnalysis:\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n\n\nclass FRSHTTHolder:\n frshtt_code = ''\n star_count_lst = [0, 0, 0, 0, 0, 0]\n counter = 0\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n\n\nclass FRSHTTHolder:\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, in_frshtt_code):\n self.frshtt_code = in_frshtt_code\n self.counter = 0\n self.star_count_lst = [0, 0, 0, 0, 0, 0]\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n\n\nclass FRSHTTHolder:\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n\n def add_rating(self, rating):\n if int(rating) == 0:\n self.star_count_lst[0] += 1\n if int(rating) == 1:\n self.star_count_lst[1] += 1\n if int(rating) == 2:\n self.star_count_lst[2] += 1\n if int(rating) == 3:\n self.star_count_lst[3] += 1\n if int(rating) == 4:\n self.star_count_lst[4] += 1\n if int(rating) == 5:\n self.star_count_lst[5] += 1\n self.counter += 1\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n\n\nclass FRSHTTHolder:\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n def is_in_code(self, in_frshtt_code):\n if self.frshtt_code == in_frshtt_code:\n return True\n else:\n return False\n <function token>\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n\n\nclass FRSHTTHolder:\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def __str__(self):\n return_str = ''\n return_str += 'Code: ' + str(self.frshtt_code) + '\\n'\n return_str += 'Count: ' + str(self.counter) + '\\n'\n if self.star_count_lst[0] == 0:\n return_str += '0 Stars: 0.00%\\n'\n else:\n return_str += '0 Stars: ' + str(round(self.star_count_lst[0] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[1] == 0:\n return_str += '1 Stars: 0.00%\\n'\n else:\n return_str += '1 Stars: ' + str(round(self.star_count_lst[1] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[2] == 0:\n return_str += '2 Stars: 0.00%\\n'\n else:\n return_str += '2 Stars: ' + str(round(self.star_count_lst[2] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[3] == 0:\n return_str += '3 Stars: 0.00%\\n'\n else:\n return_str += '3 Stars: ' + str(round(self.star_count_lst[3] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[4] == 0:\n return_str += '4 Stars: 0.00%\\n'\n else:\n return_str += '4 Stars: ' + str(round(self.star_count_lst[4] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n if self.star_count_lst[5] == 0:\n return_str += '5 Stars: 0.00%\\n'\n else:\n return_str += '5 Stars: ' + str(round(self.star_count_lst[5] /\n (self.counter * 1.0), 4) * 100) + '%\\n'\n return return_str\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n\n\nclass FRSHTTHolder:\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n<class token>\n\n\nclass FRSHTTAnalysis:\n frshtt_holder_lst = list()\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n<class token>\n\n\nclass FRSHTTAnalysis:\n <assignment token>\n\n def __init__(self):\n self.frshtt_holder_lst.append(FRSHTTHolder('000000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('010010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('100000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('001000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('011000'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000010'))\n self.frshtt_holder_lst.append(FRSHTTHolder('000100'))\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n<class token>\n\n\nclass FRSHTTAnalysis:\n <assignment token>\n <function token>\n\n def add_rating(self, rating, frshtt_code):\n for frshtt_holder in self.frshtt_holder_lst:\n if frshtt_holder.is_in_code(frshtt_code):\n frshtt_holder.add_rating(rating)\n return True\n return False\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n<class token>\n\n\nclass FRSHTTAnalysis:\n <assignment token>\n <function token>\n <function token>\n\n def __str__(self):\n return_str = 'Breakdown by Code:\\n'\n return_str += '-------------------------\\n'\n for frshtt_holder in self.frshtt_holder_lst:\n return_str += str(frshtt_holder) + '\\n'\n return return_str\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n<class token>\n\n\nclass FRSHTTAnalysis:\n <assignment token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<class token>\n<class token>\n<docstring token>\n<class token>\n<class token>\n" ]
false
748
28d8f9d9b39c40c43a362e57a7907c0a38a6bd05
""" Platformer Game """ import arcade import os from Toad_arcade import Toad # Constants SCREEN_WIDTH = 1920 SCREEN_HEIGHT = 1080 SCREEN_TITLE = "PyToads - Battletoads reimplementation" # Constants used to scale our sprites from their original size CHARACTER_SCALING = 1 TILE_SCALING = 0.5 COIN_SCALING = 0.5 MOVEMENT_SPEED = 5 class MyGame(arcade.Window): """ Main application class. """ def __init__(self, width, height, title): """ Initializer """ super().__init__(width, height, title) # Set the working directory (where we expect to find files) to the same # directory this .py file is in. You can leave this out of your own # code, but it is needed to easily run the examples using "python -m" # as mentioned at the top of this program. file_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(file_path) """ Set up the game and initialize the variables. """ # Sprite lists self.player_list = None # Set up the player self.score = 0 self.player = None def setup(self): self.player_list = arcade.SpriteList() # Set up the player self.score = 0 self.player = Toad() self.player.center_x = SCREEN_WIDTH // 2 self.player.center_y = SCREEN_HEIGHT // 2 #self.player.scale = 0.8 self.player_list.append(self.player) # Set the background color arcade.set_background_color(arcade.color.AMAZON) def on_draw(self): """ Render the screen. """ # This command has to happen before we start drawing arcade.start_render() # Draw all the sprites. self.player_list.draw() # Put the text on the screen. output = f"Score: {self.score}" arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14) def on_key_press(self, key, modifiers): """ Called whenever a key is pressed. """ if key == arcade.key.UP: self.player.change_y = MOVEMENT_SPEED elif key == arcade.key.DOWN: self.player.change_y = -MOVEMENT_SPEED elif key == arcade.key.LEFT: self.player.change_x = -MOVEMENT_SPEED elif key == arcade.key.RIGHT: self.player.change_x = MOVEMENT_SPEED def on_key_release(self, key, modifiers): """ Called when the user releases a key. """ if key == arcade.key.UP or key == arcade.key.DOWN: self.player.change_y = 0 elif key == arcade.key.LEFT or key == arcade.key.RIGHT: self.player.change_x = 0 def on_update(self, delta_time): """ Movement and game logic """ self.player_list.update() self.player_list.update_animation() def main(): """ Main method """ window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) window.setup() arcade.run() if __name__ == "__main__": main()
[ "\"\"\"\nPlatformer Game\n\"\"\"\nimport arcade\nimport os\nfrom Toad_arcade import Toad\n# Constants\nSCREEN_WIDTH = 1920\nSCREEN_HEIGHT = 1080\nSCREEN_TITLE = \"PyToads - Battletoads reimplementation\"\n\n# Constants used to scale our sprites from their original size\nCHARACTER_SCALING = 1\nTILE_SCALING = 0.5\nCOIN_SCALING = 0.5\nMOVEMENT_SPEED = 5\n\nclass MyGame(arcade.Window):\n \"\"\" Main application class. \"\"\"\n\n def __init__(self, width, height, title):\n \"\"\"\n Initializer\n \"\"\"\n super().__init__(width, height, title)\n\n # Set the working directory (where we expect to find files) to the same\n # directory this .py file is in. You can leave this out of your own\n # code, but it is needed to easily run the examples using \"python -m\"\n # as mentioned at the top of this program.\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n\n \"\"\" Set up the game and initialize the variables. \"\"\"\n\n # Sprite lists\n self.player_list = None\n\n # Set up the player\n self.score = 0\n self.player = None\n\n def setup(self):\n self.player_list = arcade.SpriteList()\n # Set up the player\n self.score = 0\n self.player = Toad()\n\n self.player.center_x = SCREEN_WIDTH // 2\n self.player.center_y = SCREEN_HEIGHT // 2\n #self.player.scale = 0.8\n\n self.player_list.append(self.player)\n # Set the background color\n arcade.set_background_color(arcade.color.AMAZON)\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n # This command has to happen before we start drawing\n arcade.start_render()\n\n # Draw all the sprites.\n self.player_list.draw()\n\n # Put the text on the screen.\n output = f\"Score: {self.score}\"\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)\n\n def on_key_press(self, key, modifiers):\n \"\"\"\n Called whenever a key is pressed.\n \"\"\"\n if key == arcade.key.UP:\n self.player.change_y = MOVEMENT_SPEED\n elif key == arcade.key.DOWN:\n self.player.change_y = -MOVEMENT_SPEED\n elif key == arcade.key.LEFT:\n self.player.change_x = -MOVEMENT_SPEED\n elif key == arcade.key.RIGHT:\n self.player.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"\n Called when the user releases a key.\n \"\"\"\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n\n self.player_list.update()\n self.player_list.update_animation()\n\n\ndef main():\n \"\"\" Main method \"\"\"\n window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n window.setup()\n arcade.run()\n\n\nif __name__ == \"__main__\":\n main()", "<docstring token>\nimport arcade\nimport os\nfrom Toad_arcade import Toad\nSCREEN_WIDTH = 1920\nSCREEN_HEIGHT = 1080\nSCREEN_TITLE = 'PyToads - Battletoads reimplementation'\nCHARACTER_SCALING = 1\nTILE_SCALING = 0.5\nCOIN_SCALING = 0.5\nMOVEMENT_SPEED = 5\n\n\nclass MyGame(arcade.Window):\n \"\"\" Main application class. \"\"\"\n\n def __init__(self, width, height, title):\n \"\"\"\n Initializer\n \"\"\"\n super().__init__(width, height, title)\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n \"\"\" Set up the game and initialize the variables. \"\"\"\n self.player_list = None\n self.score = 0\n self.player = None\n\n def setup(self):\n self.player_list = arcade.SpriteList()\n self.score = 0\n self.player = Toad()\n self.player.center_x = SCREEN_WIDTH // 2\n self.player.center_y = SCREEN_HEIGHT // 2\n self.player_list.append(self.player)\n arcade.set_background_color(arcade.color.AMAZON)\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n arcade.start_render()\n self.player_list.draw()\n output = f'Score: {self.score}'\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)\n\n def on_key_press(self, key, modifiers):\n \"\"\"\n Called whenever a key is pressed.\n \"\"\"\n if key == arcade.key.UP:\n self.player.change_y = MOVEMENT_SPEED\n elif key == arcade.key.DOWN:\n self.player.change_y = -MOVEMENT_SPEED\n elif key == arcade.key.LEFT:\n self.player.change_x = -MOVEMENT_SPEED\n elif key == arcade.key.RIGHT:\n self.player.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"\n Called when the user releases a key.\n \"\"\"\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.player_list.update()\n self.player_list.update_animation()\n\n\ndef main():\n \"\"\" Main method \"\"\"\n window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n window.setup()\n arcade.run()\n\n\nif __name__ == '__main__':\n main()\n", "<docstring token>\n<import token>\nSCREEN_WIDTH = 1920\nSCREEN_HEIGHT = 1080\nSCREEN_TITLE = 'PyToads - Battletoads reimplementation'\nCHARACTER_SCALING = 1\nTILE_SCALING = 0.5\nCOIN_SCALING = 0.5\nMOVEMENT_SPEED = 5\n\n\nclass MyGame(arcade.Window):\n \"\"\" Main application class. \"\"\"\n\n def __init__(self, width, height, title):\n \"\"\"\n Initializer\n \"\"\"\n super().__init__(width, height, title)\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n \"\"\" Set up the game and initialize the variables. \"\"\"\n self.player_list = None\n self.score = 0\n self.player = None\n\n def setup(self):\n self.player_list = arcade.SpriteList()\n self.score = 0\n self.player = Toad()\n self.player.center_x = SCREEN_WIDTH // 2\n self.player.center_y = SCREEN_HEIGHT // 2\n self.player_list.append(self.player)\n arcade.set_background_color(arcade.color.AMAZON)\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n arcade.start_render()\n self.player_list.draw()\n output = f'Score: {self.score}'\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)\n\n def on_key_press(self, key, modifiers):\n \"\"\"\n Called whenever a key is pressed.\n \"\"\"\n if key == arcade.key.UP:\n self.player.change_y = MOVEMENT_SPEED\n elif key == arcade.key.DOWN:\n self.player.change_y = -MOVEMENT_SPEED\n elif key == arcade.key.LEFT:\n self.player.change_x = -MOVEMENT_SPEED\n elif key == arcade.key.RIGHT:\n self.player.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"\n Called when the user releases a key.\n \"\"\"\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.player_list.update()\n self.player_list.update_animation()\n\n\ndef main():\n \"\"\" Main method \"\"\"\n window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n window.setup()\n arcade.run()\n\n\nif __name__ == '__main__':\n main()\n", "<docstring token>\n<import token>\n<assignment token>\n\n\nclass MyGame(arcade.Window):\n \"\"\" Main application class. \"\"\"\n\n def __init__(self, width, height, title):\n \"\"\"\n Initializer\n \"\"\"\n super().__init__(width, height, title)\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n \"\"\" Set up the game and initialize the variables. \"\"\"\n self.player_list = None\n self.score = 0\n self.player = None\n\n def setup(self):\n self.player_list = arcade.SpriteList()\n self.score = 0\n self.player = Toad()\n self.player.center_x = SCREEN_WIDTH // 2\n self.player.center_y = SCREEN_HEIGHT // 2\n self.player_list.append(self.player)\n arcade.set_background_color(arcade.color.AMAZON)\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n arcade.start_render()\n self.player_list.draw()\n output = f'Score: {self.score}'\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)\n\n def on_key_press(self, key, modifiers):\n \"\"\"\n Called whenever a key is pressed.\n \"\"\"\n if key == arcade.key.UP:\n self.player.change_y = MOVEMENT_SPEED\n elif key == arcade.key.DOWN:\n self.player.change_y = -MOVEMENT_SPEED\n elif key == arcade.key.LEFT:\n self.player.change_x = -MOVEMENT_SPEED\n elif key == arcade.key.RIGHT:\n self.player.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"\n Called when the user releases a key.\n \"\"\"\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.player_list.update()\n self.player_list.update_animation()\n\n\ndef main():\n \"\"\" Main method \"\"\"\n window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n window.setup()\n arcade.run()\n\n\nif __name__ == '__main__':\n main()\n", "<docstring token>\n<import token>\n<assignment token>\n\n\nclass MyGame(arcade.Window):\n \"\"\" Main application class. \"\"\"\n\n def __init__(self, width, height, title):\n \"\"\"\n Initializer\n \"\"\"\n super().__init__(width, height, title)\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n \"\"\" Set up the game and initialize the variables. \"\"\"\n self.player_list = None\n self.score = 0\n self.player = None\n\n def setup(self):\n self.player_list = arcade.SpriteList()\n self.score = 0\n self.player = Toad()\n self.player.center_x = SCREEN_WIDTH // 2\n self.player.center_y = SCREEN_HEIGHT // 2\n self.player_list.append(self.player)\n arcade.set_background_color(arcade.color.AMAZON)\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n arcade.start_render()\n self.player_list.draw()\n output = f'Score: {self.score}'\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)\n\n def on_key_press(self, key, modifiers):\n \"\"\"\n Called whenever a key is pressed.\n \"\"\"\n if key == arcade.key.UP:\n self.player.change_y = MOVEMENT_SPEED\n elif key == arcade.key.DOWN:\n self.player.change_y = -MOVEMENT_SPEED\n elif key == arcade.key.LEFT:\n self.player.change_x = -MOVEMENT_SPEED\n elif key == arcade.key.RIGHT:\n self.player.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"\n Called when the user releases a key.\n \"\"\"\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.player_list.update()\n self.player_list.update_animation()\n\n\ndef main():\n \"\"\" Main method \"\"\"\n window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n window.setup()\n arcade.run()\n\n\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n\n\nclass MyGame(arcade.Window):\n \"\"\" Main application class. \"\"\"\n\n def __init__(self, width, height, title):\n \"\"\"\n Initializer\n \"\"\"\n super().__init__(width, height, title)\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n \"\"\" Set up the game and initialize the variables. \"\"\"\n self.player_list = None\n self.score = 0\n self.player = None\n\n def setup(self):\n self.player_list = arcade.SpriteList()\n self.score = 0\n self.player = Toad()\n self.player.center_x = SCREEN_WIDTH // 2\n self.player.center_y = SCREEN_HEIGHT // 2\n self.player_list.append(self.player)\n arcade.set_background_color(arcade.color.AMAZON)\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n arcade.start_render()\n self.player_list.draw()\n output = f'Score: {self.score}'\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)\n\n def on_key_press(self, key, modifiers):\n \"\"\"\n Called whenever a key is pressed.\n \"\"\"\n if key == arcade.key.UP:\n self.player.change_y = MOVEMENT_SPEED\n elif key == arcade.key.DOWN:\n self.player.change_y = -MOVEMENT_SPEED\n elif key == arcade.key.LEFT:\n self.player.change_x = -MOVEMENT_SPEED\n elif key == arcade.key.RIGHT:\n self.player.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"\n Called when the user releases a key.\n \"\"\"\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.player_list.update()\n self.player_list.update_animation()\n\n\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n\n\nclass MyGame(arcade.Window):\n <docstring token>\n\n def __init__(self, width, height, title):\n \"\"\"\n Initializer\n \"\"\"\n super().__init__(width, height, title)\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n \"\"\" Set up the game and initialize the variables. \"\"\"\n self.player_list = None\n self.score = 0\n self.player = None\n\n def setup(self):\n self.player_list = arcade.SpriteList()\n self.score = 0\n self.player = Toad()\n self.player.center_x = SCREEN_WIDTH // 2\n self.player.center_y = SCREEN_HEIGHT // 2\n self.player_list.append(self.player)\n arcade.set_background_color(arcade.color.AMAZON)\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n arcade.start_render()\n self.player_list.draw()\n output = f'Score: {self.score}'\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)\n\n def on_key_press(self, key, modifiers):\n \"\"\"\n Called whenever a key is pressed.\n \"\"\"\n if key == arcade.key.UP:\n self.player.change_y = MOVEMENT_SPEED\n elif key == arcade.key.DOWN:\n self.player.change_y = -MOVEMENT_SPEED\n elif key == arcade.key.LEFT:\n self.player.change_x = -MOVEMENT_SPEED\n elif key == arcade.key.RIGHT:\n self.player.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"\n Called when the user releases a key.\n \"\"\"\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.player_list.update()\n self.player_list.update_animation()\n\n\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n\n\nclass MyGame(arcade.Window):\n <docstring token>\n\n def __init__(self, width, height, title):\n \"\"\"\n Initializer\n \"\"\"\n super().__init__(width, height, title)\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n \"\"\" Set up the game and initialize the variables. \"\"\"\n self.player_list = None\n self.score = 0\n self.player = None\n <function token>\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n arcade.start_render()\n self.player_list.draw()\n output = f'Score: {self.score}'\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)\n\n def on_key_press(self, key, modifiers):\n \"\"\"\n Called whenever a key is pressed.\n \"\"\"\n if key == arcade.key.UP:\n self.player.change_y = MOVEMENT_SPEED\n elif key == arcade.key.DOWN:\n self.player.change_y = -MOVEMENT_SPEED\n elif key == arcade.key.LEFT:\n self.player.change_x = -MOVEMENT_SPEED\n elif key == arcade.key.RIGHT:\n self.player.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"\n Called when the user releases a key.\n \"\"\"\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.player_list.update()\n self.player_list.update_animation()\n\n\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n\n\nclass MyGame(arcade.Window):\n <docstring token>\n <function token>\n <function token>\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n arcade.start_render()\n self.player_list.draw()\n output = f'Score: {self.score}'\n arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)\n\n def on_key_press(self, key, modifiers):\n \"\"\"\n Called whenever a key is pressed.\n \"\"\"\n if key == arcade.key.UP:\n self.player.change_y = MOVEMENT_SPEED\n elif key == arcade.key.DOWN:\n self.player.change_y = -MOVEMENT_SPEED\n elif key == arcade.key.LEFT:\n self.player.change_x = -MOVEMENT_SPEED\n elif key == arcade.key.RIGHT:\n self.player.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"\n Called when the user releases a key.\n \"\"\"\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.player_list.update()\n self.player_list.update_animation()\n\n\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n\n\nclass MyGame(arcade.Window):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def on_key_press(self, key, modifiers):\n \"\"\"\n Called whenever a key is pressed.\n \"\"\"\n if key == arcade.key.UP:\n self.player.change_y = MOVEMENT_SPEED\n elif key == arcade.key.DOWN:\n self.player.change_y = -MOVEMENT_SPEED\n elif key == arcade.key.LEFT:\n self.player.change_x = -MOVEMENT_SPEED\n elif key == arcade.key.RIGHT:\n self.player.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"\n Called when the user releases a key.\n \"\"\"\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.player_list.update()\n self.player_list.update_animation()\n\n\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n\n\nclass MyGame(arcade.Window):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def on_key_release(self, key, modifiers):\n \"\"\"\n Called when the user releases a key.\n \"\"\"\n if key == arcade.key.UP or key == arcade.key.DOWN:\n self.player.change_y = 0\n elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n self.player.change_x = 0\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.player_list.update()\n self.player_list.update_animation()\n\n\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n\n\nclass MyGame(arcade.Window):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def on_update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n self.player_list.update()\n self.player_list.update_animation()\n\n\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n\n\nclass MyGame(arcade.Window):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n", "<docstring token>\n<import token>\n<assignment token>\n<class token>\n<function token>\n<code token>\n" ]
false
749
b51591de921f6e153c1dd478cec7fad42ff4251a
from flask import request, Flask import ldap3 app = Flask(__name__) @app.route("/normal") def normal(): """ A RemoteFlowSource is used directly as DN and search filter """ unsafe_dc = request.args['dc'] unsafe_filter = request.args['username'] dn = "dc={}".format(unsafe_dc) search_filter = "(user={})".format(unsafe_filter) srv = ldap3.Server('ldap://127.0.0.1') conn = ldap3.Connection(srv, user=dn, auto_bind=True) conn.search(dn, search_filter) @app.route("/direct") def direct(): """ A RemoteFlowSource is used directly as DN and search filter using a oneline call to .search """ unsafe_dc = request.args['dc'] unsafe_filter = request.args['username'] dn = "dc={}".format(unsafe_dc) search_filter = "(user={})".format(unsafe_filter) srv = ldap3.Server('ldap://127.0.0.1') conn = ldap3.Connection(srv, user=dn, auto_bind=True).search( dn, search_filter) # if __name__ == "__main__": # app.run(debug=True)
[ "from flask import request, Flask\nimport ldap3\n\napp = Flask(__name__)\n\n\[email protected](\"/normal\")\ndef normal():\n \"\"\"\n A RemoteFlowSource is used directly as DN and search filter\n \"\"\"\n\n unsafe_dc = request.args['dc']\n unsafe_filter = request.args['username']\n\n dn = \"dc={}\".format(unsafe_dc)\n search_filter = \"(user={})\".format(unsafe_filter)\n\n srv = ldap3.Server('ldap://127.0.0.1')\n conn = ldap3.Connection(srv, user=dn, auto_bind=True)\n conn.search(dn, search_filter)\n\n\[email protected](\"/direct\")\ndef direct():\n \"\"\"\n A RemoteFlowSource is used directly as DN and search filter using a oneline call to .search\n \"\"\"\n\n unsafe_dc = request.args['dc']\n unsafe_filter = request.args['username']\n\n dn = \"dc={}\".format(unsafe_dc)\n search_filter = \"(user={})\".format(unsafe_filter)\n\n srv = ldap3.Server('ldap://127.0.0.1')\n conn = ldap3.Connection(srv, user=dn, auto_bind=True).search(\n dn, search_filter)\n\n# if __name__ == \"__main__\":\n# app.run(debug=True)\n", "from flask import request, Flask\nimport ldap3\napp = Flask(__name__)\n\n\[email protected]('/normal')\ndef normal():\n \"\"\"\n A RemoteFlowSource is used directly as DN and search filter\n \"\"\"\n unsafe_dc = request.args['dc']\n unsafe_filter = request.args['username']\n dn = 'dc={}'.format(unsafe_dc)\n search_filter = '(user={})'.format(unsafe_filter)\n srv = ldap3.Server('ldap://127.0.0.1')\n conn = ldap3.Connection(srv, user=dn, auto_bind=True)\n conn.search(dn, search_filter)\n\n\[email protected]('/direct')\ndef direct():\n \"\"\"\n A RemoteFlowSource is used directly as DN and search filter using a oneline call to .search\n \"\"\"\n unsafe_dc = request.args['dc']\n unsafe_filter = request.args['username']\n dn = 'dc={}'.format(unsafe_dc)\n search_filter = '(user={})'.format(unsafe_filter)\n srv = ldap3.Server('ldap://127.0.0.1')\n conn = ldap3.Connection(srv, user=dn, auto_bind=True).search(dn,\n search_filter)\n", "<import token>\napp = Flask(__name__)\n\n\[email protected]('/normal')\ndef normal():\n \"\"\"\n A RemoteFlowSource is used directly as DN and search filter\n \"\"\"\n unsafe_dc = request.args['dc']\n unsafe_filter = request.args['username']\n dn = 'dc={}'.format(unsafe_dc)\n search_filter = '(user={})'.format(unsafe_filter)\n srv = ldap3.Server('ldap://127.0.0.1')\n conn = ldap3.Connection(srv, user=dn, auto_bind=True)\n conn.search(dn, search_filter)\n\n\[email protected]('/direct')\ndef direct():\n \"\"\"\n A RemoteFlowSource is used directly as DN and search filter using a oneline call to .search\n \"\"\"\n unsafe_dc = request.args['dc']\n unsafe_filter = request.args['username']\n dn = 'dc={}'.format(unsafe_dc)\n search_filter = '(user={})'.format(unsafe_filter)\n srv = ldap3.Server('ldap://127.0.0.1')\n conn = ldap3.Connection(srv, user=dn, auto_bind=True).search(dn,\n search_filter)\n", "<import token>\n<assignment token>\n\n\[email protected]('/normal')\ndef normal():\n \"\"\"\n A RemoteFlowSource is used directly as DN and search filter\n \"\"\"\n unsafe_dc = request.args['dc']\n unsafe_filter = request.args['username']\n dn = 'dc={}'.format(unsafe_dc)\n search_filter = '(user={})'.format(unsafe_filter)\n srv = ldap3.Server('ldap://127.0.0.1')\n conn = ldap3.Connection(srv, user=dn, auto_bind=True)\n conn.search(dn, search_filter)\n\n\[email protected]('/direct')\ndef direct():\n \"\"\"\n A RemoteFlowSource is used directly as DN and search filter using a oneline call to .search\n \"\"\"\n unsafe_dc = request.args['dc']\n unsafe_filter = request.args['username']\n dn = 'dc={}'.format(unsafe_dc)\n search_filter = '(user={})'.format(unsafe_filter)\n srv = ldap3.Server('ldap://127.0.0.1')\n conn = ldap3.Connection(srv, user=dn, auto_bind=True).search(dn,\n search_filter)\n", "<import token>\n<assignment token>\n\n\[email protected]('/normal')\ndef normal():\n \"\"\"\n A RemoteFlowSource is used directly as DN and search filter\n \"\"\"\n unsafe_dc = request.args['dc']\n unsafe_filter = request.args['username']\n dn = 'dc={}'.format(unsafe_dc)\n search_filter = '(user={})'.format(unsafe_filter)\n srv = ldap3.Server('ldap://127.0.0.1')\n conn = ldap3.Connection(srv, user=dn, auto_bind=True)\n conn.search(dn, search_filter)\n\n\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n" ]
false
750
555f4e41661ff4cbf4b9d72feab41ca8b7da2d5f
# -*- coding: utf-8 -*- """ Created on Sun Jan 28 12:54:27 2018 @author: Alex """ import numpy as np def saveListToCSV(filepath, _list): with open(filepath,'ab') as f: np.savetxt(f, [_list], delimiter=',', fmt='%f')
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 28 12:54:27 2018\n\n@author: Alex\n\"\"\"\n\nimport numpy as np\n\ndef saveListToCSV(filepath, _list):\n with open(filepath,'ab') as f:\n np.savetxt(f, [_list], delimiter=',', fmt='%f')", "<docstring token>\nimport numpy as np\n\n\ndef saveListToCSV(filepath, _list):\n with open(filepath, 'ab') as f:\n np.savetxt(f, [_list], delimiter=',', fmt='%f')\n", "<docstring token>\n<import token>\n\n\ndef saveListToCSV(filepath, _list):\n with open(filepath, 'ab') as f:\n np.savetxt(f, [_list], delimiter=',', fmt='%f')\n", "<docstring token>\n<import token>\n<function token>\n" ]
false
751
81f5753e8d0004244b4ee8e26895cb2b38fbb8b6
#coding=utf-8 import shutil import zipfile # shutil.copyfile("file03.txt","file05.txt") #拷贝 # shutil.copytree("movie/大陆","电影") #拷贝文件夹 #忽略不需要拷贝的文件 # shutil.copytree("movie/大陆","电影",ignore=shutil.ignore_patterns("*.txt","*.html")) #压缩和解压缩 # shutil.make_archive("电影/压缩","zip","movie/大陆") z1 = zipfile.ZipFile("a.zip","w") z1.write("file05.txt") z1.write("file03.txt") z1.close() #解压缩 z2 = zipfile.ZipFile("a.zip","r") z2.extractall("电影") z2.close()
[ "#coding=utf-8\n\nimport shutil\nimport zipfile\n# shutil.copyfile(\"file03.txt\",\"file05.txt\") #拷贝\n\n# shutil.copytree(\"movie/大陆\",\"电影\") #拷贝文件夹\n\n#忽略不需要拷贝的文件\n# shutil.copytree(\"movie/大陆\",\"电影\",ignore=shutil.ignore_patterns(\"*.txt\",\"*.html\"))\n\n#压缩和解压缩\n# shutil.make_archive(\"电影/压缩\",\"zip\",\"movie/大陆\")\n\n\nz1 = zipfile.ZipFile(\"a.zip\",\"w\")\nz1.write(\"file05.txt\")\nz1.write(\"file03.txt\")\nz1.close()\n\n\n#解压缩\nz2 = zipfile.ZipFile(\"a.zip\",\"r\")\nz2.extractall(\"电影\")\nz2.close()\n\n\n", "import shutil\nimport zipfile\nz1 = zipfile.ZipFile('a.zip', 'w')\nz1.write('file05.txt')\nz1.write('file03.txt')\nz1.close()\nz2 = zipfile.ZipFile('a.zip', 'r')\nz2.extractall('电影')\nz2.close()\n", "<import token>\nz1 = zipfile.ZipFile('a.zip', 'w')\nz1.write('file05.txt')\nz1.write('file03.txt')\nz1.close()\nz2 = zipfile.ZipFile('a.zip', 'r')\nz2.extractall('电影')\nz2.close()\n", "<import token>\n<assignment token>\nz1.write('file05.txt')\nz1.write('file03.txt')\nz1.close()\n<assignment token>\nz2.extractall('电影')\nz2.close()\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
752
ea2e9399a8384600d8457a9de3f263db44dc883d
import pandas as pd # 데이터 로드 train_data = pd.read_csv('./dataset/train_park_daycare.csv') cctv = pd.read_csv("./dataset/cctv_origin.csv", encoding="EUC-KR") ## 데이터 전처리 # 데이터 추출 cctv = cctv.iloc[1:, :2] # 구 매핑 gu_dict_num = {'용산구': 0, '양천구': 1, '강동구': 2, '관악구': 3, '노원구': 4, '영등포': 5, '영등포구': 5, '마포구': 6, '서초구': 7, '성동구': 8, '금천구': 9, '도봉구': 10, '동작구': 11, '강서구': 12, '동대문': 13, '동대문구': 13, '강북구': 14, '서대문': 15, '서대문구': 15, '광진구': 16, '구로구': 17, '성북구': 18, '강남구': 19, '종로구': 20, '중구': 21, '중랑구': 22, '송파구': 23, '은평구': 24} gu_list = [] for i in cctv['구분']: gu_list.append(gu_dict_num[i]) cctv['gu'] = gu_list cctv.drop(['구분'], axis=1, inplace=True) # 컬럼 이름 변경 cctv = cctv.rename(columns={'총계': 'cctv_num'}) # 데이터 타입 변경 cctv['cctv_num'] = cctv['cctv_num'].apply(lambda x: "".join(x.split(','))) cctv['cctv_num'] = pd.to_numeric(cctv['cctv_num']) # 조인 new_data = pd.merge(train_data, cctv, on='gu', how='left') print(new_data.info()) # 저장 new_data.to_csv("./dataset/train_add_cctv.csv", header=True, index=False)
[ "import pandas as pd\n\n# 데이터 로드\ntrain_data = pd.read_csv('./dataset/train_park_daycare.csv')\ncctv = pd.read_csv(\"./dataset/cctv_origin.csv\", encoding=\"EUC-KR\")\n\n## 데이터 전처리\n# 데이터 추출\ncctv = cctv.iloc[1:, :2]\n\n# 구 매핑\ngu_dict_num = {'용산구': 0, '양천구': 1, '강동구': 2, '관악구': 3, '노원구': 4, '영등포': 5, '영등포구': 5, '마포구': 6, '서초구': 7, '성동구': 8, '금천구': 9, '도봉구': 10, '동작구': 11, '강서구': 12, '동대문': 13, '동대문구': 13, '강북구': 14, '서대문': 15, '서대문구': 15, '광진구': 16, '구로구': 17, '성북구': 18, '강남구': 19, '종로구': 20, '중구': 21, '중랑구': 22, '송파구': 23, '은평구': 24}\ngu_list = []\nfor i in cctv['구분']:\n gu_list.append(gu_dict_num[i])\ncctv['gu'] = gu_list\ncctv.drop(['구분'], axis=1, inplace=True)\n\n# 컬럼 이름 변경\ncctv = cctv.rename(columns={'총계': 'cctv_num'})\n\n# 데이터 타입 변경\ncctv['cctv_num'] = cctv['cctv_num'].apply(lambda x: \"\".join(x.split(',')))\ncctv['cctv_num'] = pd.to_numeric(cctv['cctv_num'])\n\n# 조인\nnew_data = pd.merge(train_data, cctv, on='gu', how='left')\n\nprint(new_data.info())\n# 저장\nnew_data.to_csv(\"./dataset/train_add_cctv.csv\", header=True, index=False)\n\n", "import pandas as pd\ntrain_data = pd.read_csv('./dataset/train_park_daycare.csv')\ncctv = pd.read_csv('./dataset/cctv_origin.csv', encoding='EUC-KR')\ncctv = cctv.iloc[1:, :2]\ngu_dict_num = {'용산구': 0, '양천구': 1, '강동구': 2, '관악구': 3, '노원구': 4, '영등포': 5,\n '영등포구': 5, '마포구': 6, '서초구': 7, '성동구': 8, '금천구': 9, '도봉구': 10, '동작구': 11,\n '강서구': 12, '동대문': 13, '동대문구': 13, '강북구': 14, '서대문': 15, '서대문구': 15,\n '광진구': 16, '구로구': 17, '성북구': 18, '강남구': 19, '종로구': 20, '중구': 21, '중랑구':\n 22, '송파구': 23, '은평구': 24}\ngu_list = []\nfor i in cctv['구분']:\n gu_list.append(gu_dict_num[i])\ncctv['gu'] = gu_list\ncctv.drop(['구분'], axis=1, inplace=True)\ncctv = cctv.rename(columns={'총계': 'cctv_num'})\ncctv['cctv_num'] = cctv['cctv_num'].apply(lambda x: ''.join(x.split(',')))\ncctv['cctv_num'] = pd.to_numeric(cctv['cctv_num'])\nnew_data = pd.merge(train_data, cctv, on='gu', how='left')\nprint(new_data.info())\nnew_data.to_csv('./dataset/train_add_cctv.csv', header=True, index=False)\n", "<import token>\ntrain_data = pd.read_csv('./dataset/train_park_daycare.csv')\ncctv = pd.read_csv('./dataset/cctv_origin.csv', encoding='EUC-KR')\ncctv = cctv.iloc[1:, :2]\ngu_dict_num = {'용산구': 0, '양천구': 1, '강동구': 2, '관악구': 3, '노원구': 4, '영등포': 5,\n '영등포구': 5, '마포구': 6, '서초구': 7, '성동구': 8, '금천구': 9, '도봉구': 10, '동작구': 11,\n '강서구': 12, '동대문': 13, '동대문구': 13, '강북구': 14, '서대문': 15, '서대문구': 15,\n '광진구': 16, '구로구': 17, '성북구': 18, '강남구': 19, '종로구': 20, '중구': 21, '중랑구':\n 22, '송파구': 23, '은평구': 24}\ngu_list = []\nfor i in cctv['구분']:\n gu_list.append(gu_dict_num[i])\ncctv['gu'] = gu_list\ncctv.drop(['구분'], axis=1, inplace=True)\ncctv = cctv.rename(columns={'총계': 'cctv_num'})\ncctv['cctv_num'] = cctv['cctv_num'].apply(lambda x: ''.join(x.split(',')))\ncctv['cctv_num'] = pd.to_numeric(cctv['cctv_num'])\nnew_data = pd.merge(train_data, cctv, on='gu', how='left')\nprint(new_data.info())\nnew_data.to_csv('./dataset/train_add_cctv.csv', header=True, index=False)\n", "<import token>\n<assignment token>\nfor i in cctv['구분']:\n gu_list.append(gu_dict_num[i])\n<assignment token>\ncctv.drop(['구분'], axis=1, inplace=True)\n<assignment token>\nprint(new_data.info())\nnew_data.to_csv('./dataset/train_add_cctv.csv', header=True, index=False)\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
753
86d42716e05155f9e659b22c42635a8f5b8c4a60
import tensorflow as tf from typing import Optional, Tuple, Union, Callable _data_augmentation = tf.keras.Sequential( [ tf.keras.layers.experimental.preprocessing.RandomFlip("horizontal"), tf.keras.layers.experimental.preprocessing.RandomRotation(0.2), ] ) def _freeze_model( model: tf.keras.Model, freeze: Union[bool, int, float] = False, ): # Obs: # When you set layer.trainable = False, the BatchNormalization layer will # run in inference mode, and will not update its mean and variance statistics # https://www.tensorflow.org/tutorials/images/transfer_learning#important_note_about_batchnormalization_layers if isinstance(freeze, int): freeze_len = freeze elif isinstance(freeze, float): freeze_len = int(freeze * len(model.layers)) else: # isinstance(freeze, bool): if freeze: freeze_len = len(model.layers) else: freeze_len = 0 if freeze_len != len(model.layers): model.trainable = True for layer in model.layers[:freeze_len]: layer.trainable = False def generate_model( base_model: tf.keras.Model, img_shape: Tuple[Optional[int], Optional[int], Optional[int]], freeze: Union[bool, int, float] = False, preprocess_input: Optional[Callable] = None, use_data_augmentation: bool = True, ): inputs = tf.keras.layers.Input(shape=img_shape) if use_data_augmentation: x = _data_augmentation(inputs) if preprocess_input is not None: x = preprocess_input(inputs) x = base_model(x, training=False) x = tf.keras.layers.GlobalAveragePooling2D()(x) x = tf.keras.layers.Dropout(0.2)(x) outputs = tf.keras.layers.Dense(1, activation="sigmoid")(x) model = tf.keras.Model(inputs, outputs) _freeze_model(base_model, freeze) base_learning_rate = 0.0001 model.compile( optimizer=tf.keras.optimizers.Adam(learning_rate=base_learning_rate), loss=tf.keras.losses.BinaryCrossentropy(), metrics=["accuracy"], ) return model
[ "import tensorflow as tf\nfrom typing import Optional, Tuple, Union, Callable\n\n_data_augmentation = tf.keras.Sequential(\n [\n tf.keras.layers.experimental.preprocessing.RandomFlip(\"horizontal\"),\n tf.keras.layers.experimental.preprocessing.RandomRotation(0.2),\n ]\n)\n\n\ndef _freeze_model(\n model: tf.keras.Model,\n freeze: Union[bool, int, float] = False,\n):\n # Obs:\n # When you set layer.trainable = False, the BatchNormalization layer will\n # run in inference mode, and will not update its mean and variance statistics\n # https://www.tensorflow.org/tutorials/images/transfer_learning#important_note_about_batchnormalization_layers\n\n if isinstance(freeze, int):\n freeze_len = freeze\n elif isinstance(freeze, float):\n freeze_len = int(freeze * len(model.layers))\n else: # isinstance(freeze, bool):\n if freeze:\n freeze_len = len(model.layers)\n else:\n freeze_len = 0\n\n if freeze_len != len(model.layers):\n model.trainable = True\n\n for layer in model.layers[:freeze_len]:\n layer.trainable = False\n\n\ndef generate_model(\n base_model: tf.keras.Model,\n img_shape: Tuple[Optional[int], Optional[int], Optional[int]],\n freeze: Union[bool, int, float] = False,\n preprocess_input: Optional[Callable] = None,\n use_data_augmentation: bool = True,\n):\n inputs = tf.keras.layers.Input(shape=img_shape)\n if use_data_augmentation:\n x = _data_augmentation(inputs)\n if preprocess_input is not None:\n x = preprocess_input(inputs)\n x = base_model(x, training=False)\n x = tf.keras.layers.GlobalAveragePooling2D()(x)\n x = tf.keras.layers.Dropout(0.2)(x)\n outputs = tf.keras.layers.Dense(1, activation=\"sigmoid\")(x)\n\n model = tf.keras.Model(inputs, outputs)\n\n _freeze_model(base_model, freeze)\n\n base_learning_rate = 0.0001\n model.compile(\n optimizer=tf.keras.optimizers.Adam(learning_rate=base_learning_rate),\n loss=tf.keras.losses.BinaryCrossentropy(),\n metrics=[\"accuracy\"],\n )\n\n return model\n", "import tensorflow as tf\nfrom typing import Optional, Tuple, Union, Callable\n_data_augmentation = tf.keras.Sequential([tf.keras.layers.experimental.\n preprocessing.RandomFlip('horizontal'), tf.keras.layers.experimental.\n preprocessing.RandomRotation(0.2)])\n\n\ndef _freeze_model(model: tf.keras.Model, freeze: Union[bool, int, float]=False\n ):\n if isinstance(freeze, int):\n freeze_len = freeze\n elif isinstance(freeze, float):\n freeze_len = int(freeze * len(model.layers))\n elif freeze:\n freeze_len = len(model.layers)\n else:\n freeze_len = 0\n if freeze_len != len(model.layers):\n model.trainable = True\n for layer in model.layers[:freeze_len]:\n layer.trainable = False\n\n\ndef generate_model(base_model: tf.keras.Model, img_shape: Tuple[Optional[\n int], Optional[int], Optional[int]], freeze: Union[bool, int, float]=\n False, preprocess_input: Optional[Callable]=None, use_data_augmentation:\n bool=True):\n inputs = tf.keras.layers.Input(shape=img_shape)\n if use_data_augmentation:\n x = _data_augmentation(inputs)\n if preprocess_input is not None:\n x = preprocess_input(inputs)\n x = base_model(x, training=False)\n x = tf.keras.layers.GlobalAveragePooling2D()(x)\n x = tf.keras.layers.Dropout(0.2)(x)\n outputs = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n model = tf.keras.Model(inputs, outputs)\n _freeze_model(base_model, freeze)\n base_learning_rate = 0.0001\n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=\n base_learning_rate), loss=tf.keras.losses.BinaryCrossentropy(),\n metrics=['accuracy'])\n return model\n", "<import token>\n_data_augmentation = tf.keras.Sequential([tf.keras.layers.experimental.\n preprocessing.RandomFlip('horizontal'), tf.keras.layers.experimental.\n preprocessing.RandomRotation(0.2)])\n\n\ndef _freeze_model(model: tf.keras.Model, freeze: Union[bool, int, float]=False\n ):\n if isinstance(freeze, int):\n freeze_len = freeze\n elif isinstance(freeze, float):\n freeze_len = int(freeze * len(model.layers))\n elif freeze:\n freeze_len = len(model.layers)\n else:\n freeze_len = 0\n if freeze_len != len(model.layers):\n model.trainable = True\n for layer in model.layers[:freeze_len]:\n layer.trainable = False\n\n\ndef generate_model(base_model: tf.keras.Model, img_shape: Tuple[Optional[\n int], Optional[int], Optional[int]], freeze: Union[bool, int, float]=\n False, preprocess_input: Optional[Callable]=None, use_data_augmentation:\n bool=True):\n inputs = tf.keras.layers.Input(shape=img_shape)\n if use_data_augmentation:\n x = _data_augmentation(inputs)\n if preprocess_input is not None:\n x = preprocess_input(inputs)\n x = base_model(x, training=False)\n x = tf.keras.layers.GlobalAveragePooling2D()(x)\n x = tf.keras.layers.Dropout(0.2)(x)\n outputs = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n model = tf.keras.Model(inputs, outputs)\n _freeze_model(base_model, freeze)\n base_learning_rate = 0.0001\n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=\n base_learning_rate), loss=tf.keras.losses.BinaryCrossentropy(),\n metrics=['accuracy'])\n return model\n", "<import token>\n<assignment token>\n\n\ndef _freeze_model(model: tf.keras.Model, freeze: Union[bool, int, float]=False\n ):\n if isinstance(freeze, int):\n freeze_len = freeze\n elif isinstance(freeze, float):\n freeze_len = int(freeze * len(model.layers))\n elif freeze:\n freeze_len = len(model.layers)\n else:\n freeze_len = 0\n if freeze_len != len(model.layers):\n model.trainable = True\n for layer in model.layers[:freeze_len]:\n layer.trainable = False\n\n\ndef generate_model(base_model: tf.keras.Model, img_shape: Tuple[Optional[\n int], Optional[int], Optional[int]], freeze: Union[bool, int, float]=\n False, preprocess_input: Optional[Callable]=None, use_data_augmentation:\n bool=True):\n inputs = tf.keras.layers.Input(shape=img_shape)\n if use_data_augmentation:\n x = _data_augmentation(inputs)\n if preprocess_input is not None:\n x = preprocess_input(inputs)\n x = base_model(x, training=False)\n x = tf.keras.layers.GlobalAveragePooling2D()(x)\n x = tf.keras.layers.Dropout(0.2)(x)\n outputs = tf.keras.layers.Dense(1, activation='sigmoid')(x)\n model = tf.keras.Model(inputs, outputs)\n _freeze_model(base_model, freeze)\n base_learning_rate = 0.0001\n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=\n base_learning_rate), loss=tf.keras.losses.BinaryCrossentropy(),\n metrics=['accuracy'])\n return model\n", "<import token>\n<assignment token>\n\n\ndef _freeze_model(model: tf.keras.Model, freeze: Union[bool, int, float]=False\n ):\n if isinstance(freeze, int):\n freeze_len = freeze\n elif isinstance(freeze, float):\n freeze_len = int(freeze * len(model.layers))\n elif freeze:\n freeze_len = len(model.layers)\n else:\n freeze_len = 0\n if freeze_len != len(model.layers):\n model.trainable = True\n for layer in model.layers[:freeze_len]:\n layer.trainable = False\n\n\n<function token>\n", "<import token>\n<assignment token>\n<function token>\n<function token>\n" ]
false
754
cac9d84f20a79b115c84ff4fe8cf4640182a42d7
"""Those things that are core to tests. This module provides the most fundamental test entities, which include such things as: - Tests - Suites - Test states """ from __future__ import print_function __docformat__ = "restructuredtext" import os import textwrap import time import weakref import inspect from cleversheep3.Prog.Aspects import intelliprop from cleversheep3.Prog.Enum import Enum from cleversheep3.Test.Tester import Context from cleversheep3.Test.Tester import Coordinator from cleversheep3.Test.Tester import options State = Enum("State") # Static test states. NOT_RUN = State("NOT_RUN") PASS = State("PASS") FAIL = State("FAIL") SKIPPED = State("SKIPPED") BROKEN = State("BROKEN") DISABLED = State("DISABLED") BUG = State("BUG") BUG_PASS = State("BUG_PASS") TODO = State("TODO") # Dynamic test states. SET_UP = State("SET_UP") TEAR_DOWN = State("TEAR_DOWN") RUNNING = State("RUNNING") FINISHED = State("FINISHED") # TODO: To remove! # Suite specific states. CHILD_FAIL = State("CHILD_FAIL") PART_RUN = State("PART_RUN") # Reason codes. Note that this list is those codes that are only used as # reasons, some states are also used as reason code. NONE = State("NONE") ERROR = State("ERROR") BAD_SETUP = State("BAD_SETUP") BAD_SUITE_SETUP = State("BAD_SUITE_SETUP") EXIT_SUITE = State("EXIT_SUITE") EXIT_ALL = State("EXIT_ALL") USER_STOPPED = State("USER_STOPPED") def dedentLines(lines): return textwrap.dedent("\n".join(lines)).splitlines() class TestInfo: """Information about a test function. This class supports the ``@test(...)`` decorator that is used by cleversheep3 to mark test functions. All such marked functions are given an attribute called ``cs_test_info``, which is in an instance of this class. This is most commonly used in test filter functions, as registered by `addTestFilter`. When tests are marked using the ``@test`` decorator they can be given one or more tags and/or flags. Currently this is little more than a struct, except that it provides a `__getattr__` that returns ``None`` by default. """ def __init__(self, *args, **kwargs): """Constructor: :Parameters: args Non-keyword arguments are interpreted by the test framework. Each argument is a string. The supported forms are: plat:<platformType> The test will only be executed if ``<platformType>`` matches `Sys.Platform.platformType`. For example: ``"plat:windows"``. kwargs Any keyword arguments are simply stored as attributes. So, if you decorate a ``test_x`` with ``test(xyz=123)`` then ``test_x.cs_test_info.xyz`` will be ``123``. """ self.reserved_cs_flags = {} self.cs_flags = {} self.cs_tags = {} for arg in args: if ":" in arg: name, value = arg.split(":", 1) self.cs_flags[name] = value else: self.cs_flags[arg] = True for name in kwargs: if name.startswith("cs_"): self.reserved_cs_flags[name[3:]] = kwargs[name] else: self.cs_tags[name] = kwargs[name] self.reserved_cs_flags['defined_in_base'] = None def __getattr__(self, name): """Attribute access: Provides read access to test method tags. For example, if you mark a test:<py>: @test(abc="Hello") Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will be ``"Hello"``. If the test does not have ``abc`` set then the result is ``None``. """ if name in self.__dict__: return self.__dict__.get(name) return self.cs_tags.get(name, None) class Result: """Full result details for a test.""" def __init__(self, state, reason): self.state, self.reason = state, reason @property def reportCode(self): if self.reason is NONE: return self.state return self.reason class StepRecord: """A single record used to store informmation about the success or otherwise of a test phase. A test phase is one of: - A suite set-up/tear-down. - A test set-up/tear-down. - The execution of the test-method itself. :Ivariables: result TODO reason TODO """ def __init__(self, result=NOT_RUN, reason=NONE, details=None): self.result, self.reason = result, reason self.exc = None self.reported = False def setResult(self, state, reason=NONE, details=None): self._state, self._reason = state, reason self._details = details # TODO: Just transitional. @property def state(self): return self.result @property def hasFailed(self): return self.result in (FAIL, BAD_SETUP) def __str__(self): return "StepRecord: %s/%s" % (self.state, self.reason) class StepRecordList: def __init__(self): self.entries = [] class RunRecord: """A set of records containing all information about a single test's run. This stores multiple `StepRecord` instances. The records are stored in a dictionary keyed by the following names: setUp, tearDown, prevTearDown, rn Each maps to a single `StepRecord`. suiteSetUp, suiteTearDown, prevSuiteTearDown Each mapping to a list of `StepRecord` instances, in execution order. """ _simpleNames = """setUp tearDown prevTearDown run postCheck""".split() _listNames = """suiteSetUp suiteTearDown prevSuiteTearDown""".split() _recordNames = _simpleNames + _listNames _runTime = None def __init__(self): #assert RunRecord._runTime is not None self.runTime = RunRecord._runTime self.invalid = False self._records = {} self.extraInfo = {} def __setstate__(self, state): self.invalid = False self.__dict__.update(state) @classmethod def startNewRun(cls): cls._runTime = time.time() @classmethod def finishRun(cls): cls._runTime = None def addStepRecord(self, name): """Add a new phase record to this run record. Adds a new `StepRecord` for a test phase, which must be one of those defined for a `RunRecord`. :Parameters: name The name for the record. It must be the name of a defined test phase. :Return: The newly added `StepRecord` instance. This will always be a newly created instance. """ assert name in RunRecord._recordNames record = StepRecord() if name in RunRecord._simpleNames: assert name not in self._records self._records[name] = record else: if name not in self._records: self._records[name] = StepRecordList() self._records[name].entries.append(record) return record def getResult(self, name): pass @property def result(self): # Is set-up failed then we report that as bad setup. try: rec = self._records["setUp"] except KeyError: pass else: if rec.state is not PASS: result = Result(BAD_SETUP, BAD_SETUP) return result # See if the test was actually executed. try: rec = self._records["run"] except KeyError: pass else: result = Result(rec.state, rec.reason) return result # Test was not run, so we need to find out why. A suite set-up # failure means we consider the test not-run. for rec in self._records.get("suiteSetUp", []): if rec.state is not PASS: return Result(NOT_RUN, BAD_SUITE_SETUP) try: rec = self._records["setUp"] except KeyError: pass else: if rec.state is not PASS: return Result(NOT_RUN, BAD_SETUP) return Result(NOT_RUN, NONE) @property def state(self): # If set-up failed then we report that as bad setup. try: rec = self._records["setUp"] except KeyError: pass else: if rec.state is NOT_RUN: return NOT_RUN if rec.state not in (PASS, BUG, BUG_PASS): return BAD_SETUP # If the test has a 'run' entry then that defines the state. try: rec = self._records["run"] #if rec.state is NOT_RUN: # return RUNNING return rec.state except KeyError: pass # Otherwise the state is not-run. return NOT_RUN @property def isRunnable(self): for name in ("suiteTearDown", "tearDown", "suiteSetUp", "setUp"): try: if self._records[name].state not in (PASS, SKIPPED, NOT_RUN): return True except KeyError: pass return False @property def hasRunProblem(self): for name in ("tearDown", "suiteTearDown", "suiteSetUp", "setUp", "run", "postCheck"): try: record = self._records[name] except KeyError: continue if name in ("tearDown", "setUp", "run", "postCheck"): if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True else: for rec in record.entries: if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True return False @property def hasFailed(self): for name in ("suiteSetUp", "setUp", "run"): try: record = self._records[name] except KeyError: continue if name in ("setUp", "run"): if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True else: for rec in record.entries: if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG, BUG_PASS): return True return False @property def phaseRecord(self): """Get the most recent phaseRecord. This is used to get the most pertinent record for this test; i.e. the one that provides the most useful result for the test. TODO: This is not yet well defined. """ for name in ("tearDown", "run", "setUp"): try: return name, self._records[name] except KeyError: pass #return None, None seq = self._records.get("suiteSetUp", None) if seq is None: return None, None for ent in seq.entries: if ent.hasFailed: return "suiteSetUp", ent return "suiteSetUp", seq.entries[0] def getStepRecord(self, phase): """Get the record details for a test run phase.""" ent = self._records.get(phase, None) if hasattr(ent, "append"): # Yurk! seq = ent for ent in seq: if ent.hasFailed: return ent return seq.entries[0] if hasattr(ent, "entries"): # Double yurk! seq = ent.entries for ent in seq: if ent.hasFailed: return ent if seq: return seq[0] return return ent class TestItem: """Base class for `Test` and `Suite` classes. """ def __init__(self, item, uid, parentUid, context, namespace=None): """Constructor: :Parameters: item The concrete test item. For a test function/method this is the function/method itself. For a `ClassSuite` this is the instance and for a `ModuleSuite` this is the the module instance. uid The unique ID for this item, which is a tuple of strings. parentUid The unique ID of the parent item or ``None``. Only the root `Suite` of a test tree has a parent of ``None``. namespace A dictionary that provides the containing namespace for the test item. """ self.item = item self.uid = uid self.context = context self.parentUid = parentUid self.namespace = self._getNamespace(namespace) self._collection = None self._running = False self._marks = {} self.extraInfo = {} def setMark(self, mark): self._marks[mark] = None def clearMark(self, mark): if mark in self._marks: del self._marks[mark] def isMarked(self, mark): return mark in self._marks def setCollection(self, collection): self._collection = weakref.proxy(collection) # TODO: To remove. def setPhase(self, phase): self._phase = phase @intelliprop def state(self): """The current state of the test. """ result = self.getResult() return result.state def setState(self, state): if state is PASS: pass @intelliprop def level(self): """This item's level in the test tree. This is the number of ancestors this item has. If zero then this is the 'root' item. """ return len(self.ancestors) @intelliprop def parent(self): """The parent of this item, which may be ``None``. If this is ``None`` then this item is the root of a (possibly nested) suite of tests. """ return self._collection.parent(self) @intelliprop def ancestors(self): """A list of all ancestors for this item. Each entry is a UID. The first entry is the oldest ancesctor and the last entry is the immediate parent's UID. """ return self._collection.getAncestors(self) def hasFailingAncestor(self): """Check if any ancestor is considered to have failed. An ancestor suite has failed if, for example, its ``suiteSetup`` failed. :Return: ``True`` if any ancestors has failed. """ parent = self.parent if parent is None: return # TODO: Temporarily disabled. return return parent.hasFailed or parent.hasFailingAncestor() def _getNamespace(self, namespace=None): return namespace or dict([(n, getattr(self.item, n)) for n in dir(self.item)]) @intelliprop def rawDoc(self): """The raw docstring, no cleaning up performed at all.""" return self.namespace["__doc__"] @intelliprop def docLines(self): """The docstring as lines. This is cleaned up to remove leading and trailing blank lines from the summary and details. :Return: A sequence of (non-nul terminated) lines for the docstring. The summary (if present) is separated from the details by a single empty line. """ summary, description = self._getDocParts() if description: return summary + [""] + description return summary @intelliprop def doc(self): """The docstring after being cleaned up. :Return: The cleaned up docstrinc as a multiline string. Leading and trailing blank lines are removed and the summary is separated from any details by a single blakn line. Common leading whitspace is also removed from each line. """ return "\n".join(self.docLines) def _getDocParts(self): # Lose leading blank lines. lines = self.rawDoc.splitlines() while lines and not lines[0].strip(): lines.pop(0) # All lines up to next blank line are the summary. summary = [] while lines and lines[0].strip(): summary.append(lines.pop(0)) # Strip leading and trailing blank lines from the remaining details. while lines and not lines[0].strip(): lines.pop(0) while lines and not lines[-1].strip(): lines.pop() # Dedent the summary and details before returning them. summary = summary[:1] + dedentLines(summary[1:]) details = dedentLines(lines) return summary, details @property def summary(self): summary, description = self._getDocParts() return " ".join(summary) @property def details(self): summary, description = self._getDocParts() return description @property def sourcesUnderTest(self): sources = [] for p in self.namespace.get("sources_under_test", []): if not os.path.isabs(p): p = os.path.abspath(os.path.join(self.dirname, p)) sources.append(p) p = self.parent if p is not None: sources.extend(p.sourcesUnderTest) return sources @property def klass(self): return None @property def path(self): p = self.namespace.get("__file__", None) if p is None: return self.parent.path if p.endswith(".pyc"): p = p[:-1] return p @property def dirname(self): f = self.path if f: return os.path.dirname(f) @property def isBug(self): return False class Test(TestItem): typeName = "Test" isSuite = False amNull = False def __init__(self, *args, **kwargs): super(Test, self).__init__(*args, **kwargs) self._runHistory = [] self.stopAll = False if self.func: self.func.cs_test_info.test = weakref.proxy(self) def getHistory(self): return self._runHistory def dumpHist(self): return self._runHistory[-1].dump() def startNewRun(self): rec = RunRecord() self._runHistory.append(rec) def abortRun(self): self._runHistory.pop() def addStepRecord(self, name): runRecord = self._runHistory[-1] return runRecord.addStepRecord(name) @property def postCheck(self): return self.parent.postCheck @intelliprop def hasFailed(self): """Check if this test has properly failed. :Return: ``True`` if the test has failed to run for any reason. """ record = self.getRunRecord().getRecord("run") return record.state is FAIL @property def klass(self): return self.parent.klass @property def funcName(self): return self.item.__name__ @property def func(self): return self.item @property def info(self): return self.func.cs_test_info @property def isBroken(self): if not hasattr(self, "info"): raise PropertyError("%r has no attribute %r" % ( self.__class__.__name__, "info")) flag = self.info.reserved_cs_flags.get("broken", None) if flag is None: flag = self.info.cs_flags.get("broken", False) # deprecated return flag @property def isTodo(self): if not hasattr(self, "info"): raise PropertyError("%r has no attribute %r" % ( self.__class__.__name__, "info")) return self.info.cs_flags.get("todo", False) @property def isBug(self): if not hasattr(self, "info"): raise PropertyError("%r has no attribute %r" % ( self.__class__.__name__, "info")) flag = self.info.reserved_cs_flags.get("bug", None) if flag is None: flag = self.info.cs_flags.get("bug", False) # deprecated return flag @property def shouldFork(self): if not hasattr(self, "info"): raise PropertyError("%r has no attribute %r" % ( self.__class__.__name__, "info")) if self.info.reserved_cs_flags.get("fork", False): return True parent = self.parent try: return parent.suite.cs_attrs.fork_all except AttributeError: return False @property def testID(self): return self.info.cs_tags.get("testID", None) @property def title(self): return self.info.cs_flags.get("title", None) @property def isRunnable(self): #if self.isBroken and not options.no_disabled: # return False if self.parent.exited: return False return True @property def state(self): rec = self.runRecord if rec: return rec.state return NOT_RUN @property def result(self): rec = self.runRecord if rec: return rec.result return NOT_RUN @property def hasRunProblem(self): rec = self.runRecord if rec: return rec.hasRunProblem return False @property def hasFailed(self): rec = self.runRecord if rec: return rec.hasFailed return False def addRunRecord(self, record): self._runHistory.append(record) if len(self._runHistory) > 5: self._runHistory[:] = self._runHistory[-5:] @property def runRecord(self): """The XXX TODO""" if self._runHistory: for rec in reversed(self._runHistory): if not rec.invalid: return rec # TODO: Should now be StepRecord. @property def phaseRecord(self): """The XXX TODO""" if not self._runHistory: return None, None return self._runHistory[-1].phaseRecord def getStepRecord(self, phase): return self._runHistory[-1].getStepRecord(phase) def getTestProcedure(self): return self._collection.spec.getThing(self) class NullTest(Test): amNull = True def __init__(self): context = Context.getContext(dirPath=os.getcwd()) super(NullTest, self).__init__(None, None, None, context) self.number = 0 self.startNewRun() def startNewRun(self): rec = RunRecord() self._runHistory.append(rec) def abortRun(self): self._runHistory.pop() @property def isBug(self): return False def __bool__(self): return False class Suite(TestItem): typeName = "Suite" isSuite = True def __init__(self, *args, **kwargs): self.myDir = kwargs.pop("myDir") super(Suite, self).__init__(*args, **kwargs) self.exited = False self.number = 0 self.skipTests = False self.entered = False def reset(self): self.entered = False self.skipTests = False @intelliprop def children(self): """All the direct children of this item.""" tests = [t for t in self._collection if t.parent is self] suites = [t for t in self._collection.suites if t.parent is self] return suites + tests @intelliprop def tests(self): """All the direct test children of this item.""" return [t for t in self._collection if t.parent is self] @property def suite(self): return self.item @property def runAfter(self): """The _run_after for this source.""" return self.namespace.get("_run_after", []) @property def postCheck(self): return self.namespace.get("postCheck", lambda: None) @property def setUp(self): return self.namespace.get("setUp", lambda: None) @property def postSetUp(self): return self.namespace.get("postSetUp", lambda: None) @property def tearDown(self): return self.namespace.get("tearDown", lambda: None) @property def suiteSetUp(self): return self.namespace.get("suiteSetUp", lambda: None) @property def suiteTearDown(self): return self.namespace.get("suiteTearDown", lambda: None) def getResult(self, name=None): runCount = 0 childStates = {} result = Result(PASS, NONE) if not self.children: result.state = NOT_RUN return result for c in self.children: state = c.state runCount += state is not NOT_RUN childStates[state] = None if FAIL in childStates: result.state = CHILD_FAIL elif CHILD_FAIL in childStates: result.state = CHILD_FAIL elif BAD_SETUP in childStates: result.state = CHILD_FAIL elif PART_RUN in childStates: result.state = PART_RUN elif NOT_RUN in childStates: if runCount: result.state = PART_RUN else: result.state = NOT_RUN return result @property def result(self): return self.getResult() @property def state(self): result = self.getResult() return result.reportCode def hasTests(self): # Deprecated. Only used for old reporter support. for t in self._collection: if t.parent is self: return True class ModuleSuite(Suite): pass class ClassSuite(Suite): @property def klass(self): return self.item.__class__.__name__ def enter_pdb(): """Enter the python debugger.""" import sys, pdb sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__ pdb.set_trace()
[ "\"\"\"Those things that are core to tests.\n\nThis module provides the most fundamental test entities, which include such\nthings as:\n\n- Tests\n- Suites\n- Test states\n\n\"\"\"\nfrom __future__ import print_function\n__docformat__ = \"restructuredtext\"\n\nimport os\nimport textwrap\nimport time\nimport weakref\nimport inspect\n\nfrom cleversheep3.Prog.Aspects import intelliprop\nfrom cleversheep3.Prog.Enum import Enum\n\nfrom cleversheep3.Test.Tester import Context\nfrom cleversheep3.Test.Tester import Coordinator\nfrom cleversheep3.Test.Tester import options\n\nState = Enum(\"State\")\n\n# Static test states.\nNOT_RUN = State(\"NOT_RUN\")\nPASS = State(\"PASS\")\nFAIL = State(\"FAIL\")\nSKIPPED = State(\"SKIPPED\")\nBROKEN = State(\"BROKEN\")\nDISABLED = State(\"DISABLED\")\nBUG = State(\"BUG\")\nBUG_PASS = State(\"BUG_PASS\")\nTODO = State(\"TODO\")\n\n# Dynamic test states.\nSET_UP = State(\"SET_UP\")\nTEAR_DOWN = State(\"TEAR_DOWN\")\nRUNNING = State(\"RUNNING\")\nFINISHED = State(\"FINISHED\") # TODO: To remove!\n\n# Suite specific states.\nCHILD_FAIL = State(\"CHILD_FAIL\")\nPART_RUN = State(\"PART_RUN\")\n\n# Reason codes. Note that this list is those codes that are only used as\n# reasons, some states are also used as reason code.\nNONE = State(\"NONE\")\nERROR = State(\"ERROR\")\nBAD_SETUP = State(\"BAD_SETUP\")\nBAD_SUITE_SETUP = State(\"BAD_SUITE_SETUP\")\nEXIT_SUITE = State(\"EXIT_SUITE\")\nEXIT_ALL = State(\"EXIT_ALL\")\nUSER_STOPPED = State(\"USER_STOPPED\")\n\ndef dedentLines(lines):\n return textwrap.dedent(\"\\n\".join(lines)).splitlines()\n\n\nclass TestInfo:\n \"\"\"Information about a test function.\n\n This class supports the ``@test(...)`` decorator that is used by\n cleversheep3 to mark test functions. All such marked functions are given\n an attribute called ``cs_test_info``, which is in an instance of this\n class.\n\n This is most commonly used in test filter functions, as registered by\n `addTestFilter`. When tests are marked using the ``@test`` decorator\n they can be given one or more tags and/or flags.\n\n Currently this is little more than a struct, except that it provides\n a `__getattr__` that returns ``None`` by default.\n\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor:\n\n :Parameters:\n args\n Non-keyword arguments are interpreted by the test framework.\n Each argument is a string. The supported forms are:\n\n plat:<platformType>\n The test will only be executed if ``<platformType>`` matches\n `Sys.Platform.platformType`. For example: ``\"plat:windows\"``.\n\n kwargs\n Any keyword arguments are simply stored as attributes. So, if\n you decorate a ``test_x`` with ``test(xyz=123)`` then\n ``test_x.cs_test_info.xyz`` will be ``123``.\n \"\"\"\n self.reserved_cs_flags = {}\n self.cs_flags = {}\n self.cs_tags = {}\n for arg in args:\n if \":\" in arg:\n name, value = arg.split(\":\", 1)\n self.cs_flags[name] = value\n else:\n self.cs_flags[arg] = True\n\n for name in kwargs:\n if name.startswith(\"cs_\"):\n self.reserved_cs_flags[name[3:]] = kwargs[name]\n else:\n self.cs_tags[name] = kwargs[name]\n self.reserved_cs_flags['defined_in_base'] = None\n\n def __getattr__(self, name):\n \"\"\"Attribute access:\n\n Provides read access to test method tags. For example, if you mark a\n test:<py>:\n\n @test(abc=\"Hello\")\n\n Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will\n be ``\"Hello\"``. If the test does not have ``abc`` set then the result\n is ``None``.\n \"\"\"\n if name in self.__dict__:\n return self.__dict__.get(name)\n return self.cs_tags.get(name, None)\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n # TODO: Just transitional.\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return \"StepRecord: %s/%s\" % (self.state, self.reason)\n\n\nclass StepRecordList:\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = \"\"\"setUp tearDown prevTearDown run postCheck\"\"\".split()\n _listNames = \"\"\"suiteSetUp suiteTearDown prevSuiteTearDown\"\"\".split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n #assert RunRecord._runTime is not None\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n # Is set-up failed then we report that as bad setup.\n try:\n rec = self._records[\"setUp\"]\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n\n # See if the test was actually executed.\n try:\n rec = self._records[\"run\"]\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n\n # Test was not run, so we need to find out why. A suite set-up\n # failure means we consider the test not-run.\n for rec in self._records.get(\"suiteSetUp\", []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n\n try:\n rec = self._records[\"setUp\"]\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n # If set-up failed then we report that as bad setup.\n try:\n rec = self._records[\"setUp\"]\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n\n # If the test has a 'run' entry then that defines the state.\n try:\n rec = self._records[\"run\"]\n #if rec.state is NOT_RUN:\n # return RUNNING\n return rec.state\n except KeyError:\n pass\n\n # Otherwise the state is not-run.\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in (\"suiteTearDown\", \"tearDown\", \"suiteSetUp\", \"setUp\"):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n\n return False\n\n @property\n def hasRunProblem(self):\n for name in (\"tearDown\", \"suiteTearDown\", \"suiteSetUp\", \"setUp\",\n \"run\", \"postCheck\"):\n try:\n record = self._records[name]\n except KeyError:\n continue\n\n if name in (\"tearDown\", \"setUp\", \"run\", \"postCheck\"):\n if record.state not in (PASS, SKIPPED, NOT_RUN,\n TODO, BUG, BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN,\n TODO, BUG, BUG_PASS):\n return True\n\n return False\n\n @property\n def hasFailed(self):\n for name in (\"suiteSetUp\", \"setUp\", \"run\"):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in (\"setUp\", \"run\"):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN,\n TODO, BUG, BUG_PASS):\n return True\n\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in (\"tearDown\", \"run\", \"setUp\"):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n #return None, None\n seq = self._records.get(\"suiteSetUp\", None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return \"suiteSetUp\", ent\n return \"suiteSetUp\", seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, \"append\"): # Yurk!\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, \"entries\"): # Double yurk!\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n # TODO: To remove.\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n # TODO: Temporarily disabled.\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n))\n for n in dir(self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace[\"__doc__\"]\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [\"\"] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return \"\\n\".join(self.docLines)\n\n def _getDocParts(self):\n # Lose leading blank lines.\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n\n # All lines up to next blank line are the summary.\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n\n # Strip leading and trailing blank lines from the remaining details.\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n\n # Dedent the summary and details before returning them.\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return \" \".join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get(\"sources_under_test\", []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get(\"__file__\", None)\n if p is None:\n return self.parent.path\n if p.endswith(\".pyc\"):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = \"Test\"\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord(\"run\")\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n flag = self.info.reserved_cs_flags.get(\"broken\", None)\n if flag is None:\n flag = self.info.cs_flags.get(\"broken\", False) # deprecated\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n return self.info.cs_flags.get(\"todo\", False)\n\n @property\n def isBug(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n flag = self.info.reserved_cs_flags.get(\"bug\", None)\n if flag is None:\n flag = self.info.cs_flags.get(\"bug\", False) # deprecated\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n if self.info.reserved_cs_flags.get(\"fork\", False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get(\"testID\", None)\n\n @property\n def title(self):\n return self.info.cs_flags.get(\"title\", None)\n\n @property\n def isRunnable(self):\n #if self.isBroken and not options.no_disabled:\n # return False\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n # TODO: Should now be StepRecord.\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = \"Suite\"\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop(\"myDir\")\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get(\"_run_after\", [])\n\n @property\n def postCheck(self):\n return self.namespace.get(\"postCheck\", lambda: None)\n\n @property\n def setUp(self):\n return self.namespace.get(\"setUp\", lambda: None)\n\n @property\n def postSetUp(self):\n return self.namespace.get(\"postSetUp\", lambda: None)\n\n @property\n def tearDown(self):\n return self.namespace.get(\"tearDown\", lambda: None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get(\"suiteSetUp\", lambda: None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get(\"suiteTearDown\", lambda: None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n # Deprecated. Only used for old reporter support.\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\ndef enter_pdb():\n \"\"\"Enter the python debugger.\"\"\"\n import sys, pdb\n sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__\n pdb.set_trace()\n", "<docstring token>\nfrom __future__ import print_function\n__docformat__ = 'restructuredtext'\nimport os\nimport textwrap\nimport time\nimport weakref\nimport inspect\nfrom cleversheep3.Prog.Aspects import intelliprop\nfrom cleversheep3.Prog.Enum import Enum\nfrom cleversheep3.Test.Tester import Context\nfrom cleversheep3.Test.Tester import Coordinator\nfrom cleversheep3.Test.Tester import options\nState = Enum('State')\nNOT_RUN = State('NOT_RUN')\nPASS = State('PASS')\nFAIL = State('FAIL')\nSKIPPED = State('SKIPPED')\nBROKEN = State('BROKEN')\nDISABLED = State('DISABLED')\nBUG = State('BUG')\nBUG_PASS = State('BUG_PASS')\nTODO = State('TODO')\nSET_UP = State('SET_UP')\nTEAR_DOWN = State('TEAR_DOWN')\nRUNNING = State('RUNNING')\nFINISHED = State('FINISHED')\nCHILD_FAIL = State('CHILD_FAIL')\nPART_RUN = State('PART_RUN')\nNONE = State('NONE')\nERROR = State('ERROR')\nBAD_SETUP = State('BAD_SETUP')\nBAD_SUITE_SETUP = State('BAD_SUITE_SETUP')\nEXIT_SUITE = State('EXIT_SUITE')\nEXIT_ALL = State('EXIT_ALL')\nUSER_STOPPED = State('USER_STOPPED')\n\n\ndef dedentLines(lines):\n return textwrap.dedent('\\n'.join(lines)).splitlines()\n\n\nclass TestInfo:\n \"\"\"Information about a test function.\n\n This class supports the ``@test(...)`` decorator that is used by\n cleversheep3 to mark test functions. All such marked functions are given\n an attribute called ``cs_test_info``, which is in an instance of this\n class.\n\n This is most commonly used in test filter functions, as registered by\n `addTestFilter`. When tests are marked using the ``@test`` decorator\n they can be given one or more tags and/or flags.\n\n Currently this is little more than a struct, except that it provides\n a `__getattr__` that returns ``None`` by default.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor:\n\n :Parameters:\n args\n Non-keyword arguments are interpreted by the test framework.\n Each argument is a string. The supported forms are:\n\n plat:<platformType>\n The test will only be executed if ``<platformType>`` matches\n `Sys.Platform.platformType`. For example: ``\"plat:windows\"``.\n\n kwargs\n Any keyword arguments are simply stored as attributes. So, if\n you decorate a ``test_x`` with ``test(xyz=123)`` then\n ``test_x.cs_test_info.xyz`` will be ``123``.\n \"\"\"\n self.reserved_cs_flags = {}\n self.cs_flags = {}\n self.cs_tags = {}\n for arg in args:\n if ':' in arg:\n name, value = arg.split(':', 1)\n self.cs_flags[name] = value\n else:\n self.cs_flags[arg] = True\n for name in kwargs:\n if name.startswith('cs_'):\n self.reserved_cs_flags[name[3:]] = kwargs[name]\n else:\n self.cs_tags[name] = kwargs[name]\n self.reserved_cs_flags['defined_in_base'] = None\n\n def __getattr__(self, name):\n \"\"\"Attribute access:\n\n Provides read access to test method tags. For example, if you mark a\n test:<py>:\n\n @test(abc=\"Hello\")\n\n Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will\n be ``\"Hello\"``. If the test does not have ``abc`` set then the result\n is ``None``.\n \"\"\"\n if name in self.__dict__:\n return self.__dict__.get(name)\n return self.cs_tags.get(name, None)\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\ndef enter_pdb():\n \"\"\"Enter the python debugger.\"\"\"\n import sys, pdb\n sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__\n pdb.set_trace()\n", "<docstring token>\n<import token>\n__docformat__ = 'restructuredtext'\n<import token>\nState = Enum('State')\nNOT_RUN = State('NOT_RUN')\nPASS = State('PASS')\nFAIL = State('FAIL')\nSKIPPED = State('SKIPPED')\nBROKEN = State('BROKEN')\nDISABLED = State('DISABLED')\nBUG = State('BUG')\nBUG_PASS = State('BUG_PASS')\nTODO = State('TODO')\nSET_UP = State('SET_UP')\nTEAR_DOWN = State('TEAR_DOWN')\nRUNNING = State('RUNNING')\nFINISHED = State('FINISHED')\nCHILD_FAIL = State('CHILD_FAIL')\nPART_RUN = State('PART_RUN')\nNONE = State('NONE')\nERROR = State('ERROR')\nBAD_SETUP = State('BAD_SETUP')\nBAD_SUITE_SETUP = State('BAD_SUITE_SETUP')\nEXIT_SUITE = State('EXIT_SUITE')\nEXIT_ALL = State('EXIT_ALL')\nUSER_STOPPED = State('USER_STOPPED')\n\n\ndef dedentLines(lines):\n return textwrap.dedent('\\n'.join(lines)).splitlines()\n\n\nclass TestInfo:\n \"\"\"Information about a test function.\n\n This class supports the ``@test(...)`` decorator that is used by\n cleversheep3 to mark test functions. All such marked functions are given\n an attribute called ``cs_test_info``, which is in an instance of this\n class.\n\n This is most commonly used in test filter functions, as registered by\n `addTestFilter`. When tests are marked using the ``@test`` decorator\n they can be given one or more tags and/or flags.\n\n Currently this is little more than a struct, except that it provides\n a `__getattr__` that returns ``None`` by default.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor:\n\n :Parameters:\n args\n Non-keyword arguments are interpreted by the test framework.\n Each argument is a string. The supported forms are:\n\n plat:<platformType>\n The test will only be executed if ``<platformType>`` matches\n `Sys.Platform.platformType`. For example: ``\"plat:windows\"``.\n\n kwargs\n Any keyword arguments are simply stored as attributes. So, if\n you decorate a ``test_x`` with ``test(xyz=123)`` then\n ``test_x.cs_test_info.xyz`` will be ``123``.\n \"\"\"\n self.reserved_cs_flags = {}\n self.cs_flags = {}\n self.cs_tags = {}\n for arg in args:\n if ':' in arg:\n name, value = arg.split(':', 1)\n self.cs_flags[name] = value\n else:\n self.cs_flags[arg] = True\n for name in kwargs:\n if name.startswith('cs_'):\n self.reserved_cs_flags[name[3:]] = kwargs[name]\n else:\n self.cs_tags[name] = kwargs[name]\n self.reserved_cs_flags['defined_in_base'] = None\n\n def __getattr__(self, name):\n \"\"\"Attribute access:\n\n Provides read access to test method tags. For example, if you mark a\n test:<py>:\n\n @test(abc=\"Hello\")\n\n Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will\n be ``\"Hello\"``. If the test does not have ``abc`` set then the result\n is ``None``.\n \"\"\"\n if name in self.__dict__:\n return self.__dict__.get(name)\n return self.cs_tags.get(name, None)\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\ndef enter_pdb():\n \"\"\"Enter the python debugger.\"\"\"\n import sys, pdb\n sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__\n pdb.set_trace()\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n\n\ndef dedentLines(lines):\n return textwrap.dedent('\\n'.join(lines)).splitlines()\n\n\nclass TestInfo:\n \"\"\"Information about a test function.\n\n This class supports the ``@test(...)`` decorator that is used by\n cleversheep3 to mark test functions. All such marked functions are given\n an attribute called ``cs_test_info``, which is in an instance of this\n class.\n\n This is most commonly used in test filter functions, as registered by\n `addTestFilter`. When tests are marked using the ``@test`` decorator\n they can be given one or more tags and/or flags.\n\n Currently this is little more than a struct, except that it provides\n a `__getattr__` that returns ``None`` by default.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor:\n\n :Parameters:\n args\n Non-keyword arguments are interpreted by the test framework.\n Each argument is a string. The supported forms are:\n\n plat:<platformType>\n The test will only be executed if ``<platformType>`` matches\n `Sys.Platform.platformType`. For example: ``\"plat:windows\"``.\n\n kwargs\n Any keyword arguments are simply stored as attributes. So, if\n you decorate a ``test_x`` with ``test(xyz=123)`` then\n ``test_x.cs_test_info.xyz`` will be ``123``.\n \"\"\"\n self.reserved_cs_flags = {}\n self.cs_flags = {}\n self.cs_tags = {}\n for arg in args:\n if ':' in arg:\n name, value = arg.split(':', 1)\n self.cs_flags[name] = value\n else:\n self.cs_flags[arg] = True\n for name in kwargs:\n if name.startswith('cs_'):\n self.reserved_cs_flags[name[3:]] = kwargs[name]\n else:\n self.cs_tags[name] = kwargs[name]\n self.reserved_cs_flags['defined_in_base'] = None\n\n def __getattr__(self, name):\n \"\"\"Attribute access:\n\n Provides read access to test method tags. For example, if you mark a\n test:<py>:\n\n @test(abc=\"Hello\")\n\n Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will\n be ``\"Hello\"``. If the test does not have ``abc`` set then the result\n is ``None``.\n \"\"\"\n if name in self.__dict__:\n return self.__dict__.get(name)\n return self.cs_tags.get(name, None)\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\ndef enter_pdb():\n \"\"\"Enter the python debugger.\"\"\"\n import sys, pdb\n sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__\n pdb.set_trace()\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n\n\ndef dedentLines(lines):\n return textwrap.dedent('\\n'.join(lines)).splitlines()\n\n\nclass TestInfo:\n \"\"\"Information about a test function.\n\n This class supports the ``@test(...)`` decorator that is used by\n cleversheep3 to mark test functions. All such marked functions are given\n an attribute called ``cs_test_info``, which is in an instance of this\n class.\n\n This is most commonly used in test filter functions, as registered by\n `addTestFilter`. When tests are marked using the ``@test`` decorator\n they can be given one or more tags and/or flags.\n\n Currently this is little more than a struct, except that it provides\n a `__getattr__` that returns ``None`` by default.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor:\n\n :Parameters:\n args\n Non-keyword arguments are interpreted by the test framework.\n Each argument is a string. The supported forms are:\n\n plat:<platformType>\n The test will only be executed if ``<platformType>`` matches\n `Sys.Platform.platformType`. For example: ``\"plat:windows\"``.\n\n kwargs\n Any keyword arguments are simply stored as attributes. So, if\n you decorate a ``test_x`` with ``test(xyz=123)`` then\n ``test_x.cs_test_info.xyz`` will be ``123``.\n \"\"\"\n self.reserved_cs_flags = {}\n self.cs_flags = {}\n self.cs_tags = {}\n for arg in args:\n if ':' in arg:\n name, value = arg.split(':', 1)\n self.cs_flags[name] = value\n else:\n self.cs_flags[arg] = True\n for name in kwargs:\n if name.startswith('cs_'):\n self.reserved_cs_flags[name[3:]] = kwargs[name]\n else:\n self.cs_tags[name] = kwargs[name]\n self.reserved_cs_flags['defined_in_base'] = None\n\n def __getattr__(self, name):\n \"\"\"Attribute access:\n\n Provides read access to test method tags. For example, if you mark a\n test:<py>:\n\n @test(abc=\"Hello\")\n\n Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will\n be ``\"Hello\"``. If the test does not have ``abc`` set then the result\n is ``None``.\n \"\"\"\n if name in self.__dict__:\n return self.__dict__.get(name)\n return self.cs_tags.get(name, None)\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass TestInfo:\n \"\"\"Information about a test function.\n\n This class supports the ``@test(...)`` decorator that is used by\n cleversheep3 to mark test functions. All such marked functions are given\n an attribute called ``cs_test_info``, which is in an instance of this\n class.\n\n This is most commonly used in test filter functions, as registered by\n `addTestFilter`. When tests are marked using the ``@test`` decorator\n they can be given one or more tags and/or flags.\n\n Currently this is little more than a struct, except that it provides\n a `__getattr__` that returns ``None`` by default.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor:\n\n :Parameters:\n args\n Non-keyword arguments are interpreted by the test framework.\n Each argument is a string. The supported forms are:\n\n plat:<platformType>\n The test will only be executed if ``<platformType>`` matches\n `Sys.Platform.platformType`. For example: ``\"plat:windows\"``.\n\n kwargs\n Any keyword arguments are simply stored as attributes. So, if\n you decorate a ``test_x`` with ``test(xyz=123)`` then\n ``test_x.cs_test_info.xyz`` will be ``123``.\n \"\"\"\n self.reserved_cs_flags = {}\n self.cs_flags = {}\n self.cs_tags = {}\n for arg in args:\n if ':' in arg:\n name, value = arg.split(':', 1)\n self.cs_flags[name] = value\n else:\n self.cs_flags[arg] = True\n for name in kwargs:\n if name.startswith('cs_'):\n self.reserved_cs_flags[name[3:]] = kwargs[name]\n else:\n self.cs_tags[name] = kwargs[name]\n self.reserved_cs_flags['defined_in_base'] = None\n\n def __getattr__(self, name):\n \"\"\"Attribute access:\n\n Provides read access to test method tags. For example, if you mark a\n test:<py>:\n\n @test(abc=\"Hello\")\n\n Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will\n be ``\"Hello\"``. If the test does not have ``abc`` set then the result\n is ``None``.\n \"\"\"\n if name in self.__dict__:\n return self.__dict__.get(name)\n return self.cs_tags.get(name, None)\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass TestInfo:\n <docstring token>\n\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor:\n\n :Parameters:\n args\n Non-keyword arguments are interpreted by the test framework.\n Each argument is a string. The supported forms are:\n\n plat:<platformType>\n The test will only be executed if ``<platformType>`` matches\n `Sys.Platform.platformType`. For example: ``\"plat:windows\"``.\n\n kwargs\n Any keyword arguments are simply stored as attributes. So, if\n you decorate a ``test_x`` with ``test(xyz=123)`` then\n ``test_x.cs_test_info.xyz`` will be ``123``.\n \"\"\"\n self.reserved_cs_flags = {}\n self.cs_flags = {}\n self.cs_tags = {}\n for arg in args:\n if ':' in arg:\n name, value = arg.split(':', 1)\n self.cs_flags[name] = value\n else:\n self.cs_flags[arg] = True\n for name in kwargs:\n if name.startswith('cs_'):\n self.reserved_cs_flags[name[3:]] = kwargs[name]\n else:\n self.cs_tags[name] = kwargs[name]\n self.reserved_cs_flags['defined_in_base'] = None\n\n def __getattr__(self, name):\n \"\"\"Attribute access:\n\n Provides read access to test method tags. For example, if you mark a\n test:<py>:\n\n @test(abc=\"Hello\")\n\n Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will\n be ``\"Hello\"``. If the test does not have ``abc`` set then the result\n is ``None``.\n \"\"\"\n if name in self.__dict__:\n return self.__dict__.get(name)\n return self.cs_tags.get(name, None)\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass TestInfo:\n <docstring token>\n <function token>\n\n def __getattr__(self, name):\n \"\"\"Attribute access:\n\n Provides read access to test method tags. For example, if you mark a\n test:<py>:\n\n @test(abc=\"Hello\")\n\n Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will\n be ``\"Hello\"``. If the test does not have ``abc`` set then the result\n is ``None``.\n \"\"\"\n if name in self.__dict__:\n return self.__dict__.get(name)\n return self.cs_tags.get(name, None)\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n\n\nclass TestInfo:\n <docstring token>\n <function token>\n <function token>\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n\n\nclass Result:\n <docstring token>\n\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n\n\nclass Result:\n <docstring token>\n\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n <function token>\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n\n\nclass Result:\n <docstring token>\n <function token>\n <function token>\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass StepRecord:\n <docstring token>\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass StepRecord:\n <docstring token>\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n <function token>\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return 'StepRecord: %s/%s' % (self.state, self.reason)\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass StepRecord:\n <docstring token>\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n <function token>\n\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n <function token>\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass StepRecord:\n <docstring token>\n\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n <function token>\n <function token>\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n <function token>\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass StepRecord:\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n <function token>\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n\n\nclass StepRecord:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n\n\nclass StepRecordList:\n <function token>\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n <function token>\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n <function token>\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n <function token>\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n <function token>\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n <function token>\n <function token>\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n <function token>\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n <function token>\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n <function token>\n <function token>\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n <function token>\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n <function token>\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n <function token>\n <function token>\n\n def getResult(self, name):\n pass\n <function token>\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n <function token>\n <function token>\n\n def getResult(self, name):\n pass\n <function token>\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n <function token>\n <function token>\n\n def getResult(self, name):\n pass\n <function token>\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n <function token>\n <function token>\n\n def getResult(self, name):\n pass\n <function token>\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass RunRecord:\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n <function token>\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n <function token>\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n <function token>\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n <function token>\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n <function token>\n <function token>\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n <function token>\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n <function token>\n <function token>\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n <function token>\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n <function token>\n <function token>\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n <function token>\n <function token>\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n <function token>\n <function token>\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n <function token>\n <function token>\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n <function token>\n <function token>\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n <function token>\n\n @property\n def klass(self):\n return None\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n <function token>\n\n @property\n def klass(self):\n return None\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n <function token>\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n <function token>\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n <function token>\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n <function token>\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n <function token>\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n <function token>\n <function token>\n <function token>\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass TestItem:\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n <function token>\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n <function token>\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n <function token>\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n <function token>\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n <function token>\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n <function token>\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n <function token>\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n <function token>\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n <function token>\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n <function token>\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n <function token>\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n <function token>\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n <function token>\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n <function token>\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n <function token>\n <function token>\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n <function token>\n <function token>\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n <function token>\n <function token>\n <function token>\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n <function token>\n <function token>\n <function token>\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n <function token>\n <function token>\n <function token>\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n <function token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n\n @property\n def info(self):\n return self.func.cs_test_info\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n <function token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n <function token>\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n <function token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n <function token>\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n <function token>\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n <function token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n <function token>\n <function token>\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n <function token>\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n <function token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n <function token>\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n <function token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n <function token>\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n <function token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n <function token>\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n <function token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n <function token>\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n <function token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n <function token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Test(TestItem):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass NullTest(Test):\n <assignment token>\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass NullTest(Test):\n <assignment token>\n <function token>\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass NullTest(Test):\n <assignment token>\n <function token>\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n <function token>\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass NullTest(Test):\n <assignment token>\n <function token>\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n <function token>\n\n @property\n def isBug(self):\n return False\n <function token>\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass NullTest(Test):\n <assignment token>\n <function token>\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n <function token>\n <function token>\n <function token>\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass NullTest(Test):\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n <function token>\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n <function token>\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n <function token>\n\n @property\n def suite(self):\n return self.item\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n <function token>\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n <function token>\n <function token>\n\n @property\n def suite(self):\n return self.item\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n <function token>\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n <function token>\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n <function token>\n <function token>\n\n @property\n def suite(self):\n return self.item\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n <function token>\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n <function token>\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n <function token>\n <function token>\n\n @property\n def suite(self):\n return self.item\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n <function token>\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n <function token>\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n <function token>\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n <function token>\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n <function token>\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n <function token>\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n <function token>\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n <function token>\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n <function token>\n <function token>\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n <function token>\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n <function token>\n <function token>\n <function token>\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n <function token>\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Suite(TestItem):\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass ClassSuite(Suite):\n <function token>\n\n\n<function token>\n", "<docstring token>\n<import token>\n<assignment token>\n<import token>\n<assignment token>\n<function token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n<function token>\n" ]
false
755
7b1c7228c1fc9501ab857cba62a7e073691e75c9
""" @Description: @Author : HCQ @Contact_1: [email protected] @Project : pytorch @File : call_test @Time : 2022/5/24 下午10:19 @Last Modify Time @Version @Desciption -------------------- -------- ----------- 2022/5/24 下午10:19 1.0 None """ class Person(): def __call__(self, name): print("__call__" + " Hello " + name) def hello(self, name): print("hello " + name) person = Person() person("hcq") # 直接调用call person.hello("hcq")
[ "\"\"\"\n@Description: \n@Author : HCQ\n@Contact_1: [email protected]\n@Project : pytorch\n@File : call_test\n@Time : 2022/5/24 下午10:19\n@Last Modify Time @Version @Desciption\n-------------------- -------- -----------\n2022/5/24 下午10:19 1.0 None\n\"\"\"\n\nclass Person():\n def __call__(self, name):\n print(\"__call__\" + \" Hello \" + name)\n\n def hello(self, name):\n print(\"hello \" + name)\n\nperson = Person()\nperson(\"hcq\") # 直接调用call\nperson.hello(\"hcq\")", "<docstring token>\n\n\nclass Person:\n\n def __call__(self, name):\n print('__call__' + ' Hello ' + name)\n\n def hello(self, name):\n print('hello ' + name)\n\n\nperson = Person()\nperson('hcq')\nperson.hello('hcq')\n", "<docstring token>\n\n\nclass Person:\n\n def __call__(self, name):\n print('__call__' + ' Hello ' + name)\n\n def hello(self, name):\n print('hello ' + name)\n\n\n<assignment token>\nperson('hcq')\nperson.hello('hcq')\n", "<docstring token>\n\n\nclass Person:\n\n def __call__(self, name):\n print('__call__' + ' Hello ' + name)\n\n def hello(self, name):\n print('hello ' + name)\n\n\n<assignment token>\n<code token>\n", "<docstring token>\n\n\nclass Person:\n <function token>\n\n def hello(self, name):\n print('hello ' + name)\n\n\n<assignment token>\n<code token>\n", "<docstring token>\n\n\nclass Person:\n <function token>\n <function token>\n\n\n<assignment token>\n<code token>\n", "<docstring token>\n<class token>\n<assignment token>\n<code token>\n" ]
false
756
6a7e5a78f516cecf083ca3900bdaaf427bedd497
# -*- coding: utf-8 -*- """ Created on Tue May 22 15:01:21 2018 @author: Weiyu_Lee """ import numpy as np import pandas as pd import pickle import matplotlib.pyplot as plt from datetime import datetime, timedelta import config as conf def get_stock_time_series(data_df, stock_id): curr_ID_data = data_df.loc[stock_id] output = np.array(curr_ID_data[0]) for i in range(1, len(curr_ID_data.index)): output = np.vstack((output, curr_ID_data[i])) return output ID_conf = conf.config('feature_conf').config['ID'] #ETF_ID = ID_conf["ID"] #ETF_ID_list = ["0050"] ETF_ID_list = ["0050", "0052", "0053", "0054", "0055", "0056", "0057", "0058", "0059", "006201", "006203", "006204", "006208"] output_date = {} for ETF_ID in ETF_ID_list: Nm_conf = conf.config('feature_conf').config['Nm'] if Nm_conf["enable"] is True: Nm_method = Nm_conf["method"] file_postfix = '_Nm_' + str(Nm_conf["type"][0]) + '_' + Nm_method + '_' + str(94) + "_" + ETF_ID + '.pkl' else: file_postfix = "_" + str(94) + '.pkl' src_file_path = './Data/all_feature_data' + file_postfix meta_file_path = './Data/all_meta_data' + file_postfix data = pd.read_pickle(src_file_path) f = open(meta_file_path, "rb") tasharep_ID = pickle.load(f) member_ID = pickle.load(f) Date = pickle.load(f) feature_list = pickle.load(f) price_scaler = pickle.load(f) trade_scaler = pickle.load(f) f_idx = 59 # MACD src_time_period = ['20000101', '20180511'] # eval_time_period = ['20180511', '20180518'] eval_time_period = ['20180402', '20180518'] eval_time_len = Date.index(eval_time_period[1]) - Date.index(eval_time_period[0]) + 1 total_acc = 0 for day_shift in range(eval_time_len-5): eval_start_date = Date.index(eval_time_period[0]) + day_shift target_start_date = eval_start_date - 21 target_time_period = [Date[target_start_date], Date[eval_start_date]] next_time_period = [Date[eval_start_date], Date[eval_start_date + 5]] date_mask = (data.columns > src_time_period[0]) & (data.columns <= src_time_period[1]) src_data = data.iloc[:, date_mask] date_mask = (data.columns > target_time_period[0]) & (data.columns <= target_time_period[1]) target_data = data.iloc[:, date_mask] date_mask = (data.columns > next_time_period[0]) & (data.columns <= next_time_period[1]) next_data = data.iloc[:, date_mask] src_TS = get_stock_time_series(src_data, ETF_ID) target_TS = get_stock_time_series(target_data, ETF_ID) next_TS = get_stock_time_series(next_data, ETF_ID) overall_TS = get_stock_time_series(data, ETF_ID) target_xcorr = np.correlate(src_TS[:, f_idx], target_TS[:, f_idx], mode='valid') # next_xcorr = np.correlate(src_TS[:, f_idx], next_TS[:, f_idx], mode='valid') target_len = len(target_TS) max_target_xcorr_idx = target_xcorr.argsort()[::-1] predict_target_idx = max_target_xcorr_idx + target_len next_len = len(next_TS) max_next_xcorr_idx = next_xcorr.argsort()[::-1] # plt.plot(target_xcorr) # plt.savefig("target_xcorr_{}.png".format(ETF_ID)) #for idx in max_target_xcorr_idx[:10]: # plt.figure() # plt.plot(target_TS[:, 84]) # plt.plot(src_TS[max_target_xcorr_idx[idx]:max_target_xcorr_idx[idx]+target_len, 84]) #plt.figure() #plt.plot(target_xcorr) #plt.plot(next_xcorr) top_num = 10 acc = [] label = np.argmax(next_TS[:, -3:], axis=-1) for idx in max_target_xcorr_idx[:top_num]: predict = np.argmax(overall_TS[predict_target_idx[idx]:predict_target_idx[idx]+next_len, -3:], axis=-1) acc.append(sum(label == predict) / next_len) max_acc_idx = np.argsort(acc)[::-1] output_xcorr_idx = [max_target_xcorr_idx[acc_idx] for acc_idx in max_acc_idx] top_num = 3 avg_acc = 0 acc = [] for idx in output_xcorr_idx[:top_num]: #plt.figure() #plt.plot(next_TS[:, 84]) #plt.plot(overall_TS[predict_target_idx[idx]:predict_target_idx[idx]+next_len, 84]) #plt.figure() #plt.plot(overall_TS[predict_target_idx[idx]:predict_target_idx[idx]+next_len, 3]) predict = np.argmax(overall_TS[predict_target_idx[idx]:predict_target_idx[idx]+next_len, -3:], axis=-1) acc.append(sum(label == predict) / next_len) avg_acc = avg_acc + acc[-1] #print("Acc.: [{}]".format(acc[-1])) print("Avg. Acc.: [{}]".format(avg_acc/top_num)) total_acc = total_acc + avg_acc/top_num print("[{}] Overall Acc.: [{}]".format(ETF_ID, total_acc/(eval_time_len-5))) output_date[ETF_ID] = [Date[i] for i in output_xcorr_idx[:10]] f = open('./Data/xcorr_date_data.pkl', 'wb') pickle.dump(output_date, f, True) f.close()
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 22 15:01:21 2018\r\n\r\n@author: Weiyu_Lee\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nimport pickle\r\nimport matplotlib.pyplot as plt\r\nfrom datetime import datetime, timedelta\r\n\r\nimport config as conf\r\n\r\ndef get_stock_time_series(data_df, stock_id):\r\n \r\n curr_ID_data = data_df.loc[stock_id]\r\n\r\n output = np.array(curr_ID_data[0])\r\n for i in range(1, len(curr_ID_data.index)):\r\n output = np.vstack((output, curr_ID_data[i]))\r\n \r\n return output \r\n\r\nID_conf = conf.config('feature_conf').config['ID']\r\n#ETF_ID = ID_conf[\"ID\"]\r\n#ETF_ID_list = [\"0050\"]\r\nETF_ID_list = [\"0050\", \"0052\", \"0053\", \"0054\", \"0055\", \"0056\", \"0057\", \"0058\", \"0059\", \r\n \"006201\", \"006203\", \"006204\", \"006208\"]\r\n\r\noutput_date = {}\r\nfor ETF_ID in ETF_ID_list:\r\n Nm_conf = conf.config('feature_conf').config['Nm']\r\n if Nm_conf[\"enable\"] is True:\r\n Nm_method = Nm_conf[\"method\"]\r\n file_postfix = '_Nm_' + str(Nm_conf[\"type\"][0]) + '_' + Nm_method + '_' + str(94) + \"_\" + ETF_ID + '.pkl'\r\n else:\r\n file_postfix = \"_\" + str(94) + '.pkl'\r\n \r\n src_file_path = './Data/all_feature_data' + file_postfix\r\n meta_file_path = './Data/all_meta_data' + file_postfix\r\n \r\n data = pd.read_pickle(src_file_path)\r\n \r\n f = open(meta_file_path, \"rb\")\r\n tasharep_ID = pickle.load(f)\r\n member_ID = pickle.load(f)\r\n Date = pickle.load(f)\r\n feature_list = pickle.load(f)\r\n price_scaler = pickle.load(f)\r\n trade_scaler = pickle.load(f)\r\n \r\n f_idx = 59 # MACD\r\n \r\n src_time_period = ['20000101', '20180511']\r\n# eval_time_period = ['20180511', '20180518']\r\n eval_time_period = ['20180402', '20180518']\r\n eval_time_len = Date.index(eval_time_period[1]) - Date.index(eval_time_period[0]) + 1\r\n \r\n total_acc = 0\r\n for day_shift in range(eval_time_len-5):\r\n \r\n eval_start_date = Date.index(eval_time_period[0]) + day_shift\r\n target_start_date = eval_start_date - 21\r\n \r\n target_time_period = [Date[target_start_date], Date[eval_start_date]]\r\n next_time_period = [Date[eval_start_date], Date[eval_start_date + 5]] \r\n \r\n date_mask = (data.columns > src_time_period[0]) & (data.columns <= src_time_period[1])\r\n src_data = data.iloc[:, date_mask]\r\n \r\n date_mask = (data.columns > target_time_period[0]) & (data.columns <= target_time_period[1])\r\n target_data = data.iloc[:, date_mask]\r\n \r\n date_mask = (data.columns > next_time_period[0]) & (data.columns <= next_time_period[1])\r\n next_data = data.iloc[:, date_mask]\r\n \r\n src_TS = get_stock_time_series(src_data, ETF_ID)\r\n target_TS = get_stock_time_series(target_data, ETF_ID)\r\n next_TS = get_stock_time_series(next_data, ETF_ID)\r\n overall_TS = get_stock_time_series(data, ETF_ID)\r\n \r\n target_xcorr = np.correlate(src_TS[:, f_idx], target_TS[:, f_idx], mode='valid')\r\n# next_xcorr = np.correlate(src_TS[:, f_idx], next_TS[:, f_idx], mode='valid')\r\n \r\n target_len = len(target_TS)\r\n max_target_xcorr_idx = target_xcorr.argsort()[::-1]\r\n predict_target_idx = max_target_xcorr_idx + target_len\r\n \r\n next_len = len(next_TS)\r\n max_next_xcorr_idx = next_xcorr.argsort()[::-1]\r\n \r\n # plt.plot(target_xcorr)\r\n # plt.savefig(\"target_xcorr_{}.png\".format(ETF_ID))\r\n \r\n #for idx in max_target_xcorr_idx[:10]:\r\n # plt.figure()\r\n # plt.plot(target_TS[:, 84])\r\n # plt.plot(src_TS[max_target_xcorr_idx[idx]:max_target_xcorr_idx[idx]+target_len, 84])\r\n \r\n #plt.figure()\r\n #plt.plot(target_xcorr)\r\n #plt.plot(next_xcorr)\r\n \r\n top_num = 10\r\n acc = []\r\n label = np.argmax(next_TS[:, -3:], axis=-1)\r\n for idx in max_target_xcorr_idx[:top_num]:\r\n predict = np.argmax(overall_TS[predict_target_idx[idx]:predict_target_idx[idx]+next_len, -3:], axis=-1)\r\n acc.append(sum(label == predict) / next_len)\r\n \r\n max_acc_idx = np.argsort(acc)[::-1]\r\n output_xcorr_idx = [max_target_xcorr_idx[acc_idx] for acc_idx in max_acc_idx]\r\n \r\n top_num = 3\r\n avg_acc = 0\r\n acc = []\r\n for idx in output_xcorr_idx[:top_num]:\r\n #plt.figure()\r\n #plt.plot(next_TS[:, 84])\r\n #plt.plot(overall_TS[predict_target_idx[idx]:predict_target_idx[idx]+next_len, 84]) \r\n #plt.figure()\r\n #plt.plot(overall_TS[predict_target_idx[idx]:predict_target_idx[idx]+next_len, 3])\r\n \r\n predict = np.argmax(overall_TS[predict_target_idx[idx]:predict_target_idx[idx]+next_len, -3:], axis=-1)\r\n acc.append(sum(label == predict) / next_len)\r\n \r\n avg_acc = avg_acc + acc[-1]\r\n #print(\"Acc.: [{}]\".format(acc[-1]))\r\n \r\n print(\"Avg. Acc.: [{}]\".format(avg_acc/top_num))\r\n \r\n total_acc = total_acc + avg_acc/top_num\r\n \r\n print(\"[{}] Overall Acc.: [{}]\".format(ETF_ID, total_acc/(eval_time_len-5)))\r\n output_date[ETF_ID] = [Date[i] for i in output_xcorr_idx[:10]]\r\n\r\nf = open('./Data/xcorr_date_data.pkl', 'wb')\r\npickle.dump(output_date, f, True) \r\nf.close()\r\n\r\n\r\n\r\n\r\n", "<docstring token>\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport matplotlib.pyplot as plt\nfrom datetime import datetime, timedelta\nimport config as conf\n\n\ndef get_stock_time_series(data_df, stock_id):\n curr_ID_data = data_df.loc[stock_id]\n output = np.array(curr_ID_data[0])\n for i in range(1, len(curr_ID_data.index)):\n output = np.vstack((output, curr_ID_data[i]))\n return output\n\n\nID_conf = conf.config('feature_conf').config['ID']\nETF_ID_list = ['0050', '0052', '0053', '0054', '0055', '0056', '0057',\n '0058', '0059', '006201', '006203', '006204', '006208']\noutput_date = {}\nfor ETF_ID in ETF_ID_list:\n Nm_conf = conf.config('feature_conf').config['Nm']\n if Nm_conf['enable'] is True:\n Nm_method = Nm_conf['method']\n file_postfix = '_Nm_' + str(Nm_conf['type'][0]\n ) + '_' + Nm_method + '_' + str(94) + '_' + ETF_ID + '.pkl'\n else:\n file_postfix = '_' + str(94) + '.pkl'\n src_file_path = './Data/all_feature_data' + file_postfix\n meta_file_path = './Data/all_meta_data' + file_postfix\n data = pd.read_pickle(src_file_path)\n f = open(meta_file_path, 'rb')\n tasharep_ID = pickle.load(f)\n member_ID = pickle.load(f)\n Date = pickle.load(f)\n feature_list = pickle.load(f)\n price_scaler = pickle.load(f)\n trade_scaler = pickle.load(f)\n f_idx = 59\n src_time_period = ['20000101', '20180511']\n eval_time_period = ['20180402', '20180518']\n eval_time_len = Date.index(eval_time_period[1]) - Date.index(\n eval_time_period[0]) + 1\n total_acc = 0\n for day_shift in range(eval_time_len - 5):\n eval_start_date = Date.index(eval_time_period[0]) + day_shift\n target_start_date = eval_start_date - 21\n target_time_period = [Date[target_start_date], Date[eval_start_date]]\n next_time_period = [Date[eval_start_date], Date[eval_start_date + 5]]\n date_mask = (data.columns > src_time_period[0]) & (data.columns <=\n src_time_period[1])\n src_data = data.iloc[:, date_mask]\n date_mask = (data.columns > target_time_period[0]) & (data.columns <=\n target_time_period[1])\n target_data = data.iloc[:, date_mask]\n date_mask = (data.columns > next_time_period[0]) & (data.columns <=\n next_time_period[1])\n next_data = data.iloc[:, date_mask]\n src_TS = get_stock_time_series(src_data, ETF_ID)\n target_TS = get_stock_time_series(target_data, ETF_ID)\n next_TS = get_stock_time_series(next_data, ETF_ID)\n overall_TS = get_stock_time_series(data, ETF_ID)\n target_xcorr = np.correlate(src_TS[:, f_idx], target_TS[:, f_idx],\n mode='valid')\n target_len = len(target_TS)\n max_target_xcorr_idx = target_xcorr.argsort()[::-1]\n predict_target_idx = max_target_xcorr_idx + target_len\n next_len = len(next_TS)\n max_next_xcorr_idx = next_xcorr.argsort()[::-1]\n top_num = 10\n acc = []\n label = np.argmax(next_TS[:, -3:], axis=-1)\n for idx in max_target_xcorr_idx[:top_num]:\n predict = np.argmax(overall_TS[predict_target_idx[idx]:\n predict_target_idx[idx] + next_len, -3:], axis=-1)\n acc.append(sum(label == predict) / next_len)\n max_acc_idx = np.argsort(acc)[::-1]\n output_xcorr_idx = [max_target_xcorr_idx[acc_idx] for acc_idx in\n max_acc_idx]\n top_num = 3\n avg_acc = 0\n acc = []\n for idx in output_xcorr_idx[:top_num]:\n predict = np.argmax(overall_TS[predict_target_idx[idx]:\n predict_target_idx[idx] + next_len, -3:], axis=-1)\n acc.append(sum(label == predict) / next_len)\n avg_acc = avg_acc + acc[-1]\n print('Avg. Acc.: [{}]'.format(avg_acc / top_num))\n total_acc = total_acc + avg_acc / top_num\n print('[{}] Overall Acc.: [{}]'.format(ETF_ID, total_acc / (\n eval_time_len - 5)))\n output_date[ETF_ID] = [Date[i] for i in output_xcorr_idx[:10]]\nf = open('./Data/xcorr_date_data.pkl', 'wb')\npickle.dump(output_date, f, True)\nf.close()\n", "<docstring token>\n<import token>\n\n\ndef get_stock_time_series(data_df, stock_id):\n curr_ID_data = data_df.loc[stock_id]\n output = np.array(curr_ID_data[0])\n for i in range(1, len(curr_ID_data.index)):\n output = np.vstack((output, curr_ID_data[i]))\n return output\n\n\nID_conf = conf.config('feature_conf').config['ID']\nETF_ID_list = ['0050', '0052', '0053', '0054', '0055', '0056', '0057',\n '0058', '0059', '006201', '006203', '006204', '006208']\noutput_date = {}\nfor ETF_ID in ETF_ID_list:\n Nm_conf = conf.config('feature_conf').config['Nm']\n if Nm_conf['enable'] is True:\n Nm_method = Nm_conf['method']\n file_postfix = '_Nm_' + str(Nm_conf['type'][0]\n ) + '_' + Nm_method + '_' + str(94) + '_' + ETF_ID + '.pkl'\n else:\n file_postfix = '_' + str(94) + '.pkl'\n src_file_path = './Data/all_feature_data' + file_postfix\n meta_file_path = './Data/all_meta_data' + file_postfix\n data = pd.read_pickle(src_file_path)\n f = open(meta_file_path, 'rb')\n tasharep_ID = pickle.load(f)\n member_ID = pickle.load(f)\n Date = pickle.load(f)\n feature_list = pickle.load(f)\n price_scaler = pickle.load(f)\n trade_scaler = pickle.load(f)\n f_idx = 59\n src_time_period = ['20000101', '20180511']\n eval_time_period = ['20180402', '20180518']\n eval_time_len = Date.index(eval_time_period[1]) - Date.index(\n eval_time_period[0]) + 1\n total_acc = 0\n for day_shift in range(eval_time_len - 5):\n eval_start_date = Date.index(eval_time_period[0]) + day_shift\n target_start_date = eval_start_date - 21\n target_time_period = [Date[target_start_date], Date[eval_start_date]]\n next_time_period = [Date[eval_start_date], Date[eval_start_date + 5]]\n date_mask = (data.columns > src_time_period[0]) & (data.columns <=\n src_time_period[1])\n src_data = data.iloc[:, date_mask]\n date_mask = (data.columns > target_time_period[0]) & (data.columns <=\n target_time_period[1])\n target_data = data.iloc[:, date_mask]\n date_mask = (data.columns > next_time_period[0]) & (data.columns <=\n next_time_period[1])\n next_data = data.iloc[:, date_mask]\n src_TS = get_stock_time_series(src_data, ETF_ID)\n target_TS = get_stock_time_series(target_data, ETF_ID)\n next_TS = get_stock_time_series(next_data, ETF_ID)\n overall_TS = get_stock_time_series(data, ETF_ID)\n target_xcorr = np.correlate(src_TS[:, f_idx], target_TS[:, f_idx],\n mode='valid')\n target_len = len(target_TS)\n max_target_xcorr_idx = target_xcorr.argsort()[::-1]\n predict_target_idx = max_target_xcorr_idx + target_len\n next_len = len(next_TS)\n max_next_xcorr_idx = next_xcorr.argsort()[::-1]\n top_num = 10\n acc = []\n label = np.argmax(next_TS[:, -3:], axis=-1)\n for idx in max_target_xcorr_idx[:top_num]:\n predict = np.argmax(overall_TS[predict_target_idx[idx]:\n predict_target_idx[idx] + next_len, -3:], axis=-1)\n acc.append(sum(label == predict) / next_len)\n max_acc_idx = np.argsort(acc)[::-1]\n output_xcorr_idx = [max_target_xcorr_idx[acc_idx] for acc_idx in\n max_acc_idx]\n top_num = 3\n avg_acc = 0\n acc = []\n for idx in output_xcorr_idx[:top_num]:\n predict = np.argmax(overall_TS[predict_target_idx[idx]:\n predict_target_idx[idx] + next_len, -3:], axis=-1)\n acc.append(sum(label == predict) / next_len)\n avg_acc = avg_acc + acc[-1]\n print('Avg. Acc.: [{}]'.format(avg_acc / top_num))\n total_acc = total_acc + avg_acc / top_num\n print('[{}] Overall Acc.: [{}]'.format(ETF_ID, total_acc / (\n eval_time_len - 5)))\n output_date[ETF_ID] = [Date[i] for i in output_xcorr_idx[:10]]\nf = open('./Data/xcorr_date_data.pkl', 'wb')\npickle.dump(output_date, f, True)\nf.close()\n", "<docstring token>\n<import token>\n\n\ndef get_stock_time_series(data_df, stock_id):\n curr_ID_data = data_df.loc[stock_id]\n output = np.array(curr_ID_data[0])\n for i in range(1, len(curr_ID_data.index)):\n output = np.vstack((output, curr_ID_data[i]))\n return output\n\n\n<assignment token>\nfor ETF_ID in ETF_ID_list:\n Nm_conf = conf.config('feature_conf').config['Nm']\n if Nm_conf['enable'] is True:\n Nm_method = Nm_conf['method']\n file_postfix = '_Nm_' + str(Nm_conf['type'][0]\n ) + '_' + Nm_method + '_' + str(94) + '_' + ETF_ID + '.pkl'\n else:\n file_postfix = '_' + str(94) + '.pkl'\n src_file_path = './Data/all_feature_data' + file_postfix\n meta_file_path = './Data/all_meta_data' + file_postfix\n data = pd.read_pickle(src_file_path)\n f = open(meta_file_path, 'rb')\n tasharep_ID = pickle.load(f)\n member_ID = pickle.load(f)\n Date = pickle.load(f)\n feature_list = pickle.load(f)\n price_scaler = pickle.load(f)\n trade_scaler = pickle.load(f)\n f_idx = 59\n src_time_period = ['20000101', '20180511']\n eval_time_period = ['20180402', '20180518']\n eval_time_len = Date.index(eval_time_period[1]) - Date.index(\n eval_time_period[0]) + 1\n total_acc = 0\n for day_shift in range(eval_time_len - 5):\n eval_start_date = Date.index(eval_time_period[0]) + day_shift\n target_start_date = eval_start_date - 21\n target_time_period = [Date[target_start_date], Date[eval_start_date]]\n next_time_period = [Date[eval_start_date], Date[eval_start_date + 5]]\n date_mask = (data.columns > src_time_period[0]) & (data.columns <=\n src_time_period[1])\n src_data = data.iloc[:, date_mask]\n date_mask = (data.columns > target_time_period[0]) & (data.columns <=\n target_time_period[1])\n target_data = data.iloc[:, date_mask]\n date_mask = (data.columns > next_time_period[0]) & (data.columns <=\n next_time_period[1])\n next_data = data.iloc[:, date_mask]\n src_TS = get_stock_time_series(src_data, ETF_ID)\n target_TS = get_stock_time_series(target_data, ETF_ID)\n next_TS = get_stock_time_series(next_data, ETF_ID)\n overall_TS = get_stock_time_series(data, ETF_ID)\n target_xcorr = np.correlate(src_TS[:, f_idx], target_TS[:, f_idx],\n mode='valid')\n target_len = len(target_TS)\n max_target_xcorr_idx = target_xcorr.argsort()[::-1]\n predict_target_idx = max_target_xcorr_idx + target_len\n next_len = len(next_TS)\n max_next_xcorr_idx = next_xcorr.argsort()[::-1]\n top_num = 10\n acc = []\n label = np.argmax(next_TS[:, -3:], axis=-1)\n for idx in max_target_xcorr_idx[:top_num]:\n predict = np.argmax(overall_TS[predict_target_idx[idx]:\n predict_target_idx[idx] + next_len, -3:], axis=-1)\n acc.append(sum(label == predict) / next_len)\n max_acc_idx = np.argsort(acc)[::-1]\n output_xcorr_idx = [max_target_xcorr_idx[acc_idx] for acc_idx in\n max_acc_idx]\n top_num = 3\n avg_acc = 0\n acc = []\n for idx in output_xcorr_idx[:top_num]:\n predict = np.argmax(overall_TS[predict_target_idx[idx]:\n predict_target_idx[idx] + next_len, -3:], axis=-1)\n acc.append(sum(label == predict) / next_len)\n avg_acc = avg_acc + acc[-1]\n print('Avg. Acc.: [{}]'.format(avg_acc / top_num))\n total_acc = total_acc + avg_acc / top_num\n print('[{}] Overall Acc.: [{}]'.format(ETF_ID, total_acc / (\n eval_time_len - 5)))\n output_date[ETF_ID] = [Date[i] for i in output_xcorr_idx[:10]]\n<assignment token>\npickle.dump(output_date, f, True)\nf.close()\n", "<docstring token>\n<import token>\n\n\ndef get_stock_time_series(data_df, stock_id):\n curr_ID_data = data_df.loc[stock_id]\n output = np.array(curr_ID_data[0])\n for i in range(1, len(curr_ID_data.index)):\n output = np.vstack((output, curr_ID_data[i]))\n return output\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n<import token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
757
5a33aeffa740a41bd0bd1d80f45796ae37377a4c
from django.contrib.postgres.fields import JSONField from django.db import models from core.utils.time import get_now class BaseManager(models.Manager): """ Our basic manager is used to order all child models of AbstractLayer by created time (descending), therefore it creates a LIFO order, causing the recent ones appear first in results. """ use_for_related_fields = True def get_queryset(self): super(BaseManager, self).get_queryset().order_by('-created_time') class AbstractLayer(models.Model): """ All basic abstraction is done here. Also, we'll implement some methods which will simplify the work with models. """ # let's configure managers default_manager = BaseManager objects = BaseManager all_objects = models.Manager # All objects in our database are gonna have time of creation and last updated time. created_time = models.DateTimeField(default=get_now) last_updated_time = models.DateTimeField(default=get_now) @classmethod def get(cls, *args, **kwargs) -> object or None: """ We use our custom get method to avoid errors (like Not Found). This way we won't have to use try/except for the rest of our codebase (at least for non-existing objects). :param args: :param kwargs: :return: object of model """ try: return cls.objects.get(*args, **kwargs) except cls.DoesNotExist: # if objects does not exist, we use None return None @classmethod def filter(cls, *args, **kwargs) -> models.QuerySet: """ Just to reduce the model.objects.filter to model.filter :param args: :param kwargs: :return: QuerySet """ return cls.objects.filter(*args, **kwargs) @classmethod def all(cls): """ Shortcut for model.objects.all """ return cls.objects.all() def save(self, *args, **kwargs) -> None: """ We won't be using auto_now and auto_add_now for created_time and last_updated_time, since they might cause unintentional errors in future. Instead we implement custom save method to update them. :param args: :param kwargs: :return: None """ self.last_updated_time = get_now() super(AbstractLayer, self).save(*args, **kwargs) @classmethod def create(cls, *args, **kwargs): """ Since we are not using auto fields for created_time, we will be implementing our custom create method to take care of that. Also, we reduce model.objects.create to model.create. :param args: :param kwargs: :return: created object """ now = get_now() obj = cls( *args, **kwargs, created_time=now, last_updated_time=now ) obj.save() return obj class Meta: abstract = True class Country(AbstractLayer): code = models.CharField(max_length=7, unique=True) def __str__(self): return self.code class Meta: db_table = 'countries' class City(AbstractLayer): name = models.CharField(max_length=255) state = models.CharField(max_length=255) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='cities') lon = models.CharField(max_length=31) lat = models.CharField(max_length=31) def __str__(self): return self.name class Meta: db_table = 'cities' class Forecast(AbstractLayer): city = models.ForeignKey(City, on_delete=models.CASCADE, related_name='forecasts') detailed_status = models.CharField(max_length=1023, blank=True, null=True) data = JSONField(blank=True, null=True, help_text='Whole JSON data representing the forecast details') time = models.DateTimeField() class Meta: db_table = 'forecasts'
[ "from django.contrib.postgres.fields import JSONField\nfrom django.db import models\n\nfrom core.utils.time import get_now\n\n\nclass BaseManager(models.Manager):\n \"\"\"\n Our basic manager is used to order all child models of AbstractLayer\n by created time (descending), therefore it creates a LIFO order,\n causing the recent ones appear first in results.\n \"\"\"\n use_for_related_fields = True\n\n def get_queryset(self):\n super(BaseManager, self).get_queryset().order_by('-created_time')\n\n\nclass AbstractLayer(models.Model):\n \"\"\"\n All basic abstraction is done here.\n Also, we'll implement some methods which will simplify the work with models.\n \"\"\"\n\n # let's configure managers\n default_manager = BaseManager\n objects = BaseManager\n all_objects = models.Manager\n\n # All objects in our database are gonna have time of creation and last updated time.\n created_time = models.DateTimeField(default=get_now)\n last_updated_time = models.DateTimeField(default=get_now)\n\n @classmethod\n def get(cls, *args, **kwargs) -> object or None:\n \"\"\"\n We use our custom get method to avoid errors (like Not Found).\n This way we won't have to use try/except for the rest of our codebase (at least for non-existing objects).\n :param args:\n :param kwargs:\n :return: object of model\n \"\"\"\n try:\n return cls.objects.get(*args, **kwargs)\n except cls.DoesNotExist:\n # if objects does not exist, we use None\n return None\n\n @classmethod\n def filter(cls, *args, **kwargs) -> models.QuerySet:\n \"\"\"\n Just to reduce the model.objects.filter to model.filter\n :param args:\n :param kwargs:\n :return: QuerySet\n \"\"\"\n return cls.objects.filter(*args, **kwargs)\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) -> None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n\n @classmethod\n def create(cls, *args, **kwargs):\n \"\"\"\n Since we are not using auto fields for created_time,\n we will be implementing our custom create method to take care of that.\n Also, we reduce model.objects.create to model.create.\n :param args:\n :param kwargs:\n :return: created object\n \"\"\"\n now = get_now()\n obj = cls(\n *args,\n **kwargs,\n created_time=now,\n last_updated_time=now\n )\n obj.save()\n return obj\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name='forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text='Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n class Meta:\n db_table = 'forecasts'\n", "from django.contrib.postgres.fields import JSONField\nfrom django.db import models\nfrom core.utils.time import get_now\n\n\nclass BaseManager(models.Manager):\n \"\"\"\n Our basic manager is used to order all child models of AbstractLayer\n by created time (descending), therefore it creates a LIFO order,\n causing the recent ones appear first in results.\n \"\"\"\n use_for_related_fields = True\n\n def get_queryset(self):\n super(BaseManager, self).get_queryset().order_by('-created_time')\n\n\nclass AbstractLayer(models.Model):\n \"\"\"\n All basic abstraction is done here.\n Also, we'll implement some methods which will simplify the work with models.\n \"\"\"\n default_manager = BaseManager\n objects = BaseManager\n all_objects = models.Manager\n created_time = models.DateTimeField(default=get_now)\n last_updated_time = models.DateTimeField(default=get_now)\n\n @classmethod\n def get(cls, *args, **kwargs) ->(object or None):\n \"\"\"\n We use our custom get method to avoid errors (like Not Found).\n This way we won't have to use try/except for the rest of our codebase (at least for non-existing objects).\n :param args:\n :param kwargs:\n :return: object of model\n \"\"\"\n try:\n return cls.objects.get(*args, **kwargs)\n except cls.DoesNotExist:\n return None\n\n @classmethod\n def filter(cls, *args, **kwargs) ->models.QuerySet:\n \"\"\"\n Just to reduce the model.objects.filter to model.filter\n :param args:\n :param kwargs:\n :return: QuerySet\n \"\"\"\n return cls.objects.filter(*args, **kwargs)\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n\n @classmethod\n def create(cls, *args, **kwargs):\n \"\"\"\n Since we are not using auto fields for created_time,\n we will be implementing our custom create method to take care of that.\n Also, we reduce model.objects.create to model.create.\n :param args:\n :param kwargs:\n :return: created object\n \"\"\"\n now = get_now()\n obj = cls(*args, **kwargs, created_time=now, last_updated_time=now)\n obj.save()\n return obj\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n\n\nclass BaseManager(models.Manager):\n \"\"\"\n Our basic manager is used to order all child models of AbstractLayer\n by created time (descending), therefore it creates a LIFO order,\n causing the recent ones appear first in results.\n \"\"\"\n use_for_related_fields = True\n\n def get_queryset(self):\n super(BaseManager, self).get_queryset().order_by('-created_time')\n\n\nclass AbstractLayer(models.Model):\n \"\"\"\n All basic abstraction is done here.\n Also, we'll implement some methods which will simplify the work with models.\n \"\"\"\n default_manager = BaseManager\n objects = BaseManager\n all_objects = models.Manager\n created_time = models.DateTimeField(default=get_now)\n last_updated_time = models.DateTimeField(default=get_now)\n\n @classmethod\n def get(cls, *args, **kwargs) ->(object or None):\n \"\"\"\n We use our custom get method to avoid errors (like Not Found).\n This way we won't have to use try/except for the rest of our codebase (at least for non-existing objects).\n :param args:\n :param kwargs:\n :return: object of model\n \"\"\"\n try:\n return cls.objects.get(*args, **kwargs)\n except cls.DoesNotExist:\n return None\n\n @classmethod\n def filter(cls, *args, **kwargs) ->models.QuerySet:\n \"\"\"\n Just to reduce the model.objects.filter to model.filter\n :param args:\n :param kwargs:\n :return: QuerySet\n \"\"\"\n return cls.objects.filter(*args, **kwargs)\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n\n @classmethod\n def create(cls, *args, **kwargs):\n \"\"\"\n Since we are not using auto fields for created_time,\n we will be implementing our custom create method to take care of that.\n Also, we reduce model.objects.create to model.create.\n :param args:\n :param kwargs:\n :return: created object\n \"\"\"\n now = get_now()\n obj = cls(*args, **kwargs, created_time=now, last_updated_time=now)\n obj.save()\n return obj\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n\n\nclass BaseManager(models.Manager):\n <docstring token>\n use_for_related_fields = True\n\n def get_queryset(self):\n super(BaseManager, self).get_queryset().order_by('-created_time')\n\n\nclass AbstractLayer(models.Model):\n \"\"\"\n All basic abstraction is done here.\n Also, we'll implement some methods which will simplify the work with models.\n \"\"\"\n default_manager = BaseManager\n objects = BaseManager\n all_objects = models.Manager\n created_time = models.DateTimeField(default=get_now)\n last_updated_time = models.DateTimeField(default=get_now)\n\n @classmethod\n def get(cls, *args, **kwargs) ->(object or None):\n \"\"\"\n We use our custom get method to avoid errors (like Not Found).\n This way we won't have to use try/except for the rest of our codebase (at least for non-existing objects).\n :param args:\n :param kwargs:\n :return: object of model\n \"\"\"\n try:\n return cls.objects.get(*args, **kwargs)\n except cls.DoesNotExist:\n return None\n\n @classmethod\n def filter(cls, *args, **kwargs) ->models.QuerySet:\n \"\"\"\n Just to reduce the model.objects.filter to model.filter\n :param args:\n :param kwargs:\n :return: QuerySet\n \"\"\"\n return cls.objects.filter(*args, **kwargs)\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n\n @classmethod\n def create(cls, *args, **kwargs):\n \"\"\"\n Since we are not using auto fields for created_time,\n we will be implementing our custom create method to take care of that.\n Also, we reduce model.objects.create to model.create.\n :param args:\n :param kwargs:\n :return: created object\n \"\"\"\n now = get_now()\n obj = cls(*args, **kwargs, created_time=now, last_updated_time=now)\n obj.save()\n return obj\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n\n\nclass BaseManager(models.Manager):\n <docstring token>\n <assignment token>\n\n def get_queryset(self):\n super(BaseManager, self).get_queryset().order_by('-created_time')\n\n\nclass AbstractLayer(models.Model):\n \"\"\"\n All basic abstraction is done here.\n Also, we'll implement some methods which will simplify the work with models.\n \"\"\"\n default_manager = BaseManager\n objects = BaseManager\n all_objects = models.Manager\n created_time = models.DateTimeField(default=get_now)\n last_updated_time = models.DateTimeField(default=get_now)\n\n @classmethod\n def get(cls, *args, **kwargs) ->(object or None):\n \"\"\"\n We use our custom get method to avoid errors (like Not Found).\n This way we won't have to use try/except for the rest of our codebase (at least for non-existing objects).\n :param args:\n :param kwargs:\n :return: object of model\n \"\"\"\n try:\n return cls.objects.get(*args, **kwargs)\n except cls.DoesNotExist:\n return None\n\n @classmethod\n def filter(cls, *args, **kwargs) ->models.QuerySet:\n \"\"\"\n Just to reduce the model.objects.filter to model.filter\n :param args:\n :param kwargs:\n :return: QuerySet\n \"\"\"\n return cls.objects.filter(*args, **kwargs)\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n\n @classmethod\n def create(cls, *args, **kwargs):\n \"\"\"\n Since we are not using auto fields for created_time,\n we will be implementing our custom create method to take care of that.\n Also, we reduce model.objects.create to model.create.\n :param args:\n :param kwargs:\n :return: created object\n \"\"\"\n now = get_now()\n obj = cls(*args, **kwargs, created_time=now, last_updated_time=now)\n obj.save()\n return obj\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n\n\nclass BaseManager(models.Manager):\n <docstring token>\n <assignment token>\n <function token>\n\n\nclass AbstractLayer(models.Model):\n \"\"\"\n All basic abstraction is done here.\n Also, we'll implement some methods which will simplify the work with models.\n \"\"\"\n default_manager = BaseManager\n objects = BaseManager\n all_objects = models.Manager\n created_time = models.DateTimeField(default=get_now)\n last_updated_time = models.DateTimeField(default=get_now)\n\n @classmethod\n def get(cls, *args, **kwargs) ->(object or None):\n \"\"\"\n We use our custom get method to avoid errors (like Not Found).\n This way we won't have to use try/except for the rest of our codebase (at least for non-existing objects).\n :param args:\n :param kwargs:\n :return: object of model\n \"\"\"\n try:\n return cls.objects.get(*args, **kwargs)\n except cls.DoesNotExist:\n return None\n\n @classmethod\n def filter(cls, *args, **kwargs) ->models.QuerySet:\n \"\"\"\n Just to reduce the model.objects.filter to model.filter\n :param args:\n :param kwargs:\n :return: QuerySet\n \"\"\"\n return cls.objects.filter(*args, **kwargs)\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n\n @classmethod\n def create(cls, *args, **kwargs):\n \"\"\"\n Since we are not using auto fields for created_time,\n we will be implementing our custom create method to take care of that.\n Also, we reduce model.objects.create to model.create.\n :param args:\n :param kwargs:\n :return: created object\n \"\"\"\n now = get_now()\n obj = cls(*args, **kwargs, created_time=now, last_updated_time=now)\n obj.save()\n return obj\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n\n\nclass AbstractLayer(models.Model):\n \"\"\"\n All basic abstraction is done here.\n Also, we'll implement some methods which will simplify the work with models.\n \"\"\"\n default_manager = BaseManager\n objects = BaseManager\n all_objects = models.Manager\n created_time = models.DateTimeField(default=get_now)\n last_updated_time = models.DateTimeField(default=get_now)\n\n @classmethod\n def get(cls, *args, **kwargs) ->(object or None):\n \"\"\"\n We use our custom get method to avoid errors (like Not Found).\n This way we won't have to use try/except for the rest of our codebase (at least for non-existing objects).\n :param args:\n :param kwargs:\n :return: object of model\n \"\"\"\n try:\n return cls.objects.get(*args, **kwargs)\n except cls.DoesNotExist:\n return None\n\n @classmethod\n def filter(cls, *args, **kwargs) ->models.QuerySet:\n \"\"\"\n Just to reduce the model.objects.filter to model.filter\n :param args:\n :param kwargs:\n :return: QuerySet\n \"\"\"\n return cls.objects.filter(*args, **kwargs)\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n\n @classmethod\n def create(cls, *args, **kwargs):\n \"\"\"\n Since we are not using auto fields for created_time,\n we will be implementing our custom create method to take care of that.\n Also, we reduce model.objects.create to model.create.\n :param args:\n :param kwargs:\n :return: created object\n \"\"\"\n now = get_now()\n obj = cls(*args, **kwargs, created_time=now, last_updated_time=now)\n obj.save()\n return obj\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n\n\nclass AbstractLayer(models.Model):\n <docstring token>\n default_manager = BaseManager\n objects = BaseManager\n all_objects = models.Manager\n created_time = models.DateTimeField(default=get_now)\n last_updated_time = models.DateTimeField(default=get_now)\n\n @classmethod\n def get(cls, *args, **kwargs) ->(object or None):\n \"\"\"\n We use our custom get method to avoid errors (like Not Found).\n This way we won't have to use try/except for the rest of our codebase (at least for non-existing objects).\n :param args:\n :param kwargs:\n :return: object of model\n \"\"\"\n try:\n return cls.objects.get(*args, **kwargs)\n except cls.DoesNotExist:\n return None\n\n @classmethod\n def filter(cls, *args, **kwargs) ->models.QuerySet:\n \"\"\"\n Just to reduce the model.objects.filter to model.filter\n :param args:\n :param kwargs:\n :return: QuerySet\n \"\"\"\n return cls.objects.filter(*args, **kwargs)\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n\n @classmethod\n def create(cls, *args, **kwargs):\n \"\"\"\n Since we are not using auto fields for created_time,\n we will be implementing our custom create method to take care of that.\n Also, we reduce model.objects.create to model.create.\n :param args:\n :param kwargs:\n :return: created object\n \"\"\"\n now = get_now()\n obj = cls(*args, **kwargs, created_time=now, last_updated_time=now)\n obj.save()\n return obj\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n\n\nclass AbstractLayer(models.Model):\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n @classmethod\n def get(cls, *args, **kwargs) ->(object or None):\n \"\"\"\n We use our custom get method to avoid errors (like Not Found).\n This way we won't have to use try/except for the rest of our codebase (at least for non-existing objects).\n :param args:\n :param kwargs:\n :return: object of model\n \"\"\"\n try:\n return cls.objects.get(*args, **kwargs)\n except cls.DoesNotExist:\n return None\n\n @classmethod\n def filter(cls, *args, **kwargs) ->models.QuerySet:\n \"\"\"\n Just to reduce the model.objects.filter to model.filter\n :param args:\n :param kwargs:\n :return: QuerySet\n \"\"\"\n return cls.objects.filter(*args, **kwargs)\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n\n @classmethod\n def create(cls, *args, **kwargs):\n \"\"\"\n Since we are not using auto fields for created_time,\n we will be implementing our custom create method to take care of that.\n Also, we reduce model.objects.create to model.create.\n :param args:\n :param kwargs:\n :return: created object\n \"\"\"\n now = get_now()\n obj = cls(*args, **kwargs, created_time=now, last_updated_time=now)\n obj.save()\n return obj\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n\n\nclass AbstractLayer(models.Model):\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n @classmethod\n def filter(cls, *args, **kwargs) ->models.QuerySet:\n \"\"\"\n Just to reduce the model.objects.filter to model.filter\n :param args:\n :param kwargs:\n :return: QuerySet\n \"\"\"\n return cls.objects.filter(*args, **kwargs)\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n\n @classmethod\n def create(cls, *args, **kwargs):\n \"\"\"\n Since we are not using auto fields for created_time,\n we will be implementing our custom create method to take care of that.\n Also, we reduce model.objects.create to model.create.\n :param args:\n :param kwargs:\n :return: created object\n \"\"\"\n now = get_now()\n obj = cls(*args, **kwargs, created_time=now, last_updated_time=now)\n obj.save()\n return obj\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n\n\nclass AbstractLayer(models.Model):\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n\n @classmethod\n def create(cls, *args, **kwargs):\n \"\"\"\n Since we are not using auto fields for created_time,\n we will be implementing our custom create method to take care of that.\n Also, we reduce model.objects.create to model.create.\n :param args:\n :param kwargs:\n :return: created object\n \"\"\"\n now = get_now()\n obj = cls(*args, **kwargs, created_time=now, last_updated_time=now)\n obj.save()\n return obj\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n\n\nclass AbstractLayer(models.Model):\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n\n @classmethod\n def all(cls):\n \"\"\"\n Shortcut for model.objects.all\n \"\"\"\n return cls.objects.all()\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n <function token>\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n\n\nclass AbstractLayer(models.Model):\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n\n def save(self, *args, **kwargs) ->None:\n \"\"\"\n We won't be using auto_now and auto_add_now for created_time and last_updated_time,\n since they might cause unintentional errors in future.\n Instead we implement custom save method to update them.\n :param args:\n :param kwargs:\n :return: None\n \"\"\"\n self.last_updated_time = get_now()\n super(AbstractLayer, self).save(*args, **kwargs)\n <function token>\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n\n\nclass AbstractLayer(models.Model):\n <docstring token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n class Meta:\n abstract = True\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n<class token>\n\n\nclass Country(AbstractLayer):\n code = models.CharField(max_length=7, unique=True)\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n<class token>\n\n\nclass Country(AbstractLayer):\n <assignment token>\n\n def __str__(self):\n return self.code\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n<class token>\n\n\nclass Country(AbstractLayer):\n <assignment token>\n <function token>\n\n\n class Meta:\n db_table = 'countries'\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass City(AbstractLayer):\n name = models.CharField(max_length=255)\n state = models.CharField(max_length=255)\n country = models.ForeignKey(Country, on_delete=models.CASCADE,\n related_name='cities')\n lon = models.CharField(max_length=31)\n lat = models.CharField(max_length=31)\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass City(AbstractLayer):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return self.name\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass City(AbstractLayer):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\n class Meta:\n db_table = 'cities'\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Forecast(AbstractLayer):\n city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=\n 'forecasts')\n detailed_status = models.CharField(max_length=1023, blank=True, null=True)\n data = JSONField(blank=True, null=True, help_text=\n 'Whole JSON data representing the forecast details')\n time = models.DateTimeField()\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass Forecast(AbstractLayer):\n <assignment token>\n <assignment token>\n <assignment token>\n <assignment token>\n\n\n class Meta:\n db_table = 'forecasts'\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n" ]
false
758
5cfd7744f98c80483cb4dd318c17a7cd83ed3ae3
""" Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? Example: Input: [4,3,2,7,8,2,3,1] Output: [2,3] """ # O(n) TC and SC class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: cnt = {} for num in nums: cnt[num] = cnt.get(num, 0) + 1 res = [] for k, v in cnt.items(): if v > 1: res.append(k) return res # O(n) TC and O(1) SC class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: res = [] for num in nums: if nums[abs(num)-1] < 0: res.append(abs(num)) else: nums[abs(num)-1] *= -1 return res
[ "\"\"\"\nGiven an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.\nFind all the elements that appear twice in this array.\nCould you do it without extra space and in O(n) runtime?\n\nExample:\nInput:\n[4,3,2,7,8,2,3,1]\n\nOutput:\n[2,3]\n\"\"\"\n\n# O(n) TC and SC\nclass Solution:\n def findDuplicates(self, nums: List[int]) -> List[int]:\n cnt = {}\n\n for num in nums:\n cnt[num] = cnt.get(num, 0) + 1\n\n res = []\n\n for k, v in cnt.items():\n if v > 1:\n res.append(k)\n\n return res\n\n\n# O(n) TC and O(1) SC\nclass Solution:\n def findDuplicates(self, nums: List[int]) -> List[int]:\n res = []\n \n for num in nums:\n if nums[abs(num)-1] < 0:\n res.append(abs(num))\n else:\n nums[abs(num)-1] *= -1\n \n return res\n", "<docstring token>\n\n\nclass Solution:\n\n def findDuplicates(self, nums: List[int]) ->List[int]:\n cnt = {}\n for num in nums:\n cnt[num] = cnt.get(num, 0) + 1\n res = []\n for k, v in cnt.items():\n if v > 1:\n res.append(k)\n return res\n\n\nclass Solution:\n\n def findDuplicates(self, nums: List[int]) ->List[int]:\n res = []\n for num in nums:\n if nums[abs(num) - 1] < 0:\n res.append(abs(num))\n else:\n nums[abs(num) - 1] *= -1\n return res\n", "<docstring token>\n\n\nclass Solution:\n <function token>\n\n\nclass Solution:\n\n def findDuplicates(self, nums: List[int]) ->List[int]:\n res = []\n for num in nums:\n if nums[abs(num) - 1] < 0:\n res.append(abs(num))\n else:\n nums[abs(num) - 1] *= -1\n return res\n", "<docstring token>\n<class token>\n\n\nclass Solution:\n\n def findDuplicates(self, nums: List[int]) ->List[int]:\n res = []\n for num in nums:\n if nums[abs(num) - 1] < 0:\n res.append(abs(num))\n else:\n nums[abs(num) - 1] *= -1\n return res\n", "<docstring token>\n<class token>\n\n\nclass Solution:\n <function token>\n", "<docstring token>\n<class token>\n<class token>\n" ]
false
759
cfa862988edf9d70aa5e975cca58b4e61a4de847
""" USAGE: o install in develop mode: navigate to the folder containing this file, and type 'python setup.py develop --user'. (ommit '--user' if you want to install for all users) """ from setuptools import setup setup(name='gromacsplotter', version='0.1', description='Read xvg files created with gromacs for plotting with matplotlib', url='', author='Ilyas Kuhlemann', author_email='[email protected]', license='MIT', packages=["gromacsplotter"], scripts=[], install_requires=['numpy', "matplotlib"], entry_points = { 'console_scripts': ["gromacsplotter = gromacsplotter.plot_xvg_data:main"] }, zip_safe=False)
[ "\"\"\"\nUSAGE: \n o install in develop mode: navigate to the folder containing this file,\n and type 'python setup.py develop --user'.\n (ommit '--user' if you want to install for \n all users) \n\"\"\"\n\n\nfrom setuptools import setup\n\nsetup(name='gromacsplotter',\n version='0.1',\n description='Read xvg files created with gromacs for plotting with matplotlib',\n url='',\n author='Ilyas Kuhlemann',\n author_email='[email protected]',\n license='MIT',\n packages=[\"gromacsplotter\"],\n scripts=[],\n install_requires=['numpy',\n \"matplotlib\"],\n entry_points = {\n 'console_scripts': [\"gromacsplotter = gromacsplotter.plot_xvg_data:main\"]\n },\n zip_safe=False)\n", "<docstring token>\nfrom setuptools import setup\nsetup(name='gromacsplotter', version='0.1', description=\n 'Read xvg files created with gromacs for plotting with matplotlib', url\n ='', author='Ilyas Kuhlemann', author_email='[email protected]',\n license='MIT', packages=['gromacsplotter'], scripts=[],\n install_requires=['numpy', 'matplotlib'], entry_points={\n 'console_scripts': [\n 'gromacsplotter = gromacsplotter.plot_xvg_data:main']}, zip_safe=False)\n", "<docstring token>\n<import token>\nsetup(name='gromacsplotter', version='0.1', description=\n 'Read xvg files created with gromacs for plotting with matplotlib', url\n ='', author='Ilyas Kuhlemann', author_email='[email protected]',\n license='MIT', packages=['gromacsplotter'], scripts=[],\n install_requires=['numpy', 'matplotlib'], entry_points={\n 'console_scripts': [\n 'gromacsplotter = gromacsplotter.plot_xvg_data:main']}, zip_safe=False)\n", "<docstring token>\n<import token>\n<code token>\n" ]
false
760
7b9660bba6fcb8c725251971f3733a1cc915c0e7
""" Rectangles: Compute overlapping region of two rectangles. Point(x: number, y: number): Cartesian coordinate pair Rect(ll: Point, ur: Point): A rectangle defined by lower left and upper right coordinates Rect.overlaps(other: Rect) -> boolean: True if non-empty overlap Rect.intersect(other: Rect) -> Rect: region of intersection if non-empty, or empty Rect from 0,0 to 0,0 if not Rect.overlaps(other) CIS 211 Project 1 Author: Noah Tigner UO email: [email protected] """ import numbers import logging logging.basicConfig() log = logging.getLogger(__name__) log.setLevel(logging.INFO) # To turn on debugging output, change the above to # log.setLevel(logging.DEBUG) class Point(object): """A point is an ordered pair, (x,y)""" def __init__(self, x, y): assert isinstance(x, numbers.Number) assert isinstance(y, numbers.Number) self.x = x self.y = y log.debug("Created Point {}".format(repr(self))) def __repr__(self): return "Point({},{})".format(self.x, self.y) def __str__(self): return "({}, {})".format(self.x, self.y) def __eq__(self, other): assert(isinstance(other, Point)) return self.x == other.x and self.y == other.y class Rect(object): """A rectangle identified by its lower left and upper right corners. """ def __init__(self, ll, ur): """Initialize rectangle with ll and ur as corners.""" log.debug("Rect from ll {}, ur {}".format(repr(ll), repr(ur))) # Ensure ll really is lower left and ur really is upper right self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y)) log.debug("ll will be {}".format(self.ll)) self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y)) log.debug("ur will be {}".format(self.ur)) log.debug("Created rect {}".format(repr(self))) def __repr__(self): return "Rect({},{})".format(self.ll, self.ur) def __str__(self): return "Rect({},{})".format(self.ll, self.ur) def __eq__(self, other): assert isinstance(other, Rect) return self.ll == other.ll and self.ur == other.ur def overlaps(self, other): """r1.overlaps(r2) if there is an area of positive size within r1 and also within r2. "Of positive size" means that touching at a corner or along an edge is not enough ... the area of overlap must be positive. """ if self.ll.x >= other.ur.x: return False if self.ll.y >= other.ur.y: return False if self.ur.x <= other.ll.x: return False if self.ur.y <= other.ll.y: return False return True def intersect(self, other): """Region of overlap, or (0,0),(0,0) if none""" if self.overlaps(other): return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y, other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur.y, other.ur.y))) else: return Rect(Point(0, 0), Point(0, 0))
[ "\"\"\"\nRectangles: Compute overlapping region of two rectangles.\n Point(x: number, y: number): Cartesian coordinate pair\n Rect(ll: Point, ur: Point): A rectangle defined by lower left\n and upper right coordinates\n Rect.overlaps(other: Rect) -> boolean: True if non-empty overlap\n Rect.intersect(other: Rect) -> Rect:\n region of intersection if non-empty,\n or empty Rect from 0,0 to 0,0 if not Rect.overlaps(other)\n\nCIS 211 Project 1\nAuthor: Noah Tigner\nUO email: [email protected]\n\"\"\"\n\nimport numbers\n\nimport logging\nlogging.basicConfig()\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.INFO)\n# To turn on debugging output, change the above to\n# log.setLevel(logging.DEBUG)\n\n\nclass Point(object):\n \"\"\"A point is an ordered pair, (x,y)\"\"\"\n\n def __init__(self, x, y):\n assert isinstance(x, numbers.Number)\n assert isinstance(y, numbers.Number)\n self.x = x\n self.y = y\n log.debug(\"Created Point {}\".format(repr(self)))\n\n def __repr__(self):\n return \"Point({},{})\".format(self.x, self.y)\n\n def __str__(self):\n return \"({}, {})\".format(self.x, self.y)\n\n def __eq__(self, other):\n assert(isinstance(other, Point))\n return self.x == other.x and self.y == other.y\n\n\nclass Rect(object):\n \"\"\"A rectangle identified by its lower left\n and upper right corners.\n \"\"\"\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug(\"Rect from ll {}, ur {}\".format(repr(ll), repr(ur)))\n # Ensure ll really is lower left and ur really is upper right\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug(\"ll will be {}\".format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug(\"ur will be {}\".format(self.ur))\n log.debug(\"Created rect {}\".format(repr(self)))\n\n def __repr__(self):\n return \"Rect({},{})\".format(self.ll, self.ur)\n\n def __str__(self):\n return \"Rect({},{})\".format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n\n if self.ll.x >= other.ur.x:\n return False\n \n if self.ll.y >= other.ur.y:\n return False\n \n if self.ur.x <= other.ll.x:\n return False\n \n if self.ur.y <= other.ll.y:\n return False\n \n return True\n \n \n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n \n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y, other.ll.y)),\n Point(min(self.ur.x, other.ur.x), min(self.ur.y, other.ur.y)))\n\n\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\nimport numbers\nimport logging\nlogging.basicConfig()\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.INFO)\n\n\nclass Point(object):\n \"\"\"A point is an ordered pair, (x,y)\"\"\"\n\n def __init__(self, x, y):\n assert isinstance(x, numbers.Number)\n assert isinstance(y, numbers.Number)\n self.x = x\n self.y = y\n log.debug('Created Point {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Point({},{})'.format(self.x, self.y)\n\n def __str__(self):\n return '({}, {})'.format(self.x, self.y)\n\n def __eq__(self, other):\n assert isinstance(other, Point)\n return self.x == other.x and self.y == other.y\n\n\nclass Rect(object):\n \"\"\"A rectangle identified by its lower left\n and upper right corners.\n \"\"\"\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug('Rect from ll {}, ur {}'.format(repr(ll), repr(ur)))\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug('ll will be {}'.format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug('ur will be {}'.format(self.ur))\n log.debug('Created rect {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\nlogging.basicConfig()\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.INFO)\n\n\nclass Point(object):\n \"\"\"A point is an ordered pair, (x,y)\"\"\"\n\n def __init__(self, x, y):\n assert isinstance(x, numbers.Number)\n assert isinstance(y, numbers.Number)\n self.x = x\n self.y = y\n log.debug('Created Point {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Point({},{})'.format(self.x, self.y)\n\n def __str__(self):\n return '({}, {})'.format(self.x, self.y)\n\n def __eq__(self, other):\n assert isinstance(other, Point)\n return self.x == other.x and self.y == other.y\n\n\nclass Rect(object):\n \"\"\"A rectangle identified by its lower left\n and upper right corners.\n \"\"\"\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug('Rect from ll {}, ur {}'.format(repr(ll), repr(ur)))\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug('ll will be {}'.format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug('ur will be {}'.format(self.ur))\n log.debug('Created rect {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\nlogging.basicConfig()\n<assignment token>\nlog.setLevel(logging.INFO)\n\n\nclass Point(object):\n \"\"\"A point is an ordered pair, (x,y)\"\"\"\n\n def __init__(self, x, y):\n assert isinstance(x, numbers.Number)\n assert isinstance(y, numbers.Number)\n self.x = x\n self.y = y\n log.debug('Created Point {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Point({},{})'.format(self.x, self.y)\n\n def __str__(self):\n return '({}, {})'.format(self.x, self.y)\n\n def __eq__(self, other):\n assert isinstance(other, Point)\n return self.x == other.x and self.y == other.y\n\n\nclass Rect(object):\n \"\"\"A rectangle identified by its lower left\n and upper right corners.\n \"\"\"\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug('Rect from ll {}, ur {}'.format(repr(ll), repr(ur)))\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug('ll will be {}'.format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug('ur will be {}'.format(self.ur))\n log.debug('Created rect {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n\n\nclass Point(object):\n \"\"\"A point is an ordered pair, (x,y)\"\"\"\n\n def __init__(self, x, y):\n assert isinstance(x, numbers.Number)\n assert isinstance(y, numbers.Number)\n self.x = x\n self.y = y\n log.debug('Created Point {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Point({},{})'.format(self.x, self.y)\n\n def __str__(self):\n return '({}, {})'.format(self.x, self.y)\n\n def __eq__(self, other):\n assert isinstance(other, Point)\n return self.x == other.x and self.y == other.y\n\n\nclass Rect(object):\n \"\"\"A rectangle identified by its lower left\n and upper right corners.\n \"\"\"\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug('Rect from ll {}, ur {}'.format(repr(ll), repr(ur)))\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug('ll will be {}'.format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug('ur will be {}'.format(self.ur))\n log.debug('Created rect {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n\n\nclass Point(object):\n <docstring token>\n\n def __init__(self, x, y):\n assert isinstance(x, numbers.Number)\n assert isinstance(y, numbers.Number)\n self.x = x\n self.y = y\n log.debug('Created Point {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Point({},{})'.format(self.x, self.y)\n\n def __str__(self):\n return '({}, {})'.format(self.x, self.y)\n\n def __eq__(self, other):\n assert isinstance(other, Point)\n return self.x == other.x and self.y == other.y\n\n\nclass Rect(object):\n \"\"\"A rectangle identified by its lower left\n and upper right corners.\n \"\"\"\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug('Rect from ll {}, ur {}'.format(repr(ll), repr(ur)))\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug('ll will be {}'.format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug('ur will be {}'.format(self.ur))\n log.debug('Created rect {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n\n\nclass Point(object):\n <docstring token>\n\n def __init__(self, x, y):\n assert isinstance(x, numbers.Number)\n assert isinstance(y, numbers.Number)\n self.x = x\n self.y = y\n log.debug('Created Point {}'.format(repr(self)))\n <function token>\n\n def __str__(self):\n return '({}, {})'.format(self.x, self.y)\n\n def __eq__(self, other):\n assert isinstance(other, Point)\n return self.x == other.x and self.y == other.y\n\n\nclass Rect(object):\n \"\"\"A rectangle identified by its lower left\n and upper right corners.\n \"\"\"\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug('Rect from ll {}, ur {}'.format(repr(ll), repr(ur)))\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug('ll will be {}'.format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug('ur will be {}'.format(self.ur))\n log.debug('Created rect {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n\n\nclass Point(object):\n <docstring token>\n <function token>\n <function token>\n\n def __str__(self):\n return '({}, {})'.format(self.x, self.y)\n\n def __eq__(self, other):\n assert isinstance(other, Point)\n return self.x == other.x and self.y == other.y\n\n\nclass Rect(object):\n \"\"\"A rectangle identified by its lower left\n and upper right corners.\n \"\"\"\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug('Rect from ll {}, ur {}'.format(repr(ll), repr(ur)))\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug('ll will be {}'.format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug('ur will be {}'.format(self.ur))\n log.debug('Created rect {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n\n\nclass Point(object):\n <docstring token>\n <function token>\n <function token>\n\n def __str__(self):\n return '({}, {})'.format(self.x, self.y)\n <function token>\n\n\nclass Rect(object):\n \"\"\"A rectangle identified by its lower left\n and upper right corners.\n \"\"\"\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug('Rect from ll {}, ur {}'.format(repr(ll), repr(ur)))\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug('ll will be {}'.format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug('ur will be {}'.format(self.ur))\n log.debug('Created rect {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n\n\nclass Point(object):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass Rect(object):\n \"\"\"A rectangle identified by its lower left\n and upper right corners.\n \"\"\"\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug('Rect from ll {}, ur {}'.format(repr(ll), repr(ur)))\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug('ll will be {}'.format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug('ur will be {}'.format(self.ur))\n log.debug('Created rect {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n<class token>\n\n\nclass Rect(object):\n \"\"\"A rectangle identified by its lower left\n and upper right corners.\n \"\"\"\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug('Rect from ll {}, ur {}'.format(repr(ll), repr(ur)))\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug('ll will be {}'.format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug('ur will be {}'.format(self.ur))\n log.debug('Created rect {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n<class token>\n\n\nclass Rect(object):\n <docstring token>\n\n def __init__(self, ll, ur):\n \"\"\"Initialize rectangle with ll and ur as corners.\"\"\"\n log.debug('Rect from ll {}, ur {}'.format(repr(ll), repr(ur)))\n self.ll = Point(min(ll.x, ur.x), min(ll.y, ur.y))\n log.debug('ll will be {}'.format(self.ll))\n self.ur = Point(max(ll.x, ur.x), max(ll.y, ur.y))\n log.debug('ur will be {}'.format(self.ur))\n log.debug('Created rect {}'.format(repr(self)))\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n<class token>\n\n\nclass Rect(object):\n <docstring token>\n <function token>\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __eq__(self, other):\n assert isinstance(other, Rect)\n return self.ll == other.ll and self.ur == other.ur\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n<class token>\n\n\nclass Rect(object):\n <docstring token>\n <function token>\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n <function token>\n\n def overlaps(self, other):\n \"\"\"r1.overlaps(r2) if there is an area of positive\n size within r1 and also within r2. \"Of positive size\"\n means that touching at a corner or along an edge is\n not enough ... the area of overlap must be positive.\n \"\"\"\n if self.ll.x >= other.ur.x:\n return False\n if self.ll.y >= other.ur.y:\n return False\n if self.ur.x <= other.ll.x:\n return False\n if self.ur.y <= other.ll.y:\n return False\n return True\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n<class token>\n\n\nclass Rect(object):\n <docstring token>\n <function token>\n\n def __repr__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n <function token>\n <function token>\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n<class token>\n\n\nclass Rect(object):\n <docstring token>\n <function token>\n <function token>\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n <function token>\n <function token>\n\n def intersect(self, other):\n \"\"\"Region of overlap, or (0,0),(0,0) if none\"\"\"\n if self.overlaps(other):\n return Rect(Point(max(self.ll.x, other.ll.x), max(self.ll.y,\n other.ll.y)), Point(min(self.ur.x, other.ur.x), min(self.ur\n .y, other.ur.y)))\n else:\n return Rect(Point(0, 0), Point(0, 0))\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n<class token>\n\n\nclass Rect(object):\n <docstring token>\n <function token>\n <function token>\n\n def __str__(self):\n return 'Rect({},{})'.format(self.ll, self.ur)\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n<class token>\n\n\nclass Rect(object):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<docstring token>\n<import token>\n<code token>\n<assignment token>\n<code token>\n<class token>\n<class token>\n" ]
false
761
f25351a3cb7bf583152baa8e7ec47b0f2161cb9c
# Copyright 2014 The crabapple Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import abc class Notifier(object): __metaclass__ = abc.ABCMeta def __init__(self): pass @abc.abstractmethod def config(self, kwargs): pass @abc.abstractmethod def send(self, msg): pass
[ "# Copyright 2014 The crabapple Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nimport abc\n\n\nclass Notifier(object):\n __metaclass__ = abc.ABCMeta\n\n def __init__(self):\n pass\n\n @abc.abstractmethod\n def config(self, kwargs):\n pass\n\n @abc.abstractmethod\n def send(self, msg):\n pass\n", "import abc\n\n\nclass Notifier(object):\n __metaclass__ = abc.ABCMeta\n\n def __init__(self):\n pass\n\n @abc.abstractmethod\n def config(self, kwargs):\n pass\n\n @abc.abstractmethod\n def send(self, msg):\n pass\n", "<import token>\n\n\nclass Notifier(object):\n __metaclass__ = abc.ABCMeta\n\n def __init__(self):\n pass\n\n @abc.abstractmethod\n def config(self, kwargs):\n pass\n\n @abc.abstractmethod\n def send(self, msg):\n pass\n", "<import token>\n\n\nclass Notifier(object):\n <assignment token>\n\n def __init__(self):\n pass\n\n @abc.abstractmethod\n def config(self, kwargs):\n pass\n\n @abc.abstractmethod\n def send(self, msg):\n pass\n", "<import token>\n\n\nclass Notifier(object):\n <assignment token>\n <function token>\n\n @abc.abstractmethod\n def config(self, kwargs):\n pass\n\n @abc.abstractmethod\n def send(self, msg):\n pass\n", "<import token>\n\n\nclass Notifier(object):\n <assignment token>\n <function token>\n <function token>\n\n @abc.abstractmethod\n def send(self, msg):\n pass\n", "<import token>\n\n\nclass Notifier(object):\n <assignment token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n" ]
false
762
d0eb6ea2e816ac59ae93684edb38ff3a49909633
def usage_list(self): print('Available modules') print('=================') for module in sorted(self.list()): if ('module' not in self.mods[module]): self.import_module(module) if (not self.mods[module]['module'].__doc__): continue text = self.mods[module]['module'].__doc__.strip('\n ') text = text.split('\n') if (len(text) > 2): if text[1].startswith('='): text[1] = ('=' * (14 + len(text[1]))) text = '\n'.join(text) print(('\n%-12s: %s' % (module, text)))
[ "def usage_list(self):\n print('Available modules')\n print('=================')\n for module in sorted(self.list()):\n if ('module' not in self.mods[module]):\n self.import_module(module)\n if (not self.mods[module]['module'].__doc__):\n continue\n text = self.mods[module]['module'].__doc__.strip('\\n ')\n text = text.split('\\n')\n if (len(text) > 2):\n if text[1].startswith('='):\n text[1] = ('=' * (14 + len(text[1])))\n text = '\\n'.join(text)\n print(('\\n%-12s: %s' % (module, text)))", "def usage_list(self):\n print('Available modules')\n print('=================')\n for module in sorted(self.list()):\n if 'module' not in self.mods[module]:\n self.import_module(module)\n if not self.mods[module]['module'].__doc__:\n continue\n text = self.mods[module]['module'].__doc__.strip('\\n ')\n text = text.split('\\n')\n if len(text) > 2:\n if text[1].startswith('='):\n text[1] = '=' * (14 + len(text[1]))\n text = '\\n'.join(text)\n print('\\n%-12s: %s' % (module, text))\n", "<function token>\n" ]
false
763
f3329962004a4454c04327da56d8dd1d0f1d45e7
import csv import datetime import json import re import requests import os r = requests.get("https://www.hithit.com/cs/project/4067/volebni-kalkulacka-on-steroids") path = os.path.dirname(os.path.realpath(__file__)) + "/" if r.status_code == 200: text = r.text pattern = 'Přispěvatel' m = re.search(pattern, text) pattern2 = '<strong>([0-9]{1,})' m2 = re.search(pattern2, text[m.start():]) pattern3 = 'currency " >([0-9]{1,})' m3 = re.search(pattern3, text.replace('&nbsp;', '')) with open(path + "data.json", "w") as fdata: json.dump({ "date": datetime.datetime.now().isoformat(), "amount": m3.group(1), "supporters": m2.group(1) }, fdata)
[ "import csv\nimport datetime\nimport json\nimport re\nimport requests\nimport os\n\nr = requests.get(\"https://www.hithit.com/cs/project/4067/volebni-kalkulacka-on-steroids\")\n\npath = os.path.dirname(os.path.realpath(__file__)) + \"/\"\n\nif r.status_code == 200:\n text = r.text\n pattern = 'Přispěvatel'\n m = re.search(pattern, text)\n pattern2 = '<strong>([0-9]{1,})'\n m2 = re.search(pattern2, text[m.start():])\n pattern3 = 'currency \" >([0-9]{1,})'\n m3 = re.search(pattern3, text.replace('&nbsp;', ''))\n with open(path + \"data.json\", \"w\") as fdata:\n json.dump({\n \"date\": datetime.datetime.now().isoformat(),\n \"amount\": m3.group(1),\n \"supporters\": m2.group(1)\n }, fdata)\n", "import csv\nimport datetime\nimport json\nimport re\nimport requests\nimport os\nr = requests.get(\n 'https://www.hithit.com/cs/project/4067/volebni-kalkulacka-on-steroids')\npath = os.path.dirname(os.path.realpath(__file__)) + '/'\nif r.status_code == 200:\n text = r.text\n pattern = 'Přispěvatel'\n m = re.search(pattern, text)\n pattern2 = '<strong>([0-9]{1,})'\n m2 = re.search(pattern2, text[m.start():])\n pattern3 = 'currency \" >([0-9]{1,})'\n m3 = re.search(pattern3, text.replace('&nbsp;', ''))\n with open(path + 'data.json', 'w') as fdata:\n json.dump({'date': datetime.datetime.now().isoformat(), 'amount':\n m3.group(1), 'supporters': m2.group(1)}, fdata)\n", "<import token>\nr = requests.get(\n 'https://www.hithit.com/cs/project/4067/volebni-kalkulacka-on-steroids')\npath = os.path.dirname(os.path.realpath(__file__)) + '/'\nif r.status_code == 200:\n text = r.text\n pattern = 'Přispěvatel'\n m = re.search(pattern, text)\n pattern2 = '<strong>([0-9]{1,})'\n m2 = re.search(pattern2, text[m.start():])\n pattern3 = 'currency \" >([0-9]{1,})'\n m3 = re.search(pattern3, text.replace('&nbsp;', ''))\n with open(path + 'data.json', 'w') as fdata:\n json.dump({'date': datetime.datetime.now().isoformat(), 'amount':\n m3.group(1), 'supporters': m2.group(1)}, fdata)\n", "<import token>\n<assignment token>\nif r.status_code == 200:\n text = r.text\n pattern = 'Přispěvatel'\n m = re.search(pattern, text)\n pattern2 = '<strong>([0-9]{1,})'\n m2 = re.search(pattern2, text[m.start():])\n pattern3 = 'currency \" >([0-9]{1,})'\n m3 = re.search(pattern3, text.replace('&nbsp;', ''))\n with open(path + 'data.json', 'w') as fdata:\n json.dump({'date': datetime.datetime.now().isoformat(), 'amount':\n m3.group(1), 'supporters': m2.group(1)}, fdata)\n", "<import token>\n<assignment token>\n<code token>\n" ]
false
764
2c505f3f1dfdefae8edbea0916873229bcda901f
from flask import Blueprint class NestableBlueprint(Blueprint): def register_blueprint(self, blueprint, **options): def deferred(state): # state.url_prefix => 自己url前缀 + blueprint.url_prefix => /v3/api/cmdb/ url_prefix = (state.url_prefix or u"") + (options.get('url_prefix', blueprint.url_prefix) or u"") if 'url_prefix' in options: del options['url_prefix'] # app.register_blueprint(blueprint, '/v3/api/cmdb/') state.app.register_blueprint(blueprint, url_prefix=url_prefix, **options) self.record(deferred)
[ "from flask import Blueprint\n\n\nclass NestableBlueprint(Blueprint):\n def register_blueprint(self, blueprint, **options):\n def deferred(state):\n # state.url_prefix => 自己url前缀 + blueprint.url_prefix => /v3/api/cmdb/\n url_prefix = (state.url_prefix or u\"\") + (options.get('url_prefix', blueprint.url_prefix) or u\"\")\n if 'url_prefix' in options:\n del options['url_prefix']\n # app.register_blueprint(blueprint, '/v3/api/cmdb/')\n state.app.register_blueprint(blueprint, url_prefix=url_prefix, **options)\n self.record(deferred)\n", "from flask import Blueprint\n\n\nclass NestableBlueprint(Blueprint):\n\n def register_blueprint(self, blueprint, **options):\n\n def deferred(state):\n url_prefix = (state.url_prefix or u'') + (options.get(\n 'url_prefix', blueprint.url_prefix) or u'')\n if 'url_prefix' in options:\n del options['url_prefix']\n state.app.register_blueprint(blueprint, url_prefix=url_prefix,\n **options)\n self.record(deferred)\n", "<import token>\n\n\nclass NestableBlueprint(Blueprint):\n\n def register_blueprint(self, blueprint, **options):\n\n def deferred(state):\n url_prefix = (state.url_prefix or u'') + (options.get(\n 'url_prefix', blueprint.url_prefix) or u'')\n if 'url_prefix' in options:\n del options['url_prefix']\n state.app.register_blueprint(blueprint, url_prefix=url_prefix,\n **options)\n self.record(deferred)\n", "<import token>\n\n\nclass NestableBlueprint(Blueprint):\n <function token>\n", "<import token>\n<class token>\n" ]
false
765
5721786b61cf8706b1d401a46d06f2d32153df8b
n=int(input("enter the number\n")) sum=0 for i in range(1,n-1): rem=n%i if(rem==0): sum=sum+i if(sum==n): print("the number is perfect") else: print("not prime")
[ "n=int(input(\"enter the number\\n\"))\nsum=0\nfor i in range(1,n-1):\n rem=n%i\n if(rem==0):\n sum=sum+i\nif(sum==n):\n print(\"the number is perfect\")\nelse:\n print(\"not prime\")\n", "n = int(input('enter the number\\n'))\nsum = 0\nfor i in range(1, n - 1):\n rem = n % i\n if rem == 0:\n sum = sum + i\nif sum == n:\n print('the number is perfect')\nelse:\n print('not prime')\n", "<assignment token>\nfor i in range(1, n - 1):\n rem = n % i\n if rem == 0:\n sum = sum + i\nif sum == n:\n print('the number is perfect')\nelse:\n print('not prime')\n", "<assignment token>\n<code token>\n" ]
false
766
24f87bd6aab0ff65cf2153e27df31122818ad0ac
import unittest from Spreadsheet.HTML import Table class TestColGroup(unittest.TestCase): def test_colgroup(self): return data = [ ['a','b','c'], [1,2,3], [4,5,6], ] gen = Table( { 'data': data, 'colgroup': { 'span': 3, 'width': 100 }, 'attr_sort': 1 } ) self.assertEqual( '<table><colgroup span="3" width="100" /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>', gen.generate(), "colgroup present from generate()" ) self.assertEqual( '<table><colgroup span="3" width="100" /><thead><tr><th>a</th><th>b</th><th>c</th></tr></thead><tfoot><tr><td>4</td><td>5</td><td>6</td></tr></tfoot><tbody><tr><td>1</td><td>2</td><td>3</td></tr></tbody></table>', gen.generate( { 'tgroups': 2 } ), "colgroup present from generate() with tgroups" ) self.assertEqual( '<table><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>', gen.generate( { 'colgroup': None } ), "colgroup can be overriden" ) self.assertEqual( '<table><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>', gen.generate( { 'colgroup': 1 } ), "colgroup yields no-op if scalar" ) self.assertEqual( '<table><colgroup color="red" span="1" /><colgroup color="blue" span="2" /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>', gen.generate( { 'colgroup': [ { 'span': 1, 'color': 'red' }, { 'span': 2, 'color': 'blue' } ] } ), "can specify multiple colgroups" ) def test_col(self): return data = [ ['a','b','c'], [1,2,3], [4,5,6], ] gen = Table( { 'data': data, 'colgroup': { 'span': 3, 'width': 100 }, 'attr_sort': 1 } ); self.assertEqual( '<table><colgroup span="3" width="100"><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>', gen.generate( { 'col': {} } ), "colgroup wraps col" ) self.assertEqual( '<table><colgroup span="3" width="100"><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>', gen.generate( { 'col': [{},{},{}] } ), "colgroup wraps multiple cols" ) self.assertEqual( '<table><colgroup><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>', gen.generate( { 'colgroup': None, 'col': {} } ), "colgroup can be overriden when col is present too" ) gen = Table( { 'data': data, 'col': [{},{},{}] } ); self.assertEqual( '<table><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>', gen.generate( { 'colgroup': {} } ), "multiple cols against single colgroup" ) self.assertEqual( '<table><colgroup /><colgroup /><colgroup /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>', gen.generate( { 'col': None, 'colgroup': [{},{},{}] } ), "no cols against multiple colgroups" ) self.assertEqual( '<table><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>', gen.generate( { 'colgroup': [{},{},{}] } ), "multiple cols against multiple colgroups" ) if __name__ == '__main__': unittest.main()
[ "import unittest\nfrom Spreadsheet.HTML import Table\n\nclass TestColGroup(unittest.TestCase):\n\n def test_colgroup(self):\n return\n\n data = [\n ['a','b','c'],\n [1,2,3],\n [4,5,6],\n ]\n\n gen = Table( { 'data': data, 'colgroup': { 'span': 3, 'width': 100 }, 'attr_sort': 1 } )\n\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\" /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>',\n gen.generate(),\n \"colgroup present from generate()\"\n )\n\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\" /><thead><tr><th>a</th><th>b</th><th>c</th></tr></thead><tfoot><tr><td>4</td><td>5</td><td>6</td></tr></tfoot><tbody><tr><td>1</td><td>2</td><td>3</td></tr></tbody></table>',\n gen.generate( { 'tgroups': 2 } ),\n \"colgroup present from generate() with tgroups\"\n )\n\n self.assertEqual(\n '<table><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>',\n gen.generate( { 'colgroup': None } ),\n \"colgroup can be overriden\"\n )\n\n self.assertEqual(\n '<table><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>',\n gen.generate( { 'colgroup': 1 } ),\n \"colgroup yields no-op if scalar\"\n )\n\n self.assertEqual(\n '<table><colgroup color=\"red\" span=\"1\" /><colgroup color=\"blue\" span=\"2\" /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>',\n gen.generate( { 'colgroup': [ { 'span': 1, 'color': 'red' }, { 'span': 2, 'color': 'blue' } ] } ),\n \"can specify multiple colgroups\"\n )\n\n\n def test_col(self):\n return\n\n data = [\n ['a','b','c'],\n [1,2,3],\n [4,5,6],\n ]\n\n gen = Table( { 'data': data, 'colgroup': { 'span': 3, 'width': 100 }, 'attr_sort': 1 } );\n\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\"><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>',\n gen.generate( { 'col': {} } ),\n \"colgroup wraps col\"\n )\n\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\"><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>',\n gen.generate( { 'col': [{},{},{}] } ),\n \"colgroup wraps multiple cols\"\n )\n\n self.assertEqual(\n '<table><colgroup><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>',\n gen.generate( { 'colgroup': None, 'col': {} } ),\n \"colgroup can be overriden when col is present too\"\n )\n\n\n gen = Table( { 'data': data, 'col': [{},{},{}] } );\n\n self.assertEqual(\n '<table><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>',\n gen.generate( { 'colgroup': {} } ),\n \"multiple cols against single colgroup\"\n )\n\n self.assertEqual(\n '<table><colgroup /><colgroup /><colgroup /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>',\n gen.generate( { 'col': None, 'colgroup': [{},{},{}] } ),\n \"no cols against multiple colgroups\"\n )\n\n self.assertEqual(\n '<table><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>',\n gen.generate( { 'colgroup': [{},{},{}] } ),\n \"multiple cols against multiple colgroups\"\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n", "import unittest\nfrom Spreadsheet.HTML import Table\n\n\nclass TestColGroup(unittest.TestCase):\n\n def test_colgroup(self):\n return\n data = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]\n gen = Table({'data': data, 'colgroup': {'span': 3, 'width': 100},\n 'attr_sort': 1})\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\" /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate(), 'colgroup present from generate()')\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\" /><thead><tr><th>a</th><th>b</th><th>c</th></tr></thead><tfoot><tr><td>4</td><td>5</td><td>6</td></tr></tfoot><tbody><tr><td>1</td><td>2</td><td>3</td></tr></tbody></table>'\n , gen.generate({'tgroups': 2}),\n 'colgroup present from generate() with tgroups')\n self.assertEqual(\n '<table><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': None}), 'colgroup can be overriden')\n self.assertEqual(\n '<table><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': 1}), 'colgroup yields no-op if scalar')\n self.assertEqual(\n '<table><colgroup color=\"red\" span=\"1\" /><colgroup color=\"blue\" span=\"2\" /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': [{'span': 1, 'color': 'red'}, {\n 'span': 2, 'color': 'blue'}]}), 'can specify multiple colgroups')\n\n def test_col(self):\n return\n data = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]\n gen = Table({'data': data, 'colgroup': {'span': 3, 'width': 100},\n 'attr_sort': 1})\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\"><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': {}}), 'colgroup wraps col')\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\"><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': [{}, {}, {}]}),\n 'colgroup wraps multiple cols')\n self.assertEqual(\n '<table><colgroup><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': None, 'col': {}}),\n 'colgroup can be overriden when col is present too')\n gen = Table({'data': data, 'col': [{}, {}, {}]})\n self.assertEqual(\n '<table><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': {}}),\n 'multiple cols against single colgroup')\n self.assertEqual(\n '<table><colgroup /><colgroup /><colgroup /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': None, 'colgroup': [{}, {}, {}]}),\n 'no cols against multiple colgroups')\n self.assertEqual(\n '<table><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': [{}, {}, {}]}),\n 'multiple cols against multiple colgroups')\n\n\nif __name__ == '__main__':\n unittest.main()\n", "<import token>\n\n\nclass TestColGroup(unittest.TestCase):\n\n def test_colgroup(self):\n return\n data = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]\n gen = Table({'data': data, 'colgroup': {'span': 3, 'width': 100},\n 'attr_sort': 1})\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\" /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate(), 'colgroup present from generate()')\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\" /><thead><tr><th>a</th><th>b</th><th>c</th></tr></thead><tfoot><tr><td>4</td><td>5</td><td>6</td></tr></tfoot><tbody><tr><td>1</td><td>2</td><td>3</td></tr></tbody></table>'\n , gen.generate({'tgroups': 2}),\n 'colgroup present from generate() with tgroups')\n self.assertEqual(\n '<table><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': None}), 'colgroup can be overriden')\n self.assertEqual(\n '<table><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': 1}), 'colgroup yields no-op if scalar')\n self.assertEqual(\n '<table><colgroup color=\"red\" span=\"1\" /><colgroup color=\"blue\" span=\"2\" /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': [{'span': 1, 'color': 'red'}, {\n 'span': 2, 'color': 'blue'}]}), 'can specify multiple colgroups')\n\n def test_col(self):\n return\n data = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]\n gen = Table({'data': data, 'colgroup': {'span': 3, 'width': 100},\n 'attr_sort': 1})\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\"><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': {}}), 'colgroup wraps col')\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\"><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': [{}, {}, {}]}),\n 'colgroup wraps multiple cols')\n self.assertEqual(\n '<table><colgroup><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': None, 'col': {}}),\n 'colgroup can be overriden when col is present too')\n gen = Table({'data': data, 'col': [{}, {}, {}]})\n self.assertEqual(\n '<table><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': {}}),\n 'multiple cols against single colgroup')\n self.assertEqual(\n '<table><colgroup /><colgroup /><colgroup /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': None, 'colgroup': [{}, {}, {}]}),\n 'no cols against multiple colgroups')\n self.assertEqual(\n '<table><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': [{}, {}, {}]}),\n 'multiple cols against multiple colgroups')\n\n\nif __name__ == '__main__':\n unittest.main()\n", "<import token>\n\n\nclass TestColGroup(unittest.TestCase):\n\n def test_colgroup(self):\n return\n data = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]\n gen = Table({'data': data, 'colgroup': {'span': 3, 'width': 100},\n 'attr_sort': 1})\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\" /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate(), 'colgroup present from generate()')\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\" /><thead><tr><th>a</th><th>b</th><th>c</th></tr></thead><tfoot><tr><td>4</td><td>5</td><td>6</td></tr></tfoot><tbody><tr><td>1</td><td>2</td><td>3</td></tr></tbody></table>'\n , gen.generate({'tgroups': 2}),\n 'colgroup present from generate() with tgroups')\n self.assertEqual(\n '<table><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': None}), 'colgroup can be overriden')\n self.assertEqual(\n '<table><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': 1}), 'colgroup yields no-op if scalar')\n self.assertEqual(\n '<table><colgroup color=\"red\" span=\"1\" /><colgroup color=\"blue\" span=\"2\" /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': [{'span': 1, 'color': 'red'}, {\n 'span': 2, 'color': 'blue'}]}), 'can specify multiple colgroups')\n\n def test_col(self):\n return\n data = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]\n gen = Table({'data': data, 'colgroup': {'span': 3, 'width': 100},\n 'attr_sort': 1})\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\"><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': {}}), 'colgroup wraps col')\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\"><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': [{}, {}, {}]}),\n 'colgroup wraps multiple cols')\n self.assertEqual(\n '<table><colgroup><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': None, 'col': {}}),\n 'colgroup can be overriden when col is present too')\n gen = Table({'data': data, 'col': [{}, {}, {}]})\n self.assertEqual(\n '<table><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': {}}),\n 'multiple cols against single colgroup')\n self.assertEqual(\n '<table><colgroup /><colgroup /><colgroup /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': None, 'colgroup': [{}, {}, {}]}),\n 'no cols against multiple colgroups')\n self.assertEqual(\n '<table><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': [{}, {}, {}]}),\n 'multiple cols against multiple colgroups')\n\n\n<code token>\n", "<import token>\n\n\nclass TestColGroup(unittest.TestCase):\n <function token>\n\n def test_col(self):\n return\n data = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]\n gen = Table({'data': data, 'colgroup': {'span': 3, 'width': 100},\n 'attr_sort': 1})\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\"><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': {}}), 'colgroup wraps col')\n self.assertEqual(\n '<table><colgroup span=\"3\" width=\"100\"><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': [{}, {}, {}]}),\n 'colgroup wraps multiple cols')\n self.assertEqual(\n '<table><colgroup><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': None, 'col': {}}),\n 'colgroup can be overriden when col is present too')\n gen = Table({'data': data, 'col': [{}, {}, {}]})\n self.assertEqual(\n '<table><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': {}}),\n 'multiple cols against single colgroup')\n self.assertEqual(\n '<table><colgroup /><colgroup /><colgroup /><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'col': None, 'colgroup': [{}, {}, {}]}),\n 'no cols against multiple colgroups')\n self.assertEqual(\n '<table><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><colgroup><col /><col /><col /></colgroup><tr><th>a</th><th>b</th><th>c</th></tr><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>4</td><td>5</td><td>6</td></tr></table>'\n , gen.generate({'colgroup': [{}, {}, {}]}),\n 'multiple cols against multiple colgroups')\n\n\n<code token>\n", "<import token>\n\n\nclass TestColGroup(unittest.TestCase):\n <function token>\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<code token>\n" ]
false
767
2a0172641c48c47f048bf5e9f1889b29abbb0b7c
#!/usr/bin/env python3 #coding=utf8 from __future__ import (division,absolute_import,print_function,unicode_literals) import argparse, csv, sys,subprocess,time NR_THREAD=20 def shell(cmd): subprocess.call(cmd,shell=True) print("Done! {0}.".format(cmd)) start=time.time() cmd = 'mkdir FTRL/tmp -p' shell(cmd) cmd = 'mkdir FTRL/data -p' shell(cmd) #cmd = 'FTRL/ensamble/ensamble.py -s {nr_thread} -f 5 ffmData/Filter100/click_train.ffm ffmData/Filter100/click_test.ffm FTRL/data/click_train_out.txt FTRL/data/click_test_out.txt '.format(nr_thread=NR_THREAD) #shell(cmd) cmd = 'FTRL/FTRLStarter.py ffmData/filter100/split_train.ffm ffmData/filter100/split_test.ffm FTRL/tmp/split_test_cv.out ffmData/filter100/click_test.ffm FTRL/tmp/click_test_cv.out' shell(cmd) cmd='util/map.py FTRL/tmp/split_test_cv.out data/split_test.csv' shell(cmd) print('time used = {0:.0f}'.format(time.time()-start))
[ "#!/usr/bin/env python3\n#coding=utf8\nfrom __future__ import (division,absolute_import,print_function,unicode_literals)\nimport argparse, csv, sys,subprocess,time\n\nNR_THREAD=20\ndef shell(cmd):\n subprocess.call(cmd,shell=True)\n print(\"Done! {0}.\".format(cmd))\n\nstart=time.time()\n\ncmd = 'mkdir FTRL/tmp -p'\nshell(cmd)\n\ncmd = 'mkdir FTRL/data -p'\nshell(cmd)\n\n#cmd = 'FTRL/ensamble/ensamble.py -s {nr_thread} -f 5 ffmData/Filter100/click_train.ffm ffmData/Filter100/click_test.ffm FTRL/data/click_train_out.txt FTRL/data/click_test_out.txt '.format(nr_thread=NR_THREAD)\n#shell(cmd)\n\ncmd = 'FTRL/FTRLStarter.py ffmData/filter100/split_train.ffm ffmData/filter100/split_test.ffm FTRL/tmp/split_test_cv.out ffmData/filter100/click_test.ffm FTRL/tmp/click_test_cv.out'\nshell(cmd)\n\ncmd='util/map.py FTRL/tmp/split_test_cv.out data/split_test.csv'\nshell(cmd)\n\nprint('time used = {0:.0f}'.format(time.time()-start))\n", "from __future__ import division, absolute_import, print_function, unicode_literals\nimport argparse, csv, sys, subprocess, time\nNR_THREAD = 20\n\n\ndef shell(cmd):\n subprocess.call(cmd, shell=True)\n print('Done! {0}.'.format(cmd))\n\n\nstart = time.time()\ncmd = 'mkdir FTRL/tmp -p'\nshell(cmd)\ncmd = 'mkdir FTRL/data -p'\nshell(cmd)\ncmd = (\n 'FTRL/FTRLStarter.py ffmData/filter100/split_train.ffm ffmData/filter100/split_test.ffm FTRL/tmp/split_test_cv.out ffmData/filter100/click_test.ffm FTRL/tmp/click_test_cv.out'\n )\nshell(cmd)\ncmd = 'util/map.py FTRL/tmp/split_test_cv.out data/split_test.csv'\nshell(cmd)\nprint('time used = {0:.0f}'.format(time.time() - start))\n", "<import token>\nNR_THREAD = 20\n\n\ndef shell(cmd):\n subprocess.call(cmd, shell=True)\n print('Done! {0}.'.format(cmd))\n\n\nstart = time.time()\ncmd = 'mkdir FTRL/tmp -p'\nshell(cmd)\ncmd = 'mkdir FTRL/data -p'\nshell(cmd)\ncmd = (\n 'FTRL/FTRLStarter.py ffmData/filter100/split_train.ffm ffmData/filter100/split_test.ffm FTRL/tmp/split_test_cv.out ffmData/filter100/click_test.ffm FTRL/tmp/click_test_cv.out'\n )\nshell(cmd)\ncmd = 'util/map.py FTRL/tmp/split_test_cv.out data/split_test.csv'\nshell(cmd)\nprint('time used = {0:.0f}'.format(time.time() - start))\n", "<import token>\n<assignment token>\n\n\ndef shell(cmd):\n subprocess.call(cmd, shell=True)\n print('Done! {0}.'.format(cmd))\n\n\n<assignment token>\nshell(cmd)\n<assignment token>\nshell(cmd)\n<assignment token>\nshell(cmd)\n<assignment token>\nshell(cmd)\nprint('time used = {0:.0f}'.format(time.time() - start))\n", "<import token>\n<assignment token>\n\n\ndef shell(cmd):\n subprocess.call(cmd, shell=True)\n print('Done! {0}.'.format(cmd))\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
768
eab5bf4776582349615ad56ee1ed93bc8f868565
from common import * import serial CMD_BAUD = chr(129) BAUD_RATES = [300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200] class Communication(Module): def __init__(self, parent, port_name, baud_rate): self.parent = parent if not isinstance(port_name, str): raise Exception("Port name must be a string.") if not isinstance(baud_rate, int): raise Exception("Baud rate must be an integer.") if baud_rate not in BAUD_RATES: raise Exception("%d is not a valid baud rate; check the SCI Specification for acceptable values." % baud_rate) self.port = serial.Serial(port_name, baud_rate) def send(self, data): if not isinstance(data, str): raise Exception("Data must be a string.") self.port.write(data) def receive(self, length): if not isinstance(length, int): raise Exception("Receive length must be an integer.") return self.port.read(length) _port = None @property def port(self): return self._port @port.setter def port(self, value): self._port = value
[ "from common import *\n\nimport serial\n\nCMD_BAUD = chr(129)\n\nBAUD_RATES = [300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200]\n\nclass Communication(Module):\n def __init__(self, parent, port_name, baud_rate):\n self.parent = parent\n\n if not isinstance(port_name, str):\n raise Exception(\"Port name must be a string.\")\n if not isinstance(baud_rate, int):\n raise Exception(\"Baud rate must be an integer.\")\n if baud_rate not in BAUD_RATES:\n raise Exception(\"%d is not a valid baud rate; check the SCI Specification for acceptable values.\" % baud_rate)\n\n self.port = serial.Serial(port_name, baud_rate)\n\n def send(self, data):\n if not isinstance(data, str):\n raise Exception(\"Data must be a string.\")\n self.port.write(data)\n\n def receive(self, length):\n if not isinstance(length, int):\n raise Exception(\"Receive length must be an integer.\")\n return self.port.read(length)\n\n _port = None\n @property\n def port(self):\n return self._port\n @port.setter\n def port(self, value):\n self._port = value\n", "from common import *\nimport serial\nCMD_BAUD = chr(129)\nBAUD_RATES = [300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400,\n 57600, 115200]\n\n\nclass Communication(Module):\n\n def __init__(self, parent, port_name, baud_rate):\n self.parent = parent\n if not isinstance(port_name, str):\n raise Exception('Port name must be a string.')\n if not isinstance(baud_rate, int):\n raise Exception('Baud rate must be an integer.')\n if baud_rate not in BAUD_RATES:\n raise Exception(\n '%d is not a valid baud rate; check the SCI Specification for acceptable values.'\n % baud_rate)\n self.port = serial.Serial(port_name, baud_rate)\n\n def send(self, data):\n if not isinstance(data, str):\n raise Exception('Data must be a string.')\n self.port.write(data)\n\n def receive(self, length):\n if not isinstance(length, int):\n raise Exception('Receive length must be an integer.')\n return self.port.read(length)\n _port = None\n\n @property\n def port(self):\n return self._port\n\n @port.setter\n def port(self, value):\n self._port = value\n", "<import token>\nCMD_BAUD = chr(129)\nBAUD_RATES = [300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400,\n 57600, 115200]\n\n\nclass Communication(Module):\n\n def __init__(self, parent, port_name, baud_rate):\n self.parent = parent\n if not isinstance(port_name, str):\n raise Exception('Port name must be a string.')\n if not isinstance(baud_rate, int):\n raise Exception('Baud rate must be an integer.')\n if baud_rate not in BAUD_RATES:\n raise Exception(\n '%d is not a valid baud rate; check the SCI Specification for acceptable values.'\n % baud_rate)\n self.port = serial.Serial(port_name, baud_rate)\n\n def send(self, data):\n if not isinstance(data, str):\n raise Exception('Data must be a string.')\n self.port.write(data)\n\n def receive(self, length):\n if not isinstance(length, int):\n raise Exception('Receive length must be an integer.')\n return self.port.read(length)\n _port = None\n\n @property\n def port(self):\n return self._port\n\n @port.setter\n def port(self, value):\n self._port = value\n", "<import token>\n<assignment token>\n\n\nclass Communication(Module):\n\n def __init__(self, parent, port_name, baud_rate):\n self.parent = parent\n if not isinstance(port_name, str):\n raise Exception('Port name must be a string.')\n if not isinstance(baud_rate, int):\n raise Exception('Baud rate must be an integer.')\n if baud_rate not in BAUD_RATES:\n raise Exception(\n '%d is not a valid baud rate; check the SCI Specification for acceptable values.'\n % baud_rate)\n self.port = serial.Serial(port_name, baud_rate)\n\n def send(self, data):\n if not isinstance(data, str):\n raise Exception('Data must be a string.')\n self.port.write(data)\n\n def receive(self, length):\n if not isinstance(length, int):\n raise Exception('Receive length must be an integer.')\n return self.port.read(length)\n _port = None\n\n @property\n def port(self):\n return self._port\n\n @port.setter\n def port(self, value):\n self._port = value\n", "<import token>\n<assignment token>\n\n\nclass Communication(Module):\n\n def __init__(self, parent, port_name, baud_rate):\n self.parent = parent\n if not isinstance(port_name, str):\n raise Exception('Port name must be a string.')\n if not isinstance(baud_rate, int):\n raise Exception('Baud rate must be an integer.')\n if baud_rate not in BAUD_RATES:\n raise Exception(\n '%d is not a valid baud rate; check the SCI Specification for acceptable values.'\n % baud_rate)\n self.port = serial.Serial(port_name, baud_rate)\n\n def send(self, data):\n if not isinstance(data, str):\n raise Exception('Data must be a string.')\n self.port.write(data)\n\n def receive(self, length):\n if not isinstance(length, int):\n raise Exception('Receive length must be an integer.')\n return self.port.read(length)\n <assignment token>\n\n @property\n def port(self):\n return self._port\n\n @port.setter\n def port(self, value):\n self._port = value\n", "<import token>\n<assignment token>\n\n\nclass Communication(Module):\n\n def __init__(self, parent, port_name, baud_rate):\n self.parent = parent\n if not isinstance(port_name, str):\n raise Exception('Port name must be a string.')\n if not isinstance(baud_rate, int):\n raise Exception('Baud rate must be an integer.')\n if baud_rate not in BAUD_RATES:\n raise Exception(\n '%d is not a valid baud rate; check the SCI Specification for acceptable values.'\n % baud_rate)\n self.port = serial.Serial(port_name, baud_rate)\n <function token>\n\n def receive(self, length):\n if not isinstance(length, int):\n raise Exception('Receive length must be an integer.')\n return self.port.read(length)\n <assignment token>\n\n @property\n def port(self):\n return self._port\n\n @port.setter\n def port(self, value):\n self._port = value\n", "<import token>\n<assignment token>\n\n\nclass Communication(Module):\n\n def __init__(self, parent, port_name, baud_rate):\n self.parent = parent\n if not isinstance(port_name, str):\n raise Exception('Port name must be a string.')\n if not isinstance(baud_rate, int):\n raise Exception('Baud rate must be an integer.')\n if baud_rate not in BAUD_RATES:\n raise Exception(\n '%d is not a valid baud rate; check the SCI Specification for acceptable values.'\n % baud_rate)\n self.port = serial.Serial(port_name, baud_rate)\n <function token>\n <function token>\n <assignment token>\n\n @property\n def port(self):\n return self._port\n\n @port.setter\n def port(self, value):\n self._port = value\n", "<import token>\n<assignment token>\n\n\nclass Communication(Module):\n\n def __init__(self, parent, port_name, baud_rate):\n self.parent = parent\n if not isinstance(port_name, str):\n raise Exception('Port name must be a string.')\n if not isinstance(baud_rate, int):\n raise Exception('Baud rate must be an integer.')\n if baud_rate not in BAUD_RATES:\n raise Exception(\n '%d is not a valid baud rate; check the SCI Specification for acceptable values.'\n % baud_rate)\n self.port = serial.Serial(port_name, baud_rate)\n <function token>\n <function token>\n <assignment token>\n <function token>\n\n @port.setter\n def port(self, value):\n self._port = value\n", "<import token>\n<assignment token>\n\n\nclass Communication(Module):\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n\n @port.setter\n def port(self, value):\n self._port = value\n", "<import token>\n<assignment token>\n\n\nclass Communication(Module):\n <function token>\n <function token>\n <function token>\n <assignment token>\n <function token>\n <function token>\n", "<import token>\n<assignment token>\n<class token>\n" ]
false
769
abbad57e945d2195021948a0e0838c6bfd9c6a1e
#connect4_JayNa.py #Jay Na #CS111 Spring 2018 #This file creates a version of the game Connect4, where the user plays against an AI from graphics import * import random class ConnectWindow: def __init__(self): self.window = GraphWin("Connect Four", 690, 590) self.window.setMouseHandler(self.handleClick) self.startScreen() self.currentUser = 1 self.limitCounter = 0 def startScreen(self): '''This function creates the board and intializes the board count for each column''' #draws blue rectangle as the background self.background = Rectangle(Point(0,0), Point(690,590)) self.background.setFill('blue') self.background.draw(self.window) #draws white circles to represent the spots for the game for i in range(7): for j in range(6): self.Circles = Circle(Point(i*100+50,j*100+50),(30)) self.Circles.setFill('white') self.Circles.draw(self.window) #draws lines to separate circles in rectangle for i in range(6): self.horizLine = Line(Point(0,i*100+100), Point(900,i*100+100)) self.vertLine = Line(Point(100*i+100,0), Point(100*i+100,900)) self.horizLine.draw(self.window) self.vertLine.draw(self.window) #initiates counts for each column and creates grid self.grid = [[],[],[],[],[],[],[]] self.boardCount = [0,0,0,0,0,0,0] counter = 2 #help from CS Major, Joh Farmer for x in range(7): for y in range(6): self.grid[x].append(counter) counter += 1 def validClick(self, x): '''This function checks if there is enough space vertically for move to be valid''' if self.boardCount[x] >= 6: print("Invalid Move") return False else: return True def drawUmove(self): '''This function prints the pieces onto the board at the given position from the user''' piece = Circle(Point(self.x*100+50, 600-(self.y*100+50)),30) piece.setFill('red') piece.draw(self.window) return def handleClick(self, point): '''This function works with the user to add each move into the board count and to the current grid''' self.newX = point.getX() self.x = self.newX//100 self.y = self.boardCount[self.x] if self.validClick(self.x): self.boardCount[self.x] += 1 self.limitCounter += 1 self.grid[self.x][self.y] = self.currentUser if self.isWon() == False: self.limitCounter += 1 self.computerMove() self.drawUmove() def isWon(self): '''This function checks if there is a winner in the game (True/False) and calls printWinner function''' #checks to see if there is a winner vertically for i in range(7): for j in range(3): self.square1 = self.grid[i][j] self.square2 = self.grid[i][j+1] self.square3 = self.grid[i][j+2] self.square4 = self.grid[i][j+3] if self.square1 == self.square2 and self.square2 == self.square3 and self.square3 == self.square4: self.printWinner(self.square1) return True #checks to see if there is a winner diagonally from lower left to upper right for i in range(4): for j in range(3): self.square1 = self.grid[i][j] self.square2 = self.grid[i+1][j+1] self.square3 = self.grid[i+2][j+2] self.square4 = self.grid[i+3][j+3] if self.square1 == self.square2 and self.square2 == self.square3 and self.square3 == self.square4: self.printWinner(self.square1) return True #checks to see if there is a winner diagonally from upper left to lower right for i in range(3,7): for j in range(3): self.square1 = self.grid[i][j] self.square2 = self.grid[i-1][j+1] self.square3 = self.grid[i-2][j+2] self.square4 = self.grid[i-3][j+3] if self.square1 == self.square2 and self.square2 == self.square3 and self.square3 == self.square4: self.printWinner(self.square1) return True #checks to see if there is a winner horizontally for i in range(4): for j in range(6): self.square1 = self.grid[i][j] self.square2 = self.grid[i+1][j] self.square3 = self.grid[i+2][j] self.square4 = self.grid[i+3][j] if self.square1 == self.square2 and self.square2 == self.square3 and self.square3 == self.square4: self.printWinner(self.square1) return True #checks if board is full without a winner (tie) if self.limitCounter == 42: self.printWinner(3) return True return False def printWinner(self, winner): '''This function prints who the winner is or if it is a tie''' #if input is 3 from isWon() fxn, game is tied and so "Tie Game!" is printed if winner == 3: txt = Text(Point(345, 300), "Tie Game!") txt.setFill('white') txt.setSize(35) txt.draw(self.window) return else: #prints "You Won!" if user wins if winner == 1: txt = Text(Point(345, 300), "You Won!") txt.setFill('white') txt.setSize(35) txt.draw(self.window) return else: #prints "Computer Won!" if computer wins txt = Text(Point(345, 300), "Computer Won!") txt.setFill('white') txt.setSize(35) txt.draw(self.window) return def validCmove(self, x, y): '''This function checks if the computer's move will be valid''' #checks if '''if it tries to place it higher than the highest piece''' if self.boardCount[x] > y: return False ''' if it tries to place below the highest piece''' if self.boardCount[x] < y: return False '''if it tries to place it in a column with 6 pieces already''' if self.boardCount[x] >= 6: return False else: return True def drawCmove(self, x ,y): '''This function adds the computer's move to the game board and adds it to the board count''' piece = Circle(Point((x)*100+50, 600 - ((y)*100+50)),30) piece.setFill('yellow') piece.draw(self.window) self.boardCount[x] += 1 self.grid[x][y] = -1 return def computerMove(self): '''This function computes where the computer will put its next move and calls the drawCmove() fxn to do so. The computer will add its piece to wherever there are three in a row in either color then looks to see when there are two in a row. Move will be placed randomly if no pieces are placed in a row''' #checks if there are three pieces lined up vertically in a row and places its move to win or prevent the win''' for i in range(7): for j in range(3): self.square1 = self.grid[i][j] self.square2 = self.grid[i][j+1] self.square3 = self.grid[i][j+2] if self.square1 == self.square2 and self.square2 == self.square3: if self.validCmove(i,j+3): self.drawCmove(i,j+3) return else: self.randomMove() return #checks if there are three pieces lined up diagonally from lower left to upper right and places its move to win or prevent the win #help from CS major, Joh Farmer for i in range(4): for j in range(3): self.square1 = self.grid[i][j] self.square2 = self.grid[i+1][j+1] self.square3 = self.grid[i+2][j+2] if self.square1 == self.square2 and self.square2 == self.square3: if self.validCmove(i+3,j+3): self.drawCmove(i+3,j+3) return if self.validCmove(i-1,j-1): self.drawCmove(i-1,j-1) else: self.randomMove() return #checks if there are three pieces lined up diagonally from lower right to upper left and places its move to win or prevent the win for i in range(3,7): for j in range(3): self.square1 = self.grid[i][j] self.square2 = self.grid[i-1][j+1] self.square3 = self.grid[i-2][j+2] if self.square1 == self.square2 and self.square2 == self.square3: if self.validCmove(i-3,j+3): self.drawCmove(i-3,j+3) return if self.validCmove(i+1,j-1): self.drawCmove(i+1,j-1) else: self.randomMove() return #checks if there are three pieces lined up horizontally in a row and places its move to win or prevent the win (either side)''' for i in range(4): for j in range(6): self.square1 = self.grid[i][j] self.square2 = self.grid[i+1][j] self.square3 = self.grid[i+2][j] if self.square1 == self.square2 and self.square2 == self.square3: if self.validCmove(i+3,j): self.drawCmove(i+3,j) return if self.validCmove(i-1,j): self.drawCmove(i-1,j) return else: self.randomMove() return #checks if there are two in a row diagonally from lower left to upper right and places its move accordingly for i in range(4): for j in range(3): self.square1 = self.grid[i][j] self.square2 = self.grid[i+1][j+1] if self.square1 == self.square2: if self.validCmove(i+2,j+2): self.drawCmove(i+2,j+2) return if self.validCmove(i-1,j-1): self.drawCmove(i-1,j-1) else: self.randomMove() return #checks if there are two in a row vertically and places its move accordingly for i in range(7): for j in range(3): self.square1 = self.grid[i][j] self.square2 = self.grid[i][j+1] if self.square1 == self.square2: if self.validCmove(i,j+2): self.drawCmove(i,j+2) return if self.validCmove(i,j-1): self.drawCmove(i,j-1) return else: self.randomMove() return #checks if there are two in a row diagonally from lower right to upper left and places its move accordingly for i in range(3,7): for j in range(3): self.square1 = self.grid[i][j] self.square2 = self.grid[i-1][j+1] if self.square1 == self.square2: if self.validCmove(i-2,j+2): self.drawCmove(i-2,j+2) return if self.validCmove(i+1,j-1): self.drawCmove(i+1,j-1) else: self.randomMove() return #checks if there are two in a row horizontally and places its move accordingly for i in range(4): for j in range(6): self.square1 = self.grid[i][j] self.square2 = self.grid[i+1][j] if self.square1 == self.square2: if self.validCmove(i+2,j): self.drawCmove(i+2,j) return if self.validCmove(i-1,j): self.drawCmove(i-1,j) return else: self.randomMove() return #places move randomly if no pieces are being placed in a row else: self.randomMove() def randomMove(self): '''This function creates a random coordinate for its move, checks if it's valid, then prints the move. It will continue to run until numbers are valid for current board''' randY = random.randint(0,6) randX = random.randint(0,7) if self.validCmove(randY,randX): self.drawCmove(randY,randX) return else: self.randomMove() def main(): gameOver = False connect4 = ConnectWindow() while gameOver == False: connect4.window.getMouse() gameOver = connect4.isWon() input("Hit enter to quit") main()
[ "#connect4_JayNa.py\n#Jay Na\n#CS111 Spring 2018\n#This file creates a version of the game Connect4, where the user plays against an AI\n\nfrom graphics import *\nimport random\n\nclass ConnectWindow:\n\n\tdef __init__(self):\n\t\tself.window = GraphWin(\"Connect Four\", 690, 590)\n\t\tself.window.setMouseHandler(self.handleClick)\n\t\tself.startScreen()\n\t\tself.currentUser = 1\n\t\tself.limitCounter = 0\n\t\t\n\n\tdef startScreen(self):\n\t\t'''This function creates the board and intializes the board count for each column'''\n\n\t#draws blue rectangle as the background\n\t\tself.background = Rectangle(Point(0,0), Point(690,590))\n\t\tself.background.setFill('blue')\n\t\tself.background.draw(self.window)\n\t\t\n\t#draws white circles to represent the spots for the game\t\n\t\tfor i in range(7):\n\t\t\tfor j in range(6):\n\t\t\t\tself.Circles = Circle(Point(i*100+50,j*100+50),(30))\n\t\t\t\tself.Circles.setFill('white')\n\t\t\t\tself.Circles.draw(self.window)\n\t\t\t\t\n\t#draws lines to separate circles in rectangle\n\t\tfor i in range(6):\n\t\t\tself.horizLine = Line(Point(0,i*100+100), Point(900,i*100+100))\n\t\t\tself.vertLine = Line(Point(100*i+100,0), Point(100*i+100,900))\n\t\t\tself.horizLine.draw(self.window)\n\t\t\tself.vertLine.draw(self.window)\n\t\t\t\n\t#initiates counts for each column and creates grid\n\t\tself.grid = [[],[],[],[],[],[],[]]\n\t\tself.boardCount = [0,0,0,0,0,0,0]\n\t\tcounter = 2\n\t\t\n\t\t#help from CS Major, Joh Farmer\n\t\tfor x in range(7):\n\t\t\tfor y in range(6):\n\t\t\t\tself.grid[x].append(counter)\n\t\t\t\tcounter += 1\n\t\t\t\t\n\n\tdef validClick(self, x):\n\t\t'''This function checks if there is enough space vertically for move to be valid'''\n\t\t\n\t\tif self.boardCount[x] >= 6:\n\t\t\tprint(\"Invalid Move\")\n\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\n\n\tdef drawUmove(self):\n\t\t'''This function prints the pieces onto the board at the given position from the user'''\n\t\t\n\t\tpiece = Circle(Point(self.x*100+50, 600-(self.y*100+50)),30)\n\t\tpiece.setFill('red')\n\t\tpiece.draw(self.window)\n\t\treturn\n\n\tdef handleClick(self, point):\n\t\t'''This function works with the user to add each move into the board count and to the current grid'''\n\n\t\tself.newX = point.getX()\n\t\tself.x = self.newX//100\n\t\tself.y = self.boardCount[self.x]\n\t\t\n\t\tif self.validClick(self.x):\n\t\t\tself.boardCount[self.x] += 1\n\t\t\tself.limitCounter += 1\n\t\t\tself.grid[self.x][self.y] = self.currentUser\n\t\t\t\n\t\tif self.isWon() == False:\n\t\t\tself.limitCounter += 1\n\t\t\tself.computerMove()\n\t\t\tself.drawUmove()\n\n\n\tdef isWon(self):\n\t\t'''This function checks if there is a winner in the game (True/False) and calls printWinner function'''\n\n\t#checks to see if there is a winner vertically\n\t\tfor i in range(7):\n\t\t\tfor j in range(3):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i][j+1]\n\t\t\t\tself.square3 = self.grid[i][j+2]\n\t\t\t\tself.square4 = self.grid[i][j+3]\n\t\t\t\tif self.square1 == self.square2 and self.square2 == self.square3 and self.square3 == self.square4:\n\t\t\t\t\tself.printWinner(self.square1)\n\t\t\t\t\treturn True\n\n\t#checks to see if there is a winner diagonally from lower left to upper right\n\t\tfor i in range(4):\n\t\t\tfor j in range(3):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i+1][j+1]\n\t\t\t\tself.square3 = self.grid[i+2][j+2]\n\t\t\t\tself.square4 = self.grid[i+3][j+3]\n\t\t\t\tif self.square1 == self.square2 and self.square2 == self.square3 and self.square3 == self.square4:\n\t\t\t\t\tself.printWinner(self.square1)\n\t\t\t\t\treturn True\n\t\t\t\t\t\n\t#checks to see if there is a winner diagonally from upper left to lower right\n\t\tfor i in range(3,7):\n\t\t\tfor j in range(3):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i-1][j+1]\n\t\t\t\tself.square3 = self.grid[i-2][j+2]\n\t\t\t\tself.square4 = self.grid[i-3][j+3]\n\t\t\t\tif self.square1 == self.square2 and self.square2 == self.square3 and self.square3 == self.square4:\n\t\t\t\t\tself.printWinner(self.square1)\n\t\t\t\t\treturn True\t\t\t\n\t\t\t\t\t\n\t#checks to see if there is a winner horizontally\n\t\tfor i in range(4):\n\t\t\tfor j in range(6):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i+1][j]\n\t\t\t\tself.square3 = self.grid[i+2][j]\n\t\t\t\tself.square4 = self.grid[i+3][j]\n\t\t\t\tif self.square1 == self.square2 and self.square2 == self.square3 and self.square3 == self.square4: \n\t\t\t\t\tself.printWinner(self.square1)\n\t\t\t\t\treturn True\t\t\t\t\n\t\t\t\t\t\n\t#checks if board is full without a winner (tie)\n\t\tif self.limitCounter == 42:\n\t\t\tself.printWinner(3)\n\t\t\treturn True\n\t\treturn False\n\n\n\tdef printWinner(self, winner):\n\t\t'''This function prints who the winner is or if it is a tie'''\n\t\t\n\t#if input is 3 from isWon() fxn, game is tied and so \"Tie Game!\" is printed \n\t\tif winner == 3:\n\t\t\ttxt = Text(Point(345, 300), \"Tie Game!\")\n\t\t\ttxt.setFill('white')\n\t\t\ttxt.setSize(35)\n\t\t\ttxt.draw(self.window)\n\t\t\treturn\t\t\n\t\telse:\n\t#prints \"You Won!\" if user wins\n\t\t\tif winner == 1:\n\t\t\t\ttxt = Text(Point(345, 300), \"You Won!\")\n\t\t\t\ttxt.setFill('white')\n\t\t\t\ttxt.setSize(35)\n\t\t\t\ttxt.draw(self.window)\n\t\t\t\treturn\n\t\t\telse:\n\t#prints \"Computer Won!\" if computer wins\n\t\t\t\ttxt = Text(Point(345, 300), \"Computer Won!\")\n\t\t\t\ttxt.setFill('white')\n\t\t\t\ttxt.setSize(35)\n\t\t\t\ttxt.draw(self.window)\n\t\t\t\treturn\n\n\n\tdef validCmove(self, x, y):\n\t\t'''This function checks if the computer's move will be valid'''\n\t\n\t#checks if \t'''if it tries to place it higher than the highest piece'''\n\t\tif self.boardCount[x] > y:\n\t\t\treturn False\n\t\t''' if it tries to place below the highest piece'''\n\t\tif self.boardCount[x] < y:\n\t\t\treturn False\n\t\t'''if it tries to place it in a column with 6 pieces already'''\n\t\tif self.boardCount[x] >= 6:\n\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\t\n\n\tdef drawCmove(self, x ,y):\n\t\t'''This function adds the computer's move to the game board and adds it to the board count'''\n\n\t\tpiece = Circle(Point((x)*100+50, 600 - ((y)*100+50)),30)\n\t\tpiece.setFill('yellow')\n\t\tpiece.draw(self.window)\n\t\tself.boardCount[x] += 1\n\t\tself.grid[x][y] = -1\n\t\treturn\n\n\n\tdef computerMove(self):\n\t\t'''This function computes where the computer will put its next move and calls the drawCmove() fxn to do so.\n\t\tThe computer will add its piece to wherever there are three in a row in either color then looks to see when \n\t\tthere are two in a row. Move will be placed randomly if no pieces are placed in a row'''\n\n\t#checks if there are three pieces lined up vertically in a row and places its move to win or prevent the win'''\n\t\tfor i in range(7):\n\t\t\tfor j in range(3):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i][j+1]\n\t\t\t\tself.square3 = self.grid[i][j+2]\n\t\t\t\tif self.square1 == self.square2 and self.square2 == self.square3:\n\t\t\t\t\tif self.validCmove(i,j+3):\n\t\t\t\t\t\tself.drawCmove(i,j+3)\n\t\t\t\t\t\treturn\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.randomMove()\n\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\n\t#checks if there are three pieces lined up diagonally from lower left to upper right and places its move to win or prevent the win\n\t#help from CS major, Joh Farmer\n\t\tfor i in range(4):\n\t\t\tfor j in range(3):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i+1][j+1]\n\t\t\t\tself.square3 = self.grid[i+2][j+2]\n\t\t\t\tif self.square1 == self.square2 and self.square2 == self.square3:\n\t\t\t\t\tif self.validCmove(i+3,j+3):\n\t\t\t\t\t\tself.drawCmove(i+3,j+3)\n\t\t\t\t\t\treturn\n\t\t\t\t\tif self.validCmove(i-1,j-1):\n\t\t\t\t\t\tself.drawCmove(i-1,j-1)\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.randomMove()\n\t\t\t\t\t\treturn\n\t\t\t\t\t\t\n\t#checks if there are three pieces lined up diagonally from lower right to upper left and places its move to win or prevent the win\t\t\n\t\tfor i in range(3,7):\n\t\t\tfor j in range(3):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i-1][j+1]\n\t\t\t\tself.square3 = self.grid[i-2][j+2]\n\t\t\t\tif self.square1 == self.square2 and self.square2 == self.square3:\n\t\t\t\t\tif self.validCmove(i-3,j+3):\n\t\t\t\t\t\tself.drawCmove(i-3,j+3)\n\t\t\t\t\t\treturn\n\t\t\t\t\tif self.validCmove(i+1,j-1):\n\t\t\t\t\t\tself.drawCmove(i+1,j-1)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.randomMove()\n\t\t\t\t\t\treturn\n\t\t\t\t\t\t\n\t#checks if there are three pieces lined up horizontally in a row and places its move to win or prevent the win (either side)'''\n\t\tfor i in range(4):\n\t\t\tfor j in range(6):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i+1][j]\n\t\t\t\tself.square3 = self.grid[i+2][j]\n\t\t\t\tif self.square1 == self.square2 and self.square2 == self.square3:\n\t\t\t\t\tif self.validCmove(i+3,j):\n\t\t\t\t\t\tself.drawCmove(i+3,j)\n\t\t\t\t\t\treturn\n\t\t\t\t\tif self.validCmove(i-1,j):\n\t\t\t\t\t\tself.drawCmove(i-1,j)\n\t\t\t\t\t\treturn\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.randomMove()\n\t\t\t\t\t\treturn\n\n\n\n\t#checks if there are two in a row diagonally from lower left to upper right and places its move accordingly\n\t\tfor i in range(4):\n\t\t\tfor j in range(3):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i+1][j+1]\n\t\t\t\tif self.square1 == self.square2:\n\t\t\t\t\tif self.validCmove(i+2,j+2):\n\t\t\t\t\t\tself.drawCmove(i+2,j+2)\n\t\t\t\t\t\treturn\n\t\t\t\t\tif self.validCmove(i-1,j-1):\n\t\t\t\t\t\tself.drawCmove(i-1,j-1)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.randomMove()\n\t\t\t\t\t\treturn\n\t\t\t\t\t\t\n\t#checks if there are two in a row vertically and places its move accordingly\n\t\tfor i in range(7):\n\t\t\tfor j in range(3):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i][j+1]\n\t\t\t\tif self.square1 == self.square2:\n\t\t\t\t\tif self.validCmove(i,j+2):\n\t\t\t\t\t\tself.drawCmove(i,j+2)\n\t\t\t\t\t\treturn\n\t\t\t\t\tif self.validCmove(i,j-1):\n\t\t\t\t\t\tself.drawCmove(i,j-1)\n\t\t\t\t\t\treturn\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.randomMove()\n\t\t\t\t\t\treturn\t\t\t\t\t\n\t\t\t\t\t\t\n\t#checks if there are two in a row diagonally from lower right to upper left and places its move accordingly\t\n\t\tfor i in range(3,7):\n\t\t\tfor j in range(3):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i-1][j+1]\n\t\t\t\tif self.square1 == self.square2:\n\t\t\t\t\tif self.validCmove(i-2,j+2):\n\t\t\t\t\t\tself.drawCmove(i-2,j+2)\n\t\t\t\t\t\treturn\n\t\t\t\t\tif self.validCmove(i+1,j-1):\n\t\t\t\t\t\tself.drawCmove(i+1,j-1)\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.randomMove()\n\t\t\t\t\t\treturn\n\t\t\t\t\t\n\t#checks if there are two in a row horizontally and places its move accordingly\n\t\tfor i in range(4):\n\t\t\tfor j in range(6):\n\t\t\t\tself.square1 = self.grid[i][j]\n\t\t\t\tself.square2 = self.grid[i+1][j]\n\t\t\t\tif self.square1 == self.square2:\n\t\t\t\t\tif self.validCmove(i+2,j):\n\t\t\t\t\t\tself.drawCmove(i+2,j)\n\t\t\t\t\t\treturn\n\t\t\t\t\tif self.validCmove(i-1,j):\n\t\t\t\t\t\tself.drawCmove(i-1,j)\n\t\t\t\t\t\treturn\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.randomMove()\n\t\t\t\t\t\treturn\n\n\t#places move randomly if no pieces are being placed in a row\n\t\telse:\n\t\t\tself.randomMove()\n\n\n\tdef randomMove(self):\n\t\t'''This function creates a random coordinate for its move, checks if it's valid, then prints the move.\n\t\tIt will continue to run until numbers are valid for current board'''\n\t\n\t\trandY = random.randint(0,6)\n\t\trandX = random.randint(0,7)\n\t\t\n\t\tif self.validCmove(randY,randX):\n\t\t\tself.drawCmove(randY,randX)\n\t\t\treturn\n\t\telse:\n\t\t\tself.randomMove()\n\n\ndef main():\n\tgameOver = False\n\tconnect4 = ConnectWindow()\n\twhile gameOver == False:\n\t\tconnect4.window.getMouse()\n\t\tgameOver = connect4.isWon()\n\tinput(\"Hit enter to quit\")\n\n\t\nmain()\n\n\n\n\n\n\n\n", "from graphics import *\nimport random\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n\n def startScreen(self):\n \"\"\"This function creates the board and intializes the board count for each column\"\"\"\n self.background = Rectangle(Point(0, 0), Point(690, 590))\n self.background.setFill('blue')\n self.background.draw(self.window)\n for i in range(7):\n for j in range(6):\n self.Circles = Circle(Point(i * 100 + 50, j * 100 + 50), 30)\n self.Circles.setFill('white')\n self.Circles.draw(self.window)\n for i in range(6):\n self.horizLine = Line(Point(0, i * 100 + 100), Point(900, i * \n 100 + 100))\n self.vertLine = Line(Point(100 * i + 100, 0), Point(100 * i + \n 100, 900))\n self.horizLine.draw(self.window)\n self.vertLine.draw(self.window)\n self.grid = [[], [], [], [], [], [], []]\n self.boardCount = [0, 0, 0, 0, 0, 0, 0]\n counter = 2\n for x in range(7):\n for y in range(6):\n self.grid[x].append(counter)\n counter += 1\n\n def validClick(self, x):\n \"\"\"This function checks if there is enough space vertically for move to be valid\"\"\"\n if self.boardCount[x] >= 6:\n print('Invalid Move')\n return False\n else:\n return True\n\n def drawUmove(self):\n \"\"\"This function prints the pieces onto the board at the given position from the user\"\"\"\n piece = Circle(Point(self.x * 100 + 50, 600 - (self.y * 100 + 50)), 30)\n piece.setFill('red')\n piece.draw(self.window)\n return\n\n def handleClick(self, point):\n \"\"\"This function works with the user to add each move into the board count and to the current grid\"\"\"\n self.newX = point.getX()\n self.x = self.newX // 100\n self.y = self.boardCount[self.x]\n if self.validClick(self.x):\n self.boardCount[self.x] += 1\n self.limitCounter += 1\n self.grid[self.x][self.y] = self.currentUser\n if self.isWon() == False:\n self.limitCounter += 1\n self.computerMove()\n self.drawUmove()\n\n def isWon(self):\n \"\"\"This function checks if there is a winner in the game (True/False) and calls printWinner function\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n self.square4 = self.grid[i][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n self.square4 = self.grid[i + 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n self.square4 = self.grid[i - 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n self.square4 = self.grid[i + 3][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n if self.limitCounter == 42:\n self.printWinner(3)\n return True\n return False\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n\n def validCmove(self, x, y):\n \"\"\"This function checks if the computer's move will be valid\"\"\"\n if self.boardCount[x] > y:\n return False\n \"\"\" if it tries to place below the highest piece\"\"\"\n if self.boardCount[x] < y:\n return False\n \"\"\"if it tries to place it in a column with 6 pieces already\"\"\"\n if self.boardCount[x] >= 6:\n return False\n else:\n return True\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n\n def computerMove(self):\n \"\"\"This function computes where the computer will put its next move and calls the drawCmove() fxn to do so.\n\t\tThe computer will add its piece to wherever there are three in a row in either color then looks to see when \n\t\tthere are two in a row. Move will be placed randomly if no pieces are placed in a row\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i, j + 3):\n self.drawCmove(i, j + 3)\n return\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i + 3, j + 3):\n self.drawCmove(i + 3, j + 3)\n return\n if self.validCmove(i - 1, j - 1):\n self.drawCmove(i - 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i - 3, j + 3):\n self.drawCmove(i - 3, j + 3)\n return\n if self.validCmove(i + 1, j - 1):\n self.drawCmove(i + 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i + 3, j):\n self.drawCmove(i + 3, j)\n return\n if self.validCmove(i - 1, j):\n self.drawCmove(i - 1, j)\n return\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i + 2, j + 2):\n self.drawCmove(i + 2, j + 2)\n return\n if self.validCmove(i - 1, j - 1):\n self.drawCmove(i - 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i, j + 2):\n self.drawCmove(i, j + 2)\n return\n if self.validCmove(i, j - 1):\n self.drawCmove(i, j - 1)\n return\n else:\n self.randomMove()\n return\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i - 2, j + 2):\n self.drawCmove(i - 2, j + 2)\n return\n if self.validCmove(i + 1, j - 1):\n self.drawCmove(i + 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n if self.square1 == self.square2:\n if self.validCmove(i + 2, j):\n self.drawCmove(i + 2, j)\n return\n if self.validCmove(i - 1, j):\n self.drawCmove(i - 1, j)\n return\n else:\n self.randomMove()\n return\n else:\n self.randomMove()\n\n def randomMove(self):\n \"\"\"This function creates a random coordinate for its move, checks if it's valid, then prints the move.\n\t\tIt will continue to run until numbers are valid for current board\"\"\"\n randY = random.randint(0, 6)\n randX = random.randint(0, 7)\n if self.validCmove(randY, randX):\n self.drawCmove(randY, randX)\n return\n else:\n self.randomMove()\n\n\ndef main():\n gameOver = False\n connect4 = ConnectWindow()\n while gameOver == False:\n connect4.window.getMouse()\n gameOver = connect4.isWon()\n input('Hit enter to quit')\n\n\nmain()\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n\n def startScreen(self):\n \"\"\"This function creates the board and intializes the board count for each column\"\"\"\n self.background = Rectangle(Point(0, 0), Point(690, 590))\n self.background.setFill('blue')\n self.background.draw(self.window)\n for i in range(7):\n for j in range(6):\n self.Circles = Circle(Point(i * 100 + 50, j * 100 + 50), 30)\n self.Circles.setFill('white')\n self.Circles.draw(self.window)\n for i in range(6):\n self.horizLine = Line(Point(0, i * 100 + 100), Point(900, i * \n 100 + 100))\n self.vertLine = Line(Point(100 * i + 100, 0), Point(100 * i + \n 100, 900))\n self.horizLine.draw(self.window)\n self.vertLine.draw(self.window)\n self.grid = [[], [], [], [], [], [], []]\n self.boardCount = [0, 0, 0, 0, 0, 0, 0]\n counter = 2\n for x in range(7):\n for y in range(6):\n self.grid[x].append(counter)\n counter += 1\n\n def validClick(self, x):\n \"\"\"This function checks if there is enough space vertically for move to be valid\"\"\"\n if self.boardCount[x] >= 6:\n print('Invalid Move')\n return False\n else:\n return True\n\n def drawUmove(self):\n \"\"\"This function prints the pieces onto the board at the given position from the user\"\"\"\n piece = Circle(Point(self.x * 100 + 50, 600 - (self.y * 100 + 50)), 30)\n piece.setFill('red')\n piece.draw(self.window)\n return\n\n def handleClick(self, point):\n \"\"\"This function works with the user to add each move into the board count and to the current grid\"\"\"\n self.newX = point.getX()\n self.x = self.newX // 100\n self.y = self.boardCount[self.x]\n if self.validClick(self.x):\n self.boardCount[self.x] += 1\n self.limitCounter += 1\n self.grid[self.x][self.y] = self.currentUser\n if self.isWon() == False:\n self.limitCounter += 1\n self.computerMove()\n self.drawUmove()\n\n def isWon(self):\n \"\"\"This function checks if there is a winner in the game (True/False) and calls printWinner function\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n self.square4 = self.grid[i][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n self.square4 = self.grid[i + 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n self.square4 = self.grid[i - 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n self.square4 = self.grid[i + 3][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n if self.limitCounter == 42:\n self.printWinner(3)\n return True\n return False\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n\n def validCmove(self, x, y):\n \"\"\"This function checks if the computer's move will be valid\"\"\"\n if self.boardCount[x] > y:\n return False\n \"\"\" if it tries to place below the highest piece\"\"\"\n if self.boardCount[x] < y:\n return False\n \"\"\"if it tries to place it in a column with 6 pieces already\"\"\"\n if self.boardCount[x] >= 6:\n return False\n else:\n return True\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n\n def computerMove(self):\n \"\"\"This function computes where the computer will put its next move and calls the drawCmove() fxn to do so.\n\t\tThe computer will add its piece to wherever there are three in a row in either color then looks to see when \n\t\tthere are two in a row. Move will be placed randomly if no pieces are placed in a row\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i, j + 3):\n self.drawCmove(i, j + 3)\n return\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i + 3, j + 3):\n self.drawCmove(i + 3, j + 3)\n return\n if self.validCmove(i - 1, j - 1):\n self.drawCmove(i - 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i - 3, j + 3):\n self.drawCmove(i - 3, j + 3)\n return\n if self.validCmove(i + 1, j - 1):\n self.drawCmove(i + 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i + 3, j):\n self.drawCmove(i + 3, j)\n return\n if self.validCmove(i - 1, j):\n self.drawCmove(i - 1, j)\n return\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i + 2, j + 2):\n self.drawCmove(i + 2, j + 2)\n return\n if self.validCmove(i - 1, j - 1):\n self.drawCmove(i - 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i, j + 2):\n self.drawCmove(i, j + 2)\n return\n if self.validCmove(i, j - 1):\n self.drawCmove(i, j - 1)\n return\n else:\n self.randomMove()\n return\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i - 2, j + 2):\n self.drawCmove(i - 2, j + 2)\n return\n if self.validCmove(i + 1, j - 1):\n self.drawCmove(i + 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n if self.square1 == self.square2:\n if self.validCmove(i + 2, j):\n self.drawCmove(i + 2, j)\n return\n if self.validCmove(i - 1, j):\n self.drawCmove(i - 1, j)\n return\n else:\n self.randomMove()\n return\n else:\n self.randomMove()\n\n def randomMove(self):\n \"\"\"This function creates a random coordinate for its move, checks if it's valid, then prints the move.\n\t\tIt will continue to run until numbers are valid for current board\"\"\"\n randY = random.randint(0, 6)\n randX = random.randint(0, 7)\n if self.validCmove(randY, randX):\n self.drawCmove(randY, randX)\n return\n else:\n self.randomMove()\n\n\ndef main():\n gameOver = False\n connect4 = ConnectWindow()\n while gameOver == False:\n connect4.window.getMouse()\n gameOver = connect4.isWon()\n input('Hit enter to quit')\n\n\nmain()\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n\n def startScreen(self):\n \"\"\"This function creates the board and intializes the board count for each column\"\"\"\n self.background = Rectangle(Point(0, 0), Point(690, 590))\n self.background.setFill('blue')\n self.background.draw(self.window)\n for i in range(7):\n for j in range(6):\n self.Circles = Circle(Point(i * 100 + 50, j * 100 + 50), 30)\n self.Circles.setFill('white')\n self.Circles.draw(self.window)\n for i in range(6):\n self.horizLine = Line(Point(0, i * 100 + 100), Point(900, i * \n 100 + 100))\n self.vertLine = Line(Point(100 * i + 100, 0), Point(100 * i + \n 100, 900))\n self.horizLine.draw(self.window)\n self.vertLine.draw(self.window)\n self.grid = [[], [], [], [], [], [], []]\n self.boardCount = [0, 0, 0, 0, 0, 0, 0]\n counter = 2\n for x in range(7):\n for y in range(6):\n self.grid[x].append(counter)\n counter += 1\n\n def validClick(self, x):\n \"\"\"This function checks if there is enough space vertically for move to be valid\"\"\"\n if self.boardCount[x] >= 6:\n print('Invalid Move')\n return False\n else:\n return True\n\n def drawUmove(self):\n \"\"\"This function prints the pieces onto the board at the given position from the user\"\"\"\n piece = Circle(Point(self.x * 100 + 50, 600 - (self.y * 100 + 50)), 30)\n piece.setFill('red')\n piece.draw(self.window)\n return\n\n def handleClick(self, point):\n \"\"\"This function works with the user to add each move into the board count and to the current grid\"\"\"\n self.newX = point.getX()\n self.x = self.newX // 100\n self.y = self.boardCount[self.x]\n if self.validClick(self.x):\n self.boardCount[self.x] += 1\n self.limitCounter += 1\n self.grid[self.x][self.y] = self.currentUser\n if self.isWon() == False:\n self.limitCounter += 1\n self.computerMove()\n self.drawUmove()\n\n def isWon(self):\n \"\"\"This function checks if there is a winner in the game (True/False) and calls printWinner function\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n self.square4 = self.grid[i][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n self.square4 = self.grid[i + 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n self.square4 = self.grid[i - 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n self.square4 = self.grid[i + 3][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n if self.limitCounter == 42:\n self.printWinner(3)\n return True\n return False\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n\n def validCmove(self, x, y):\n \"\"\"This function checks if the computer's move will be valid\"\"\"\n if self.boardCount[x] > y:\n return False\n \"\"\" if it tries to place below the highest piece\"\"\"\n if self.boardCount[x] < y:\n return False\n \"\"\"if it tries to place it in a column with 6 pieces already\"\"\"\n if self.boardCount[x] >= 6:\n return False\n else:\n return True\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n\n def computerMove(self):\n \"\"\"This function computes where the computer will put its next move and calls the drawCmove() fxn to do so.\n\t\tThe computer will add its piece to wherever there are three in a row in either color then looks to see when \n\t\tthere are two in a row. Move will be placed randomly if no pieces are placed in a row\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i, j + 3):\n self.drawCmove(i, j + 3)\n return\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i + 3, j + 3):\n self.drawCmove(i + 3, j + 3)\n return\n if self.validCmove(i - 1, j - 1):\n self.drawCmove(i - 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i - 3, j + 3):\n self.drawCmove(i - 3, j + 3)\n return\n if self.validCmove(i + 1, j - 1):\n self.drawCmove(i + 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i + 3, j):\n self.drawCmove(i + 3, j)\n return\n if self.validCmove(i - 1, j):\n self.drawCmove(i - 1, j)\n return\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i + 2, j + 2):\n self.drawCmove(i + 2, j + 2)\n return\n if self.validCmove(i - 1, j - 1):\n self.drawCmove(i - 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i, j + 2):\n self.drawCmove(i, j + 2)\n return\n if self.validCmove(i, j - 1):\n self.drawCmove(i, j - 1)\n return\n else:\n self.randomMove()\n return\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i - 2, j + 2):\n self.drawCmove(i - 2, j + 2)\n return\n if self.validCmove(i + 1, j - 1):\n self.drawCmove(i + 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n if self.square1 == self.square2:\n if self.validCmove(i + 2, j):\n self.drawCmove(i + 2, j)\n return\n if self.validCmove(i - 1, j):\n self.drawCmove(i - 1, j)\n return\n else:\n self.randomMove()\n return\n else:\n self.randomMove()\n\n def randomMove(self):\n \"\"\"This function creates a random coordinate for its move, checks if it's valid, then prints the move.\n\t\tIt will continue to run until numbers are valid for current board\"\"\"\n randY = random.randint(0, 6)\n randX = random.randint(0, 7)\n if self.validCmove(randY, randX):\n self.drawCmove(randY, randX)\n return\n else:\n self.randomMove()\n\n\ndef main():\n gameOver = False\n connect4 = ConnectWindow()\n while gameOver == False:\n connect4.window.getMouse()\n gameOver = connect4.isWon()\n input('Hit enter to quit')\n\n\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n\n def startScreen(self):\n \"\"\"This function creates the board and intializes the board count for each column\"\"\"\n self.background = Rectangle(Point(0, 0), Point(690, 590))\n self.background.setFill('blue')\n self.background.draw(self.window)\n for i in range(7):\n for j in range(6):\n self.Circles = Circle(Point(i * 100 + 50, j * 100 + 50), 30)\n self.Circles.setFill('white')\n self.Circles.draw(self.window)\n for i in range(6):\n self.horizLine = Line(Point(0, i * 100 + 100), Point(900, i * \n 100 + 100))\n self.vertLine = Line(Point(100 * i + 100, 0), Point(100 * i + \n 100, 900))\n self.horizLine.draw(self.window)\n self.vertLine.draw(self.window)\n self.grid = [[], [], [], [], [], [], []]\n self.boardCount = [0, 0, 0, 0, 0, 0, 0]\n counter = 2\n for x in range(7):\n for y in range(6):\n self.grid[x].append(counter)\n counter += 1\n\n def validClick(self, x):\n \"\"\"This function checks if there is enough space vertically for move to be valid\"\"\"\n if self.boardCount[x] >= 6:\n print('Invalid Move')\n return False\n else:\n return True\n\n def drawUmove(self):\n \"\"\"This function prints the pieces onto the board at the given position from the user\"\"\"\n piece = Circle(Point(self.x * 100 + 50, 600 - (self.y * 100 + 50)), 30)\n piece.setFill('red')\n piece.draw(self.window)\n return\n\n def handleClick(self, point):\n \"\"\"This function works with the user to add each move into the board count and to the current grid\"\"\"\n self.newX = point.getX()\n self.x = self.newX // 100\n self.y = self.boardCount[self.x]\n if self.validClick(self.x):\n self.boardCount[self.x] += 1\n self.limitCounter += 1\n self.grid[self.x][self.y] = self.currentUser\n if self.isWon() == False:\n self.limitCounter += 1\n self.computerMove()\n self.drawUmove()\n\n def isWon(self):\n \"\"\"This function checks if there is a winner in the game (True/False) and calls printWinner function\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n self.square4 = self.grid[i][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n self.square4 = self.grid[i + 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n self.square4 = self.grid[i - 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n self.square4 = self.grid[i + 3][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n if self.limitCounter == 42:\n self.printWinner(3)\n return True\n return False\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n\n def validCmove(self, x, y):\n \"\"\"This function checks if the computer's move will be valid\"\"\"\n if self.boardCount[x] > y:\n return False\n \"\"\" if it tries to place below the highest piece\"\"\"\n if self.boardCount[x] < y:\n return False\n \"\"\"if it tries to place it in a column with 6 pieces already\"\"\"\n if self.boardCount[x] >= 6:\n return False\n else:\n return True\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n\n def computerMove(self):\n \"\"\"This function computes where the computer will put its next move and calls the drawCmove() fxn to do so.\n\t\tThe computer will add its piece to wherever there are three in a row in either color then looks to see when \n\t\tthere are two in a row. Move will be placed randomly if no pieces are placed in a row\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i, j + 3):\n self.drawCmove(i, j + 3)\n return\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i + 3, j + 3):\n self.drawCmove(i + 3, j + 3)\n return\n if self.validCmove(i - 1, j - 1):\n self.drawCmove(i - 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i - 3, j + 3):\n self.drawCmove(i - 3, j + 3)\n return\n if self.validCmove(i + 1, j - 1):\n self.drawCmove(i + 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3):\n if self.validCmove(i + 3, j):\n self.drawCmove(i + 3, j)\n return\n if self.validCmove(i - 1, j):\n self.drawCmove(i - 1, j)\n return\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i + 2, j + 2):\n self.drawCmove(i + 2, j + 2)\n return\n if self.validCmove(i - 1, j - 1):\n self.drawCmove(i - 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i, j + 2):\n self.drawCmove(i, j + 2)\n return\n if self.validCmove(i, j - 1):\n self.drawCmove(i, j - 1)\n return\n else:\n self.randomMove()\n return\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n if self.square1 == self.square2:\n if self.validCmove(i - 2, j + 2):\n self.drawCmove(i - 2, j + 2)\n return\n if self.validCmove(i + 1, j - 1):\n self.drawCmove(i + 1, j - 1)\n else:\n self.randomMove()\n return\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n if self.square1 == self.square2:\n if self.validCmove(i + 2, j):\n self.drawCmove(i + 2, j)\n return\n if self.validCmove(i - 1, j):\n self.drawCmove(i - 1, j)\n return\n else:\n self.randomMove()\n return\n else:\n self.randomMove()\n\n def randomMove(self):\n \"\"\"This function creates a random coordinate for its move, checks if it's valid, then prints the move.\n\t\tIt will continue to run until numbers are valid for current board\"\"\"\n randY = random.randint(0, 6)\n randX = random.randint(0, 7)\n if self.validCmove(randY, randX):\n self.drawCmove(randY, randX)\n return\n else:\n self.randomMove()\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n\n def startScreen(self):\n \"\"\"This function creates the board and intializes the board count for each column\"\"\"\n self.background = Rectangle(Point(0, 0), Point(690, 590))\n self.background.setFill('blue')\n self.background.draw(self.window)\n for i in range(7):\n for j in range(6):\n self.Circles = Circle(Point(i * 100 + 50, j * 100 + 50), 30)\n self.Circles.setFill('white')\n self.Circles.draw(self.window)\n for i in range(6):\n self.horizLine = Line(Point(0, i * 100 + 100), Point(900, i * \n 100 + 100))\n self.vertLine = Line(Point(100 * i + 100, 0), Point(100 * i + \n 100, 900))\n self.horizLine.draw(self.window)\n self.vertLine.draw(self.window)\n self.grid = [[], [], [], [], [], [], []]\n self.boardCount = [0, 0, 0, 0, 0, 0, 0]\n counter = 2\n for x in range(7):\n for y in range(6):\n self.grid[x].append(counter)\n counter += 1\n\n def validClick(self, x):\n \"\"\"This function checks if there is enough space vertically for move to be valid\"\"\"\n if self.boardCount[x] >= 6:\n print('Invalid Move')\n return False\n else:\n return True\n\n def drawUmove(self):\n \"\"\"This function prints the pieces onto the board at the given position from the user\"\"\"\n piece = Circle(Point(self.x * 100 + 50, 600 - (self.y * 100 + 50)), 30)\n piece.setFill('red')\n piece.draw(self.window)\n return\n\n def handleClick(self, point):\n \"\"\"This function works with the user to add each move into the board count and to the current grid\"\"\"\n self.newX = point.getX()\n self.x = self.newX // 100\n self.y = self.boardCount[self.x]\n if self.validClick(self.x):\n self.boardCount[self.x] += 1\n self.limitCounter += 1\n self.grid[self.x][self.y] = self.currentUser\n if self.isWon() == False:\n self.limitCounter += 1\n self.computerMove()\n self.drawUmove()\n\n def isWon(self):\n \"\"\"This function checks if there is a winner in the game (True/False) and calls printWinner function\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n self.square4 = self.grid[i][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n self.square4 = self.grid[i + 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n self.square4 = self.grid[i - 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n self.square4 = self.grid[i + 3][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n if self.limitCounter == 42:\n self.printWinner(3)\n return True\n return False\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n\n def validCmove(self, x, y):\n \"\"\"This function checks if the computer's move will be valid\"\"\"\n if self.boardCount[x] > y:\n return False\n \"\"\" if it tries to place below the highest piece\"\"\"\n if self.boardCount[x] < y:\n return False\n \"\"\"if it tries to place it in a column with 6 pieces already\"\"\"\n if self.boardCount[x] >= 6:\n return False\n else:\n return True\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n <function token>\n\n def randomMove(self):\n \"\"\"This function creates a random coordinate for its move, checks if it's valid, then prints the move.\n\t\tIt will continue to run until numbers are valid for current board\"\"\"\n randY = random.randint(0, 6)\n randX = random.randint(0, 7)\n if self.validCmove(randY, randX):\n self.drawCmove(randY, randX)\n return\n else:\n self.randomMove()\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n\n def startScreen(self):\n \"\"\"This function creates the board and intializes the board count for each column\"\"\"\n self.background = Rectangle(Point(0, 0), Point(690, 590))\n self.background.setFill('blue')\n self.background.draw(self.window)\n for i in range(7):\n for j in range(6):\n self.Circles = Circle(Point(i * 100 + 50, j * 100 + 50), 30)\n self.Circles.setFill('white')\n self.Circles.draw(self.window)\n for i in range(6):\n self.horizLine = Line(Point(0, i * 100 + 100), Point(900, i * \n 100 + 100))\n self.vertLine = Line(Point(100 * i + 100, 0), Point(100 * i + \n 100, 900))\n self.horizLine.draw(self.window)\n self.vertLine.draw(self.window)\n self.grid = [[], [], [], [], [], [], []]\n self.boardCount = [0, 0, 0, 0, 0, 0, 0]\n counter = 2\n for x in range(7):\n for y in range(6):\n self.grid[x].append(counter)\n counter += 1\n\n def validClick(self, x):\n \"\"\"This function checks if there is enough space vertically for move to be valid\"\"\"\n if self.boardCount[x] >= 6:\n print('Invalid Move')\n return False\n else:\n return True\n <function token>\n\n def handleClick(self, point):\n \"\"\"This function works with the user to add each move into the board count and to the current grid\"\"\"\n self.newX = point.getX()\n self.x = self.newX // 100\n self.y = self.boardCount[self.x]\n if self.validClick(self.x):\n self.boardCount[self.x] += 1\n self.limitCounter += 1\n self.grid[self.x][self.y] = self.currentUser\n if self.isWon() == False:\n self.limitCounter += 1\n self.computerMove()\n self.drawUmove()\n\n def isWon(self):\n \"\"\"This function checks if there is a winner in the game (True/False) and calls printWinner function\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n self.square4 = self.grid[i][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n self.square4 = self.grid[i + 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n self.square4 = self.grid[i - 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n self.square4 = self.grid[i + 3][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n if self.limitCounter == 42:\n self.printWinner(3)\n return True\n return False\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n\n def validCmove(self, x, y):\n \"\"\"This function checks if the computer's move will be valid\"\"\"\n if self.boardCount[x] > y:\n return False\n \"\"\" if it tries to place below the highest piece\"\"\"\n if self.boardCount[x] < y:\n return False\n \"\"\"if it tries to place it in a column with 6 pieces already\"\"\"\n if self.boardCount[x] >= 6:\n return False\n else:\n return True\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n <function token>\n\n def randomMove(self):\n \"\"\"This function creates a random coordinate for its move, checks if it's valid, then prints the move.\n\t\tIt will continue to run until numbers are valid for current board\"\"\"\n randY = random.randint(0, 6)\n randX = random.randint(0, 7)\n if self.validCmove(randY, randX):\n self.drawCmove(randY, randX)\n return\n else:\n self.randomMove()\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n\n def startScreen(self):\n \"\"\"This function creates the board and intializes the board count for each column\"\"\"\n self.background = Rectangle(Point(0, 0), Point(690, 590))\n self.background.setFill('blue')\n self.background.draw(self.window)\n for i in range(7):\n for j in range(6):\n self.Circles = Circle(Point(i * 100 + 50, j * 100 + 50), 30)\n self.Circles.setFill('white')\n self.Circles.draw(self.window)\n for i in range(6):\n self.horizLine = Line(Point(0, i * 100 + 100), Point(900, i * \n 100 + 100))\n self.vertLine = Line(Point(100 * i + 100, 0), Point(100 * i + \n 100, 900))\n self.horizLine.draw(self.window)\n self.vertLine.draw(self.window)\n self.grid = [[], [], [], [], [], [], []]\n self.boardCount = [0, 0, 0, 0, 0, 0, 0]\n counter = 2\n for x in range(7):\n for y in range(6):\n self.grid[x].append(counter)\n counter += 1\n <function token>\n <function token>\n\n def handleClick(self, point):\n \"\"\"This function works with the user to add each move into the board count and to the current grid\"\"\"\n self.newX = point.getX()\n self.x = self.newX // 100\n self.y = self.boardCount[self.x]\n if self.validClick(self.x):\n self.boardCount[self.x] += 1\n self.limitCounter += 1\n self.grid[self.x][self.y] = self.currentUser\n if self.isWon() == False:\n self.limitCounter += 1\n self.computerMove()\n self.drawUmove()\n\n def isWon(self):\n \"\"\"This function checks if there is a winner in the game (True/False) and calls printWinner function\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n self.square4 = self.grid[i][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n self.square4 = self.grid[i + 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n self.square4 = self.grid[i - 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n self.square4 = self.grid[i + 3][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n if self.limitCounter == 42:\n self.printWinner(3)\n return True\n return False\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n\n def validCmove(self, x, y):\n \"\"\"This function checks if the computer's move will be valid\"\"\"\n if self.boardCount[x] > y:\n return False\n \"\"\" if it tries to place below the highest piece\"\"\"\n if self.boardCount[x] < y:\n return False\n \"\"\"if it tries to place it in a column with 6 pieces already\"\"\"\n if self.boardCount[x] >= 6:\n return False\n else:\n return True\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n <function token>\n\n def randomMove(self):\n \"\"\"This function creates a random coordinate for its move, checks if it's valid, then prints the move.\n\t\tIt will continue to run until numbers are valid for current board\"\"\"\n randY = random.randint(0, 6)\n randX = random.randint(0, 7)\n if self.validCmove(randY, randX):\n self.drawCmove(randY, randX)\n return\n else:\n self.randomMove()\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n\n def startScreen(self):\n \"\"\"This function creates the board and intializes the board count for each column\"\"\"\n self.background = Rectangle(Point(0, 0), Point(690, 590))\n self.background.setFill('blue')\n self.background.draw(self.window)\n for i in range(7):\n for j in range(6):\n self.Circles = Circle(Point(i * 100 + 50, j * 100 + 50), 30)\n self.Circles.setFill('white')\n self.Circles.draw(self.window)\n for i in range(6):\n self.horizLine = Line(Point(0, i * 100 + 100), Point(900, i * \n 100 + 100))\n self.vertLine = Line(Point(100 * i + 100, 0), Point(100 * i + \n 100, 900))\n self.horizLine.draw(self.window)\n self.vertLine.draw(self.window)\n self.grid = [[], [], [], [], [], [], []]\n self.boardCount = [0, 0, 0, 0, 0, 0, 0]\n counter = 2\n for x in range(7):\n for y in range(6):\n self.grid[x].append(counter)\n counter += 1\n <function token>\n <function token>\n <function token>\n\n def isWon(self):\n \"\"\"This function checks if there is a winner in the game (True/False) and calls printWinner function\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n self.square4 = self.grid[i][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n self.square4 = self.grid[i + 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n self.square4 = self.grid[i - 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n self.square4 = self.grid[i + 3][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n if self.limitCounter == 42:\n self.printWinner(3)\n return True\n return False\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n\n def validCmove(self, x, y):\n \"\"\"This function checks if the computer's move will be valid\"\"\"\n if self.boardCount[x] > y:\n return False\n \"\"\" if it tries to place below the highest piece\"\"\"\n if self.boardCount[x] < y:\n return False\n \"\"\"if it tries to place it in a column with 6 pieces already\"\"\"\n if self.boardCount[x] >= 6:\n return False\n else:\n return True\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n <function token>\n\n def randomMove(self):\n \"\"\"This function creates a random coordinate for its move, checks if it's valid, then prints the move.\n\t\tIt will continue to run until numbers are valid for current board\"\"\"\n randY = random.randint(0, 6)\n randX = random.randint(0, 7)\n if self.validCmove(randY, randX):\n self.drawCmove(randY, randX)\n return\n else:\n self.randomMove()\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n <function token>\n <function token>\n <function token>\n <function token>\n\n def isWon(self):\n \"\"\"This function checks if there is a winner in the game (True/False) and calls printWinner function\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n self.square4 = self.grid[i][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n self.square4 = self.grid[i + 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n self.square4 = self.grid[i - 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n self.square4 = self.grid[i + 3][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n if self.limitCounter == 42:\n self.printWinner(3)\n return True\n return False\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n\n def validCmove(self, x, y):\n \"\"\"This function checks if the computer's move will be valid\"\"\"\n if self.boardCount[x] > y:\n return False\n \"\"\" if it tries to place below the highest piece\"\"\"\n if self.boardCount[x] < y:\n return False\n \"\"\"if it tries to place it in a column with 6 pieces already\"\"\"\n if self.boardCount[x] >= 6:\n return False\n else:\n return True\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n <function token>\n\n def randomMove(self):\n \"\"\"This function creates a random coordinate for its move, checks if it's valid, then prints the move.\n\t\tIt will continue to run until numbers are valid for current board\"\"\"\n randY = random.randint(0, 6)\n randX = random.randint(0, 7)\n if self.validCmove(randY, randX):\n self.drawCmove(randY, randX)\n return\n else:\n self.randomMove()\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n <function token>\n <function token>\n <function token>\n <function token>\n\n def isWon(self):\n \"\"\"This function checks if there is a winner in the game (True/False) and calls printWinner function\"\"\"\n for i in range(7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i][j + 1]\n self.square3 = self.grid[i][j + 2]\n self.square4 = self.grid[i][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j + 1]\n self.square3 = self.grid[i + 2][j + 2]\n self.square4 = self.grid[i + 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(3, 7):\n for j in range(3):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i - 1][j + 1]\n self.square3 = self.grid[i - 2][j + 2]\n self.square4 = self.grid[i - 3][j + 3]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n for i in range(4):\n for j in range(6):\n self.square1 = self.grid[i][j]\n self.square2 = self.grid[i + 1][j]\n self.square3 = self.grid[i + 2][j]\n self.square4 = self.grid[i + 3][j]\n if (self.square1 == self.square2 and self.square2 == self.\n square3 and self.square3 == self.square4):\n self.printWinner(self.square1)\n return True\n if self.limitCounter == 42:\n self.printWinner(3)\n return True\n return False\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n\n def validCmove(self, x, y):\n \"\"\"This function checks if the computer's move will be valid\"\"\"\n if self.boardCount[x] > y:\n return False\n \"\"\" if it tries to place below the highest piece\"\"\"\n if self.boardCount[x] < y:\n return False\n \"\"\"if it tries to place it in a column with 6 pieces already\"\"\"\n if self.boardCount[x] >= 6:\n return False\n else:\n return True\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n\n def validCmove(self, x, y):\n \"\"\"This function checks if the computer's move will be valid\"\"\"\n if self.boardCount[x] > y:\n return False\n \"\"\" if it tries to place below the highest piece\"\"\"\n if self.boardCount[x] < y:\n return False\n \"\"\"if it tries to place it in a column with 6 pieces already\"\"\"\n if self.boardCount[x] >= 6:\n return False\n else:\n return True\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n <function token>\n\n def drawCmove(self, x, y):\n \"\"\"This function adds the computer's move to the game board and adds it to the board count\"\"\"\n piece = Circle(Point(x * 100 + 50, 600 - (y * 100 + 50)), 30)\n piece.setFill('yellow')\n piece.draw(self.window)\n self.boardCount[x] += 1\n self.grid[x][y] = -1\n return\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n\n def __init__(self):\n self.window = GraphWin('Connect Four', 690, 590)\n self.window.setMouseHandler(self.handleClick)\n self.startScreen()\n self.currentUser = 1\n self.limitCounter = 0\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def printWinner(self, winner):\n \"\"\"This function prints who the winner is or if it is a tie\"\"\"\n if winner == 3:\n txt = Text(Point(345, 300), 'Tie Game!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n elif winner == 1:\n txt = Text(Point(345, 300), 'You Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n else:\n txt = Text(Point(345, 300), 'Computer Won!')\n txt.setFill('white')\n txt.setSize(35)\n txt.draw(self.window)\n return\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass ConnectWindow:\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<function token>\n<code token>\n" ]
false
770
96d5cf948a9b0f622889977e8b26993299bceead
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 18 13:37:10 2018 @author: ninja1mmm """ import os import numpy as np import pandas as pd from sklearn import preprocessing def file_name(file_dir): root_tmp=[] dirs_tmp=[] files_tmp=[] for root, dirs, files in os.walk(file_dir): root_tmp.append(root) dirs_tmp.append(dirs) files_tmp.append(files) return root_tmp, dirs_tmp, files_tmp root = '/home/ninja1mmm/Desktop/phm/data' root_tmp, dirs_tmp, files_tmp = file_name(root) combined_all = {} feature_all = pd.DataFrame(columns = ['mean', 'std','root amplitude', 'rms','max','skewness','kurtosis', 'peak factor','margin','waveform', 'pulse','start_time', 'end_time', 'recipe', 'stage', 'Lot']) #df_check = pd.DataFrame() # read the first file to test here file_tmp = files_tmp[2][0] # iterate through the files if needed #for file_tmp in files_tmp[2]: path_tmp = root_tmp[2]+'/'+file_tmp df = pd.read_pickle(path_tmp) #df_tmp = df[df['Lot']==28113] #if len(df_tmp)>0: # df_tmp = df_tmp.iloc[0,:] # df_check = df_check.append(df_tmp) #------------------------------------------------------------------------------ # Crucial step df=df.replace([np.inf, -np.inf], np.nan).dropna() df=df.reset_index(drop=True) df_scaler = preprocessing.MinMaxScaler(feature_range = (0,1)) #------------------------------------------------------------------------------ lot_list = list(set(df.Lot)) # Check if Lot already existed for key in lot_list: if key in combined_all.keys(): print('The Lot %d in %s already existed in %s' % (key, file_tmp, combined_all[key])) # for tmp in lot_list: # combined_all[tmp] = file_tmp # Select and save all the wafer processing cycles list_tmp = [] lot_last = df.Lot[0] counter = 0 idx = 0 # Specify the range. Here set to 100000 for the ease of test for row_tmp in df.index: lot_tmp = df.iloc[row_tmp,:].Lot if lot_tmp == lot_last: list_tmp.append(df.iloc[row_tmp,:]) counter += 1 else: df_tmp = pd.concat(list_tmp, axis = 1) # lot_last serves as the key, can be changed # combined_all[lot_last] = df_tmp.T combined_all[df_tmp.T.time.iloc[-1]] = df_tmp.T # Calculate mean and save in feature dictionary as an example # Normalize the data again because for some parameters we need the local (within cycle) feature feature_tmp = df_tmp.T.iloc[:,7:] # Not a correct way, because shutter position also need to be excluded feature_tmp = df_scaler.fit_transform(feature_tmp) # ------------------------------------------------------------------ # Add features here. Remember to add new columns when initialzing df t1 = np.mean(feature_tmp) t2 = np.std(feature_tmp) t3 = np.mean(np.sqrt(np.abs(feature_tmp)))**2 t4 = np.sqrt(np.mean(feature_tmp**2)) t5 = np.max(feature_tmp) t6 = np.sum((feature_tmp-t1)**3)/((len(feature_tmp)-1)*(t2**3)) t7 = np.sum((feature_tmp-t1)**4)/((len(feature_tmp)-1)*(t2**4)) t8 = t5/t4 t9 = t5/t3 t10 = t4/(np.sum(np.abs(feature_tmp))/len(feature_tmp)) t11 = t5/(np.sum(np.abs(feature_tmp))/(len(feature_tmp))) # Newly added # First order difference # --------------------------------------------------------------------- feature_all.loc[idx,:] = [t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11, df_tmp.T.time.iloc[0],df_tmp.T.time.iloc[-1], df_tmp.T.recipe.iloc[0],df_tmp.T.stage.iloc[0], lot_last] list_tmp = [] idx += 1 counter = 0 lot_last = lot_tmp print(row_tmp) #------------------------------------------------------------------------------
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jul 18 13:37:10 2018\n\n@author: ninja1mmm\n\"\"\"\nimport os\nimport numpy as np\nimport pandas as pd\nfrom sklearn import preprocessing\n\ndef file_name(file_dir): \n root_tmp=[]\n dirs_tmp=[]\n files_tmp=[]\n for root, dirs, files in os.walk(file_dir): \n root_tmp.append(root)\n dirs_tmp.append(dirs)\n files_tmp.append(files)\n return root_tmp, dirs_tmp, files_tmp\n \n \nroot = '/home/ninja1mmm/Desktop/phm/data'\nroot_tmp, dirs_tmp, files_tmp = file_name(root)\n\ncombined_all = {}\nfeature_all = pd.DataFrame(columns = ['mean', 'std','root amplitude',\n 'rms','max','skewness','kurtosis',\n 'peak factor','margin','waveform',\n 'pulse','start_time', 'end_time',\n 'recipe', 'stage', 'Lot'])\n#df_check = pd.DataFrame()\n\n# read the first file to test here\nfile_tmp = files_tmp[2][0]\n# iterate through the files if needed\n#for file_tmp in files_tmp[2]:\n \npath_tmp = root_tmp[2]+'/'+file_tmp\ndf = pd.read_pickle(path_tmp)\n#df_tmp = df[df['Lot']==28113]\n#if len(df_tmp)>0:\n# df_tmp = df_tmp.iloc[0,:]\n# df_check = df_check.append(df_tmp)\n #------------------------------------------------------------------------------\n# Crucial step\ndf=df.replace([np.inf, -np.inf], np.nan).dropna()\ndf=df.reset_index(drop=True)\ndf_scaler = preprocessing.MinMaxScaler(feature_range = (0,1))\n\n#------------------------------------------------------------------------------\n \n\n\n\nlot_list = list(set(df.Lot))\n# Check if Lot already existed\nfor key in lot_list:\n if key in combined_all.keys():\n print('The Lot %d in %s already existed in %s' % (key, file_tmp, \n combined_all[key]))\n \n# for tmp in lot_list:\n# combined_all[tmp] = file_tmp\n# Select and save all the wafer processing cycles\nlist_tmp = []\nlot_last = df.Lot[0]\ncounter = 0\nidx = 0\n# Specify the range. Here set to 100000 for the ease of test\nfor row_tmp in df.index:\n lot_tmp = df.iloc[row_tmp,:].Lot\n if lot_tmp == lot_last:\n list_tmp.append(df.iloc[row_tmp,:])\n counter += 1\n else:\n df_tmp = pd.concat(list_tmp, axis = 1)\n # lot_last serves as the key, can be changed \n# combined_all[lot_last] = df_tmp.T\n combined_all[df_tmp.T.time.iloc[-1]] = df_tmp.T\n # Calculate mean and save in feature dictionary as an example\n # Normalize the data again because for some parameters we need the local (within cycle) feature\n feature_tmp = df_tmp.T.iloc[:,7:] # Not a correct way, because shutter position also need to be excluded\n feature_tmp = df_scaler.fit_transform(feature_tmp)\n# ------------------------------------------------------------------\n # Add features here. Remember to add new columns when initialzing df\n t1 = np.mean(feature_tmp) \n t2 = np.std(feature_tmp)\n t3 = np.mean(np.sqrt(np.abs(feature_tmp)))**2\n t4 = np.sqrt(np.mean(feature_tmp**2))\n t5 = np.max(feature_tmp)\n t6 = np.sum((feature_tmp-t1)**3)/((len(feature_tmp)-1)*(t2**3))\n t7 = np.sum((feature_tmp-t1)**4)/((len(feature_tmp)-1)*(t2**4))\n t8 = t5/t4\n t9 = t5/t3\n t10 = t4/(np.sum(np.abs(feature_tmp))/len(feature_tmp))\n t11 = t5/(np.sum(np.abs(feature_tmp))/(len(feature_tmp)))\n # Newly added\n \n \n # First order difference\n \n# ---------------------------------------------------------------------\n feature_all.loc[idx,:] = [t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,\n df_tmp.T.time.iloc[0],df_tmp.T.time.iloc[-1],\n df_tmp.T.recipe.iloc[0],df_tmp.T.stage.iloc[0],\n lot_last]\n \n list_tmp = []\n idx += 1\n counter = 0\n lot_last = lot_tmp\n print(row_tmp)\n \n \n \n#------------------------------------------------------------------------------\n\n\n\n\n", "<docstring token>\nimport os\nimport numpy as np\nimport pandas as pd\nfrom sklearn import preprocessing\n\n\ndef file_name(file_dir):\n root_tmp = []\n dirs_tmp = []\n files_tmp = []\n for root, dirs, files in os.walk(file_dir):\n root_tmp.append(root)\n dirs_tmp.append(dirs)\n files_tmp.append(files)\n return root_tmp, dirs_tmp, files_tmp\n\n\nroot = '/home/ninja1mmm/Desktop/phm/data'\nroot_tmp, dirs_tmp, files_tmp = file_name(root)\ncombined_all = {}\nfeature_all = pd.DataFrame(columns=['mean', 'std', 'root amplitude', 'rms',\n 'max', 'skewness', 'kurtosis', 'peak factor', 'margin', 'waveform',\n 'pulse', 'start_time', 'end_time', 'recipe', 'stage', 'Lot'])\nfile_tmp = files_tmp[2][0]\npath_tmp = root_tmp[2] + '/' + file_tmp\ndf = pd.read_pickle(path_tmp)\ndf = df.replace([np.inf, -np.inf], np.nan).dropna()\ndf = df.reset_index(drop=True)\ndf_scaler = preprocessing.MinMaxScaler(feature_range=(0, 1))\nlot_list = list(set(df.Lot))\nfor key in lot_list:\n if key in combined_all.keys():\n print('The Lot %d in %s already existed in %s' % (key, file_tmp,\n combined_all[key]))\nlist_tmp = []\nlot_last = df.Lot[0]\ncounter = 0\nidx = 0\nfor row_tmp in df.index:\n lot_tmp = df.iloc[row_tmp, :].Lot\n if lot_tmp == lot_last:\n list_tmp.append(df.iloc[row_tmp, :])\n counter += 1\n else:\n df_tmp = pd.concat(list_tmp, axis=1)\n combined_all[df_tmp.T.time.iloc[-1]] = df_tmp.T\n feature_tmp = df_tmp.T.iloc[:, 7:]\n feature_tmp = df_scaler.fit_transform(feature_tmp)\n t1 = np.mean(feature_tmp)\n t2 = np.std(feature_tmp)\n t3 = np.mean(np.sqrt(np.abs(feature_tmp))) ** 2\n t4 = np.sqrt(np.mean(feature_tmp ** 2))\n t5 = np.max(feature_tmp)\n t6 = np.sum((feature_tmp - t1) ** 3) / ((len(feature_tmp) - 1) * t2 **\n 3)\n t7 = np.sum((feature_tmp - t1) ** 4) / ((len(feature_tmp) - 1) * t2 **\n 4)\n t8 = t5 / t4\n t9 = t5 / t3\n t10 = t4 / (np.sum(np.abs(feature_tmp)) / len(feature_tmp))\n t11 = t5 / (np.sum(np.abs(feature_tmp)) / len(feature_tmp))\n feature_all.loc[idx, :] = [t1, t2, t3, t4, t5, t6, t7, t8, t9, t10,\n t11, df_tmp.T.time.iloc[0], df_tmp.T.time.iloc[-1], df_tmp.T.\n recipe.iloc[0], df_tmp.T.stage.iloc[0], lot_last]\n list_tmp = []\n idx += 1\n counter = 0\n lot_last = lot_tmp\n print(row_tmp)\n", "<docstring token>\n<import token>\n\n\ndef file_name(file_dir):\n root_tmp = []\n dirs_tmp = []\n files_tmp = []\n for root, dirs, files in os.walk(file_dir):\n root_tmp.append(root)\n dirs_tmp.append(dirs)\n files_tmp.append(files)\n return root_tmp, dirs_tmp, files_tmp\n\n\nroot = '/home/ninja1mmm/Desktop/phm/data'\nroot_tmp, dirs_tmp, files_tmp = file_name(root)\ncombined_all = {}\nfeature_all = pd.DataFrame(columns=['mean', 'std', 'root amplitude', 'rms',\n 'max', 'skewness', 'kurtosis', 'peak factor', 'margin', 'waveform',\n 'pulse', 'start_time', 'end_time', 'recipe', 'stage', 'Lot'])\nfile_tmp = files_tmp[2][0]\npath_tmp = root_tmp[2] + '/' + file_tmp\ndf = pd.read_pickle(path_tmp)\ndf = df.replace([np.inf, -np.inf], np.nan).dropna()\ndf = df.reset_index(drop=True)\ndf_scaler = preprocessing.MinMaxScaler(feature_range=(0, 1))\nlot_list = list(set(df.Lot))\nfor key in lot_list:\n if key in combined_all.keys():\n print('The Lot %d in %s already existed in %s' % (key, file_tmp,\n combined_all[key]))\nlist_tmp = []\nlot_last = df.Lot[0]\ncounter = 0\nidx = 0\nfor row_tmp in df.index:\n lot_tmp = df.iloc[row_tmp, :].Lot\n if lot_tmp == lot_last:\n list_tmp.append(df.iloc[row_tmp, :])\n counter += 1\n else:\n df_tmp = pd.concat(list_tmp, axis=1)\n combined_all[df_tmp.T.time.iloc[-1]] = df_tmp.T\n feature_tmp = df_tmp.T.iloc[:, 7:]\n feature_tmp = df_scaler.fit_transform(feature_tmp)\n t1 = np.mean(feature_tmp)\n t2 = np.std(feature_tmp)\n t3 = np.mean(np.sqrt(np.abs(feature_tmp))) ** 2\n t4 = np.sqrt(np.mean(feature_tmp ** 2))\n t5 = np.max(feature_tmp)\n t6 = np.sum((feature_tmp - t1) ** 3) / ((len(feature_tmp) - 1) * t2 **\n 3)\n t7 = np.sum((feature_tmp - t1) ** 4) / ((len(feature_tmp) - 1) * t2 **\n 4)\n t8 = t5 / t4\n t9 = t5 / t3\n t10 = t4 / (np.sum(np.abs(feature_tmp)) / len(feature_tmp))\n t11 = t5 / (np.sum(np.abs(feature_tmp)) / len(feature_tmp))\n feature_all.loc[idx, :] = [t1, t2, t3, t4, t5, t6, t7, t8, t9, t10,\n t11, df_tmp.T.time.iloc[0], df_tmp.T.time.iloc[-1], df_tmp.T.\n recipe.iloc[0], df_tmp.T.stage.iloc[0], lot_last]\n list_tmp = []\n idx += 1\n counter = 0\n lot_last = lot_tmp\n print(row_tmp)\n", "<docstring token>\n<import token>\n\n\ndef file_name(file_dir):\n root_tmp = []\n dirs_tmp = []\n files_tmp = []\n for root, dirs, files in os.walk(file_dir):\n root_tmp.append(root)\n dirs_tmp.append(dirs)\n files_tmp.append(files)\n return root_tmp, dirs_tmp, files_tmp\n\n\n<assignment token>\nfor key in lot_list:\n if key in combined_all.keys():\n print('The Lot %d in %s already existed in %s' % (key, file_tmp,\n combined_all[key]))\n<assignment token>\nfor row_tmp in df.index:\n lot_tmp = df.iloc[row_tmp, :].Lot\n if lot_tmp == lot_last:\n list_tmp.append(df.iloc[row_tmp, :])\n counter += 1\n else:\n df_tmp = pd.concat(list_tmp, axis=1)\n combined_all[df_tmp.T.time.iloc[-1]] = df_tmp.T\n feature_tmp = df_tmp.T.iloc[:, 7:]\n feature_tmp = df_scaler.fit_transform(feature_tmp)\n t1 = np.mean(feature_tmp)\n t2 = np.std(feature_tmp)\n t3 = np.mean(np.sqrt(np.abs(feature_tmp))) ** 2\n t4 = np.sqrt(np.mean(feature_tmp ** 2))\n t5 = np.max(feature_tmp)\n t6 = np.sum((feature_tmp - t1) ** 3) / ((len(feature_tmp) - 1) * t2 **\n 3)\n t7 = np.sum((feature_tmp - t1) ** 4) / ((len(feature_tmp) - 1) * t2 **\n 4)\n t8 = t5 / t4\n t9 = t5 / t3\n t10 = t4 / (np.sum(np.abs(feature_tmp)) / len(feature_tmp))\n t11 = t5 / (np.sum(np.abs(feature_tmp)) / len(feature_tmp))\n feature_all.loc[idx, :] = [t1, t2, t3, t4, t5, t6, t7, t8, t9, t10,\n t11, df_tmp.T.time.iloc[0], df_tmp.T.time.iloc[-1], df_tmp.T.\n recipe.iloc[0], df_tmp.T.stage.iloc[0], lot_last]\n list_tmp = []\n idx += 1\n counter = 0\n lot_last = lot_tmp\n print(row_tmp)\n", "<docstring token>\n<import token>\n\n\ndef file_name(file_dir):\n root_tmp = []\n dirs_tmp = []\n files_tmp = []\n for root, dirs, files in os.walk(file_dir):\n root_tmp.append(root)\n dirs_tmp.append(dirs)\n files_tmp.append(files)\n return root_tmp, dirs_tmp, files_tmp\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<docstring token>\n<import token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
771
d09984c6e6a0ce82389dbbbade63507e9687355d
# Generated by Django 2.2.6 on 2019-12-23 16:38 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('Pages', '0014_auto_20191223_2032'), ] operations = [ migrations.AlterField( model_name='dept', name='Hospital_id', field=models.ForeignKey(default='null', on_delete=django.db.models.deletion.CASCADE, to='Pages.Hospital'), ), ]
[ "# Generated by Django 2.2.6 on 2019-12-23 16:38\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Pages', '0014_auto_20191223_2032'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='dept',\n name='Hospital_id',\n field=models.ForeignKey(default='null', on_delete=django.db.models.deletion.CASCADE, to='Pages.Hospital'),\n ),\n ]\n", "from django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n dependencies = [('Pages', '0014_auto_20191223_2032')]\n operations = [migrations.AlterField(model_name='dept', name=\n 'Hospital_id', field=models.ForeignKey(default='null', on_delete=\n django.db.models.deletion.CASCADE, to='Pages.Hospital'))]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('Pages', '0014_auto_20191223_2032')]\n operations = [migrations.AlterField(model_name='dept', name=\n 'Hospital_id', field=models.ForeignKey(default='null', on_delete=\n django.db.models.deletion.CASCADE, to='Pages.Hospital'))]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n <assignment token>\n <assignment token>\n", "<import token>\n<class token>\n" ]
false
772
5d4ef314bb7169f5de4795e5c1aca62a1a060bae
from django.db import models # Login Admin Model class AdminLoginModel(models.Model): user_name = models.CharField(max_length=30,unique=True) password = models.CharField(max_length=16) # Swiggy Admin State Table class AdminStateModel(models.Model): state_id = models.AutoField(primary_key=True) state_name = models.CharField(max_length=30,unique=True) def __str__(self): return self.state_name # Admin City Table class AdminCityTable(models.Model): city_id = models.AutoField(primary_key = True) city_name = models.CharField(max_length=30,unique=True) state = models.ForeignKey(AdminStateModel,on_delete=models.CASCADE) def __str__(self): return self.city_name #Admin Area Models for Area Operations class AdminAreaModel(models.Model): area_id = models.AutoField(primary_key = True) area_name = models.CharField(max_length=30,unique=True) city = models.ForeignKey(AdminCityTable,on_delete=models.CASCADE) def __str__(self): return self.area_name #Admin Restaurant type Model class AdminRestaurantTypeModel(models.Model): restaurant_type_id = models.AutoField(primary_key = True) restaurant_type_name = models.CharField(max_length=30,unique=True) def __str__(self): return self.restaurant_type_name
[ "from django.db import models\n\n\n# Login Admin Model\nclass AdminLoginModel(models.Model):\n user_name = models.CharField(max_length=30,unique=True)\n password = models.CharField(max_length=16)\n\n\n\n# Swiggy Admin State Table\n\nclass AdminStateModel(models.Model):\n state_id = models.AutoField(primary_key=True)\n state_name = models.CharField(max_length=30,unique=True)\n\n def __str__(self):\n return self.state_name\n\n# Admin City Table\nclass AdminCityTable(models.Model):\n city_id = models.AutoField(primary_key = True)\n city_name = models.CharField(max_length=30,unique=True)\n state = models.ForeignKey(AdminStateModel,on_delete=models.CASCADE)\n\n def __str__(self):\n return self.city_name\n \n#Admin Area Models for Area Operations\nclass AdminAreaModel(models.Model):\n area_id = models.AutoField(primary_key = True)\n area_name = models.CharField(max_length=30,unique=True)\n\n city = models.ForeignKey(AdminCityTable,on_delete=models.CASCADE)\n def __str__(self):\n return self.area_name\n\n#Admin Restaurant type Model\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key = True)\n restaurant_type_name = models.CharField(max_length=30,unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n\n\n\n\n\n", "from django.db import models\n\n\nclass AdminLoginModel(models.Model):\n user_name = models.CharField(max_length=30, unique=True)\n password = models.CharField(max_length=16)\n\n\nclass AdminStateModel(models.Model):\n state_id = models.AutoField(primary_key=True)\n state_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.state_name\n\n\nclass AdminCityTable(models.Model):\n city_id = models.AutoField(primary_key=True)\n city_name = models.CharField(max_length=30, unique=True)\n state = models.ForeignKey(AdminStateModel, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.city_name\n\n\nclass AdminAreaModel(models.Model):\n area_id = models.AutoField(primary_key=True)\n area_name = models.CharField(max_length=30, unique=True)\n city = models.ForeignKey(AdminCityTable, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.area_name\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n\n\nclass AdminLoginModel(models.Model):\n user_name = models.CharField(max_length=30, unique=True)\n password = models.CharField(max_length=16)\n\n\nclass AdminStateModel(models.Model):\n state_id = models.AutoField(primary_key=True)\n state_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.state_name\n\n\nclass AdminCityTable(models.Model):\n city_id = models.AutoField(primary_key=True)\n city_name = models.CharField(max_length=30, unique=True)\n state = models.ForeignKey(AdminStateModel, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.city_name\n\n\nclass AdminAreaModel(models.Model):\n area_id = models.AutoField(primary_key=True)\n area_name = models.CharField(max_length=30, unique=True)\n city = models.ForeignKey(AdminCityTable, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.area_name\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n\n\nclass AdminLoginModel(models.Model):\n <assignment token>\n <assignment token>\n\n\nclass AdminStateModel(models.Model):\n state_id = models.AutoField(primary_key=True)\n state_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.state_name\n\n\nclass AdminCityTable(models.Model):\n city_id = models.AutoField(primary_key=True)\n city_name = models.CharField(max_length=30, unique=True)\n state = models.ForeignKey(AdminStateModel, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.city_name\n\n\nclass AdminAreaModel(models.Model):\n area_id = models.AutoField(primary_key=True)\n area_name = models.CharField(max_length=30, unique=True)\n city = models.ForeignKey(AdminCityTable, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.area_name\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n\n\nclass AdminStateModel(models.Model):\n state_id = models.AutoField(primary_key=True)\n state_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.state_name\n\n\nclass AdminCityTable(models.Model):\n city_id = models.AutoField(primary_key=True)\n city_name = models.CharField(max_length=30, unique=True)\n state = models.ForeignKey(AdminStateModel, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.city_name\n\n\nclass AdminAreaModel(models.Model):\n area_id = models.AutoField(primary_key=True)\n area_name = models.CharField(max_length=30, unique=True)\n city = models.ForeignKey(AdminCityTable, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.area_name\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n\n\nclass AdminStateModel(models.Model):\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return self.state_name\n\n\nclass AdminCityTable(models.Model):\n city_id = models.AutoField(primary_key=True)\n city_name = models.CharField(max_length=30, unique=True)\n state = models.ForeignKey(AdminStateModel, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.city_name\n\n\nclass AdminAreaModel(models.Model):\n area_id = models.AutoField(primary_key=True)\n area_name = models.CharField(max_length=30, unique=True)\n city = models.ForeignKey(AdminCityTable, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.area_name\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n\n\nclass AdminStateModel(models.Model):\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass AdminCityTable(models.Model):\n city_id = models.AutoField(primary_key=True)\n city_name = models.CharField(max_length=30, unique=True)\n state = models.ForeignKey(AdminStateModel, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.city_name\n\n\nclass AdminAreaModel(models.Model):\n area_id = models.AutoField(primary_key=True)\n area_name = models.CharField(max_length=30, unique=True)\n city = models.ForeignKey(AdminCityTable, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.area_name\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n<class token>\n\n\nclass AdminCityTable(models.Model):\n city_id = models.AutoField(primary_key=True)\n city_name = models.CharField(max_length=30, unique=True)\n state = models.ForeignKey(AdminStateModel, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.city_name\n\n\nclass AdminAreaModel(models.Model):\n area_id = models.AutoField(primary_key=True)\n area_name = models.CharField(max_length=30, unique=True)\n city = models.ForeignKey(AdminCityTable, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.area_name\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n<class token>\n\n\nclass AdminCityTable(models.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return self.city_name\n\n\nclass AdminAreaModel(models.Model):\n area_id = models.AutoField(primary_key=True)\n area_name = models.CharField(max_length=30, unique=True)\n city = models.ForeignKey(AdminCityTable, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.area_name\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n<class token>\n\n\nclass AdminCityTable(models.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass AdminAreaModel(models.Model):\n area_id = models.AutoField(primary_key=True)\n area_name = models.CharField(max_length=30, unique=True)\n city = models.ForeignKey(AdminCityTable, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.area_name\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass AdminAreaModel(models.Model):\n area_id = models.AutoField(primary_key=True)\n area_name = models.CharField(max_length=30, unique=True)\n city = models.ForeignKey(AdminCityTable, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.area_name\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass AdminAreaModel(models.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return self.area_name\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass AdminAreaModel(models.Model):\n <assignment token>\n <assignment token>\n <assignment token>\n <function token>\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass AdminRestaurantTypeModel(models.Model):\n restaurant_type_id = models.AutoField(primary_key=True)\n restaurant_type_name = models.CharField(max_length=30, unique=True)\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass AdminRestaurantTypeModel(models.Model):\n <assignment token>\n <assignment token>\n\n def __str__(self):\n return self.restaurant_type_name\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n\n\nclass AdminRestaurantTypeModel(models.Model):\n <assignment token>\n <assignment token>\n <function token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<class token>\n" ]
false
773
5c5f00084f37837b749e1fbb52a18d515e09ba06
import graph as Graph def BFS(graph: Graph.Graph, start, end): visited = set() parent = dict() parent[start] = None queue = [] queue.append(start) visited.add(start) while queue: current = queue.pop(0) if current == end: break for v in graph.neighbors(current): if v not in visited: queue.append(v) visited.add(v) parent[v] = current return parent
[ "import graph as Graph\n\ndef BFS(graph: Graph.Graph, start, end):\n visited = set()\n\n parent = dict()\n parent[start] = None\n\n queue = []\n queue.append(start)\n visited.add(start)\n\n while queue:\n current = queue.pop(0)\n\n if current == end:\n break\n\n for v in graph.neighbors(current):\n if v not in visited:\n queue.append(v)\n visited.add(v)\n parent[v] = current\n\n return parent\n", "import graph as Graph\n\n\ndef BFS(graph: Graph.Graph, start, end):\n visited = set()\n parent = dict()\n parent[start] = None\n queue = []\n queue.append(start)\n visited.add(start)\n while queue:\n current = queue.pop(0)\n if current == end:\n break\n for v in graph.neighbors(current):\n if v not in visited:\n queue.append(v)\n visited.add(v)\n parent[v] = current\n return parent\n", "<import token>\n\n\ndef BFS(graph: Graph.Graph, start, end):\n visited = set()\n parent = dict()\n parent[start] = None\n queue = []\n queue.append(start)\n visited.add(start)\n while queue:\n current = queue.pop(0)\n if current == end:\n break\n for v in graph.neighbors(current):\n if v not in visited:\n queue.append(v)\n visited.add(v)\n parent[v] = current\n return parent\n", "<import token>\n<function token>\n" ]
false
774
6b785502e8a8983c164ebdffdd304da47c926acb
from django.apps import AppConfig class LaughsappConfig(AppConfig): name = 'laughsApp'
[ "from django.apps import AppConfig\n\n\nclass LaughsappConfig(AppConfig):\n name = 'laughsApp'\n", "<import token>\n\n\nclass LaughsappConfig(AppConfig):\n name = 'laughsApp'\n", "<import token>\n\n\nclass LaughsappConfig(AppConfig):\n <assignment token>\n", "<import token>\n<class token>\n" ]
false
775
4a7f8221208e8252c7f5c0adff2949f0e552def1
from azureml.core import Workspace from azureml.pipeline.core import Pipeline from azureml.core import Experiment from azureml.pipeline.steps import PythonScriptStep import requests ws = Workspace.from_config() # Step to run a Python script step1 = PythonScriptStep( name = "prepare data", source_directory = "scripts", script_name = "data_prep.py", compute_target = "aml-cluster" ) # Step to train a model step2 = PythonScriptStep( name = "train model", source_directory = "scripts", script_name = "train_model.py", compute_target = "aml-cluster" ) # Construct the pipeline train_pipeline = Pipeline(workspace = ws, steps = [step1, step2]) # Create an experiment and run the pipeline with it experiment = Experiment(workspace = ws, name = "training-pipeline") pipeline_run = experiment.submit(train_pipeline) # To run all pipeline steps without cached results # pipeline_run = experiment.submit(train_pipeline, regenerate_outputs=True) # Publish the pipeline run published_pipeline = pipeline_run.publish( name="training_pipeline", description="Model training pipeline", version="1.0" ) # Get the endpoint for the published pipeline rest_endpoint = published_pipeline.endpoint print(rest_endpoint) # Consume the pipeline through REST request response = requests.post( rest_endpoint, headers=some_auth_header, json={"ExperimentName": "run_training_pipeline"}) run_id = response.json()["Id"] print(run_id)
[ "from azureml.core import Workspace\r\nfrom azureml.pipeline.core import Pipeline\r\nfrom azureml.core import Experiment\r\nfrom azureml.pipeline.steps import PythonScriptStep\r\nimport requests\r\n\r\nws = Workspace.from_config()\r\n\r\n# Step to run a Python script\r\nstep1 = PythonScriptStep(\r\n name = \"prepare data\",\r\n source_directory = \"scripts\",\r\n script_name = \"data_prep.py\",\r\n compute_target = \"aml-cluster\"\r\n)\r\n\r\n# Step to train a model\r\nstep2 = PythonScriptStep(\r\n name = \"train model\",\r\n source_directory = \"scripts\",\r\n script_name = \"train_model.py\",\r\n compute_target = \"aml-cluster\"\r\n)\r\n\r\n# Construct the pipeline\r\ntrain_pipeline = Pipeline(workspace = ws, steps = [step1, step2])\r\n\r\n# Create an experiment and run the pipeline with it\r\nexperiment = Experiment(workspace = ws, name = \"training-pipeline\")\r\npipeline_run = experiment.submit(train_pipeline)\r\n# To run all pipeline steps without cached results\r\n# pipeline_run = experiment.submit(train_pipeline, regenerate_outputs=True)\r\n\r\n# Publish the pipeline run\r\npublished_pipeline = pipeline_run.publish(\r\n name=\"training_pipeline\",\r\n description=\"Model training pipeline\",\r\n version=\"1.0\"\r\n)\r\n\r\n# Get the endpoint for the published pipeline\r\nrest_endpoint = published_pipeline.endpoint\r\nprint(rest_endpoint)\r\n# Consume the pipeline through REST request\r\nresponse = requests.post(\r\n rest_endpoint,\r\n headers=some_auth_header,\r\n json={\"ExperimentName\": \"run_training_pipeline\"})\r\nrun_id = response.json()[\"Id\"]\r\nprint(run_id)", "from azureml.core import Workspace\nfrom azureml.pipeline.core import Pipeline\nfrom azureml.core import Experiment\nfrom azureml.pipeline.steps import PythonScriptStep\nimport requests\nws = Workspace.from_config()\nstep1 = PythonScriptStep(name='prepare data', source_directory='scripts',\n script_name='data_prep.py', compute_target='aml-cluster')\nstep2 = PythonScriptStep(name='train model', source_directory='scripts',\n script_name='train_model.py', compute_target='aml-cluster')\ntrain_pipeline = Pipeline(workspace=ws, steps=[step1, step2])\nexperiment = Experiment(workspace=ws, name='training-pipeline')\npipeline_run = experiment.submit(train_pipeline)\npublished_pipeline = pipeline_run.publish(name='training_pipeline',\n description='Model training pipeline', version='1.0')\nrest_endpoint = published_pipeline.endpoint\nprint(rest_endpoint)\nresponse = requests.post(rest_endpoint, headers=some_auth_header, json={\n 'ExperimentName': 'run_training_pipeline'})\nrun_id = response.json()['Id']\nprint(run_id)\n", "<import token>\nws = Workspace.from_config()\nstep1 = PythonScriptStep(name='prepare data', source_directory='scripts',\n script_name='data_prep.py', compute_target='aml-cluster')\nstep2 = PythonScriptStep(name='train model', source_directory='scripts',\n script_name='train_model.py', compute_target='aml-cluster')\ntrain_pipeline = Pipeline(workspace=ws, steps=[step1, step2])\nexperiment = Experiment(workspace=ws, name='training-pipeline')\npipeline_run = experiment.submit(train_pipeline)\npublished_pipeline = pipeline_run.publish(name='training_pipeline',\n description='Model training pipeline', version='1.0')\nrest_endpoint = published_pipeline.endpoint\nprint(rest_endpoint)\nresponse = requests.post(rest_endpoint, headers=some_auth_header, json={\n 'ExperimentName': 'run_training_pipeline'})\nrun_id = response.json()['Id']\nprint(run_id)\n", "<import token>\n<assignment token>\nprint(rest_endpoint)\n<assignment token>\nprint(run_id)\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
776
03fb1cf0aac0c37858dd8163562a7139ed4e1179
import dtw import stats import glob import argparse import matplotlib.pyplot as plt GRAPH = False PERCENTAGE = False VERBOSE = False def buildExpectations(queryPath, searchPatternPath): """ Based on SpeechCommand_v0.02 directory structure. """ expectations = [] currentDirectory = "" queryFilename = queryPath.split("/")[-1] queryDirectory = queryPath.split("/")[-2] queryCode = queryFilename.split("_")[0] searchFileList = sorted(glob.glob(searchPatternPath)) for searchFile in searchFileList: searchFilename = searchFile.split("/")[-1] searchDirectory = searchFile.split("/")[-2] searchCode = searchFilename.split("_")[0] if searchDirectory != currentDirectory: currentDirectory = searchDirectory if searchCode == queryCode: if currentDirectory == queryDirectory: expectations.append([[0, 1]]) else: expectations.append([[0, 0]]) return expectations if __name__ == "__main__": # Parse arguments parser = argparse.ArgumentParser(description='Dynamic Time Warping') parser.add_argument('-g', '--graph', action='store_true', help='Enable graph display') parser.add_argument('-t', '--threshold', type=float, default=0.4, help='Set score threshold') parser.add_argument('query_path') parser.add_argument('search_pattern_path') printGroup = parser.add_mutually_exclusive_group() printGroup.add_argument('-p', '--percentage', action='store_true', help='Enable percentage display') printGroup.add_argument('-v', '--verbose', action='store_true', help='Enable verbose display') args = parser.parse_args() GRAPH = args.graph PERCENTAGE = args.percentage threshold = args.threshold VERBOSE = args.verbose queryPath = args.query_path searchPatternPath = args.search_pattern_path dtw.VERBOSE = VERBOSE stats.VERBOSE = VERBOSE labels, sweepList, bestList = dtw.runSearch(queryPath, searchPatternPath) results = dtw.computeResultsPrecisely(sweepList, threshold, positiveOnly=True) for i, result in enumerate(results): print(labels[i] + ": ", end='') for j, (hitIndex, _) in enumerate(result): print(hitIndex * 3, end='') if j < len(result) - 1: print(" | ", end='') print() if GRAPH: dtw.showSweeps(labels, sweepList, bestList) plt.show()
[ "import dtw\nimport stats\n\nimport glob\nimport argparse\nimport matplotlib.pyplot as plt\n\nGRAPH = False\nPERCENTAGE = False\nVERBOSE = False\n\ndef buildExpectations(queryPath, searchPatternPath):\n \"\"\"\n Based on SpeechCommand_v0.02 directory structure.\n \"\"\"\n expectations = []\n currentDirectory = \"\"\n queryFilename = queryPath.split(\"/\")[-1]\n queryDirectory = queryPath.split(\"/\")[-2]\n queryCode = queryFilename.split(\"_\")[0]\n searchFileList = sorted(glob.glob(searchPatternPath))\n for searchFile in searchFileList:\n searchFilename = searchFile.split(\"/\")[-1]\n searchDirectory = searchFile.split(\"/\")[-2]\n searchCode = searchFilename.split(\"_\")[0]\n if searchDirectory != currentDirectory:\n currentDirectory = searchDirectory\n if searchCode == queryCode:\n if currentDirectory == queryDirectory:\n expectations.append([[0, 1]])\n else:\n expectations.append([[0, 0]])\n return expectations\n\nif __name__ == \"__main__\":\n # Parse arguments\n parser = argparse.ArgumentParser(description='Dynamic Time Warping')\n parser.add_argument('-g', '--graph', action='store_true', help='Enable graph display')\n parser.add_argument('-t', '--threshold', type=float, default=0.4, help='Set score threshold')\n parser.add_argument('query_path')\n parser.add_argument('search_pattern_path')\n\n printGroup = parser.add_mutually_exclusive_group()\n printGroup.add_argument('-p', '--percentage', action='store_true', help='Enable percentage display')\n printGroup.add_argument('-v', '--verbose', action='store_true', help='Enable verbose display')\n\n args = parser.parse_args()\n\n GRAPH = args.graph\n PERCENTAGE = args.percentage\n threshold = args.threshold\n VERBOSE = args.verbose\n queryPath = args.query_path\n searchPatternPath = args.search_pattern_path\n\n dtw.VERBOSE = VERBOSE\n stats.VERBOSE = VERBOSE\n\n labels, sweepList, bestList = dtw.runSearch(queryPath, searchPatternPath)\n\n results = dtw.computeResultsPrecisely(sweepList, threshold, positiveOnly=True)\n for i, result in enumerate(results):\n print(labels[i] + \": \", end='')\n for j, (hitIndex, _) in enumerate(result):\n print(hitIndex * 3, end='')\n if j < len(result) - 1:\n print(\" | \", end='')\n print()\n\n if GRAPH:\n dtw.showSweeps(labels, sweepList, bestList)\n\n plt.show()\n", "import dtw\nimport stats\nimport glob\nimport argparse\nimport matplotlib.pyplot as plt\nGRAPH = False\nPERCENTAGE = False\nVERBOSE = False\n\n\ndef buildExpectations(queryPath, searchPatternPath):\n \"\"\"\n Based on SpeechCommand_v0.02 directory structure.\n \"\"\"\n expectations = []\n currentDirectory = ''\n queryFilename = queryPath.split('/')[-1]\n queryDirectory = queryPath.split('/')[-2]\n queryCode = queryFilename.split('_')[0]\n searchFileList = sorted(glob.glob(searchPatternPath))\n for searchFile in searchFileList:\n searchFilename = searchFile.split('/')[-1]\n searchDirectory = searchFile.split('/')[-2]\n searchCode = searchFilename.split('_')[0]\n if searchDirectory != currentDirectory:\n currentDirectory = searchDirectory\n if searchCode == queryCode:\n if currentDirectory == queryDirectory:\n expectations.append([[0, 1]])\n else:\n expectations.append([[0, 0]])\n return expectations\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Dynamic Time Warping')\n parser.add_argument('-g', '--graph', action='store_true', help=\n 'Enable graph display')\n parser.add_argument('-t', '--threshold', type=float, default=0.4, help=\n 'Set score threshold')\n parser.add_argument('query_path')\n parser.add_argument('search_pattern_path')\n printGroup = parser.add_mutually_exclusive_group()\n printGroup.add_argument('-p', '--percentage', action='store_true', help\n ='Enable percentage display')\n printGroup.add_argument('-v', '--verbose', action='store_true', help=\n 'Enable verbose display')\n args = parser.parse_args()\n GRAPH = args.graph\n PERCENTAGE = args.percentage\n threshold = args.threshold\n VERBOSE = args.verbose\n queryPath = args.query_path\n searchPatternPath = args.search_pattern_path\n dtw.VERBOSE = VERBOSE\n stats.VERBOSE = VERBOSE\n labels, sweepList, bestList = dtw.runSearch(queryPath, searchPatternPath)\n results = dtw.computeResultsPrecisely(sweepList, threshold,\n positiveOnly=True)\n for i, result in enumerate(results):\n print(labels[i] + ': ', end='')\n for j, (hitIndex, _) in enumerate(result):\n print(hitIndex * 3, end='')\n if j < len(result) - 1:\n print(' | ', end='')\n print()\n if GRAPH:\n dtw.showSweeps(labels, sweepList, bestList)\n plt.show()\n", "<import token>\nGRAPH = False\nPERCENTAGE = False\nVERBOSE = False\n\n\ndef buildExpectations(queryPath, searchPatternPath):\n \"\"\"\n Based on SpeechCommand_v0.02 directory structure.\n \"\"\"\n expectations = []\n currentDirectory = ''\n queryFilename = queryPath.split('/')[-1]\n queryDirectory = queryPath.split('/')[-2]\n queryCode = queryFilename.split('_')[0]\n searchFileList = sorted(glob.glob(searchPatternPath))\n for searchFile in searchFileList:\n searchFilename = searchFile.split('/')[-1]\n searchDirectory = searchFile.split('/')[-2]\n searchCode = searchFilename.split('_')[0]\n if searchDirectory != currentDirectory:\n currentDirectory = searchDirectory\n if searchCode == queryCode:\n if currentDirectory == queryDirectory:\n expectations.append([[0, 1]])\n else:\n expectations.append([[0, 0]])\n return expectations\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Dynamic Time Warping')\n parser.add_argument('-g', '--graph', action='store_true', help=\n 'Enable graph display')\n parser.add_argument('-t', '--threshold', type=float, default=0.4, help=\n 'Set score threshold')\n parser.add_argument('query_path')\n parser.add_argument('search_pattern_path')\n printGroup = parser.add_mutually_exclusive_group()\n printGroup.add_argument('-p', '--percentage', action='store_true', help\n ='Enable percentage display')\n printGroup.add_argument('-v', '--verbose', action='store_true', help=\n 'Enable verbose display')\n args = parser.parse_args()\n GRAPH = args.graph\n PERCENTAGE = args.percentage\n threshold = args.threshold\n VERBOSE = args.verbose\n queryPath = args.query_path\n searchPatternPath = args.search_pattern_path\n dtw.VERBOSE = VERBOSE\n stats.VERBOSE = VERBOSE\n labels, sweepList, bestList = dtw.runSearch(queryPath, searchPatternPath)\n results = dtw.computeResultsPrecisely(sweepList, threshold,\n positiveOnly=True)\n for i, result in enumerate(results):\n print(labels[i] + ': ', end='')\n for j, (hitIndex, _) in enumerate(result):\n print(hitIndex * 3, end='')\n if j < len(result) - 1:\n print(' | ', end='')\n print()\n if GRAPH:\n dtw.showSweeps(labels, sweepList, bestList)\n plt.show()\n", "<import token>\n<assignment token>\n\n\ndef buildExpectations(queryPath, searchPatternPath):\n \"\"\"\n Based on SpeechCommand_v0.02 directory structure.\n \"\"\"\n expectations = []\n currentDirectory = ''\n queryFilename = queryPath.split('/')[-1]\n queryDirectory = queryPath.split('/')[-2]\n queryCode = queryFilename.split('_')[0]\n searchFileList = sorted(glob.glob(searchPatternPath))\n for searchFile in searchFileList:\n searchFilename = searchFile.split('/')[-1]\n searchDirectory = searchFile.split('/')[-2]\n searchCode = searchFilename.split('_')[0]\n if searchDirectory != currentDirectory:\n currentDirectory = searchDirectory\n if searchCode == queryCode:\n if currentDirectory == queryDirectory:\n expectations.append([[0, 1]])\n else:\n expectations.append([[0, 0]])\n return expectations\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Dynamic Time Warping')\n parser.add_argument('-g', '--graph', action='store_true', help=\n 'Enable graph display')\n parser.add_argument('-t', '--threshold', type=float, default=0.4, help=\n 'Set score threshold')\n parser.add_argument('query_path')\n parser.add_argument('search_pattern_path')\n printGroup = parser.add_mutually_exclusive_group()\n printGroup.add_argument('-p', '--percentage', action='store_true', help\n ='Enable percentage display')\n printGroup.add_argument('-v', '--verbose', action='store_true', help=\n 'Enable verbose display')\n args = parser.parse_args()\n GRAPH = args.graph\n PERCENTAGE = args.percentage\n threshold = args.threshold\n VERBOSE = args.verbose\n queryPath = args.query_path\n searchPatternPath = args.search_pattern_path\n dtw.VERBOSE = VERBOSE\n stats.VERBOSE = VERBOSE\n labels, sweepList, bestList = dtw.runSearch(queryPath, searchPatternPath)\n results = dtw.computeResultsPrecisely(sweepList, threshold,\n positiveOnly=True)\n for i, result in enumerate(results):\n print(labels[i] + ': ', end='')\n for j, (hitIndex, _) in enumerate(result):\n print(hitIndex * 3, end='')\n if j < len(result) - 1:\n print(' | ', end='')\n print()\n if GRAPH:\n dtw.showSweeps(labels, sweepList, bestList)\n plt.show()\n", "<import token>\n<assignment token>\n\n\ndef buildExpectations(queryPath, searchPatternPath):\n \"\"\"\n Based on SpeechCommand_v0.02 directory structure.\n \"\"\"\n expectations = []\n currentDirectory = ''\n queryFilename = queryPath.split('/')[-1]\n queryDirectory = queryPath.split('/')[-2]\n queryCode = queryFilename.split('_')[0]\n searchFileList = sorted(glob.glob(searchPatternPath))\n for searchFile in searchFileList:\n searchFilename = searchFile.split('/')[-1]\n searchDirectory = searchFile.split('/')[-2]\n searchCode = searchFilename.split('_')[0]\n if searchDirectory != currentDirectory:\n currentDirectory = searchDirectory\n if searchCode == queryCode:\n if currentDirectory == queryDirectory:\n expectations.append([[0, 1]])\n else:\n expectations.append([[0, 0]])\n return expectations\n\n\n<code token>\n", "<import token>\n<assignment token>\n<function token>\n<code token>\n" ]
false
777
303a8609cb21c60a416160264c3d3da805674920
import tensorflow as tf import tensorflow_probability as tfp import pytest import numpy as np from estimators import NormalizingFlowNetwork tfd = tfp.distributions tf.random.set_seed(22) np.random.seed(22) @pytest.mark.slow def test_x_noise_reg(): x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1)) noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train), scale_diag=abs(x_train)) y_train = noise.sample().numpy() too_much_noise = NormalizingFlowNetwork( 1, n_flows=2, hidden_sizes=(16, 16), noise_reg=("fixed_rate", 3.0), trainable_base_dist=True, ) too_much_noise.fit(x_train, y_train, epochs=700, verbose=0) x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1)) noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test), scale_diag=abs(x_test)) y_test = noise.sample().numpy() out1 = too_much_noise.pdf(x_test, y_test).numpy() out2 = too_much_noise.pdf(x_test, y_test).numpy() # making sure that the noise regularisation is deactivated in testing mode assert all(out1 == out2) little_noise = NormalizingFlowNetwork( 1, n_flows=2, hidden_sizes=(16, 16), noise_reg=("rule_of_thumb", 0.1), trainable_base_dist=True, ) little_noise.fit(x_train, y_train, epochs=700, verbose=0) little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)) / 700.0 too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)) / 700.0 assert little_noise_score > too_much_noise_score def test_y_noise_reg(): x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape((10, 3)) y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape((10, 3)) noise = NormalizingFlowNetwork( 3, n_flows=3, hidden_sizes=(16, 16), trainable_base_dist=True, noise_reg=("fixed_rate", 1.0), ) noise.fit(x_train, y_train, epochs=10, verbose=0) input_model = noise._get_input_model() # y_input should not include randomness during evaluation y1 = input_model(y_train, training=False).numpy() y2 = input_model(y_train, training=False).numpy() assert np.all(y1 == y2) # loss should include randomness during learning y1 = input_model(y_train, training=True).numpy() y2 = input_model(y_train, training=True).numpy() assert not np.all(y1 == y2)
[ "import tensorflow as tf\nimport tensorflow_probability as tfp\nimport pytest\nimport numpy as np\nfrom estimators import NormalizingFlowNetwork\n\ntfd = tfp.distributions\ntf.random.set_seed(22)\nnp.random.seed(22)\n\n\[email protected]\ndef test_x_noise_reg():\n x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train), scale_diag=abs(x_train))\n y_train = noise.sample().numpy()\n\n too_much_noise = NormalizingFlowNetwork(\n 1,\n n_flows=2,\n hidden_sizes=(16, 16),\n noise_reg=(\"fixed_rate\", 3.0),\n trainable_base_dist=True,\n )\n\n too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)\n\n x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test), scale_diag=abs(x_test))\n y_test = noise.sample().numpy()\n out1 = too_much_noise.pdf(x_test, y_test).numpy()\n out2 = too_much_noise.pdf(x_test, y_test).numpy()\n # making sure that the noise regularisation is deactivated in testing mode\n assert all(out1 == out2)\n\n little_noise = NormalizingFlowNetwork(\n 1,\n n_flows=2,\n hidden_sizes=(16, 16),\n noise_reg=(\"rule_of_thumb\", 0.1),\n trainable_base_dist=True,\n )\n little_noise.fit(x_train, y_train, epochs=700, verbose=0)\n\n little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)) / 700.0\n too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)) / 700.0\n assert little_noise_score > too_much_noise_score\n\n\ndef test_y_noise_reg():\n x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape((10, 3))\n y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape((10, 3))\n\n noise = NormalizingFlowNetwork(\n 3,\n n_flows=3,\n hidden_sizes=(16, 16),\n trainable_base_dist=True,\n noise_reg=(\"fixed_rate\", 1.0),\n )\n noise.fit(x_train, y_train, epochs=10, verbose=0)\n\n input_model = noise._get_input_model()\n # y_input should not include randomness during evaluation\n y1 = input_model(y_train, training=False).numpy()\n y2 = input_model(y_train, training=False).numpy()\n assert np.all(y1 == y2)\n\n # loss should include randomness during learning\n y1 = input_model(y_train, training=True).numpy()\n y2 = input_model(y_train, training=True).numpy()\n assert not np.all(y1 == y2)\n", "import tensorflow as tf\nimport tensorflow_probability as tfp\nimport pytest\nimport numpy as np\nfrom estimators import NormalizingFlowNetwork\ntfd = tfp.distributions\ntf.random.set_seed(22)\nnp.random.seed(22)\n\n\[email protected]\ndef test_x_noise_reg():\n x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),\n scale_diag=abs(x_train))\n y_train = noise.sample().numpy()\n too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,\n 16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)\n too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)\n x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),\n scale_diag=abs(x_test))\n y_test = noise.sample().numpy()\n out1 = too_much_noise.pdf(x_test, y_test).numpy()\n out2 = too_much_noise.pdf(x_test, y_test).numpy()\n assert all(out1 == out2)\n little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16, \n 16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)\n little_noise.fit(x_train, y_train, epochs=700, verbose=0)\n little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)\n ) / 700.0\n too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)\n ) / 700.0\n assert little_noise_score > too_much_noise_score\n\n\ndef test_y_noise_reg():\n x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),\n trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))\n noise.fit(x_train, y_train, epochs=10, verbose=0)\n input_model = noise._get_input_model()\n y1 = input_model(y_train, training=False).numpy()\n y2 = input_model(y_train, training=False).numpy()\n assert np.all(y1 == y2)\n y1 = input_model(y_train, training=True).numpy()\n y2 = input_model(y_train, training=True).numpy()\n assert not np.all(y1 == y2)\n", "<import token>\ntfd = tfp.distributions\ntf.random.set_seed(22)\nnp.random.seed(22)\n\n\[email protected]\ndef test_x_noise_reg():\n x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),\n scale_diag=abs(x_train))\n y_train = noise.sample().numpy()\n too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,\n 16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)\n too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)\n x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),\n scale_diag=abs(x_test))\n y_test = noise.sample().numpy()\n out1 = too_much_noise.pdf(x_test, y_test).numpy()\n out2 = too_much_noise.pdf(x_test, y_test).numpy()\n assert all(out1 == out2)\n little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16, \n 16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)\n little_noise.fit(x_train, y_train, epochs=700, verbose=0)\n little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)\n ) / 700.0\n too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)\n ) / 700.0\n assert little_noise_score > too_much_noise_score\n\n\ndef test_y_noise_reg():\n x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),\n trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))\n noise.fit(x_train, y_train, epochs=10, verbose=0)\n input_model = noise._get_input_model()\n y1 = input_model(y_train, training=False).numpy()\n y2 = input_model(y_train, training=False).numpy()\n assert np.all(y1 == y2)\n y1 = input_model(y_train, training=True).numpy()\n y2 = input_model(y_train, training=True).numpy()\n assert not np.all(y1 == y2)\n", "<import token>\n<assignment token>\ntf.random.set_seed(22)\nnp.random.seed(22)\n\n\[email protected]\ndef test_x_noise_reg():\n x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),\n scale_diag=abs(x_train))\n y_train = noise.sample().numpy()\n too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,\n 16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)\n too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)\n x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),\n scale_diag=abs(x_test))\n y_test = noise.sample().numpy()\n out1 = too_much_noise.pdf(x_test, y_test).numpy()\n out2 = too_much_noise.pdf(x_test, y_test).numpy()\n assert all(out1 == out2)\n little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16, \n 16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)\n little_noise.fit(x_train, y_train, epochs=700, verbose=0)\n little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)\n ) / 700.0\n too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)\n ) / 700.0\n assert little_noise_score > too_much_noise_score\n\n\ndef test_y_noise_reg():\n x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),\n trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))\n noise.fit(x_train, y_train, epochs=10, verbose=0)\n input_model = noise._get_input_model()\n y1 = input_model(y_train, training=False).numpy()\n y2 = input_model(y_train, training=False).numpy()\n assert np.all(y1 == y2)\n y1 = input_model(y_train, training=True).numpy()\n y2 = input_model(y_train, training=True).numpy()\n assert not np.all(y1 == y2)\n", "<import token>\n<assignment token>\n<code token>\n\n\[email protected]\ndef test_x_noise_reg():\n x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),\n scale_diag=abs(x_train))\n y_train = noise.sample().numpy()\n too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,\n 16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)\n too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)\n x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),\n scale_diag=abs(x_test))\n y_test = noise.sample().numpy()\n out1 = too_much_noise.pdf(x_test, y_test).numpy()\n out2 = too_much_noise.pdf(x_test, y_test).numpy()\n assert all(out1 == out2)\n little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16, \n 16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)\n little_noise.fit(x_train, y_train, epochs=700, verbose=0)\n little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)\n ) / 700.0\n too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)\n ) / 700.0\n assert little_noise_score > too_much_noise_score\n\n\ndef test_y_noise_reg():\n x_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n y_train = np.linspace([[-1]] * 3, [[1]] * 3, 10, dtype=np.float32).reshape(\n (10, 3))\n noise = NormalizingFlowNetwork(3, n_flows=3, hidden_sizes=(16, 16),\n trainable_base_dist=True, noise_reg=('fixed_rate', 1.0))\n noise.fit(x_train, y_train, epochs=10, verbose=0)\n input_model = noise._get_input_model()\n y1 = input_model(y_train, training=False).numpy()\n y2 = input_model(y_train, training=False).numpy()\n assert np.all(y1 == y2)\n y1 = input_model(y_train, training=True).numpy()\n y2 = input_model(y_train, training=True).numpy()\n assert not np.all(y1 == y2)\n", "<import token>\n<assignment token>\n<code token>\n\n\[email protected]\ndef test_x_noise_reg():\n x_train = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_train),\n scale_diag=abs(x_train))\n y_train = noise.sample().numpy()\n too_much_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16,\n 16), noise_reg=('fixed_rate', 3.0), trainable_base_dist=True)\n too_much_noise.fit(x_train, y_train, epochs=700, verbose=0)\n x_test = np.linspace(-3, 3, 300, dtype=np.float32).reshape((300, 1))\n noise = tfd.MultivariateNormalDiag(loc=5 * tf.math.sin(2 * x_test),\n scale_diag=abs(x_test))\n y_test = noise.sample().numpy()\n out1 = too_much_noise.pdf(x_test, y_test).numpy()\n out2 = too_much_noise.pdf(x_test, y_test).numpy()\n assert all(out1 == out2)\n little_noise = NormalizingFlowNetwork(1, n_flows=2, hidden_sizes=(16, \n 16), noise_reg=('rule_of_thumb', 0.1), trainable_base_dist=True)\n little_noise.fit(x_train, y_train, epochs=700, verbose=0)\n little_noise_score = tf.reduce_sum(little_noise.pdf(x_test, y_test)\n ) / 700.0\n too_much_noise_score = tf.reduce_sum(too_much_noise.pdf(x_test, y_test)\n ) / 700.0\n assert little_noise_score > too_much_noise_score\n\n\n<function token>\n", "<import token>\n<assignment token>\n<code token>\n<function token>\n<function token>\n" ]
false
778
830e7e84eebd6a4adb411cc95c9e9c8ff7bdac30
def isSubsetSum(set, n, sum): subset =([[False for i in range(sum + 1)] for i in range(n + 1)]) for i in range(n + 1): subset[i][0] = True for i in range(1, sum + 1): subset[0][i]= False for i in range(1, n + 1): for j in range(1, sum + 1): if j<set[i-1]: subset[i][j] = subset[i-1][j] if j>= set[i-1]: subset[i][j] = (subset[i-1][j] or subset[i - 1][j-set[i-1]]) return subset[n][sum] t=int(input()) for i in range(t): n,k=map(int,input().split()) lst=list(map(int,input().strip().split(' ')))[:n] if (isSubsetSum(lst, n, k) == True): print("YES") else: print("NO")
[ "def isSubsetSum(set, n, sum): \n subset =([[False for i in range(sum + 1)] for i in range(n + 1)]) \n for i in range(n + 1): \n subset[i][0] = True\n for i in range(1, sum + 1): \n subset[0][i]= False\n for i in range(1, n + 1): \n for j in range(1, sum + 1): \n if j<set[i-1]: \n subset[i][j] = subset[i-1][j] \n if j>= set[i-1]: \n subset[i][j] = (subset[i-1][j] or subset[i - 1][j-set[i-1]]) \n return subset[n][sum] \nt=int(input())\nfor i in range(t):\n n,k=map(int,input().split())\n lst=list(map(int,input().strip().split(' ')))[:n]\n if (isSubsetSum(lst, n, k) == True): \n print(\"YES\") \n else: \n print(\"NO\") \n \n", "def isSubsetSum(set, n, sum):\n subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n subset[i][0] = True\n for i in range(1, sum + 1):\n subset[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if j < set[i - 1]:\n subset[i][j] = subset[i - 1][j]\n if j >= set[i - 1]:\n subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1]\n ]\n return subset[n][sum]\n\n\nt = int(input())\nfor i in range(t):\n n, k = map(int, input().split())\n lst = list(map(int, input().strip().split(' ')))[:n]\n if isSubsetSum(lst, n, k) == True:\n print('YES')\n else:\n print('NO')\n", "def isSubsetSum(set, n, sum):\n subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n subset[i][0] = True\n for i in range(1, sum + 1):\n subset[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if j < set[i - 1]:\n subset[i][j] = subset[i - 1][j]\n if j >= set[i - 1]:\n subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1]\n ]\n return subset[n][sum]\n\n\n<assignment token>\nfor i in range(t):\n n, k = map(int, input().split())\n lst = list(map(int, input().strip().split(' ')))[:n]\n if isSubsetSum(lst, n, k) == True:\n print('YES')\n else:\n print('NO')\n", "def isSubsetSum(set, n, sum):\n subset = [[(False) for i in range(sum + 1)] for i in range(n + 1)]\n for i in range(n + 1):\n subset[i][0] = True\n for i in range(1, sum + 1):\n subset[0][i] = False\n for i in range(1, n + 1):\n for j in range(1, sum + 1):\n if j < set[i - 1]:\n subset[i][j] = subset[i - 1][j]\n if j >= set[i - 1]:\n subset[i][j] = subset[i - 1][j] or subset[i - 1][j - set[i - 1]\n ]\n return subset[n][sum]\n\n\n<assignment token>\n<code token>\n", "<function token>\n<assignment token>\n<code token>\n" ]
false
779
e60c3a6aececd97ec08ae32b552bcda795375b3b
import os import sys from shutil import copyfile def buildDocumentation(): """ Build eMonitor Documentation with sphinx :param sys.argv: * html: build html documentation in directory */docs/output/html* * pdf: build pdf documentation in directory */docs/output/pdf* """ helptext = 'usage: build_doc.py <output format> <type of documentation>' \ '\n - html: for html output' \ '\n - pdf: for pdf output' \ '\n\n - all: complete documentation' \ '\n - dev: only developer documentation' \ '\n - user: only user documentation' if len(sys.argv) != 3: print helptext sys.exit(1) if sys.argv[1] not in ['pdf', 'html']: print helptext sys.exit(1) if sys.argv[2] not in ['all', 'dev', 'user']: print helptext sys.exit(1) copyfile('docs/index_%s.rst.template' % sys.argv[2], 'index.rst') # copy main file into root directory os.system('sphinx-build -b %s -c docs -D master_doc=index . docs/output/%s/%s' % (sys.argv[1], sys.argv[1], sys.argv[2])) os.remove('index.rst') # delete config file from root directory if __name__ == '__main__': buildDocumentation()
[ "import os\nimport sys\nfrom shutil import copyfile\n\n\ndef buildDocumentation():\n \"\"\"\n Build eMonitor Documentation with sphinx\n\n :param sys.argv:\n\n * html: build html documentation in directory */docs/output/html*\n * pdf: build pdf documentation in directory */docs/output/pdf*\n\n \"\"\"\n helptext = 'usage: build_doc.py <output format> <type of documentation>' \\\n '\\n - html: for html output' \\\n '\\n - pdf: for pdf output' \\\n '\\n\\n - all: complete documentation' \\\n '\\n - dev: only developer documentation' \\\n '\\n - user: only user documentation'\n if len(sys.argv) != 3:\n print helptext\n sys.exit(1)\n\n if sys.argv[1] not in ['pdf', 'html']:\n print helptext\n sys.exit(1)\n if sys.argv[2] not in ['all', 'dev', 'user']:\n print helptext\n sys.exit(1)\n\n copyfile('docs/index_%s.rst.template' % sys.argv[2], 'index.rst') # copy main file into root directory\n os.system('sphinx-build -b %s -c docs -D master_doc=index . docs/output/%s/%s' % (sys.argv[1], sys.argv[1], sys.argv[2]))\n os.remove('index.rst') # delete config file from root directory\n\nif __name__ == '__main__':\n buildDocumentation()\n" ]
true
780
00a0668d5fcb8358b4bd7736c48e4867afc0f5b6
""" Copyright 2019 Enzo Busseti, Walaa Moursi, and Stephen Boyd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ #__all__ = ['solve'] import numpy as np import scs import ecos import time from .problem import * from .refine import * class SolverError(Exception): pass def scs_solve(A, b, c, dim_dict, init_z=None, **kwargs): """Wraps scs.solve for convenience.""" scs_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0, 'q': dim_dict['q'] if 'q' in dim_dict else [], 's': dim_dict['s'] if 's' in dim_dict else [], 'ep': dim_dict['ep'] if 'ep' in dim_dict else 0, 'ed': dim_dict['ed'] if 'ed' in dim_dict else 0, 'f': dim_dict['z'] if 'z' in dim_dict else 0} #print('scs_cones', scs_cones) sol = scs.solve({'A': A, 'b': b, 'c': c}, cone=scs_cones, **kwargs) info = sol['info'] if info['statusVal'] > 0: z = xsy2z(sol['x'], sol['s'], sol['y'], tau=1., kappa=0.) if info['statusVal'] < 0: x = np.zeros_like(sol['x']) \ if np.any(np.isnan(sol['x'])) else sol['x'] s = np.zeros_like(sol['s']) \ if np.any(np.isnan(sol['s'])) else sol['s'] y = np.zeros_like(sol['y']) \ if np.any(np.isnan(sol['y'])) else sol['y'] if np.allclose(y, 0.) and c@x < 0: obj = c@x # assert obj < 0 x /= -obj s /= -obj # print('primal res:', np.linalg.norm(A@x + s)) if np.allclose(s, 0.) and b@y < 0: obj = b@y # assert obj < 0 y /= -obj # print('dual res:', np.linalg.norm(A.T@y)) # print('SCS NONSOLVED') # print('x', x) # print('s', s) # print('y', y) z = xsy2z(x, s, y, tau=0., kappa=1.) return z, info def ecos_solve(A, b, c, dim_dict, **kwargs): """Wraps ecos.solve for convenience.""" ### # ECOS uses a different definition of the exp cone, # with y and z switched. In the future I might wrap it # (i.e., switch rows of A and elements of b, and switch # elements of the solutions s and y) but for now # I'm not supporting exp cones in ecos. ### ecos_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0, 'q': dim_dict['q'] if 'q' in dim_dict else []} # , # 'e': dim_dict['ep'] if 'ep' in dim_dict else 0} # print(ecos_cones) if ('ep' in dim_dict and dim_dict['ep'] > 0 or 's' in dim_dict and len(dim_dict['s']) > 0): raise SolverError( 'Only zero, linear, and second order cones supported.') zero = 0 if 'z' not in dim_dict else dim_dict['z'] ecos_A, ecos_G = A[:zero, :], A[zero:, :] ecos_b, ecos_h = b[:zero], b[zero:] sol = ecos.solve(c=c, G=ecos_G, h=ecos_h, dims=ecos_cones, A=ecos_A, b=ecos_b, **kwargs) solution = True x = sol['x'] s = np.concatenate([np.zeros(zero), sol['s']]) # not sure we can trust this # s = b - A@x y = np.concatenate([sol['y'], sol['z']]) if sol['info']['exitFlag'] == 0: # check that things make sense print('prim abs res.', np.linalg.norm(A@x + s - b)) print('dua abs res.', np.linalg.norm(A.T@y + c)) print('s^T y', s@y) if sol['info']['exitFlag'] in [1, 11]: # infeas solution = False obj = b@y assert (obj < 0) y /= -obj print('primal infeas. cert residual norm', np.linalg.norm(A.T@y)) #cones = dim2cones(dim_dict) proj = prod_cone.Pi(-y, *make_prod_cone_cache(dim_dict)) print('primal infeas dist from cone', np.linalg.norm(proj)) # if not (np.linalg.norm(proj) == 0.) and sol['info']['exitFlag'] == 1.: # raise SolverError x = np.zeros_like(x) s = np.zeros_like(s) if sol['info']['exitFlag'] in [2, 12]: # unbound solution = False obj = c@x assert (obj < 0) x /= -obj s /= -obj print('dual infeas. cert residual norm', np.linalg.norm(A@x + s)) proj = prod_cone.Pi(s, *make_prod_cone_cache(dim_dict)) print('dual infeas cert dist from cone', np.linalg.norm(s - proj)) # if not (np.linalg.norm(s - proj) == 0.) and sol['info']['exitFlag'] == 2.: # raise SolverError y = np.zeros_like(y) # print('ECOS SOLUTION') # print('solution', solution) # print('x', x) # print('s', s) # print('y', y) z = xsy2z(x, s, y, tau=solution, kappa=not solution) return z, sol['info'] def solve(A, b, c, dim_dict, solver='scs', solver_options={}, refine_solver_time_ratio=1., max_iters=10, verbose=False, max_lsqr_iters=20, return_z=False): solver_start = time.time() if solver == 'scs': z, info = scs_solve(A, b, c, dim_dict, **solver_options) elif solver == 'ecos': z, info = ecos_solve(A, b, c, dim_dict, **solver_options) else: raise Exception('The only supported solvers are ecos and scs') solver_time = time.time() - solver_start A = sp.csc_matrix(A) #A_tr = sp.csc_matrix(A.T) new_residual, u, v = residual_and_uv( z, (A.indptr, A.indices, A.data), b, c, make_prod_cone_cache(dim_dict)) x, s, y, tau, kappa = uv2xsytaukappa(u, v, A.shape[1]) pres = np.linalg.norm(A@x + s - b) / (1 + np.linalg.norm(b)) dres = np.linalg.norm(A.T@y + c) / (1 + np.linalg.norm(c)) gap = np.abs(c@x + b@y) / (1 + np.abs(c@x) + np.abs(b@y)) print('pres %.2e, dres %.2e, gap %.2e' % (pres, dres, gap)) z_plus = refine(A, b, c, dim_dict, z, verbose=verbose, iters=max_iters, lsqr_iters=max_lsqr_iters) # , # max_runtime=solver_time * refine_solver_time_ratio) if return_z: return z_plus, info else: new_residual, u, v =\ residual_and_uv(z_plus, (A.indptr, A.indices, A.data), b, c, make_prod_cone_cache(dim_dict)) x, s, y, tau, kappa = uv2xsytaukappa(u, v, A.shape[1]) pres = np.linalg.norm(A@x + s - b) / (1 + np.linalg.norm(b)) dres = np.linalg.norm(A.T@y + c) / (1 + np.linalg.norm(c)) gap = np.abs(c@x + b@y) / (1 + np.abs(c@x) + np.abs(b@y)) print('pres %.2e, dres %.2e, gap %.2e' % (pres, dres, gap)) return x, s, y, info
[ "\"\"\"\nCopyright 2019 Enzo Busseti, Walaa Moursi, and Stephen Boyd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n#__all__ = ['solve']\n\nimport numpy as np\nimport scs\nimport ecos\nimport time\n\nfrom .problem import *\nfrom .refine import *\n\n\nclass SolverError(Exception):\n pass\n\n\ndef scs_solve(A, b, c, dim_dict, init_z=None, **kwargs):\n \"\"\"Wraps scs.solve for convenience.\"\"\"\n scs_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0,\n 'q': dim_dict['q'] if 'q' in dim_dict else [],\n 's': dim_dict['s'] if 's' in dim_dict else [],\n 'ep': dim_dict['ep'] if 'ep' in dim_dict else 0,\n 'ed': dim_dict['ed'] if 'ed' in dim_dict else 0,\n 'f': dim_dict['z'] if 'z' in dim_dict else 0}\n #print('scs_cones', scs_cones)\n sol = scs.solve({'A': A, 'b': b,\n 'c': c},\n cone=scs_cones,\n **kwargs)\n info = sol['info']\n\n if info['statusVal'] > 0:\n z = xsy2z(sol['x'], sol['s'], sol['y'], tau=1., kappa=0.)\n\n if info['statusVal'] < 0:\n x = np.zeros_like(sol['x']) \\\n if np.any(np.isnan(sol['x'])) else sol['x']\n\n s = np.zeros_like(sol['s']) \\\n if np.any(np.isnan(sol['s'])) else sol['s']\n\n y = np.zeros_like(sol['y']) \\\n if np.any(np.isnan(sol['y'])) else sol['y']\n\n if np.allclose(y, 0.) and c@x < 0:\n obj = c@x\n # assert obj < 0\n x /= -obj\n s /= -obj\n # print('primal res:', np.linalg.norm(A@x + s))\n\n if np.allclose(s, 0.) and b@y < 0:\n obj = b@y\n # assert obj < 0\n y /= -obj\n # print('dual res:', np.linalg.norm(A.T@y))\n\n # print('SCS NONSOLVED')\n # print('x', x)\n # print('s', s)\n # print('y', y)\n\n z = xsy2z(x, s, y, tau=0., kappa=1.)\n\n return z, info\n\n\ndef ecos_solve(A, b, c, dim_dict, **kwargs):\n \"\"\"Wraps ecos.solve for convenience.\"\"\"\n\n ###\n # ECOS uses a different definition of the exp cone,\n # with y and z switched. In the future I might wrap it\n # (i.e., switch rows of A and elements of b, and switch\n # elements of the solutions s and y) but for now\n # I'm not supporting exp cones in ecos.\n ###\n\n ecos_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0,\n 'q': dim_dict['q'] if 'q' in dim_dict else []} # ,\n # 'e': dim_dict['ep'] if 'ep' in dim_dict else 0}\n # print(ecos_cones)\n if ('ep' in dim_dict and dim_dict['ep'] > 0\n or 's' in dim_dict and len(dim_dict['s']) > 0):\n raise SolverError(\n 'Only zero, linear, and second order cones supported.')\n zero = 0 if 'z' not in dim_dict else dim_dict['z']\n ecos_A, ecos_G = A[:zero, :], A[zero:, :]\n ecos_b, ecos_h = b[:zero], b[zero:]\n sol = ecos.solve(c=c, G=ecos_G, h=ecos_h, dims=ecos_cones,\n A=ecos_A, b=ecos_b, **kwargs)\n\n solution = True\n\n x = sol['x']\n s = np.concatenate([np.zeros(zero), sol['s']])\n # not sure we can trust this\n # s = b - A@x\n y = np.concatenate([sol['y'], sol['z']])\n\n if sol['info']['exitFlag'] == 0: # check that things make sense\n print('prim abs res.', np.linalg.norm(A@x + s - b))\n print('dua abs res.', np.linalg.norm(A.T@y + c))\n print('s^T y', s@y)\n\n if sol['info']['exitFlag'] in [1, 11]: # infeas\n solution = False\n obj = b@y\n assert (obj < 0)\n y /= -obj\n\n print('primal infeas. cert residual norm', np.linalg.norm(A.T@y))\n #cones = dim2cones(dim_dict)\n proj = prod_cone.Pi(-y, *make_prod_cone_cache(dim_dict))\n print('primal infeas dist from cone', np.linalg.norm(proj))\n # if not (np.linalg.norm(proj) == 0.) and sol['info']['exitFlag'] == 1.:\n # raise SolverError\n\n x = np.zeros_like(x)\n s = np.zeros_like(s)\n\n if sol['info']['exitFlag'] in [2, 12]: # unbound\n solution = False\n obj = c@x\n assert (obj < 0)\n x /= -obj\n s /= -obj\n\n print('dual infeas. cert residual norm', np.linalg.norm(A@x + s))\n proj = prod_cone.Pi(s, *make_prod_cone_cache(dim_dict))\n print('dual infeas cert dist from cone', np.linalg.norm(s - proj))\n # if not (np.linalg.norm(s - proj) == 0.) and sol['info']['exitFlag'] == 2.:\n # raise SolverError\n y = np.zeros_like(y)\n\n # print('ECOS SOLUTION')\n # print('solution', solution)\n # print('x', x)\n # print('s', s)\n # print('y', y)\n\n z = xsy2z(x, s, y, tau=solution, kappa=not solution)\n\n return z, sol['info']\n\n\ndef solve(A, b, c, dim_dict,\n solver='scs',\n solver_options={},\n refine_solver_time_ratio=1.,\n max_iters=10,\n verbose=False,\n max_lsqr_iters=20,\n return_z=False):\n\n solver_start = time.time()\n if solver == 'scs':\n z, info = scs_solve(A, b, c, dim_dict, **solver_options)\n elif solver == 'ecos':\n z, info = ecos_solve(A, b, c, dim_dict, **solver_options)\n else:\n raise Exception('The only supported solvers are ecos and scs')\n\n solver_time = time.time() - solver_start\n A = sp.csc_matrix(A)\n #A_tr = sp.csc_matrix(A.T)\n new_residual, u, v = residual_and_uv(\n z, (A.indptr, A.indices, A.data), b, c, make_prod_cone_cache(dim_dict))\n x, s, y, tau, kappa = uv2xsytaukappa(u, v, A.shape[1])\n\n pres = np.linalg.norm(A@x + s - b) / (1 + np.linalg.norm(b))\n dres = np.linalg.norm(A.T@y + c) / (1 + np.linalg.norm(c))\n gap = np.abs(c@x + b@y) / (1 + np.abs(c@x) + np.abs(b@y))\n\n print('pres %.2e, dres %.2e, gap %.2e' % (pres, dres, gap))\n\n z_plus = refine(A, b, c, dim_dict, z,\n verbose=verbose,\n iters=max_iters,\n lsqr_iters=max_lsqr_iters) # ,\n # max_runtime=solver_time * refine_solver_time_ratio)\n\n if return_z:\n return z_plus, info\n else:\n new_residual, u, v =\\\n residual_and_uv(z_plus, (A.indptr, A.indices, A.data), b, c,\n make_prod_cone_cache(dim_dict))\n x, s, y, tau, kappa = uv2xsytaukappa(u, v, A.shape[1])\n pres = np.linalg.norm(A@x + s - b) / (1 + np.linalg.norm(b))\n dres = np.linalg.norm(A.T@y + c) / (1 + np.linalg.norm(c))\n gap = np.abs(c@x + b@y) / (1 + np.abs(c@x) + np.abs(b@y))\n print('pres %.2e, dres %.2e, gap %.2e' % (pres, dres, gap))\n return x, s, y, info\n", "<docstring token>\nimport numpy as np\nimport scs\nimport ecos\nimport time\nfrom .problem import *\nfrom .refine import *\n\n\nclass SolverError(Exception):\n pass\n\n\ndef scs_solve(A, b, c, dim_dict, init_z=None, **kwargs):\n \"\"\"Wraps scs.solve for convenience.\"\"\"\n scs_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0, 'q': \n dim_dict['q'] if 'q' in dim_dict else [], 's': dim_dict['s'] if 's' in\n dim_dict else [], 'ep': dim_dict['ep'] if 'ep' in dim_dict else 0,\n 'ed': dim_dict['ed'] if 'ed' in dim_dict else 0, 'f': dim_dict['z'] if\n 'z' in dim_dict else 0}\n sol = scs.solve({'A': A, 'b': b, 'c': c}, cone=scs_cones, **kwargs)\n info = sol['info']\n if info['statusVal'] > 0:\n z = xsy2z(sol['x'], sol['s'], sol['y'], tau=1.0, kappa=0.0)\n if info['statusVal'] < 0:\n x = np.zeros_like(sol['x']) if np.any(np.isnan(sol['x'])) else sol['x']\n s = np.zeros_like(sol['s']) if np.any(np.isnan(sol['s'])) else sol['s']\n y = np.zeros_like(sol['y']) if np.any(np.isnan(sol['y'])) else sol['y']\n if np.allclose(y, 0.0) and c @ x < 0:\n obj = c @ x\n x /= -obj\n s /= -obj\n if np.allclose(s, 0.0) and b @ y < 0:\n obj = b @ y\n y /= -obj\n z = xsy2z(x, s, y, tau=0.0, kappa=1.0)\n return z, info\n\n\ndef ecos_solve(A, b, c, dim_dict, **kwargs):\n \"\"\"Wraps ecos.solve for convenience.\"\"\"\n ecos_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0, 'q': \n dim_dict['q'] if 'q' in dim_dict else []}\n if 'ep' in dim_dict and dim_dict['ep'] > 0 or 's' in dim_dict and len(\n dim_dict['s']) > 0:\n raise SolverError(\n 'Only zero, linear, and second order cones supported.')\n zero = 0 if 'z' not in dim_dict else dim_dict['z']\n ecos_A, ecos_G = A[:zero, :], A[zero:, :]\n ecos_b, ecos_h = b[:zero], b[zero:]\n sol = ecos.solve(c=c, G=ecos_G, h=ecos_h, dims=ecos_cones, A=ecos_A, b=\n ecos_b, **kwargs)\n solution = True\n x = sol['x']\n s = np.concatenate([np.zeros(zero), sol['s']])\n y = np.concatenate([sol['y'], sol['z']])\n if sol['info']['exitFlag'] == 0:\n print('prim abs res.', np.linalg.norm(A @ x + s - b))\n print('dua abs res.', np.linalg.norm(A.T @ y + c))\n print('s^T y', s @ y)\n if sol['info']['exitFlag'] in [1, 11]:\n solution = False\n obj = b @ y\n assert obj < 0\n y /= -obj\n print('primal infeas. cert residual norm', np.linalg.norm(A.T @ y))\n proj = prod_cone.Pi(-y, *make_prod_cone_cache(dim_dict))\n print('primal infeas dist from cone', np.linalg.norm(proj))\n x = np.zeros_like(x)\n s = np.zeros_like(s)\n if sol['info']['exitFlag'] in [2, 12]:\n solution = False\n obj = c @ x\n assert obj < 0\n x /= -obj\n s /= -obj\n print('dual infeas. cert residual norm', np.linalg.norm(A @ x + s))\n proj = prod_cone.Pi(s, *make_prod_cone_cache(dim_dict))\n print('dual infeas cert dist from cone', np.linalg.norm(s - proj))\n y = np.zeros_like(y)\n z = xsy2z(x, s, y, tau=solution, kappa=not solution)\n return z, sol['info']\n\n\ndef solve(A, b, c, dim_dict, solver='scs', solver_options={},\n refine_solver_time_ratio=1.0, max_iters=10, verbose=False,\n max_lsqr_iters=20, return_z=False):\n solver_start = time.time()\n if solver == 'scs':\n z, info = scs_solve(A, b, c, dim_dict, **solver_options)\n elif solver == 'ecos':\n z, info = ecos_solve(A, b, c, dim_dict, **solver_options)\n else:\n raise Exception('The only supported solvers are ecos and scs')\n solver_time = time.time() - solver_start\n A = sp.csc_matrix(A)\n new_residual, u, v = residual_and_uv(z, (A.indptr, A.indices, A.data),\n b, c, make_prod_cone_cache(dim_dict))\n x, s, y, tau, kappa = uv2xsytaukappa(u, v, A.shape[1])\n pres = np.linalg.norm(A @ x + s - b) / (1 + np.linalg.norm(b))\n dres = np.linalg.norm(A.T @ y + c) / (1 + np.linalg.norm(c))\n gap = np.abs(c @ x + b @ y) / (1 + np.abs(c @ x) + np.abs(b @ y))\n print('pres %.2e, dres %.2e, gap %.2e' % (pres, dres, gap))\n z_plus = refine(A, b, c, dim_dict, z, verbose=verbose, iters=max_iters,\n lsqr_iters=max_lsqr_iters)\n if return_z:\n return z_plus, info\n else:\n new_residual, u, v = residual_and_uv(z_plus, (A.indptr, A.indices,\n A.data), b, c, make_prod_cone_cache(dim_dict))\n x, s, y, tau, kappa = uv2xsytaukappa(u, v, A.shape[1])\n pres = np.linalg.norm(A @ x + s - b) / (1 + np.linalg.norm(b))\n dres = np.linalg.norm(A.T @ y + c) / (1 + np.linalg.norm(c))\n gap = np.abs(c @ x + b @ y) / (1 + np.abs(c @ x) + np.abs(b @ y))\n print('pres %.2e, dres %.2e, gap %.2e' % (pres, dres, gap))\n return x, s, y, info\n", "<docstring token>\n<import token>\n\n\nclass SolverError(Exception):\n pass\n\n\ndef scs_solve(A, b, c, dim_dict, init_z=None, **kwargs):\n \"\"\"Wraps scs.solve for convenience.\"\"\"\n scs_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0, 'q': \n dim_dict['q'] if 'q' in dim_dict else [], 's': dim_dict['s'] if 's' in\n dim_dict else [], 'ep': dim_dict['ep'] if 'ep' in dim_dict else 0,\n 'ed': dim_dict['ed'] if 'ed' in dim_dict else 0, 'f': dim_dict['z'] if\n 'z' in dim_dict else 0}\n sol = scs.solve({'A': A, 'b': b, 'c': c}, cone=scs_cones, **kwargs)\n info = sol['info']\n if info['statusVal'] > 0:\n z = xsy2z(sol['x'], sol['s'], sol['y'], tau=1.0, kappa=0.0)\n if info['statusVal'] < 0:\n x = np.zeros_like(sol['x']) if np.any(np.isnan(sol['x'])) else sol['x']\n s = np.zeros_like(sol['s']) if np.any(np.isnan(sol['s'])) else sol['s']\n y = np.zeros_like(sol['y']) if np.any(np.isnan(sol['y'])) else sol['y']\n if np.allclose(y, 0.0) and c @ x < 0:\n obj = c @ x\n x /= -obj\n s /= -obj\n if np.allclose(s, 0.0) and b @ y < 0:\n obj = b @ y\n y /= -obj\n z = xsy2z(x, s, y, tau=0.0, kappa=1.0)\n return z, info\n\n\ndef ecos_solve(A, b, c, dim_dict, **kwargs):\n \"\"\"Wraps ecos.solve for convenience.\"\"\"\n ecos_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0, 'q': \n dim_dict['q'] if 'q' in dim_dict else []}\n if 'ep' in dim_dict and dim_dict['ep'] > 0 or 's' in dim_dict and len(\n dim_dict['s']) > 0:\n raise SolverError(\n 'Only zero, linear, and second order cones supported.')\n zero = 0 if 'z' not in dim_dict else dim_dict['z']\n ecos_A, ecos_G = A[:zero, :], A[zero:, :]\n ecos_b, ecos_h = b[:zero], b[zero:]\n sol = ecos.solve(c=c, G=ecos_G, h=ecos_h, dims=ecos_cones, A=ecos_A, b=\n ecos_b, **kwargs)\n solution = True\n x = sol['x']\n s = np.concatenate([np.zeros(zero), sol['s']])\n y = np.concatenate([sol['y'], sol['z']])\n if sol['info']['exitFlag'] == 0:\n print('prim abs res.', np.linalg.norm(A @ x + s - b))\n print('dua abs res.', np.linalg.norm(A.T @ y + c))\n print('s^T y', s @ y)\n if sol['info']['exitFlag'] in [1, 11]:\n solution = False\n obj = b @ y\n assert obj < 0\n y /= -obj\n print('primal infeas. cert residual norm', np.linalg.norm(A.T @ y))\n proj = prod_cone.Pi(-y, *make_prod_cone_cache(dim_dict))\n print('primal infeas dist from cone', np.linalg.norm(proj))\n x = np.zeros_like(x)\n s = np.zeros_like(s)\n if sol['info']['exitFlag'] in [2, 12]:\n solution = False\n obj = c @ x\n assert obj < 0\n x /= -obj\n s /= -obj\n print('dual infeas. cert residual norm', np.linalg.norm(A @ x + s))\n proj = prod_cone.Pi(s, *make_prod_cone_cache(dim_dict))\n print('dual infeas cert dist from cone', np.linalg.norm(s - proj))\n y = np.zeros_like(y)\n z = xsy2z(x, s, y, tau=solution, kappa=not solution)\n return z, sol['info']\n\n\ndef solve(A, b, c, dim_dict, solver='scs', solver_options={},\n refine_solver_time_ratio=1.0, max_iters=10, verbose=False,\n max_lsqr_iters=20, return_z=False):\n solver_start = time.time()\n if solver == 'scs':\n z, info = scs_solve(A, b, c, dim_dict, **solver_options)\n elif solver == 'ecos':\n z, info = ecos_solve(A, b, c, dim_dict, **solver_options)\n else:\n raise Exception('The only supported solvers are ecos and scs')\n solver_time = time.time() - solver_start\n A = sp.csc_matrix(A)\n new_residual, u, v = residual_and_uv(z, (A.indptr, A.indices, A.data),\n b, c, make_prod_cone_cache(dim_dict))\n x, s, y, tau, kappa = uv2xsytaukappa(u, v, A.shape[1])\n pres = np.linalg.norm(A @ x + s - b) / (1 + np.linalg.norm(b))\n dres = np.linalg.norm(A.T @ y + c) / (1 + np.linalg.norm(c))\n gap = np.abs(c @ x + b @ y) / (1 + np.abs(c @ x) + np.abs(b @ y))\n print('pres %.2e, dres %.2e, gap %.2e' % (pres, dres, gap))\n z_plus = refine(A, b, c, dim_dict, z, verbose=verbose, iters=max_iters,\n lsqr_iters=max_lsqr_iters)\n if return_z:\n return z_plus, info\n else:\n new_residual, u, v = residual_and_uv(z_plus, (A.indptr, A.indices,\n A.data), b, c, make_prod_cone_cache(dim_dict))\n x, s, y, tau, kappa = uv2xsytaukappa(u, v, A.shape[1])\n pres = np.linalg.norm(A @ x + s - b) / (1 + np.linalg.norm(b))\n dres = np.linalg.norm(A.T @ y + c) / (1 + np.linalg.norm(c))\n gap = np.abs(c @ x + b @ y) / (1 + np.abs(c @ x) + np.abs(b @ y))\n print('pres %.2e, dres %.2e, gap %.2e' % (pres, dres, gap))\n return x, s, y, info\n", "<docstring token>\n<import token>\n\n\nclass SolverError(Exception):\n pass\n\n\ndef scs_solve(A, b, c, dim_dict, init_z=None, **kwargs):\n \"\"\"Wraps scs.solve for convenience.\"\"\"\n scs_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0, 'q': \n dim_dict['q'] if 'q' in dim_dict else [], 's': dim_dict['s'] if 's' in\n dim_dict else [], 'ep': dim_dict['ep'] if 'ep' in dim_dict else 0,\n 'ed': dim_dict['ed'] if 'ed' in dim_dict else 0, 'f': dim_dict['z'] if\n 'z' in dim_dict else 0}\n sol = scs.solve({'A': A, 'b': b, 'c': c}, cone=scs_cones, **kwargs)\n info = sol['info']\n if info['statusVal'] > 0:\n z = xsy2z(sol['x'], sol['s'], sol['y'], tau=1.0, kappa=0.0)\n if info['statusVal'] < 0:\n x = np.zeros_like(sol['x']) if np.any(np.isnan(sol['x'])) else sol['x']\n s = np.zeros_like(sol['s']) if np.any(np.isnan(sol['s'])) else sol['s']\n y = np.zeros_like(sol['y']) if np.any(np.isnan(sol['y'])) else sol['y']\n if np.allclose(y, 0.0) and c @ x < 0:\n obj = c @ x\n x /= -obj\n s /= -obj\n if np.allclose(s, 0.0) and b @ y < 0:\n obj = b @ y\n y /= -obj\n z = xsy2z(x, s, y, tau=0.0, kappa=1.0)\n return z, info\n\n\ndef ecos_solve(A, b, c, dim_dict, **kwargs):\n \"\"\"Wraps ecos.solve for convenience.\"\"\"\n ecos_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0, 'q': \n dim_dict['q'] if 'q' in dim_dict else []}\n if 'ep' in dim_dict and dim_dict['ep'] > 0 or 's' in dim_dict and len(\n dim_dict['s']) > 0:\n raise SolverError(\n 'Only zero, linear, and second order cones supported.')\n zero = 0 if 'z' not in dim_dict else dim_dict['z']\n ecos_A, ecos_G = A[:zero, :], A[zero:, :]\n ecos_b, ecos_h = b[:zero], b[zero:]\n sol = ecos.solve(c=c, G=ecos_G, h=ecos_h, dims=ecos_cones, A=ecos_A, b=\n ecos_b, **kwargs)\n solution = True\n x = sol['x']\n s = np.concatenate([np.zeros(zero), sol['s']])\n y = np.concatenate([sol['y'], sol['z']])\n if sol['info']['exitFlag'] == 0:\n print('prim abs res.', np.linalg.norm(A @ x + s - b))\n print('dua abs res.', np.linalg.norm(A.T @ y + c))\n print('s^T y', s @ y)\n if sol['info']['exitFlag'] in [1, 11]:\n solution = False\n obj = b @ y\n assert obj < 0\n y /= -obj\n print('primal infeas. cert residual norm', np.linalg.norm(A.T @ y))\n proj = prod_cone.Pi(-y, *make_prod_cone_cache(dim_dict))\n print('primal infeas dist from cone', np.linalg.norm(proj))\n x = np.zeros_like(x)\n s = np.zeros_like(s)\n if sol['info']['exitFlag'] in [2, 12]:\n solution = False\n obj = c @ x\n assert obj < 0\n x /= -obj\n s /= -obj\n print('dual infeas. cert residual norm', np.linalg.norm(A @ x + s))\n proj = prod_cone.Pi(s, *make_prod_cone_cache(dim_dict))\n print('dual infeas cert dist from cone', np.linalg.norm(s - proj))\n y = np.zeros_like(y)\n z = xsy2z(x, s, y, tau=solution, kappa=not solution)\n return z, sol['info']\n\n\n<function token>\n", "<docstring token>\n<import token>\n\n\nclass SolverError(Exception):\n pass\n\n\n<function token>\n\n\ndef ecos_solve(A, b, c, dim_dict, **kwargs):\n \"\"\"Wraps ecos.solve for convenience.\"\"\"\n ecos_cones = {'l': dim_dict['l'] if 'l' in dim_dict else 0, 'q': \n dim_dict['q'] if 'q' in dim_dict else []}\n if 'ep' in dim_dict and dim_dict['ep'] > 0 or 's' in dim_dict and len(\n dim_dict['s']) > 0:\n raise SolverError(\n 'Only zero, linear, and second order cones supported.')\n zero = 0 if 'z' not in dim_dict else dim_dict['z']\n ecos_A, ecos_G = A[:zero, :], A[zero:, :]\n ecos_b, ecos_h = b[:zero], b[zero:]\n sol = ecos.solve(c=c, G=ecos_G, h=ecos_h, dims=ecos_cones, A=ecos_A, b=\n ecos_b, **kwargs)\n solution = True\n x = sol['x']\n s = np.concatenate([np.zeros(zero), sol['s']])\n y = np.concatenate([sol['y'], sol['z']])\n if sol['info']['exitFlag'] == 0:\n print('prim abs res.', np.linalg.norm(A @ x + s - b))\n print('dua abs res.', np.linalg.norm(A.T @ y + c))\n print('s^T y', s @ y)\n if sol['info']['exitFlag'] in [1, 11]:\n solution = False\n obj = b @ y\n assert obj < 0\n y /= -obj\n print('primal infeas. cert residual norm', np.linalg.norm(A.T @ y))\n proj = prod_cone.Pi(-y, *make_prod_cone_cache(dim_dict))\n print('primal infeas dist from cone', np.linalg.norm(proj))\n x = np.zeros_like(x)\n s = np.zeros_like(s)\n if sol['info']['exitFlag'] in [2, 12]:\n solution = False\n obj = c @ x\n assert obj < 0\n x /= -obj\n s /= -obj\n print('dual infeas. cert residual norm', np.linalg.norm(A @ x + s))\n proj = prod_cone.Pi(s, *make_prod_cone_cache(dim_dict))\n print('dual infeas cert dist from cone', np.linalg.norm(s - proj))\n y = np.zeros_like(y)\n z = xsy2z(x, s, y, tau=solution, kappa=not solution)\n return z, sol['info']\n\n\n<function token>\n", "<docstring token>\n<import token>\n\n\nclass SolverError(Exception):\n pass\n\n\n<function token>\n<function token>\n<function token>\n", "<docstring token>\n<import token>\n<class token>\n<function token>\n<function token>\n<function token>\n" ]
false
781
f5c277da2b22debe26327464ae736892360059b4
import numpy as np import matplotlib.pyplot as plt import pandas as pd month=['Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May'] df = pd.DataFrame([[53, 0, 5, 3, 3],[51, 0, 1, 3, 2],[70, 4, 7, 5, 1],[66, 4, 1, 4, 2],[64, 4, 4, 3, 2],[69, 4, 7, 8, 2],[45, 2, 8, 4, 2],[29, 1, 6, 6, 1],[56, 4, 4, 2, 2],[41, 2, 2, 2, 1],[3, 0, 0, 0, 0],[8, 0, 0, 0, 0]],columns=['1000','2000','3000','4000','5000'],index=month) plt.pcolor(df) plt.colorbar() plt.yticks(np.arange(0.5, len(df.index), 1), df.index) plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns) plt.show()
[ "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nmonth=['Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May']\r\ndf = pd.DataFrame([[53, 0, 5, 3, 3],[51, 0, 1, 3, 2],[70, 4, 7, 5, 1],[66, 4, 1, 4, 2],[64, 4, 4, 3, 2],[69, 4, 7, 8, 2],[45, 2, 8, 4, 2],[29, 1, 6, 6, 1],[56, 4, 4, 2, 2],[41, 2, 2, 2, 1],[3, 0, 0, 0, 0],[8, 0, 0, 0, 0]],columns=['1000','2000','3000','4000','5000'],index=month)\r\nplt.pcolor(df)\r\nplt.colorbar()\r\nplt.yticks(np.arange(0.5, len(df.index), 1), df.index)\r\nplt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)\r\nplt.show()\r\n\r\n\r\n", "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nmonth = ['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb',\n 'Mar', 'Apr', 'May']\ndf = pd.DataFrame([[53, 0, 5, 3, 3], [51, 0, 1, 3, 2], [70, 4, 7, 5, 1], [\n 66, 4, 1, 4, 2], [64, 4, 4, 3, 2], [69, 4, 7, 8, 2], [45, 2, 8, 4, 2],\n [29, 1, 6, 6, 1], [56, 4, 4, 2, 2], [41, 2, 2, 2, 1], [3, 0, 0, 0, 0],\n [8, 0, 0, 0, 0]], columns=['1000', '2000', '3000', '4000', '5000'],\n index=month)\nplt.pcolor(df)\nplt.colorbar()\nplt.yticks(np.arange(0.5, len(df.index), 1), df.index)\nplt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)\nplt.show()\n", "<import token>\nmonth = ['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb',\n 'Mar', 'Apr', 'May']\ndf = pd.DataFrame([[53, 0, 5, 3, 3], [51, 0, 1, 3, 2], [70, 4, 7, 5, 1], [\n 66, 4, 1, 4, 2], [64, 4, 4, 3, 2], [69, 4, 7, 8, 2], [45, 2, 8, 4, 2],\n [29, 1, 6, 6, 1], [56, 4, 4, 2, 2], [41, 2, 2, 2, 1], [3, 0, 0, 0, 0],\n [8, 0, 0, 0, 0]], columns=['1000', '2000', '3000', '4000', '5000'],\n index=month)\nplt.pcolor(df)\nplt.colorbar()\nplt.yticks(np.arange(0.5, len(df.index), 1), df.index)\nplt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)\nplt.show()\n", "<import token>\n<assignment token>\nplt.pcolor(df)\nplt.colorbar()\nplt.yticks(np.arange(0.5, len(df.index), 1), df.index)\nplt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)\nplt.show()\n", "<import token>\n<assignment token>\n<code token>\n" ]
false
782
5c2a6802e89314c25f0264bbe2bc7ed2689a255a
a=input("Please enter the elements with spaces between them:").split() n=len(a) for i in range(n): a[i]=int(a[i]) for i in range(n-1): for j in range(n-i-1): if a[j]>a[j+1]: a[j],a[j+1]=a[j+1],a[j] print("Sortes array :",a)
[ "a=input(\"Please enter the elements with spaces between them:\").split()\nn=len(a)\nfor i in range(n):\n a[i]=int(a[i])\nfor i in range(n-1):\n for j in range(n-i-1):\n if a[j]>a[j+1]:\n a[j],a[j+1]=a[j+1],a[j]\nprint(\"Sortes array :\",a)", "a = input('Please enter the elements with spaces between them:').split()\nn = len(a)\nfor i in range(n):\n a[i] = int(a[i])\nfor i in range(n - 1):\n for j in range(n - i - 1):\n if a[j] > a[j + 1]:\n a[j], a[j + 1] = a[j + 1], a[j]\nprint('Sortes array :', a)\n", "<assignment token>\nfor i in range(n):\n a[i] = int(a[i])\nfor i in range(n - 1):\n for j in range(n - i - 1):\n if a[j] > a[j + 1]:\n a[j], a[j + 1] = a[j + 1], a[j]\nprint('Sortes array :', a)\n", "<assignment token>\n<code token>\n" ]
false
783
20f0480ee7e0782b23ec8ade150cdd8d8ad718bb
from math import pow from math import tan import plotly.figure_factory as ff from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot def euler(): h = 0.1 x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5] y_eval = [0.0] delta_y = [0.0] y_real = [0.0] eps = [0.0] for i in range(1, len(x)): y_eval.append(y_eval[i - 1] + h * fun(x[i - 1], y_eval[i - 1])) delta_y.append(h * fun(y_eval[i], x[i])) y_real.append(real_fun(x[i])) eps.append(abs(y_real[i] - y_eval[i])) # print in table format print(y_eval) print(delta_y) print(y_real) print(eps) data_matrix = [ ['k', 'x', 'y', 'delta_y', 'y_real', 'eps'] ] for i in range(0, len(x)): data_matrix.append([i, x[i], y_eval[i], delta_y[i], y_real[i], eps[i]]) table = ff.create_table(data_matrix) plot(table) def fun(x, y): return pow(x + y, 2) def real_fun(x): return tan(x) - x euler()
[ "from math import pow\nfrom math import tan\n\nimport plotly.figure_factory as ff\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\n\ndef euler():\n h = 0.1\n x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]\n y_eval = [0.0]\n delta_y = [0.0]\n y_real = [0.0]\n eps = [0.0]\n\n for i in range(1, len(x)):\n y_eval.append(y_eval[i - 1] + h * fun(x[i - 1], y_eval[i - 1]))\n delta_y.append(h * fun(y_eval[i], x[i]))\n y_real.append(real_fun(x[i]))\n eps.append(abs(y_real[i] - y_eval[i]))\n\n # print in table format\n print(y_eval)\n print(delta_y)\n print(y_real)\n print(eps)\n\n data_matrix = [\n ['k', 'x', 'y', 'delta_y', 'y_real', 'eps']\n ]\n for i in range(0, len(x)):\n data_matrix.append([i, x[i], y_eval[i], delta_y[i], y_real[i], eps[i]])\n\n table = ff.create_table(data_matrix)\n plot(table)\n\n\ndef fun(x, y):\n return pow(x + y, 2)\n\n\ndef real_fun(x):\n return tan(x) - x\n\n\neuler()\n", "from math import pow\nfrom math import tan\nimport plotly.figure_factory as ff\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\n\n\ndef euler():\n h = 0.1\n x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]\n y_eval = [0.0]\n delta_y = [0.0]\n y_real = [0.0]\n eps = [0.0]\n for i in range(1, len(x)):\n y_eval.append(y_eval[i - 1] + h * fun(x[i - 1], y_eval[i - 1]))\n delta_y.append(h * fun(y_eval[i], x[i]))\n y_real.append(real_fun(x[i]))\n eps.append(abs(y_real[i] - y_eval[i]))\n print(y_eval)\n print(delta_y)\n print(y_real)\n print(eps)\n data_matrix = [['k', 'x', 'y', 'delta_y', 'y_real', 'eps']]\n for i in range(0, len(x)):\n data_matrix.append([i, x[i], y_eval[i], delta_y[i], y_real[i], eps[i]])\n table = ff.create_table(data_matrix)\n plot(table)\n\n\ndef fun(x, y):\n return pow(x + y, 2)\n\n\ndef real_fun(x):\n return tan(x) - x\n\n\neuler()\n", "<import token>\n\n\ndef euler():\n h = 0.1\n x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]\n y_eval = [0.0]\n delta_y = [0.0]\n y_real = [0.0]\n eps = [0.0]\n for i in range(1, len(x)):\n y_eval.append(y_eval[i - 1] + h * fun(x[i - 1], y_eval[i - 1]))\n delta_y.append(h * fun(y_eval[i], x[i]))\n y_real.append(real_fun(x[i]))\n eps.append(abs(y_real[i] - y_eval[i]))\n print(y_eval)\n print(delta_y)\n print(y_real)\n print(eps)\n data_matrix = [['k', 'x', 'y', 'delta_y', 'y_real', 'eps']]\n for i in range(0, len(x)):\n data_matrix.append([i, x[i], y_eval[i], delta_y[i], y_real[i], eps[i]])\n table = ff.create_table(data_matrix)\n plot(table)\n\n\ndef fun(x, y):\n return pow(x + y, 2)\n\n\ndef real_fun(x):\n return tan(x) - x\n\n\neuler()\n", "<import token>\n\n\ndef euler():\n h = 0.1\n x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]\n y_eval = [0.0]\n delta_y = [0.0]\n y_real = [0.0]\n eps = [0.0]\n for i in range(1, len(x)):\n y_eval.append(y_eval[i - 1] + h * fun(x[i - 1], y_eval[i - 1]))\n delta_y.append(h * fun(y_eval[i], x[i]))\n y_real.append(real_fun(x[i]))\n eps.append(abs(y_real[i] - y_eval[i]))\n print(y_eval)\n print(delta_y)\n print(y_real)\n print(eps)\n data_matrix = [['k', 'x', 'y', 'delta_y', 'y_real', 'eps']]\n for i in range(0, len(x)):\n data_matrix.append([i, x[i], y_eval[i], delta_y[i], y_real[i], eps[i]])\n table = ff.create_table(data_matrix)\n plot(table)\n\n\ndef fun(x, y):\n return pow(x + y, 2)\n\n\ndef real_fun(x):\n return tan(x) - x\n\n\n<code token>\n", "<import token>\n\n\ndef euler():\n h = 0.1\n x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]\n y_eval = [0.0]\n delta_y = [0.0]\n y_real = [0.0]\n eps = [0.0]\n for i in range(1, len(x)):\n y_eval.append(y_eval[i - 1] + h * fun(x[i - 1], y_eval[i - 1]))\n delta_y.append(h * fun(y_eval[i], x[i]))\n y_real.append(real_fun(x[i]))\n eps.append(abs(y_real[i] - y_eval[i]))\n print(y_eval)\n print(delta_y)\n print(y_real)\n print(eps)\n data_matrix = [['k', 'x', 'y', 'delta_y', 'y_real', 'eps']]\n for i in range(0, len(x)):\n data_matrix.append([i, x[i], y_eval[i], delta_y[i], y_real[i], eps[i]])\n table = ff.create_table(data_matrix)\n plot(table)\n\n\n<function token>\n\n\ndef real_fun(x):\n return tan(x) - x\n\n\n<code token>\n", "<import token>\n\n\ndef euler():\n h = 0.1\n x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]\n y_eval = [0.0]\n delta_y = [0.0]\n y_real = [0.0]\n eps = [0.0]\n for i in range(1, len(x)):\n y_eval.append(y_eval[i - 1] + h * fun(x[i - 1], y_eval[i - 1]))\n delta_y.append(h * fun(y_eval[i], x[i]))\n y_real.append(real_fun(x[i]))\n eps.append(abs(y_real[i] - y_eval[i]))\n print(y_eval)\n print(delta_y)\n print(y_real)\n print(eps)\n data_matrix = [['k', 'x', 'y', 'delta_y', 'y_real', 'eps']]\n for i in range(0, len(x)):\n data_matrix.append([i, x[i], y_eval[i], delta_y[i], y_real[i], eps[i]])\n table = ff.create_table(data_matrix)\n plot(table)\n\n\n<function token>\n<function token>\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
784
f145274c8caa1e725d12003874eb54a580a6e35e
dic = {"city": "Moscow", "temperature": 20} # print(dic["city"]) # dic["temperature"] -= 5 # print(dic) print(dic.get("country", "Russia")) dic["date"] = "27.05.2019" print(dic)
[ "dic = {\"city\": \"Moscow\", \"temperature\": 20}\r\n# print(dic[\"city\"])\r\n# dic[\"temperature\"] -= 5\r\n# print(dic)\r\nprint(dic.get(\"country\", \"Russia\"))\r\ndic[\"date\"] = \"27.05.2019\" \r\nprint(dic)", "dic = {'city': 'Moscow', 'temperature': 20}\nprint(dic.get('country', 'Russia'))\ndic['date'] = '27.05.2019'\nprint(dic)\n", "<assignment token>\nprint(dic.get('country', 'Russia'))\n<assignment token>\nprint(dic)\n", "<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
785
038b8206f77b325bf43fc753f6cee8b4278f4bc9
import logging import numpy as np from deprecated import deprecated from pycqed.measurement.randomized_benchmarking.clifford_group import clifford_lookuptable from pycqed.measurement.randomized_benchmarking.clifford_decompositions import gate_decomposition from pycqed.measurement.randomized_benchmarking.two_qubit_clifford_group import Clifford, SingleQubitClifford, TwoQubitClifford def calculate_net_clifford( rb_clifford_indices: np.ndarray, Cliff:Clifford = SingleQubitClifford ) -> Clifford: """ Calculate the net-clifford from a list of cliffords indices. Args: rb_clifford_indices: list or array of integers specifying the cliffords. Cliff : Clifford object used to determine what inversion technique to use and what indices are valid. Valid choices are `SingleQubitClifford` and `TwoQubitClifford` Returns: net_clifford: a `Clifford` object containing the net-clifford. the Clifford index is contained in the Clifford.idx attribute. Note: the order corresponds to the order in a pulse sequence but is the reverse of what it would be in a chained dot product. """ # Calculate the net clifford net_clifford = Cliff(0) # assumes element 0 is the Identity for idx in rb_clifford_indices: # [2020-07-03 Victor] the `abs` below was to remove the sign that was # used to treat CZ as CZ and not the member of CNOT-like set of gates # Using negative sign convention (i.e. `-4368` for the interleaved CZ) # was a bad choice because there is no such thing as negative zero and # the clifford numer 0 is the identity that is necessary for # benchmarking an idling identity with the same duration as the time # allocated to the flux pulses, for example # cliff = Clifford(abs(idx)) # Deprecated! assert idx > -1, ( "The convention for interleaved gates has changed! " + "See notes in this function. " + "You probably need to specify {}".format(100_000 + abs(idx)) ) # In order to benchmark specific gates (and not cliffords), e.g. CZ but # not as a member of the CNOT-like set of gates, or an identity with # the same duration as the CZ we use, by convention, when specifying # the interleaved gate, the index of the corresponding # clifford + 100000, this is to keep it readable and bigger than the # 11520 elements of the Two-qubit Clifford group C2 # corresponding clifford cliff = Cliff(idx % 100_000) # order of operators applied in is right to left, therefore # the new operator is applied on the left side. net_clifford = cliff * net_clifford return net_clifford # FIXME: deprecate along with randomized_benchmarking_sequence_old() def calculate_recovery_clifford(cl_in, desired_cl=0): """ Extracts the clifford that has to be applied to cl_in to make the net operation correspond to desired_cl from the clifford lookuptable. This operation should perform the inverse of calculate_net_clifford """ row = list(clifford_lookuptable[cl_in]) return row.index(desired_cl) @deprecated(version='0.4', reason='not used within pyqed') def decompose_clifford_seq(clifford_sequence, gate_decomposition=gate_decomposition): decomposed_seq = [] for cl in clifford_sequence: decomposed_seq.extend(gate_decomposition[cl]) return decomposed_seq @deprecated(version='0.4', reason='not used within pyqed') def convert_clifford_sequence_to_tape( clifford_sequence, lutmapping, gate_decomposition=gate_decomposition ): """ Converts a list of qubit operations to the relevant pulse elements This method will be overwritten depending on the hardware implementation. """ # This is intended to replace the block below but not done because # I cannot test it at this moment (MAR) # decomposed_seq = decompose_clifford_seq(clifford_sequence, # gate_decomposition) decomposed_seq = [] for cl in clifford_sequence: decomposed_seq.extend(gate_decomposition[cl]) tape = [] for g in decomposed_seq: tape.append(lutmapping.index(g)) return tape # FIXME: deprecate, also including calculate_recovery_clifford() and clifford_lookuptable def randomized_benchmarking_sequence_old( n_cl: int, desired_net_cl: int = 0, seed: int = None ): """ Generates a sequence of "n_cl" random single qubit Cliffords followed by a a recovery Clifford to make the net result correspond to the "desired_net_cl". Args: n_cl (int) : number of Cliffords desired_net_cl (int) : idx of the desired net clifford seed (int) : seed used to initialize the random number generator. The default behaviour is that the net clifford corresponds to an identity ("0"). If you want e.g. an inverting sequence you should set the desired_net_cl to "3" (corresponds to Pauli X). """ logging.warning( "deprecation warning, only exists for testing equivalence to new function." ) if seed is None: rb_cliffords = np.random.randint(0, 24, int(n_cl)) else: rng_seed = np.random.RandomState(seed) rb_cliffords = rng_seed.randint(0, 24, int(n_cl)) net_clifford = calculate_net_clifford(rb_cliffords).idx recovery_clifford = calculate_recovery_clifford(net_clifford, desired_net_cl) rb_cliffords = np.append(rb_cliffords, recovery_clifford) return rb_cliffords ############################################################################## # New style RB sequences (using the hash-table method) compatible # with Clifford object. # More advanced sequences are available using this method. ############################################################################## def randomized_benchmarking_sequence( n_cl: int, desired_net_cl: int = 0, number_of_qubits: int = 1, max_clifford_idx: int = 11520, interleaving_cl: int = None, seed: int = None, ) -> np.ndarray: """ Generates a randomized benchmarking sequence for the one or two qubit clifford group. Args: n_cl (int) : number of Cliffords desired_net_cl (int) : idx of the desired net clifford, if None is specified no recovery Clifford is calculated number_of_qubits(int): used to determine if Cliffords are drawn from the single qubit or two qubit clifford group. max_clifford_idx (int): used to set the index of the highest random clifford generated. Useful to generate e.g., simultaneous two qubit RB sequences. FIXME: seems useless, because none of the callers set this for real, and we trim it to the group size interleaving_cl (int): interleaves the sequence with a specific clifford if desired seed (int) : seed used to initialize the random number generator. Returns: list of clifford indices (ints) N.B. in the case of the 1 qubit clifford group this function does the same as "randomized_benchmarking_sequence_old" but does not use the 24 by 24 lookuptable method to calculate the net clifford. It instead uses the "Clifford" objects used in constructing the two qubit Clifford classes. The old method exists to establish the equivalence between the two methods. """ if number_of_qubits == 1: Cl = SingleQubitClifford group_size = np.min([24, max_clifford_idx]) elif number_of_qubits == 2: Cl = TwoQubitClifford group_size = np.min([11520, max_clifford_idx]) else: raise NotImplementedError() # Generate a random sequence of Cliffords # Even if no seed is provided make sure we pick a new state such that # it is safe to run generate and compile the random sequences in # parallel using multiprocess rng_seed = np.random.RandomState(seed) rb_clifford_indices = rng_seed.randint(0, group_size, int(n_cl)) # Add interleaving cliffords if applicable if interleaving_cl is not None: rb_clif_ind_intl = np.empty(rb_clifford_indices.size * 2, dtype=int) rb_clif_ind_intl[0::2] = rb_clifford_indices rb_clif_ind_intl[1::2] = interleaving_cl rb_clifford_indices = rb_clif_ind_intl if desired_net_cl is not None: # Calculate the net clifford net_clifford = calculate_net_clifford(rb_clifford_indices, Cl) # determine the inverse of the sequence recovery_to_idx_clifford = net_clifford.get_inverse() recovery_clifford = Cl(desired_net_cl) * recovery_to_idx_clifford rb_clifford_indices = np.append(rb_clifford_indices, recovery_clifford.idx) return rb_clifford_indices
[ "import logging\nimport numpy as np\nfrom deprecated import deprecated\n\nfrom pycqed.measurement.randomized_benchmarking.clifford_group import clifford_lookuptable\nfrom pycqed.measurement.randomized_benchmarking.clifford_decompositions import gate_decomposition\nfrom pycqed.measurement.randomized_benchmarking.two_qubit_clifford_group import Clifford, SingleQubitClifford, TwoQubitClifford\n\n\ndef calculate_net_clifford(\n rb_clifford_indices: np.ndarray,\n Cliff:Clifford = SingleQubitClifford\n) -> Clifford:\n \"\"\"\n Calculate the net-clifford from a list of cliffords indices.\n\n Args:\n rb_clifford_indices: list or array of integers specifying the cliffords.\n Cliff : Clifford object used to determine what\n inversion technique to use and what indices are valid.\n Valid choices are `SingleQubitClifford` and `TwoQubitClifford`\n\n Returns:\n net_clifford: a `Clifford` object containing the net-clifford.\n the Clifford index is contained in the Clifford.idx attribute.\n\n Note: the order corresponds to the order in a pulse sequence but is\n the reverse of what it would be in a chained dot product.\n \"\"\"\n\n # Calculate the net clifford\n net_clifford = Cliff(0) # assumes element 0 is the Identity\n for idx in rb_clifford_indices:\n # [2020-07-03 Victor] the `abs` below was to remove the sign that was\n # used to treat CZ as CZ and not the member of CNOT-like set of gates\n # Using negative sign convention (i.e. `-4368` for the interleaved CZ)\n # was a bad choice because there is no such thing as negative zero and\n # the clifford numer 0 is the identity that is necessary for\n # benchmarking an idling identity with the same duration as the time\n # allocated to the flux pulses, for example\n # cliff = Clifford(abs(idx)) # Deprecated!\n assert idx > -1, (\n \"The convention for interleaved gates has changed! \"\n + \"See notes in this function. \"\n + \"You probably need to specify {}\".format(100_000 + abs(idx))\n )\n\n # In order to benchmark specific gates (and not cliffords), e.g. CZ but\n # not as a member of the CNOT-like set of gates, or an identity with\n # the same duration as the CZ we use, by convention, when specifying\n # the interleaved gate, the index of the corresponding\n # clifford + 100000, this is to keep it readable and bigger than the\n # 11520 elements of the Two-qubit Clifford group C2\n # corresponding clifford\n cliff = Cliff(idx % 100_000)\n\n # order of operators applied in is right to left, therefore\n # the new operator is applied on the left side.\n net_clifford = cliff * net_clifford\n\n return net_clifford\n\n\n# FIXME: deprecate along with randomized_benchmarking_sequence_old()\ndef calculate_recovery_clifford(cl_in, desired_cl=0):\n \"\"\"\n Extracts the clifford that has to be applied to cl_in to make the net\n operation correspond to desired_cl from the clifford lookuptable.\n\n This operation should perform the inverse of calculate_net_clifford\n \"\"\"\n row = list(clifford_lookuptable[cl_in])\n return row.index(desired_cl)\n\n\n@deprecated(version='0.4', reason='not used within pyqed')\ndef decompose_clifford_seq(clifford_sequence, gate_decomposition=gate_decomposition):\n decomposed_seq = []\n for cl in clifford_sequence:\n decomposed_seq.extend(gate_decomposition[cl])\n return decomposed_seq\n\n\n@deprecated(version='0.4', reason='not used within pyqed')\ndef convert_clifford_sequence_to_tape(\n clifford_sequence, lutmapping, gate_decomposition=gate_decomposition\n):\n \"\"\"\n Converts a list of qubit operations to the relevant pulse elements\n\n This method will be overwritten depending on the hardware implementation.\n \"\"\"\n # This is intended to replace the block below but not done because\n # I cannot test it at this moment (MAR)\n # decomposed_seq = decompose_clifford_seq(clifford_sequence,\n # gate_decomposition)\n decomposed_seq = []\n for cl in clifford_sequence:\n decomposed_seq.extend(gate_decomposition[cl])\n tape = []\n for g in decomposed_seq:\n tape.append(lutmapping.index(g))\n return tape\n\n\n# FIXME: deprecate, also including calculate_recovery_clifford() and clifford_lookuptable\ndef randomized_benchmarking_sequence_old(\n n_cl: int, desired_net_cl: int = 0, seed: int = None\n):\n \"\"\"\n Generates a sequence of \"n_cl\" random single qubit Cliffords followed\n by a a recovery Clifford to make the net result correspond\n to the \"desired_net_cl\".\n\n Args:\n n_cl (int) : number of Cliffords\n desired_net_cl (int) : idx of the desired net clifford\n seed (int) : seed used to initialize the random number\n generator.\n\n The default behaviour is that the net clifford corresponds to an\n identity (\"0\"). If you want e.g. an inverting sequence you should set\n the desired_net_cl to \"3\" (corresponds to Pauli X).\n \"\"\"\n logging.warning(\n \"deprecation warning, only exists for testing equivalence to new function.\"\n )\n\n if seed is None:\n rb_cliffords = np.random.randint(0, 24, int(n_cl))\n else:\n rng_seed = np.random.RandomState(seed)\n rb_cliffords = rng_seed.randint(0, 24, int(n_cl))\n\n net_clifford = calculate_net_clifford(rb_cliffords).idx\n recovery_clifford = calculate_recovery_clifford(net_clifford, desired_net_cl)\n\n rb_cliffords = np.append(rb_cliffords, recovery_clifford)\n\n return rb_cliffords\n\n\n##############################################################################\n# New style RB sequences (using the hash-table method) compatible\n# with Clifford object.\n# More advanced sequences are available using this method.\n##############################################################################\n\ndef randomized_benchmarking_sequence(\n n_cl: int,\n desired_net_cl: int = 0,\n number_of_qubits: int = 1,\n max_clifford_idx: int = 11520,\n interleaving_cl: int = None,\n seed: int = None,\n) -> np.ndarray:\n \"\"\"\n Generates a randomized benchmarking sequence for the one or two qubit\n clifford group.\n\n Args:\n n_cl (int) : number of Cliffords\n desired_net_cl (int) : idx of the desired net clifford, if None is\n specified no recovery Clifford is calculated\n number_of_qubits(int): used to determine if Cliffords are drawn\n from the single qubit or two qubit clifford group.\n max_clifford_idx (int): used to set the index of the highest random\n clifford generated. Useful to generate e.g., simultaneous two\n qubit RB sequences.\n FIXME: seems useless, because none of the callers set this for real, and we trim it to the group size\n interleaving_cl (int): interleaves the sequence with a specific\n clifford if desired\n seed (int) : seed used to initialize the random number\n generator.\n Returns:\n list of clifford indices (ints)\n\n N.B. in the case of the 1 qubit clifford group this function does the\n same as \"randomized_benchmarking_sequence_old\" but\n does not use the 24 by 24 lookuptable method to calculate the\n net clifford. It instead uses the \"Clifford\" objects used in\n constructing the two qubit Clifford classes.\n The old method exists to establish the equivalence between the two methods.\n\n \"\"\"\n\n if number_of_qubits == 1:\n Cl = SingleQubitClifford\n group_size = np.min([24, max_clifford_idx])\n elif number_of_qubits == 2:\n Cl = TwoQubitClifford\n group_size = np.min([11520, max_clifford_idx])\n else:\n raise NotImplementedError()\n\n # Generate a random sequence of Cliffords\n # Even if no seed is provided make sure we pick a new state such that\n # it is safe to run generate and compile the random sequences in\n # parallel using multiprocess\n rng_seed = np.random.RandomState(seed)\n rb_clifford_indices = rng_seed.randint(0, group_size, int(n_cl))\n\n # Add interleaving cliffords if applicable\n if interleaving_cl is not None:\n rb_clif_ind_intl = np.empty(rb_clifford_indices.size * 2, dtype=int)\n rb_clif_ind_intl[0::2] = rb_clifford_indices\n rb_clif_ind_intl[1::2] = interleaving_cl\n rb_clifford_indices = rb_clif_ind_intl\n\n if desired_net_cl is not None:\n # Calculate the net clifford\n net_clifford = calculate_net_clifford(rb_clifford_indices, Cl)\n\n # determine the inverse of the sequence\n recovery_to_idx_clifford = net_clifford.get_inverse()\n recovery_clifford = Cl(desired_net_cl) * recovery_to_idx_clifford\n rb_clifford_indices = np.append(rb_clifford_indices, recovery_clifford.idx)\n return rb_clifford_indices\n", "import logging\nimport numpy as np\nfrom deprecated import deprecated\nfrom pycqed.measurement.randomized_benchmarking.clifford_group import clifford_lookuptable\nfrom pycqed.measurement.randomized_benchmarking.clifford_decompositions import gate_decomposition\nfrom pycqed.measurement.randomized_benchmarking.two_qubit_clifford_group import Clifford, SingleQubitClifford, TwoQubitClifford\n\n\ndef calculate_net_clifford(rb_clifford_indices: np.ndarray, Cliff: Clifford\n =SingleQubitClifford) ->Clifford:\n \"\"\"\n Calculate the net-clifford from a list of cliffords indices.\n\n Args:\n rb_clifford_indices: list or array of integers specifying the cliffords.\n Cliff : Clifford object used to determine what\n inversion technique to use and what indices are valid.\n Valid choices are `SingleQubitClifford` and `TwoQubitClifford`\n\n Returns:\n net_clifford: a `Clifford` object containing the net-clifford.\n the Clifford index is contained in the Clifford.idx attribute.\n\n Note: the order corresponds to the order in a pulse sequence but is\n the reverse of what it would be in a chained dot product.\n \"\"\"\n net_clifford = Cliff(0)\n for idx in rb_clifford_indices:\n assert idx > -1, 'The convention for interleaved gates has changed! ' + 'See notes in this function. ' + 'You probably need to specify {}'.format(\n 100000 + abs(idx))\n cliff = Cliff(idx % 100000)\n net_clifford = cliff * net_clifford\n return net_clifford\n\n\ndef calculate_recovery_clifford(cl_in, desired_cl=0):\n \"\"\"\n Extracts the clifford that has to be applied to cl_in to make the net\n operation correspond to desired_cl from the clifford lookuptable.\n\n This operation should perform the inverse of calculate_net_clifford\n \"\"\"\n row = list(clifford_lookuptable[cl_in])\n return row.index(desired_cl)\n\n\n@deprecated(version='0.4', reason='not used within pyqed')\ndef decompose_clifford_seq(clifford_sequence, gate_decomposition=\n gate_decomposition):\n decomposed_seq = []\n for cl in clifford_sequence:\n decomposed_seq.extend(gate_decomposition[cl])\n return decomposed_seq\n\n\n@deprecated(version='0.4', reason='not used within pyqed')\ndef convert_clifford_sequence_to_tape(clifford_sequence, lutmapping,\n gate_decomposition=gate_decomposition):\n \"\"\"\n Converts a list of qubit operations to the relevant pulse elements\n\n This method will be overwritten depending on the hardware implementation.\n \"\"\"\n decomposed_seq = []\n for cl in clifford_sequence:\n decomposed_seq.extend(gate_decomposition[cl])\n tape = []\n for g in decomposed_seq:\n tape.append(lutmapping.index(g))\n return tape\n\n\ndef randomized_benchmarking_sequence_old(n_cl: int, desired_net_cl: int=0,\n seed: int=None):\n \"\"\"\n Generates a sequence of \"n_cl\" random single qubit Cliffords followed\n by a a recovery Clifford to make the net result correspond\n to the \"desired_net_cl\".\n\n Args:\n n_cl (int) : number of Cliffords\n desired_net_cl (int) : idx of the desired net clifford\n seed (int) : seed used to initialize the random number\n generator.\n\n The default behaviour is that the net clifford corresponds to an\n identity (\"0\"). If you want e.g. an inverting sequence you should set\n the desired_net_cl to \"3\" (corresponds to Pauli X).\n \"\"\"\n logging.warning(\n 'deprecation warning, only exists for testing equivalence to new function.'\n )\n if seed is None:\n rb_cliffords = np.random.randint(0, 24, int(n_cl))\n else:\n rng_seed = np.random.RandomState(seed)\n rb_cliffords = rng_seed.randint(0, 24, int(n_cl))\n net_clifford = calculate_net_clifford(rb_cliffords).idx\n recovery_clifford = calculate_recovery_clifford(net_clifford,\n desired_net_cl)\n rb_cliffords = np.append(rb_cliffords, recovery_clifford)\n return rb_cliffords\n\n\ndef randomized_benchmarking_sequence(n_cl: int, desired_net_cl: int=0,\n number_of_qubits: int=1, max_clifford_idx: int=11520, interleaving_cl:\n int=None, seed: int=None) ->np.ndarray:\n \"\"\"\n Generates a randomized benchmarking sequence for the one or two qubit\n clifford group.\n\n Args:\n n_cl (int) : number of Cliffords\n desired_net_cl (int) : idx of the desired net clifford, if None is\n specified no recovery Clifford is calculated\n number_of_qubits(int): used to determine if Cliffords are drawn\n from the single qubit or two qubit clifford group.\n max_clifford_idx (int): used to set the index of the highest random\n clifford generated. Useful to generate e.g., simultaneous two\n qubit RB sequences.\n FIXME: seems useless, because none of the callers set this for real, and we trim it to the group size\n interleaving_cl (int): interleaves the sequence with a specific\n clifford if desired\n seed (int) : seed used to initialize the random number\n generator.\n Returns:\n list of clifford indices (ints)\n\n N.B. in the case of the 1 qubit clifford group this function does the\n same as \"randomized_benchmarking_sequence_old\" but\n does not use the 24 by 24 lookuptable method to calculate the\n net clifford. It instead uses the \"Clifford\" objects used in\n constructing the two qubit Clifford classes.\n The old method exists to establish the equivalence between the two methods.\n\n \"\"\"\n if number_of_qubits == 1:\n Cl = SingleQubitClifford\n group_size = np.min([24, max_clifford_idx])\n elif number_of_qubits == 2:\n Cl = TwoQubitClifford\n group_size = np.min([11520, max_clifford_idx])\n else:\n raise NotImplementedError()\n rng_seed = np.random.RandomState(seed)\n rb_clifford_indices = rng_seed.randint(0, group_size, int(n_cl))\n if interleaving_cl is not None:\n rb_clif_ind_intl = np.empty(rb_clifford_indices.size * 2, dtype=int)\n rb_clif_ind_intl[0::2] = rb_clifford_indices\n rb_clif_ind_intl[1::2] = interleaving_cl\n rb_clifford_indices = rb_clif_ind_intl\n if desired_net_cl is not None:\n net_clifford = calculate_net_clifford(rb_clifford_indices, Cl)\n recovery_to_idx_clifford = net_clifford.get_inverse()\n recovery_clifford = Cl(desired_net_cl) * recovery_to_idx_clifford\n rb_clifford_indices = np.append(rb_clifford_indices,\n recovery_clifford.idx)\n return rb_clifford_indices\n", "<import token>\n\n\ndef calculate_net_clifford(rb_clifford_indices: np.ndarray, Cliff: Clifford\n =SingleQubitClifford) ->Clifford:\n \"\"\"\n Calculate the net-clifford from a list of cliffords indices.\n\n Args:\n rb_clifford_indices: list or array of integers specifying the cliffords.\n Cliff : Clifford object used to determine what\n inversion technique to use and what indices are valid.\n Valid choices are `SingleQubitClifford` and `TwoQubitClifford`\n\n Returns:\n net_clifford: a `Clifford` object containing the net-clifford.\n the Clifford index is contained in the Clifford.idx attribute.\n\n Note: the order corresponds to the order in a pulse sequence but is\n the reverse of what it would be in a chained dot product.\n \"\"\"\n net_clifford = Cliff(0)\n for idx in rb_clifford_indices:\n assert idx > -1, 'The convention for interleaved gates has changed! ' + 'See notes in this function. ' + 'You probably need to specify {}'.format(\n 100000 + abs(idx))\n cliff = Cliff(idx % 100000)\n net_clifford = cliff * net_clifford\n return net_clifford\n\n\ndef calculate_recovery_clifford(cl_in, desired_cl=0):\n \"\"\"\n Extracts the clifford that has to be applied to cl_in to make the net\n operation correspond to desired_cl from the clifford lookuptable.\n\n This operation should perform the inverse of calculate_net_clifford\n \"\"\"\n row = list(clifford_lookuptable[cl_in])\n return row.index(desired_cl)\n\n\n@deprecated(version='0.4', reason='not used within pyqed')\ndef decompose_clifford_seq(clifford_sequence, gate_decomposition=\n gate_decomposition):\n decomposed_seq = []\n for cl in clifford_sequence:\n decomposed_seq.extend(gate_decomposition[cl])\n return decomposed_seq\n\n\n@deprecated(version='0.4', reason='not used within pyqed')\ndef convert_clifford_sequence_to_tape(clifford_sequence, lutmapping,\n gate_decomposition=gate_decomposition):\n \"\"\"\n Converts a list of qubit operations to the relevant pulse elements\n\n This method will be overwritten depending on the hardware implementation.\n \"\"\"\n decomposed_seq = []\n for cl in clifford_sequence:\n decomposed_seq.extend(gate_decomposition[cl])\n tape = []\n for g in decomposed_seq:\n tape.append(lutmapping.index(g))\n return tape\n\n\ndef randomized_benchmarking_sequence_old(n_cl: int, desired_net_cl: int=0,\n seed: int=None):\n \"\"\"\n Generates a sequence of \"n_cl\" random single qubit Cliffords followed\n by a a recovery Clifford to make the net result correspond\n to the \"desired_net_cl\".\n\n Args:\n n_cl (int) : number of Cliffords\n desired_net_cl (int) : idx of the desired net clifford\n seed (int) : seed used to initialize the random number\n generator.\n\n The default behaviour is that the net clifford corresponds to an\n identity (\"0\"). If you want e.g. an inverting sequence you should set\n the desired_net_cl to \"3\" (corresponds to Pauli X).\n \"\"\"\n logging.warning(\n 'deprecation warning, only exists for testing equivalence to new function.'\n )\n if seed is None:\n rb_cliffords = np.random.randint(0, 24, int(n_cl))\n else:\n rng_seed = np.random.RandomState(seed)\n rb_cliffords = rng_seed.randint(0, 24, int(n_cl))\n net_clifford = calculate_net_clifford(rb_cliffords).idx\n recovery_clifford = calculate_recovery_clifford(net_clifford,\n desired_net_cl)\n rb_cliffords = np.append(rb_cliffords, recovery_clifford)\n return rb_cliffords\n\n\ndef randomized_benchmarking_sequence(n_cl: int, desired_net_cl: int=0,\n number_of_qubits: int=1, max_clifford_idx: int=11520, interleaving_cl:\n int=None, seed: int=None) ->np.ndarray:\n \"\"\"\n Generates a randomized benchmarking sequence for the one or two qubit\n clifford group.\n\n Args:\n n_cl (int) : number of Cliffords\n desired_net_cl (int) : idx of the desired net clifford, if None is\n specified no recovery Clifford is calculated\n number_of_qubits(int): used to determine if Cliffords are drawn\n from the single qubit or two qubit clifford group.\n max_clifford_idx (int): used to set the index of the highest random\n clifford generated. Useful to generate e.g., simultaneous two\n qubit RB sequences.\n FIXME: seems useless, because none of the callers set this for real, and we trim it to the group size\n interleaving_cl (int): interleaves the sequence with a specific\n clifford if desired\n seed (int) : seed used to initialize the random number\n generator.\n Returns:\n list of clifford indices (ints)\n\n N.B. in the case of the 1 qubit clifford group this function does the\n same as \"randomized_benchmarking_sequence_old\" but\n does not use the 24 by 24 lookuptable method to calculate the\n net clifford. It instead uses the \"Clifford\" objects used in\n constructing the two qubit Clifford classes.\n The old method exists to establish the equivalence between the two methods.\n\n \"\"\"\n if number_of_qubits == 1:\n Cl = SingleQubitClifford\n group_size = np.min([24, max_clifford_idx])\n elif number_of_qubits == 2:\n Cl = TwoQubitClifford\n group_size = np.min([11520, max_clifford_idx])\n else:\n raise NotImplementedError()\n rng_seed = np.random.RandomState(seed)\n rb_clifford_indices = rng_seed.randint(0, group_size, int(n_cl))\n if interleaving_cl is not None:\n rb_clif_ind_intl = np.empty(rb_clifford_indices.size * 2, dtype=int)\n rb_clif_ind_intl[0::2] = rb_clifford_indices\n rb_clif_ind_intl[1::2] = interleaving_cl\n rb_clifford_indices = rb_clif_ind_intl\n if desired_net_cl is not None:\n net_clifford = calculate_net_clifford(rb_clifford_indices, Cl)\n recovery_to_idx_clifford = net_clifford.get_inverse()\n recovery_clifford = Cl(desired_net_cl) * recovery_to_idx_clifford\n rb_clifford_indices = np.append(rb_clifford_indices,\n recovery_clifford.idx)\n return rb_clifford_indices\n", "<import token>\n\n\ndef calculate_net_clifford(rb_clifford_indices: np.ndarray, Cliff: Clifford\n =SingleQubitClifford) ->Clifford:\n \"\"\"\n Calculate the net-clifford from a list of cliffords indices.\n\n Args:\n rb_clifford_indices: list or array of integers specifying the cliffords.\n Cliff : Clifford object used to determine what\n inversion technique to use and what indices are valid.\n Valid choices are `SingleQubitClifford` and `TwoQubitClifford`\n\n Returns:\n net_clifford: a `Clifford` object containing the net-clifford.\n the Clifford index is contained in the Clifford.idx attribute.\n\n Note: the order corresponds to the order in a pulse sequence but is\n the reverse of what it would be in a chained dot product.\n \"\"\"\n net_clifford = Cliff(0)\n for idx in rb_clifford_indices:\n assert idx > -1, 'The convention for interleaved gates has changed! ' + 'See notes in this function. ' + 'You probably need to specify {}'.format(\n 100000 + abs(idx))\n cliff = Cliff(idx % 100000)\n net_clifford = cliff * net_clifford\n return net_clifford\n\n\ndef calculate_recovery_clifford(cl_in, desired_cl=0):\n \"\"\"\n Extracts the clifford that has to be applied to cl_in to make the net\n operation correspond to desired_cl from the clifford lookuptable.\n\n This operation should perform the inverse of calculate_net_clifford\n \"\"\"\n row = list(clifford_lookuptable[cl_in])\n return row.index(desired_cl)\n\n\n@deprecated(version='0.4', reason='not used within pyqed')\ndef decompose_clifford_seq(clifford_sequence, gate_decomposition=\n gate_decomposition):\n decomposed_seq = []\n for cl in clifford_sequence:\n decomposed_seq.extend(gate_decomposition[cl])\n return decomposed_seq\n\n\n@deprecated(version='0.4', reason='not used within pyqed')\ndef convert_clifford_sequence_to_tape(clifford_sequence, lutmapping,\n gate_decomposition=gate_decomposition):\n \"\"\"\n Converts a list of qubit operations to the relevant pulse elements\n\n This method will be overwritten depending on the hardware implementation.\n \"\"\"\n decomposed_seq = []\n for cl in clifford_sequence:\n decomposed_seq.extend(gate_decomposition[cl])\n tape = []\n for g in decomposed_seq:\n tape.append(lutmapping.index(g))\n return tape\n\n\ndef randomized_benchmarking_sequence_old(n_cl: int, desired_net_cl: int=0,\n seed: int=None):\n \"\"\"\n Generates a sequence of \"n_cl\" random single qubit Cliffords followed\n by a a recovery Clifford to make the net result correspond\n to the \"desired_net_cl\".\n\n Args:\n n_cl (int) : number of Cliffords\n desired_net_cl (int) : idx of the desired net clifford\n seed (int) : seed used to initialize the random number\n generator.\n\n The default behaviour is that the net clifford corresponds to an\n identity (\"0\"). If you want e.g. an inverting sequence you should set\n the desired_net_cl to \"3\" (corresponds to Pauli X).\n \"\"\"\n logging.warning(\n 'deprecation warning, only exists for testing equivalence to new function.'\n )\n if seed is None:\n rb_cliffords = np.random.randint(0, 24, int(n_cl))\n else:\n rng_seed = np.random.RandomState(seed)\n rb_cliffords = rng_seed.randint(0, 24, int(n_cl))\n net_clifford = calculate_net_clifford(rb_cliffords).idx\n recovery_clifford = calculate_recovery_clifford(net_clifford,\n desired_net_cl)\n rb_cliffords = np.append(rb_cliffords, recovery_clifford)\n return rb_cliffords\n\n\n<function token>\n", "<import token>\n\n\ndef calculate_net_clifford(rb_clifford_indices: np.ndarray, Cliff: Clifford\n =SingleQubitClifford) ->Clifford:\n \"\"\"\n Calculate the net-clifford from a list of cliffords indices.\n\n Args:\n rb_clifford_indices: list or array of integers specifying the cliffords.\n Cliff : Clifford object used to determine what\n inversion technique to use and what indices are valid.\n Valid choices are `SingleQubitClifford` and `TwoQubitClifford`\n\n Returns:\n net_clifford: a `Clifford` object containing the net-clifford.\n the Clifford index is contained in the Clifford.idx attribute.\n\n Note: the order corresponds to the order in a pulse sequence but is\n the reverse of what it would be in a chained dot product.\n \"\"\"\n net_clifford = Cliff(0)\n for idx in rb_clifford_indices:\n assert idx > -1, 'The convention for interleaved gates has changed! ' + 'See notes in this function. ' + 'You probably need to specify {}'.format(\n 100000 + abs(idx))\n cliff = Cliff(idx % 100000)\n net_clifford = cliff * net_clifford\n return net_clifford\n\n\ndef calculate_recovery_clifford(cl_in, desired_cl=0):\n \"\"\"\n Extracts the clifford that has to be applied to cl_in to make the net\n operation correspond to desired_cl from the clifford lookuptable.\n\n This operation should perform the inverse of calculate_net_clifford\n \"\"\"\n row = list(clifford_lookuptable[cl_in])\n return row.index(desired_cl)\n\n\n@deprecated(version='0.4', reason='not used within pyqed')\ndef decompose_clifford_seq(clifford_sequence, gate_decomposition=\n gate_decomposition):\n decomposed_seq = []\n for cl in clifford_sequence:\n decomposed_seq.extend(gate_decomposition[cl])\n return decomposed_seq\n\n\n<function token>\n\n\ndef randomized_benchmarking_sequence_old(n_cl: int, desired_net_cl: int=0,\n seed: int=None):\n \"\"\"\n Generates a sequence of \"n_cl\" random single qubit Cliffords followed\n by a a recovery Clifford to make the net result correspond\n to the \"desired_net_cl\".\n\n Args:\n n_cl (int) : number of Cliffords\n desired_net_cl (int) : idx of the desired net clifford\n seed (int) : seed used to initialize the random number\n generator.\n\n The default behaviour is that the net clifford corresponds to an\n identity (\"0\"). If you want e.g. an inverting sequence you should set\n the desired_net_cl to \"3\" (corresponds to Pauli X).\n \"\"\"\n logging.warning(\n 'deprecation warning, only exists for testing equivalence to new function.'\n )\n if seed is None:\n rb_cliffords = np.random.randint(0, 24, int(n_cl))\n else:\n rng_seed = np.random.RandomState(seed)\n rb_cliffords = rng_seed.randint(0, 24, int(n_cl))\n net_clifford = calculate_net_clifford(rb_cliffords).idx\n recovery_clifford = calculate_recovery_clifford(net_clifford,\n desired_net_cl)\n rb_cliffords = np.append(rb_cliffords, recovery_clifford)\n return rb_cliffords\n\n\n<function token>\n", "<import token>\n\n\ndef calculate_net_clifford(rb_clifford_indices: np.ndarray, Cliff: Clifford\n =SingleQubitClifford) ->Clifford:\n \"\"\"\n Calculate the net-clifford from a list of cliffords indices.\n\n Args:\n rb_clifford_indices: list or array of integers specifying the cliffords.\n Cliff : Clifford object used to determine what\n inversion technique to use and what indices are valid.\n Valid choices are `SingleQubitClifford` and `TwoQubitClifford`\n\n Returns:\n net_clifford: a `Clifford` object containing the net-clifford.\n the Clifford index is contained in the Clifford.idx attribute.\n\n Note: the order corresponds to the order in a pulse sequence but is\n the reverse of what it would be in a chained dot product.\n \"\"\"\n net_clifford = Cliff(0)\n for idx in rb_clifford_indices:\n assert idx > -1, 'The convention for interleaved gates has changed! ' + 'See notes in this function. ' + 'You probably need to specify {}'.format(\n 100000 + abs(idx))\n cliff = Cliff(idx % 100000)\n net_clifford = cliff * net_clifford\n return net_clifford\n\n\ndef calculate_recovery_clifford(cl_in, desired_cl=0):\n \"\"\"\n Extracts the clifford that has to be applied to cl_in to make the net\n operation correspond to desired_cl from the clifford lookuptable.\n\n This operation should perform the inverse of calculate_net_clifford\n \"\"\"\n row = list(clifford_lookuptable[cl_in])\n return row.index(desired_cl)\n\n\n@deprecated(version='0.4', reason='not used within pyqed')\ndef decompose_clifford_seq(clifford_sequence, gate_decomposition=\n gate_decomposition):\n decomposed_seq = []\n for cl in clifford_sequence:\n decomposed_seq.extend(gate_decomposition[cl])\n return decomposed_seq\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n\n\ndef calculate_recovery_clifford(cl_in, desired_cl=0):\n \"\"\"\n Extracts the clifford that has to be applied to cl_in to make the net\n operation correspond to desired_cl from the clifford lookuptable.\n\n This operation should perform the inverse of calculate_net_clifford\n \"\"\"\n row = list(clifford_lookuptable[cl_in])\n return row.index(desired_cl)\n\n\n@deprecated(version='0.4', reason='not used within pyqed')\ndef decompose_clifford_seq(clifford_sequence, gate_decomposition=\n gate_decomposition):\n decomposed_seq = []\n for cl in clifford_sequence:\n decomposed_seq.extend(gate_decomposition[cl])\n return decomposed_seq\n\n\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n\n\ndef calculate_recovery_clifford(cl_in, desired_cl=0):\n \"\"\"\n Extracts the clifford that has to be applied to cl_in to make the net\n operation correspond to desired_cl from the clifford lookuptable.\n\n This operation should perform the inverse of calculate_net_clifford\n \"\"\"\n row = list(clifford_lookuptable[cl_in])\n return row.index(desired_cl)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
786
3421c3b839721694945bdbb4f17183bceaed5296
import unittest import ConvertListToDict as cldf class MyDictTestCase(unittest.TestCase): def test_Dict(self): # Testcase1 (len(keys) == len(values)) actualDict1 = cldf.ConvertListsToDict([1, 2, 3],['a','b','c']) expectedDict1 = {1: 'a', 2: 'b', 3: 'c'} self.assertEqual(actualDict1, expectedDict1) # Testcase2 (len(keys) < len(values)) actualDict2 = cldf.ConvertListsToDict([1, 2, 3], ['a', 'b', 'c','d','e','f']) expectedDict2 = {1: 'a', 2: 'b', 3: 'c'} self.assertEqual(actualDict2, expectedDict2) # Testcase3 (len(keys) > len(values)) actualDict2 = cldf.ConvertListsToDict([1, 2, 3, 4, 5, 6, 7], ['a', 'b', 'c']) expectedDict2 = {1: 'a', 2: 'b', 3: 'c', 4: None, 5: None, 6: None, 7: None} self.assertEqual(actualDict2, expectedDict2) if __name__ == '__main__': unittest.main()
[ "import unittest\nimport ConvertListToDict as cldf\n\nclass MyDictTestCase(unittest.TestCase):\n def test_Dict(self):\n # Testcase1 (len(keys) == len(values))\n actualDict1 = cldf.ConvertListsToDict([1, 2, 3],['a','b','c'])\n expectedDict1 = {1: 'a', 2: 'b', 3: 'c'}\n self.assertEqual(actualDict1, expectedDict1)\n\n # Testcase2 (len(keys) < len(values))\n actualDict2 = cldf.ConvertListsToDict([1, 2, 3], ['a', 'b', 'c','d','e','f'])\n expectedDict2 = {1: 'a', 2: 'b', 3: 'c'}\n self.assertEqual(actualDict2, expectedDict2)\n\n # Testcase3 (len(keys) > len(values))\n actualDict2 = cldf.ConvertListsToDict([1, 2, 3, 4, 5, 6, 7], ['a', 'b', 'c'])\n expectedDict2 = {1: 'a', 2: 'b', 3: 'c', 4: None, 5: None, 6: None, 7: None}\n self.assertEqual(actualDict2, expectedDict2)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "import unittest\nimport ConvertListToDict as cldf\n\n\nclass MyDictTestCase(unittest.TestCase):\n\n def test_Dict(self):\n actualDict1 = cldf.ConvertListsToDict([1, 2, 3], ['a', 'b', 'c'])\n expectedDict1 = {(1): 'a', (2): 'b', (3): 'c'}\n self.assertEqual(actualDict1, expectedDict1)\n actualDict2 = cldf.ConvertListsToDict([1, 2, 3], ['a', 'b', 'c',\n 'd', 'e', 'f'])\n expectedDict2 = {(1): 'a', (2): 'b', (3): 'c'}\n self.assertEqual(actualDict2, expectedDict2)\n actualDict2 = cldf.ConvertListsToDict([1, 2, 3, 4, 5, 6, 7], ['a',\n 'b', 'c'])\n expectedDict2 = {(1): 'a', (2): 'b', (3): 'c', (4): None, (5): None,\n (6): None, (7): None}\n self.assertEqual(actualDict2, expectedDict2)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "<import token>\n\n\nclass MyDictTestCase(unittest.TestCase):\n\n def test_Dict(self):\n actualDict1 = cldf.ConvertListsToDict([1, 2, 3], ['a', 'b', 'c'])\n expectedDict1 = {(1): 'a', (2): 'b', (3): 'c'}\n self.assertEqual(actualDict1, expectedDict1)\n actualDict2 = cldf.ConvertListsToDict([1, 2, 3], ['a', 'b', 'c',\n 'd', 'e', 'f'])\n expectedDict2 = {(1): 'a', (2): 'b', (3): 'c'}\n self.assertEqual(actualDict2, expectedDict2)\n actualDict2 = cldf.ConvertListsToDict([1, 2, 3, 4, 5, 6, 7], ['a',\n 'b', 'c'])\n expectedDict2 = {(1): 'a', (2): 'b', (3): 'c', (4): None, (5): None,\n (6): None, (7): None}\n self.assertEqual(actualDict2, expectedDict2)\n\n\nif __name__ == '__main__':\n unittest.main()\n", "<import token>\n\n\nclass MyDictTestCase(unittest.TestCase):\n\n def test_Dict(self):\n actualDict1 = cldf.ConvertListsToDict([1, 2, 3], ['a', 'b', 'c'])\n expectedDict1 = {(1): 'a', (2): 'b', (3): 'c'}\n self.assertEqual(actualDict1, expectedDict1)\n actualDict2 = cldf.ConvertListsToDict([1, 2, 3], ['a', 'b', 'c',\n 'd', 'e', 'f'])\n expectedDict2 = {(1): 'a', (2): 'b', (3): 'c'}\n self.assertEqual(actualDict2, expectedDict2)\n actualDict2 = cldf.ConvertListsToDict([1, 2, 3, 4, 5, 6, 7], ['a',\n 'b', 'c'])\n expectedDict2 = {(1): 'a', (2): 'b', (3): 'c', (4): None, (5): None,\n (6): None, (7): None}\n self.assertEqual(actualDict2, expectedDict2)\n\n\n<code token>\n", "<import token>\n\n\nclass MyDictTestCase(unittest.TestCase):\n <function token>\n\n\n<code token>\n", "<import token>\n<class token>\n<code token>\n" ]
false
787
1ea61ab4003de80ffe9fb3e284b6686d4bf20b15
# Generated by Django 3.2.3 on 2021-08-26 09:18 import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Restaurant', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('restaurant_name', models.CharField(max_length=200)), ('city', models.CharField(max_length=200)), ('district', models.CharField(max_length=200)), ('rating', models.FloatField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(5)])), ('photo', models.ImageField(upload_to='uploads')), ], ), migrations.CreateModel( name='Reservation', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('adult', models.IntegerField()), ('entry_date', models.DateTimeField()), ('restaurant', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='restaurant.restaurant')), ], ), ]
[ "# Generated by Django 3.2.3 on 2021-08-26 09:18\n\nimport django.core.validators\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Restaurant',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('restaurant_name', models.CharField(max_length=200)),\n ('city', models.CharField(max_length=200)),\n ('district', models.CharField(max_length=200)),\n ('rating', models.FloatField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(5)])),\n ('photo', models.ImageField(upload_to='uploads')),\n ],\n ),\n migrations.CreateModel(\n name='Reservation',\n fields=[\n ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('adult', models.IntegerField()),\n ('entry_date', models.DateTimeField()),\n ('restaurant', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='restaurant.restaurant')),\n ],\n ),\n ]\n", "import django.core.validators\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='Restaurant', fields=[('id',\n models.BigAutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('restaurant_name', models.CharField(\n max_length=200)), ('city', models.CharField(max_length=200)), (\n 'district', models.CharField(max_length=200)), ('rating', models.\n FloatField(validators=[django.core.validators.MinValueValidator(0),\n django.core.validators.MaxValueValidator(5)])), ('photo', models.\n ImageField(upload_to='uploads'))]), migrations.CreateModel(name=\n 'Reservation', fields=[('id', models.BigAutoField(auto_created=True,\n primary_key=True, serialize=False, verbose_name='ID')), ('adult',\n models.IntegerField()), ('entry_date', models.DateTimeField()), (\n 'restaurant', models.ForeignKey(on_delete=django.db.models.deletion\n .CASCADE, to='restaurant.restaurant'))])]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='Restaurant', fields=[('id',\n models.BigAutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), ('restaurant_name', models.CharField(\n max_length=200)), ('city', models.CharField(max_length=200)), (\n 'district', models.CharField(max_length=200)), ('rating', models.\n FloatField(validators=[django.core.validators.MinValueValidator(0),\n django.core.validators.MaxValueValidator(5)])), ('photo', models.\n ImageField(upload_to='uploads'))]), migrations.CreateModel(name=\n 'Reservation', fields=[('id', models.BigAutoField(auto_created=True,\n primary_key=True, serialize=False, verbose_name='ID')), ('adult',\n models.IntegerField()), ('entry_date', models.DateTimeField()), (\n 'restaurant', models.ForeignKey(on_delete=django.db.models.deletion\n .CASCADE, to='restaurant.restaurant'))])]\n", "<import token>\n\n\nclass Migration(migrations.Migration):\n <assignment token>\n <assignment token>\n <assignment token>\n", "<import token>\n<class token>\n" ]
false
788
6db7189d26c63ca9f9667045b780ec11994bac28
import sys from pypregel import Pypregel from pypregel.vertex import Vertex, Edge from pypregel.reader import Reader from pypregel.writer import Writer from pypregel.combiner import Combiner class PageRankVertex(Vertex): def compute(self): if self.superstep() >= 1: s = 0 while self.has_message(): msg = self.get_message() s += msg self.set_value(0.15 / self.get_num_of_vertices() + 0.85 * s) if self.superstep() < 30: n = len(self.get_out_edges()) if n > 0: self.send_message_to_all_neighbors(self.get_value() / n) else: self.vote_to_halt() class PageRankReader(Reader): def read_num_of_vertices(self): line = self.config_fp.readline() return int(line) def read_vertex(self): line = self.graph_fp.readline() if not line: return None line = line.strip().split(':') vertex_id = int(line[0]) edges = [] if line[1]: for e in line[1].split(' '): edges.append(Edge(int(e), None)) return PageRankVertex(vertex_id, None, edges) class PageRankWriter(Writer): def write_vertex(self, vertex): return vertex.get_vertex_id(), str(vertex.get_value()) class PageRankCombiner(Combiner): def combine(self, msg_x, msg_y): msg_x_value = msg_x[1] msg_y_value = msg_y[1] return None, msg_x_value + msg_y_value def main(): if len(sys.argv) < 4: print("usage: python %s [config] [graph] [out_file]" % sys.argv[0]) return pagerank_reader = PageRankReader(sys.argv[1], sys.argv[2]) pagerank_writer = PageRankWriter(sys.argv[3]) pagerank_combiner = PageRankCombiner() pagerank = Pypregel( reader=pagerank_reader, writer=pagerank_writer, combiner=pagerank_combiner ) pagerank.run() if __name__ == "__main__": main()
[ "import sys\n\nfrom pypregel import Pypregel\nfrom pypregel.vertex import Vertex, Edge\nfrom pypregel.reader import Reader\nfrom pypregel.writer import Writer\nfrom pypregel.combiner import Combiner\n\n\nclass PageRankVertex(Vertex):\n def compute(self):\n if self.superstep() >= 1:\n s = 0\n while self.has_message():\n msg = self.get_message()\n s += msg\n\n self.set_value(0.15 / self.get_num_of_vertices() + 0.85 * s)\n\n if self.superstep() < 30:\n n = len(self.get_out_edges())\n if n > 0:\n self.send_message_to_all_neighbors(self.get_value() / n)\n else:\n self.vote_to_halt()\n\n\nclass PageRankReader(Reader):\n def read_num_of_vertices(self):\n line = self.config_fp.readline()\n return int(line)\n\n def read_vertex(self):\n line = self.graph_fp.readline()\n if not line:\n return None\n\n line = line.strip().split(':')\n vertex_id = int(line[0])\n\n edges = []\n if line[1]:\n for e in line[1].split(' '):\n edges.append(Edge(int(e), None))\n\n return PageRankVertex(vertex_id, None, edges)\n\n\nclass PageRankWriter(Writer):\n def write_vertex(self, vertex):\n return vertex.get_vertex_id(), str(vertex.get_value())\n\n\nclass PageRankCombiner(Combiner):\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\ndef main():\n if len(sys.argv) < 4:\n print(\"usage: python %s [config] [graph] [out_file]\" % sys.argv[0])\n return\n\n pagerank_reader = PageRankReader(sys.argv[1], sys.argv[2])\n pagerank_writer = PageRankWriter(sys.argv[3])\n pagerank_combiner = PageRankCombiner()\n pagerank = Pypregel(\n reader=pagerank_reader,\n writer=pagerank_writer,\n combiner=pagerank_combiner\n )\n\n pagerank.run()\n\n\nif __name__ == \"__main__\":\n main()\n", "import sys\nfrom pypregel import Pypregel\nfrom pypregel.vertex import Vertex, Edge\nfrom pypregel.reader import Reader\nfrom pypregel.writer import Writer\nfrom pypregel.combiner import Combiner\n\n\nclass PageRankVertex(Vertex):\n\n def compute(self):\n if self.superstep() >= 1:\n s = 0\n while self.has_message():\n msg = self.get_message()\n s += msg\n self.set_value(0.15 / self.get_num_of_vertices() + 0.85 * s)\n if self.superstep() < 30:\n n = len(self.get_out_edges())\n if n > 0:\n self.send_message_to_all_neighbors(self.get_value() / n)\n else:\n self.vote_to_halt()\n\n\nclass PageRankReader(Reader):\n\n def read_num_of_vertices(self):\n line = self.config_fp.readline()\n return int(line)\n\n def read_vertex(self):\n line = self.graph_fp.readline()\n if not line:\n return None\n line = line.strip().split(':')\n vertex_id = int(line[0])\n edges = []\n if line[1]:\n for e in line[1].split(' '):\n edges.append(Edge(int(e), None))\n return PageRankVertex(vertex_id, None, edges)\n\n\nclass PageRankWriter(Writer):\n\n def write_vertex(self, vertex):\n return vertex.get_vertex_id(), str(vertex.get_value())\n\n\nclass PageRankCombiner(Combiner):\n\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\ndef main():\n if len(sys.argv) < 4:\n print('usage: python %s [config] [graph] [out_file]' % sys.argv[0])\n return\n pagerank_reader = PageRankReader(sys.argv[1], sys.argv[2])\n pagerank_writer = PageRankWriter(sys.argv[3])\n pagerank_combiner = PageRankCombiner()\n pagerank = Pypregel(reader=pagerank_reader, writer=pagerank_writer,\n combiner=pagerank_combiner)\n pagerank.run()\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n\n\nclass PageRankVertex(Vertex):\n\n def compute(self):\n if self.superstep() >= 1:\n s = 0\n while self.has_message():\n msg = self.get_message()\n s += msg\n self.set_value(0.15 / self.get_num_of_vertices() + 0.85 * s)\n if self.superstep() < 30:\n n = len(self.get_out_edges())\n if n > 0:\n self.send_message_to_all_neighbors(self.get_value() / n)\n else:\n self.vote_to_halt()\n\n\nclass PageRankReader(Reader):\n\n def read_num_of_vertices(self):\n line = self.config_fp.readline()\n return int(line)\n\n def read_vertex(self):\n line = self.graph_fp.readline()\n if not line:\n return None\n line = line.strip().split(':')\n vertex_id = int(line[0])\n edges = []\n if line[1]:\n for e in line[1].split(' '):\n edges.append(Edge(int(e), None))\n return PageRankVertex(vertex_id, None, edges)\n\n\nclass PageRankWriter(Writer):\n\n def write_vertex(self, vertex):\n return vertex.get_vertex_id(), str(vertex.get_value())\n\n\nclass PageRankCombiner(Combiner):\n\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\ndef main():\n if len(sys.argv) < 4:\n print('usage: python %s [config] [graph] [out_file]' % sys.argv[0])\n return\n pagerank_reader = PageRankReader(sys.argv[1], sys.argv[2])\n pagerank_writer = PageRankWriter(sys.argv[3])\n pagerank_combiner = PageRankCombiner()\n pagerank = Pypregel(reader=pagerank_reader, writer=pagerank_writer,\n combiner=pagerank_combiner)\n pagerank.run()\n\n\nif __name__ == '__main__':\n main()\n", "<import token>\n\n\nclass PageRankVertex(Vertex):\n\n def compute(self):\n if self.superstep() >= 1:\n s = 0\n while self.has_message():\n msg = self.get_message()\n s += msg\n self.set_value(0.15 / self.get_num_of_vertices() + 0.85 * s)\n if self.superstep() < 30:\n n = len(self.get_out_edges())\n if n > 0:\n self.send_message_to_all_neighbors(self.get_value() / n)\n else:\n self.vote_to_halt()\n\n\nclass PageRankReader(Reader):\n\n def read_num_of_vertices(self):\n line = self.config_fp.readline()\n return int(line)\n\n def read_vertex(self):\n line = self.graph_fp.readline()\n if not line:\n return None\n line = line.strip().split(':')\n vertex_id = int(line[0])\n edges = []\n if line[1]:\n for e in line[1].split(' '):\n edges.append(Edge(int(e), None))\n return PageRankVertex(vertex_id, None, edges)\n\n\nclass PageRankWriter(Writer):\n\n def write_vertex(self, vertex):\n return vertex.get_vertex_id(), str(vertex.get_value())\n\n\nclass PageRankCombiner(Combiner):\n\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\ndef main():\n if len(sys.argv) < 4:\n print('usage: python %s [config] [graph] [out_file]' % sys.argv[0])\n return\n pagerank_reader = PageRankReader(sys.argv[1], sys.argv[2])\n pagerank_writer = PageRankWriter(sys.argv[3])\n pagerank_combiner = PageRankCombiner()\n pagerank = Pypregel(reader=pagerank_reader, writer=pagerank_writer,\n combiner=pagerank_combiner)\n pagerank.run()\n\n\n<code token>\n", "<import token>\n\n\nclass PageRankVertex(Vertex):\n\n def compute(self):\n if self.superstep() >= 1:\n s = 0\n while self.has_message():\n msg = self.get_message()\n s += msg\n self.set_value(0.15 / self.get_num_of_vertices() + 0.85 * s)\n if self.superstep() < 30:\n n = len(self.get_out_edges())\n if n > 0:\n self.send_message_to_all_neighbors(self.get_value() / n)\n else:\n self.vote_to_halt()\n\n\nclass PageRankReader(Reader):\n\n def read_num_of_vertices(self):\n line = self.config_fp.readline()\n return int(line)\n\n def read_vertex(self):\n line = self.graph_fp.readline()\n if not line:\n return None\n line = line.strip().split(':')\n vertex_id = int(line[0])\n edges = []\n if line[1]:\n for e in line[1].split(' '):\n edges.append(Edge(int(e), None))\n return PageRankVertex(vertex_id, None, edges)\n\n\nclass PageRankWriter(Writer):\n\n def write_vertex(self, vertex):\n return vertex.get_vertex_id(), str(vertex.get_value())\n\n\nclass PageRankCombiner(Combiner):\n\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\n<function token>\n<code token>\n", "<import token>\n\n\nclass PageRankVertex(Vertex):\n <function token>\n\n\nclass PageRankReader(Reader):\n\n def read_num_of_vertices(self):\n line = self.config_fp.readline()\n return int(line)\n\n def read_vertex(self):\n line = self.graph_fp.readline()\n if not line:\n return None\n line = line.strip().split(':')\n vertex_id = int(line[0])\n edges = []\n if line[1]:\n for e in line[1].split(' '):\n edges.append(Edge(int(e), None))\n return PageRankVertex(vertex_id, None, edges)\n\n\nclass PageRankWriter(Writer):\n\n def write_vertex(self, vertex):\n return vertex.get_vertex_id(), str(vertex.get_value())\n\n\nclass PageRankCombiner(Combiner):\n\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n\n\nclass PageRankReader(Reader):\n\n def read_num_of_vertices(self):\n line = self.config_fp.readline()\n return int(line)\n\n def read_vertex(self):\n line = self.graph_fp.readline()\n if not line:\n return None\n line = line.strip().split(':')\n vertex_id = int(line[0])\n edges = []\n if line[1]:\n for e in line[1].split(' '):\n edges.append(Edge(int(e), None))\n return PageRankVertex(vertex_id, None, edges)\n\n\nclass PageRankWriter(Writer):\n\n def write_vertex(self, vertex):\n return vertex.get_vertex_id(), str(vertex.get_value())\n\n\nclass PageRankCombiner(Combiner):\n\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n\n\nclass PageRankReader(Reader):\n\n def read_num_of_vertices(self):\n line = self.config_fp.readline()\n return int(line)\n <function token>\n\n\nclass PageRankWriter(Writer):\n\n def write_vertex(self, vertex):\n return vertex.get_vertex_id(), str(vertex.get_value())\n\n\nclass PageRankCombiner(Combiner):\n\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n\n\nclass PageRankReader(Reader):\n <function token>\n <function token>\n\n\nclass PageRankWriter(Writer):\n\n def write_vertex(self, vertex):\n return vertex.get_vertex_id(), str(vertex.get_value())\n\n\nclass PageRankCombiner(Combiner):\n\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass PageRankWriter(Writer):\n\n def write_vertex(self, vertex):\n return vertex.get_vertex_id(), str(vertex.get_value())\n\n\nclass PageRankCombiner(Combiner):\n\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n\n\nclass PageRankWriter(Writer):\n <function token>\n\n\nclass PageRankCombiner(Combiner):\n\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass PageRankCombiner(Combiner):\n\n def combine(self, msg_x, msg_y):\n msg_x_value = msg_x[1]\n msg_y_value = msg_y[1]\n return None, msg_x_value + msg_y_value\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n\n\nclass PageRankCombiner(Combiner):\n <function token>\n\n\n<function token>\n<code token>\n", "<import token>\n<class token>\n<class token>\n<class token>\n<class token>\n<function token>\n<code token>\n" ]
false
789
78dc2193c05ddb4cd4c80b1c0322890eca7fcf19
import signal import time import sdnotify n = sdnotify.SystemdNotifier() if __name__ == '__main__': n.notify("READY=1") time.sleep(2)
[ "import signal\nimport time\n\nimport sdnotify\n\nn = sdnotify.SystemdNotifier()\n\nif __name__ == '__main__':\n\n n.notify(\"READY=1\")\n time.sleep(2)\n\n", "import signal\nimport time\nimport sdnotify\nn = sdnotify.SystemdNotifier()\nif __name__ == '__main__':\n n.notify('READY=1')\n time.sleep(2)\n", "<import token>\nn = sdnotify.SystemdNotifier()\nif __name__ == '__main__':\n n.notify('READY=1')\n time.sleep(2)\n", "<import token>\n<assignment token>\nif __name__ == '__main__':\n n.notify('READY=1')\n time.sleep(2)\n", "<import token>\n<assignment token>\n<code token>\n" ]
false
790
2fadc5c90d1bae14c57fc3bf02582e12aa8abdf6
import array from PIL import Image from generic.editable import XEditable as Editable class PLTT(Editable): """Palette information""" FORMAT_16BIT = 3 FORMAT_256BIT = 4 def define(self, clr): self.clr = clr self.string('magic', length=4, default='PLTT') # not reversed self.uint32('size_') self.uint32('format') self.uint32('extended') self.uint32('datasize') self.uint32('offset') self.data = '' def load(self, reader): Editable.load(self, reader) self.data = array.array('H', reader.read(self.datasize)) def save(self, writer): writer = Editable.save(self, writer) ofs = writer.tell() writer.write(self.data.tostring()) writer.writePadding(ofs+self.datasize) return writer def get_palettes(self): palettes = [] if self.format == self.FORMAT_16BIT: num = 16 elif self.format == self.FORMAT_256BIT: num = 256 start = 0 for pal_id in range(len(self.data)/num): palette = [] for i in range(num): val = self.data[start+i] palette.append((((val >> 0) & 0x1f) << 3, ((val >> 5) & 0x1f) << 3, ((val >> 10) & 0x1f) << 3, 255)) start += num palettes.append(palette) return palettes def get_palette(self, pal_id, transparent=True): palette = [] if self.format == self.FORMAT_16BIT: num = 16 elif self.format == self.FORMAT_256BIT: num = 256 start = pal_id*num for i in range(num): if not num and transparent: palette.append(chr(0)*4) continue val = self.data[start+i] palette.append(chr(((val >> 0) & 0x1f) << 3) + chr(((val >> 5) & 0x1f) << 3) + chr(((val >> 10) & 0x1f) << 3) + chr(255)) return palette def set_palette(self, pal_id, palette): """ Parameters ---------- pal_id : int palette : list of tuple List of 4-/3-int-tuple colors """ if self.format == self.FORMAT_16BIT: num = 16 elif self.format == self.FORMAT_256BIT: num = 256 start = pal_id*num for i, color in enumerate(palette): if i > num: break r, g, b = color[:3] self.data[start+i] = ((r >> 3) | (g >> 3 << 5) | (b >> 3 << 10)) class NCLR(Editable): """2d color information """ def define(self): self.string('magic', length=4, default='RLCN') self.uint16('endian', default=0xFFFE) self.uint16('version', default=0x101) self.uint32('size_') self.uint16('headersize', default=0x10) self.uint16('numblocks', default=1) self.pltt = PLTT(self) def load(self, reader): Editable.load(self, reader) assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic) self.pltt.load(reader) def save(self, writer=None): writer = Editable.save(self, writer) writer = self.pltt.save(writer) return writer def get_palette(self, pal_id=0, transparent=True): return self.pltt.get_palette(pal_id, transparent) def get_palettes(self): return self.pltt.get_palettes() def set_palette(self, pal_id, palette): return self.pltt.set_palette(pal_id, palette)
[ "\nimport array\n\nfrom PIL import Image\n\nfrom generic.editable import XEditable as Editable\n\n\nclass PLTT(Editable):\n \"\"\"Palette information\"\"\"\n FORMAT_16BIT = 3\n FORMAT_256BIT = 4\n\n def define(self, clr):\n self.clr = clr\n self.string('magic', length=4, default='PLTT') # not reversed\n self.uint32('size_')\n self.uint32('format')\n self.uint32('extended')\n self.uint32('datasize')\n self.uint32('offset')\n self.data = ''\n\n def load(self, reader):\n Editable.load(self, reader)\n self.data = array.array('H', reader.read(self.datasize))\n\n def save(self, writer):\n writer = Editable.save(self, writer)\n ofs = writer.tell()\n writer.write(self.data.tostring())\n writer.writePadding(ofs+self.datasize)\n return writer\n\n def get_palettes(self):\n palettes = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = 0\n for pal_id in range(len(self.data)/num):\n palette = []\n for i in range(num):\n val = self.data[start+i]\n palette.append((((val >> 0) & 0x1f) << 3,\n ((val >> 5) & 0x1f) << 3,\n ((val >> 10) & 0x1f) << 3,\n 255))\n start += num\n palettes.append(palette)\n return palettes\n\n def get_palette(self, pal_id, transparent=True):\n palette = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id*num\n for i in range(num):\n if not num and transparent:\n palette.append(chr(0)*4)\n continue\n val = self.data[start+i]\n palette.append(chr(((val >> 0) & 0x1f) << 3) +\n chr(((val >> 5) & 0x1f) << 3) +\n chr(((val >> 10) & 0x1f) << 3) +\n chr(255))\n return palette\n\n def set_palette(self, pal_id, palette):\n \"\"\"\n\n Parameters\n ----------\n pal_id : int\n palette : list of tuple\n List of 4-/3-int-tuple colors\n \"\"\"\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id*num\n for i, color in enumerate(palette):\n if i > num:\n break\n r, g, b = color[:3]\n self.data[start+i] = ((r >> 3) |\n (g >> 3 << 5) |\n (b >> 3 << 10))\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=0xFFFE)\n self.uint16('version', default=0x101)\n self.uint32('size_')\n self.uint16('headersize', default=0x10)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "import array\nfrom PIL import Image\nfrom generic.editable import XEditable as Editable\n\n\nclass PLTT(Editable):\n \"\"\"Palette information\"\"\"\n FORMAT_16BIT = 3\n FORMAT_256BIT = 4\n\n def define(self, clr):\n self.clr = clr\n self.string('magic', length=4, default='PLTT')\n self.uint32('size_')\n self.uint32('format')\n self.uint32('extended')\n self.uint32('datasize')\n self.uint32('offset')\n self.data = ''\n\n def load(self, reader):\n Editable.load(self, reader)\n self.data = array.array('H', reader.read(self.datasize))\n\n def save(self, writer):\n writer = Editable.save(self, writer)\n ofs = writer.tell()\n writer.write(self.data.tostring())\n writer.writePadding(ofs + self.datasize)\n return writer\n\n def get_palettes(self):\n palettes = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = 0\n for pal_id in range(len(self.data) / num):\n palette = []\n for i in range(num):\n val = self.data[start + i]\n palette.append(((val >> 0 & 31) << 3, (val >> 5 & 31) << 3,\n (val >> 10 & 31) << 3, 255))\n start += num\n palettes.append(palette)\n return palettes\n\n def get_palette(self, pal_id, transparent=True):\n palette = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i in range(num):\n if not num and transparent:\n palette.append(chr(0) * 4)\n continue\n val = self.data[start + i]\n palette.append(chr((val >> 0 & 31) << 3) + chr((val >> 5 & 31) <<\n 3) + chr((val >> 10 & 31) << 3) + chr(255))\n return palette\n\n def set_palette(self, pal_id, palette):\n \"\"\"\n\n Parameters\n ----------\n pal_id : int\n palette : list of tuple\n List of 4-/3-int-tuple colors\n \"\"\"\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i, color in enumerate(palette):\n if i > num:\n break\n r, g, b = color[:3]\n self.data[start + i] = r >> 3 | g >> 3 << 5 | b >> 3 << 10\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n\n\nclass PLTT(Editable):\n \"\"\"Palette information\"\"\"\n FORMAT_16BIT = 3\n FORMAT_256BIT = 4\n\n def define(self, clr):\n self.clr = clr\n self.string('magic', length=4, default='PLTT')\n self.uint32('size_')\n self.uint32('format')\n self.uint32('extended')\n self.uint32('datasize')\n self.uint32('offset')\n self.data = ''\n\n def load(self, reader):\n Editable.load(self, reader)\n self.data = array.array('H', reader.read(self.datasize))\n\n def save(self, writer):\n writer = Editable.save(self, writer)\n ofs = writer.tell()\n writer.write(self.data.tostring())\n writer.writePadding(ofs + self.datasize)\n return writer\n\n def get_palettes(self):\n palettes = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = 0\n for pal_id in range(len(self.data) / num):\n palette = []\n for i in range(num):\n val = self.data[start + i]\n palette.append(((val >> 0 & 31) << 3, (val >> 5 & 31) << 3,\n (val >> 10 & 31) << 3, 255))\n start += num\n palettes.append(palette)\n return palettes\n\n def get_palette(self, pal_id, transparent=True):\n palette = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i in range(num):\n if not num and transparent:\n palette.append(chr(0) * 4)\n continue\n val = self.data[start + i]\n palette.append(chr((val >> 0 & 31) << 3) + chr((val >> 5 & 31) <<\n 3) + chr((val >> 10 & 31) << 3) + chr(255))\n return palette\n\n def set_palette(self, pal_id, palette):\n \"\"\"\n\n Parameters\n ----------\n pal_id : int\n palette : list of tuple\n List of 4-/3-int-tuple colors\n \"\"\"\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i, color in enumerate(palette):\n if i > num:\n break\n r, g, b = color[:3]\n self.data[start + i] = r >> 3 | g >> 3 << 5 | b >> 3 << 10\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n\n\nclass PLTT(Editable):\n <docstring token>\n FORMAT_16BIT = 3\n FORMAT_256BIT = 4\n\n def define(self, clr):\n self.clr = clr\n self.string('magic', length=4, default='PLTT')\n self.uint32('size_')\n self.uint32('format')\n self.uint32('extended')\n self.uint32('datasize')\n self.uint32('offset')\n self.data = ''\n\n def load(self, reader):\n Editable.load(self, reader)\n self.data = array.array('H', reader.read(self.datasize))\n\n def save(self, writer):\n writer = Editable.save(self, writer)\n ofs = writer.tell()\n writer.write(self.data.tostring())\n writer.writePadding(ofs + self.datasize)\n return writer\n\n def get_palettes(self):\n palettes = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = 0\n for pal_id in range(len(self.data) / num):\n palette = []\n for i in range(num):\n val = self.data[start + i]\n palette.append(((val >> 0 & 31) << 3, (val >> 5 & 31) << 3,\n (val >> 10 & 31) << 3, 255))\n start += num\n palettes.append(palette)\n return palettes\n\n def get_palette(self, pal_id, transparent=True):\n palette = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i in range(num):\n if not num and transparent:\n palette.append(chr(0) * 4)\n continue\n val = self.data[start + i]\n palette.append(chr((val >> 0 & 31) << 3) + chr((val >> 5 & 31) <<\n 3) + chr((val >> 10 & 31) << 3) + chr(255))\n return palette\n\n def set_palette(self, pal_id, palette):\n \"\"\"\n\n Parameters\n ----------\n pal_id : int\n palette : list of tuple\n List of 4-/3-int-tuple colors\n \"\"\"\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i, color in enumerate(palette):\n if i > num:\n break\n r, g, b = color[:3]\n self.data[start + i] = r >> 3 | g >> 3 << 5 | b >> 3 << 10\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n\n\nclass PLTT(Editable):\n <docstring token>\n <assignment token>\n <assignment token>\n\n def define(self, clr):\n self.clr = clr\n self.string('magic', length=4, default='PLTT')\n self.uint32('size_')\n self.uint32('format')\n self.uint32('extended')\n self.uint32('datasize')\n self.uint32('offset')\n self.data = ''\n\n def load(self, reader):\n Editable.load(self, reader)\n self.data = array.array('H', reader.read(self.datasize))\n\n def save(self, writer):\n writer = Editable.save(self, writer)\n ofs = writer.tell()\n writer.write(self.data.tostring())\n writer.writePadding(ofs + self.datasize)\n return writer\n\n def get_palettes(self):\n palettes = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = 0\n for pal_id in range(len(self.data) / num):\n palette = []\n for i in range(num):\n val = self.data[start + i]\n palette.append(((val >> 0 & 31) << 3, (val >> 5 & 31) << 3,\n (val >> 10 & 31) << 3, 255))\n start += num\n palettes.append(palette)\n return palettes\n\n def get_palette(self, pal_id, transparent=True):\n palette = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i in range(num):\n if not num and transparent:\n palette.append(chr(0) * 4)\n continue\n val = self.data[start + i]\n palette.append(chr((val >> 0 & 31) << 3) + chr((val >> 5 & 31) <<\n 3) + chr((val >> 10 & 31) << 3) + chr(255))\n return palette\n\n def set_palette(self, pal_id, palette):\n \"\"\"\n\n Parameters\n ----------\n pal_id : int\n palette : list of tuple\n List of 4-/3-int-tuple colors\n \"\"\"\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i, color in enumerate(palette):\n if i > num:\n break\n r, g, b = color[:3]\n self.data[start + i] = r >> 3 | g >> 3 << 5 | b >> 3 << 10\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n\n\nclass PLTT(Editable):\n <docstring token>\n <assignment token>\n <assignment token>\n\n def define(self, clr):\n self.clr = clr\n self.string('magic', length=4, default='PLTT')\n self.uint32('size_')\n self.uint32('format')\n self.uint32('extended')\n self.uint32('datasize')\n self.uint32('offset')\n self.data = ''\n\n def load(self, reader):\n Editable.load(self, reader)\n self.data = array.array('H', reader.read(self.datasize))\n <function token>\n\n def get_palettes(self):\n palettes = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = 0\n for pal_id in range(len(self.data) / num):\n palette = []\n for i in range(num):\n val = self.data[start + i]\n palette.append(((val >> 0 & 31) << 3, (val >> 5 & 31) << 3,\n (val >> 10 & 31) << 3, 255))\n start += num\n palettes.append(palette)\n return palettes\n\n def get_palette(self, pal_id, transparent=True):\n palette = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i in range(num):\n if not num and transparent:\n palette.append(chr(0) * 4)\n continue\n val = self.data[start + i]\n palette.append(chr((val >> 0 & 31) << 3) + chr((val >> 5 & 31) <<\n 3) + chr((val >> 10 & 31) << 3) + chr(255))\n return palette\n\n def set_palette(self, pal_id, palette):\n \"\"\"\n\n Parameters\n ----------\n pal_id : int\n palette : list of tuple\n List of 4-/3-int-tuple colors\n \"\"\"\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i, color in enumerate(palette):\n if i > num:\n break\n r, g, b = color[:3]\n self.data[start + i] = r >> 3 | g >> 3 << 5 | b >> 3 << 10\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n\n\nclass PLTT(Editable):\n <docstring token>\n <assignment token>\n <assignment token>\n\n def define(self, clr):\n self.clr = clr\n self.string('magic', length=4, default='PLTT')\n self.uint32('size_')\n self.uint32('format')\n self.uint32('extended')\n self.uint32('datasize')\n self.uint32('offset')\n self.data = ''\n\n def load(self, reader):\n Editable.load(self, reader)\n self.data = array.array('H', reader.read(self.datasize))\n <function token>\n\n def get_palettes(self):\n palettes = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = 0\n for pal_id in range(len(self.data) / num):\n palette = []\n for i in range(num):\n val = self.data[start + i]\n palette.append(((val >> 0 & 31) << 3, (val >> 5 & 31) << 3,\n (val >> 10 & 31) << 3, 255))\n start += num\n palettes.append(palette)\n return palettes\n <function token>\n\n def set_palette(self, pal_id, palette):\n \"\"\"\n\n Parameters\n ----------\n pal_id : int\n palette : list of tuple\n List of 4-/3-int-tuple colors\n \"\"\"\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i, color in enumerate(palette):\n if i > num:\n break\n r, g, b = color[:3]\n self.data[start + i] = r >> 3 | g >> 3 << 5 | b >> 3 << 10\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n\n\nclass PLTT(Editable):\n <docstring token>\n <assignment token>\n <assignment token>\n\n def define(self, clr):\n self.clr = clr\n self.string('magic', length=4, default='PLTT')\n self.uint32('size_')\n self.uint32('format')\n self.uint32('extended')\n self.uint32('datasize')\n self.uint32('offset')\n self.data = ''\n <function token>\n <function token>\n\n def get_palettes(self):\n palettes = []\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = 0\n for pal_id in range(len(self.data) / num):\n palette = []\n for i in range(num):\n val = self.data[start + i]\n palette.append(((val >> 0 & 31) << 3, (val >> 5 & 31) << 3,\n (val >> 10 & 31) << 3, 255))\n start += num\n palettes.append(palette)\n return palettes\n <function token>\n\n def set_palette(self, pal_id, palette):\n \"\"\"\n\n Parameters\n ----------\n pal_id : int\n palette : list of tuple\n List of 4-/3-int-tuple colors\n \"\"\"\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i, color in enumerate(palette):\n if i > num:\n break\n r, g, b = color[:3]\n self.data[start + i] = r >> 3 | g >> 3 << 5 | b >> 3 << 10\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n\n\nclass PLTT(Editable):\n <docstring token>\n <assignment token>\n <assignment token>\n\n def define(self, clr):\n self.clr = clr\n self.string('magic', length=4, default='PLTT')\n self.uint32('size_')\n self.uint32('format')\n self.uint32('extended')\n self.uint32('datasize')\n self.uint32('offset')\n self.data = ''\n <function token>\n <function token>\n <function token>\n <function token>\n\n def set_palette(self, pal_id, palette):\n \"\"\"\n\n Parameters\n ----------\n pal_id : int\n palette : list of tuple\n List of 4-/3-int-tuple colors\n \"\"\"\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i, color in enumerate(palette):\n if i > num:\n break\n r, g, b = color[:3]\n self.data[start + i] = r >> 3 | g >> 3 << 5 | b >> 3 << 10\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n\n\nclass PLTT(Editable):\n <docstring token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n def set_palette(self, pal_id, palette):\n \"\"\"\n\n Parameters\n ----------\n pal_id : int\n palette : list of tuple\n List of 4-/3-int-tuple colors\n \"\"\"\n if self.format == self.FORMAT_16BIT:\n num = 16\n elif self.format == self.FORMAT_256BIT:\n num = 256\n start = pal_id * num\n for i, color in enumerate(palette):\n if i > num:\n break\n r, g, b = color[:3]\n self.data[start + i] = r >> 3 | g >> 3 << 5 | b >> 3 << 10\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n\n\nclass PLTT(Editable):\n <docstring token>\n <assignment token>\n <assignment token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n<class token>\n\n\nclass NCLR(Editable):\n \"\"\"2d color information\n \"\"\"\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n<class token>\n\n\nclass NCLR(Editable):\n <docstring token>\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n\n def save(self, writer=None):\n writer = Editable.save(self, writer)\n writer = self.pltt.save(writer)\n return writer\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n<class token>\n\n\nclass NCLR(Editable):\n <docstring token>\n\n def define(self):\n self.string('magic', length=4, default='RLCN')\n self.uint16('endian', default=65534)\n self.uint16('version', default=257)\n self.uint32('size_')\n self.uint16('headersize', default=16)\n self.uint16('numblocks', default=1)\n self.pltt = PLTT(self)\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n <function token>\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n<class token>\n\n\nclass NCLR(Editable):\n <docstring token>\n <function token>\n\n def load(self, reader):\n Editable.load(self, reader)\n assert self.magic == 'RLCN', 'Expected RLCN got '.format(self.magic)\n self.pltt.load(reader)\n <function token>\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n<class token>\n\n\nclass NCLR(Editable):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n\n def set_palette(self, pal_id, palette):\n return self.pltt.set_palette(pal_id, palette)\n", "<import token>\n<class token>\n\n\nclass NCLR(Editable):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n\n def get_palettes(self):\n return self.pltt.get_palettes()\n <function token>\n", "<import token>\n<class token>\n\n\nclass NCLR(Editable):\n <docstring token>\n <function token>\n <function token>\n <function token>\n\n def get_palette(self, pal_id=0, transparent=True):\n return self.pltt.get_palette(pal_id, transparent)\n <function token>\n <function token>\n", "<import token>\n<class token>\n\n\nclass NCLR(Editable):\n <docstring token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n <function token>\n", "<import token>\n<class token>\n<class token>\n" ]
false
791
bd06b04666ade1e7591b02f8211bc9b62fd08936
#!/usr/bin/env python import sys import errno # read first line from stdin and discard it first_line = sys.stdin.readline() # print all other lines for line in sys.stdin: try: print line, except IOError, e: if e.errno == errno.EPIPE: exit(0)
[ "#!/usr/bin/env python\nimport sys\nimport errno\n\n# read first line from stdin and discard it\nfirst_line = sys.stdin.readline()\n\n# print all other lines\nfor line in sys.stdin:\n try:\n print line,\n except IOError, e:\n if e.errno == errno.EPIPE:\n exit(0)\n\n" ]
true
792
360063940bb82defefc4195a5e17c9778b47e9e5
from requests import post import json import argparse import base64 from ReadFromWindow import new_image_string from ParsOnText import ParsOnText # Функция возвращает IAM-токен для аккаунта на Яндексе. def get_iam_token(iam_url, oauth_token): response = post(iam_url, json={"yandexPassportOauthToken": oauth_token}) json_data = json.loads(response.text) if json_data is not None and 'iamToken' in json_data: return json_data['iamToken'] return None # Функция отправляет на сервер запрос на распознавание изображения и возвращает ответ сервера. def request_analyze(vision_url, iam_token, folder_id, image_data): response = post(vision_url, headers={'Authorization': 'Bearer '+ iam_token}, json={ 'folderId': folder_id, 'analyzeSpecs': [ { 'content': image_data, 'features': [ { 'type': 'TEXT_DETECTION', 'textDetectionConfig': {'languageCodes': ['en', 'ru']} } ], } ]}) return response.text def MainYandex(): iam_url = 'https://iam.api.cloud.yandex.net/iam/v1/tokens' oauth_token = "AgAAAAAGg6eyAATuwWwJRFQmXUwDp4RCH-96fRc" iam_token = get_iam_token(iam_url, oauth_token) vision_url = 'https://vision.api.cloud.yandex.net/vision/v1/batchAnalyze' folder_id="b1gneif5vbojdoubsq1d" # iam_token = "CggaATEVAgAAABKABGpvdJWrMiN0GIJtioMMmFcbtp8oIyD15ply3SU8iLfpSS8yabiP2U8ar1vYibjhCbmbLcwQZu12fLA3wtelEAFb6WiHyMtpXIKsStx3w9K0QVfW9n-6CEzrbzeIpfdRgcCH6oonbDJusNPYePXJ-bfXGqAXcVJVsBJ8W1WKmy1LRJdIZh3stv9dP23-334JnnlO0Hna2uKrb_wwuKruBu1P_EFECnn8f11N8UllADo5MbD5YFdvRhLCHvsAaAPH0lzwGadUDSqvU1OmZOMZqGNktgmiKUIH7QJpYb-879VZtEFtCm7TVSBAKPZCDF_kBPDEymLZY5foRWvb0nTrI9-7XspfCdyoUVcH9fGyni5d7NtFtydsv9Vyuf0EQUcCv8cJ03SZWZZXze63i785VUq1rYoCc12j_Qo8Qela_RWNnsDWTw0Va0rzk9csN0vhUz9aYnpJhb-F0i_T0NCrABsBGShAauhz20FgEaUgrQ7NdA0GwTFApJ6zsCQfzc1o0YMhUS7C2YDQ9RmTTbe1PRr5s4qNx8vVuJ-whdz0aeKUdgPVOOdxyGXFxhpkDY8ykHgQMWeFr6MomppHrXAf8qwt6Ob__rehJYEVV8iOcAxb9ust3gaobxv-QRspyRnNLvWrp7fa-iWqB2nwdXL0bRz6be6B--Qjg8PRbbyVkixxGmYKIGYyMjM1M2EwMzBlODRkYWFhNjY0ODJiZjUzMjMzMGE2EJCmpuoFGND3qOoFIiQKFGFqZTJ2b2VyZWc3aHNidmgwbjFhEgx0YWtzaGVldi5rcmlaADACOAFKCBoBMRUCAAAAUAEg9QQ" image_data = new_image_string() response_text = request_analyze(vision_url, iam_token, folder_id, image_data) # with open('output.json', 'w') as f: # f.write(response_text) print(ParsOnText(response_text)) if __name__ == '__main__': MainYandex()
[ "from requests import post\nimport json\nimport argparse\nimport base64\nfrom ReadFromWindow import new_image_string\nfrom ParsOnText import ParsOnText\n\n# Функция возвращает IAM-токен для аккаунта на Яндексе.\ndef get_iam_token(iam_url, oauth_token):\n response = post(iam_url, json={\"yandexPassportOauthToken\": oauth_token})\n json_data = json.loads(response.text)\n if json_data is not None and 'iamToken' in json_data:\n return json_data['iamToken']\n return None\n\n# Функция отправляет на сервер запрос на распознавание изображения и возвращает ответ сервера.\ndef request_analyze(vision_url, iam_token, folder_id, image_data):\n response = post(vision_url, headers={'Authorization': 'Bearer '+ iam_token}, json={\n 'folderId': folder_id,\n 'analyzeSpecs': [\n {\n 'content': image_data,\n 'features': [\n {\n 'type': 'TEXT_DETECTION',\n 'textDetectionConfig': {'languageCodes': ['en', 'ru']}\n }\n ],\n }\n ]})\n return response.text\n\n\ndef MainYandex():\n iam_url = 'https://iam.api.cloud.yandex.net/iam/v1/tokens' \n\n oauth_token = \"AgAAAAAGg6eyAATuwWwJRFQmXUwDp4RCH-96fRc\" \n\n iam_token = get_iam_token(iam_url, oauth_token)\n \n vision_url = 'https://vision.api.cloud.yandex.net/vision/v1/batchAnalyze'\n\n folder_id=\"b1gneif5vbojdoubsq1d\"\n\n# iam_token = \"CggaATEVAgAAABKABGpvdJWrMiN0GIJtioMMmFcbtp8oIyD15ply3SU8iLfpSS8yabiP2U8ar1vYibjhCbmbLcwQZu12fLA3wtelEAFb6WiHyMtpXIKsStx3w9K0QVfW9n-6CEzrbzeIpfdRgcCH6oonbDJusNPYePXJ-bfXGqAXcVJVsBJ8W1WKmy1LRJdIZh3stv9dP23-334JnnlO0Hna2uKrb_wwuKruBu1P_EFECnn8f11N8UllADo5MbD5YFdvRhLCHvsAaAPH0lzwGadUDSqvU1OmZOMZqGNktgmiKUIH7QJpYb-879VZtEFtCm7TVSBAKPZCDF_kBPDEymLZY5foRWvb0nTrI9-7XspfCdyoUVcH9fGyni5d7NtFtydsv9Vyuf0EQUcCv8cJ03SZWZZXze63i785VUq1rYoCc12j_Qo8Qela_RWNnsDWTw0Va0rzk9csN0vhUz9aYnpJhb-F0i_T0NCrABsBGShAauhz20FgEaUgrQ7NdA0GwTFApJ6zsCQfzc1o0YMhUS7C2YDQ9RmTTbe1PRr5s4qNx8vVuJ-whdz0aeKUdgPVOOdxyGXFxhpkDY8ykHgQMWeFr6MomppHrXAf8qwt6Ob__rehJYEVV8iOcAxb9ust3gaobxv-QRspyRnNLvWrp7fa-iWqB2nwdXL0bRz6be6B--Qjg8PRbbyVkixxGmYKIGYyMjM1M2EwMzBlODRkYWFhNjY0ODJiZjUzMjMzMGE2EJCmpuoFGND3qOoFIiQKFGFqZTJ2b2VyZWc3aHNidmgwbjFhEgx0YWtzaGVldi5rcmlaADACOAFKCBoBMRUCAAAAUAEg9QQ\"\n \n image_data = new_image_string()\n \n response_text = request_analyze(vision_url, iam_token, folder_id, image_data)\n# with open('output.json', 'w') as f:\n# f.write(response_text)\n print(ParsOnText(response_text))\n \n\nif __name__ == '__main__':\n MainYandex() \n", "from requests import post\nimport json\nimport argparse\nimport base64\nfrom ReadFromWindow import new_image_string\nfrom ParsOnText import ParsOnText\n\n\ndef get_iam_token(iam_url, oauth_token):\n response = post(iam_url, json={'yandexPassportOauthToken': oauth_token})\n json_data = json.loads(response.text)\n if json_data is not None and 'iamToken' in json_data:\n return json_data['iamToken']\n return None\n\n\ndef request_analyze(vision_url, iam_token, folder_id, image_data):\n response = post(vision_url, headers={'Authorization': 'Bearer ' +\n iam_token}, json={'folderId': folder_id, 'analyzeSpecs': [{\n 'content': image_data, 'features': [{'type': 'TEXT_DETECTION',\n 'textDetectionConfig': {'languageCodes': ['en', 'ru']}}]}]})\n return response.text\n\n\ndef MainYandex():\n iam_url = 'https://iam.api.cloud.yandex.net/iam/v1/tokens'\n oauth_token = 'AgAAAAAGg6eyAATuwWwJRFQmXUwDp4RCH-96fRc'\n iam_token = get_iam_token(iam_url, oauth_token)\n vision_url = 'https://vision.api.cloud.yandex.net/vision/v1/batchAnalyze'\n folder_id = 'b1gneif5vbojdoubsq1d'\n image_data = new_image_string()\n response_text = request_analyze(vision_url, iam_token, folder_id,\n image_data)\n print(ParsOnText(response_text))\n\n\nif __name__ == '__main__':\n MainYandex()\n", "<import token>\n\n\ndef get_iam_token(iam_url, oauth_token):\n response = post(iam_url, json={'yandexPassportOauthToken': oauth_token})\n json_data = json.loads(response.text)\n if json_data is not None and 'iamToken' in json_data:\n return json_data['iamToken']\n return None\n\n\ndef request_analyze(vision_url, iam_token, folder_id, image_data):\n response = post(vision_url, headers={'Authorization': 'Bearer ' +\n iam_token}, json={'folderId': folder_id, 'analyzeSpecs': [{\n 'content': image_data, 'features': [{'type': 'TEXT_DETECTION',\n 'textDetectionConfig': {'languageCodes': ['en', 'ru']}}]}]})\n return response.text\n\n\ndef MainYandex():\n iam_url = 'https://iam.api.cloud.yandex.net/iam/v1/tokens'\n oauth_token = 'AgAAAAAGg6eyAATuwWwJRFQmXUwDp4RCH-96fRc'\n iam_token = get_iam_token(iam_url, oauth_token)\n vision_url = 'https://vision.api.cloud.yandex.net/vision/v1/batchAnalyze'\n folder_id = 'b1gneif5vbojdoubsq1d'\n image_data = new_image_string()\n response_text = request_analyze(vision_url, iam_token, folder_id,\n image_data)\n print(ParsOnText(response_text))\n\n\nif __name__ == '__main__':\n MainYandex()\n", "<import token>\n\n\ndef get_iam_token(iam_url, oauth_token):\n response = post(iam_url, json={'yandexPassportOauthToken': oauth_token})\n json_data = json.loads(response.text)\n if json_data is not None and 'iamToken' in json_data:\n return json_data['iamToken']\n return None\n\n\ndef request_analyze(vision_url, iam_token, folder_id, image_data):\n response = post(vision_url, headers={'Authorization': 'Bearer ' +\n iam_token}, json={'folderId': folder_id, 'analyzeSpecs': [{\n 'content': image_data, 'features': [{'type': 'TEXT_DETECTION',\n 'textDetectionConfig': {'languageCodes': ['en', 'ru']}}]}]})\n return response.text\n\n\ndef MainYandex():\n iam_url = 'https://iam.api.cloud.yandex.net/iam/v1/tokens'\n oauth_token = 'AgAAAAAGg6eyAATuwWwJRFQmXUwDp4RCH-96fRc'\n iam_token = get_iam_token(iam_url, oauth_token)\n vision_url = 'https://vision.api.cloud.yandex.net/vision/v1/batchAnalyze'\n folder_id = 'b1gneif5vbojdoubsq1d'\n image_data = new_image_string()\n response_text = request_analyze(vision_url, iam_token, folder_id,\n image_data)\n print(ParsOnText(response_text))\n\n\n<code token>\n", "<import token>\n<function token>\n\n\ndef request_analyze(vision_url, iam_token, folder_id, image_data):\n response = post(vision_url, headers={'Authorization': 'Bearer ' +\n iam_token}, json={'folderId': folder_id, 'analyzeSpecs': [{\n 'content': image_data, 'features': [{'type': 'TEXT_DETECTION',\n 'textDetectionConfig': {'languageCodes': ['en', 'ru']}}]}]})\n return response.text\n\n\ndef MainYandex():\n iam_url = 'https://iam.api.cloud.yandex.net/iam/v1/tokens'\n oauth_token = 'AgAAAAAGg6eyAATuwWwJRFQmXUwDp4RCH-96fRc'\n iam_token = get_iam_token(iam_url, oauth_token)\n vision_url = 'https://vision.api.cloud.yandex.net/vision/v1/batchAnalyze'\n folder_id = 'b1gneif5vbojdoubsq1d'\n image_data = new_image_string()\n response_text = request_analyze(vision_url, iam_token, folder_id,\n image_data)\n print(ParsOnText(response_text))\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n\n\ndef MainYandex():\n iam_url = 'https://iam.api.cloud.yandex.net/iam/v1/tokens'\n oauth_token = 'AgAAAAAGg6eyAATuwWwJRFQmXUwDp4RCH-96fRc'\n iam_token = get_iam_token(iam_url, oauth_token)\n vision_url = 'https://vision.api.cloud.yandex.net/vision/v1/batchAnalyze'\n folder_id = 'b1gneif5vbojdoubsq1d'\n image_data = new_image_string()\n response_text = request_analyze(vision_url, iam_token, folder_id,\n image_data)\n print(ParsOnText(response_text))\n\n\n<code token>\n", "<import token>\n<function token>\n<function token>\n<function token>\n<code token>\n" ]
false
793
75716aaaca63f8ca6d32c885021c1dc0f9a12dac
# -*- coding: utf-8 -*- # Third party imports import numpy as np # Local application imports from mosqito.sound_level_meter import noct_spectrum from mosqito.sq_metrics.loudness.loudness_zwst._main_loudness import _main_loudness from mosqito.sq_metrics.loudness.loudness_zwst._calc_slopes import _calc_slopes from mosqito.utils.conversion import amp2db # Optional package import try: from SciDataTool import DataTime, DataLinspace, DataFreq except ImportError: DataTime = None DataLinspace = None DataFreq = None def loudness_zwst(signal, fs=None, field_type="free", is_sdt_output=False): """Zwicker-loudness calculation for stationary signals Calculates the acoustic loudness according to Zwicker method for stationary signals. Normatice reference: ISO 532:1975 (method B) DIN 45631:1991 ISO 532-1:2017 (method 1) The code is based on BASIC program published in "Program for calculating loudness according to DIN 45631 (ISO 532B)", E.Zwicker and H.Fastl, J.A.S.J (E) 12, 1 (1991). Note that due to normative continuity, as defined in the preceeding standards, the method is in accordance with ISO 226:1987 equal loudness contours (instead of ISO 226:2003) Parameters ---------- signal : numpy.array or DataTime object Signal time values [Pa] fs : float, optional Sampling frequency, can be omitted if the input is a DataTime object. Default to None field_type : str Type of soundfield corresponding to spec_third ("free" by default or "diffuse"). is_sdt_output : Bool, optional If True, the outputs are returned as SciDataTool objects. Default to False Outputs ------- N : float or numpy.array The overall loudness array [sones], size (Ntime,). N_specific : numpy.ndarray or DataFreq object The specific loudness array [sones/bark], size (Nbark, Ntime). bark_axis: numpy.array The Bark axis array, size (Nbark,). """ # Manage SciDataTool input type if DataTime is not None and isinstance(signal, DataTime): time = signal.get_along("time")["time"] fs = 1 / (time[1] - time[0]) signal = signal.get_along("time")[signal.symbol] # Compute third octave band spectrum spec_third, _ = noct_spectrum(signal, fs, fmin=24, fmax=12600) # Compute dB values spec_third = amp2db(spec_third, ref=2e-5) # Compute main loudness Nm = _main_loudness(spec_third, field_type) # Computation of specific loudness pattern and integration of overall # loudness by attaching slopes towards higher frequencies N, N_specific = _calc_slopes(Nm) # Define Bark axis bark_axis = np.linspace(0.1, 24, int(24 / 0.1)) # Manage SciDataTool output type if is_sdt_output: if DataLinspace is None: raise RuntimeError( "In order to handle Data objects you need the 'SciDataTool' package." ) else: bark_data = DataLinspace( name="Critical band rate", unit="Bark", initial=0, final=24, number=int(24 / 0.1), include_endpoint=True, ) N_specific = DataFreq( name="Specific loudness (Zwicker method for stationnary signal)", symbol="N'_{zwst}", axes=[bark_data], values=N_specific, unit="sone/Bark", ) return N, N_specific, bark_axis
[ "# -*- coding: utf-8 -*-\n\n# Third party imports\nimport numpy as np\n\n# Local application imports\nfrom mosqito.sound_level_meter import noct_spectrum\nfrom mosqito.sq_metrics.loudness.loudness_zwst._main_loudness import _main_loudness\nfrom mosqito.sq_metrics.loudness.loudness_zwst._calc_slopes import _calc_slopes\nfrom mosqito.utils.conversion import amp2db\n\n# Optional package import\ntry:\n from SciDataTool import DataTime, DataLinspace, DataFreq\nexcept ImportError:\n DataTime = None\n DataLinspace = None\n DataFreq = None\n\n\ndef loudness_zwst(signal, fs=None, field_type=\"free\", is_sdt_output=False):\n \"\"\"Zwicker-loudness calculation for stationary signals\n\n Calculates the acoustic loudness according to Zwicker method for\n stationary signals.\n Normatice reference:\n ISO 532:1975 (method B)\n DIN 45631:1991\n ISO 532-1:2017 (method 1)\n The code is based on BASIC program published in \"Program for\n calculating loudness according to DIN 45631 (ISO 532B)\", E.Zwicker\n and H.Fastl, J.A.S.J (E) 12, 1 (1991).\n Note that due to normative continuity, as defined in the\n preceeding standards, the method is in accordance with\n ISO 226:1987 equal loudness contours (instead of ISO 226:2003)\n\n Parameters\n ----------\n signal : numpy.array or DataTime object\n Signal time values [Pa]\n fs : float, optional\n Sampling frequency, can be omitted if the input is a DataTime\n object. Default to None\n field_type : str\n Type of soundfield corresponding to spec_third (\"free\" by\n default or \"diffuse\").\n is_sdt_output : Bool, optional\n If True, the outputs are returned as SciDataTool objects.\n Default to False\n\n Outputs\n -------\n N : float or numpy.array\n The overall loudness array [sones], size (Ntime,).\n N_specific : numpy.ndarray or DataFreq object\n The specific loudness array [sones/bark], size (Nbark, Ntime).\n bark_axis: numpy.array\n The Bark axis array, size (Nbark,).\n \"\"\"\n\n # Manage SciDataTool input type\n if DataTime is not None and isinstance(signal, DataTime):\n time = signal.get_along(\"time\")[\"time\"]\n fs = 1 / (time[1] - time[0])\n signal = signal.get_along(\"time\")[signal.symbol]\n\n # Compute third octave band spectrum\n spec_third, _ = noct_spectrum(signal, fs, fmin=24, fmax=12600)\n\n # Compute dB values\n spec_third = amp2db(spec_third, ref=2e-5)\n\n # Compute main loudness\n Nm = _main_loudness(spec_third, field_type)\n\n # Computation of specific loudness pattern and integration of overall\n # loudness by attaching slopes towards higher frequencies\n N, N_specific = _calc_slopes(Nm)\n\n # Define Bark axis\n bark_axis = np.linspace(0.1, 24, int(24 / 0.1))\n\n # Manage SciDataTool output type\n if is_sdt_output:\n if DataLinspace is None:\n raise RuntimeError(\n \"In order to handle Data objects you need the 'SciDataTool' package.\"\n )\n else:\n bark_data = DataLinspace(\n name=\"Critical band rate\",\n unit=\"Bark\",\n initial=0,\n final=24,\n number=int(24 / 0.1),\n include_endpoint=True,\n )\n N_specific = DataFreq(\n name=\"Specific loudness (Zwicker method for stationnary signal)\",\n symbol=\"N'_{zwst}\",\n axes=[bark_data],\n values=N_specific,\n unit=\"sone/Bark\",\n )\n\n return N, N_specific, bark_axis\n", "import numpy as np\nfrom mosqito.sound_level_meter import noct_spectrum\nfrom mosqito.sq_metrics.loudness.loudness_zwst._main_loudness import _main_loudness\nfrom mosqito.sq_metrics.loudness.loudness_zwst._calc_slopes import _calc_slopes\nfrom mosqito.utils.conversion import amp2db\ntry:\n from SciDataTool import DataTime, DataLinspace, DataFreq\nexcept ImportError:\n DataTime = None\n DataLinspace = None\n DataFreq = None\n\n\ndef loudness_zwst(signal, fs=None, field_type='free', is_sdt_output=False):\n \"\"\"Zwicker-loudness calculation for stationary signals\n\n Calculates the acoustic loudness according to Zwicker method for\n stationary signals.\n Normatice reference:\n ISO 532:1975 (method B)\n DIN 45631:1991\n ISO 532-1:2017 (method 1)\n The code is based on BASIC program published in \"Program for\n calculating loudness according to DIN 45631 (ISO 532B)\", E.Zwicker\n and H.Fastl, J.A.S.J (E) 12, 1 (1991).\n Note that due to normative continuity, as defined in the\n preceeding standards, the method is in accordance with\n ISO 226:1987 equal loudness contours (instead of ISO 226:2003)\n\n Parameters\n ----------\n signal : numpy.array or DataTime object\n Signal time values [Pa]\n fs : float, optional\n Sampling frequency, can be omitted if the input is a DataTime\n object. Default to None\n field_type : str\n Type of soundfield corresponding to spec_third (\"free\" by\n default or \"diffuse\").\n is_sdt_output : Bool, optional\n If True, the outputs are returned as SciDataTool objects.\n Default to False\n\n Outputs\n -------\n N : float or numpy.array\n The overall loudness array [sones], size (Ntime,).\n N_specific : numpy.ndarray or DataFreq object\n The specific loudness array [sones/bark], size (Nbark, Ntime).\n bark_axis: numpy.array\n The Bark axis array, size (Nbark,).\n \"\"\"\n if DataTime is not None and isinstance(signal, DataTime):\n time = signal.get_along('time')['time']\n fs = 1 / (time[1] - time[0])\n signal = signal.get_along('time')[signal.symbol]\n spec_third, _ = noct_spectrum(signal, fs, fmin=24, fmax=12600)\n spec_third = amp2db(spec_third, ref=2e-05)\n Nm = _main_loudness(spec_third, field_type)\n N, N_specific = _calc_slopes(Nm)\n bark_axis = np.linspace(0.1, 24, int(24 / 0.1))\n if is_sdt_output:\n if DataLinspace is None:\n raise RuntimeError(\n \"In order to handle Data objects you need the 'SciDataTool' package.\"\n )\n else:\n bark_data = DataLinspace(name='Critical band rate', unit='Bark',\n initial=0, final=24, number=int(24 / 0.1), include_endpoint\n =True)\n N_specific = DataFreq(name=\n 'Specific loudness (Zwicker method for stationnary signal)',\n symbol=\"N'_{zwst}\", axes=[bark_data], values=N_specific,\n unit='sone/Bark')\n return N, N_specific, bark_axis\n", "<import token>\ntry:\n from SciDataTool import DataTime, DataLinspace, DataFreq\nexcept ImportError:\n DataTime = None\n DataLinspace = None\n DataFreq = None\n\n\ndef loudness_zwst(signal, fs=None, field_type='free', is_sdt_output=False):\n \"\"\"Zwicker-loudness calculation for stationary signals\n\n Calculates the acoustic loudness according to Zwicker method for\n stationary signals.\n Normatice reference:\n ISO 532:1975 (method B)\n DIN 45631:1991\n ISO 532-1:2017 (method 1)\n The code is based on BASIC program published in \"Program for\n calculating loudness according to DIN 45631 (ISO 532B)\", E.Zwicker\n and H.Fastl, J.A.S.J (E) 12, 1 (1991).\n Note that due to normative continuity, as defined in the\n preceeding standards, the method is in accordance with\n ISO 226:1987 equal loudness contours (instead of ISO 226:2003)\n\n Parameters\n ----------\n signal : numpy.array or DataTime object\n Signal time values [Pa]\n fs : float, optional\n Sampling frequency, can be omitted if the input is a DataTime\n object. Default to None\n field_type : str\n Type of soundfield corresponding to spec_third (\"free\" by\n default or \"diffuse\").\n is_sdt_output : Bool, optional\n If True, the outputs are returned as SciDataTool objects.\n Default to False\n\n Outputs\n -------\n N : float or numpy.array\n The overall loudness array [sones], size (Ntime,).\n N_specific : numpy.ndarray or DataFreq object\n The specific loudness array [sones/bark], size (Nbark, Ntime).\n bark_axis: numpy.array\n The Bark axis array, size (Nbark,).\n \"\"\"\n if DataTime is not None and isinstance(signal, DataTime):\n time = signal.get_along('time')['time']\n fs = 1 / (time[1] - time[0])\n signal = signal.get_along('time')[signal.symbol]\n spec_third, _ = noct_spectrum(signal, fs, fmin=24, fmax=12600)\n spec_third = amp2db(spec_third, ref=2e-05)\n Nm = _main_loudness(spec_third, field_type)\n N, N_specific = _calc_slopes(Nm)\n bark_axis = np.linspace(0.1, 24, int(24 / 0.1))\n if is_sdt_output:\n if DataLinspace is None:\n raise RuntimeError(\n \"In order to handle Data objects you need the 'SciDataTool' package.\"\n )\n else:\n bark_data = DataLinspace(name='Critical band rate', unit='Bark',\n initial=0, final=24, number=int(24 / 0.1), include_endpoint\n =True)\n N_specific = DataFreq(name=\n 'Specific loudness (Zwicker method for stationnary signal)',\n symbol=\"N'_{zwst}\", axes=[bark_data], values=N_specific,\n unit='sone/Bark')\n return N, N_specific, bark_axis\n", "<import token>\n<code token>\n\n\ndef loudness_zwst(signal, fs=None, field_type='free', is_sdt_output=False):\n \"\"\"Zwicker-loudness calculation for stationary signals\n\n Calculates the acoustic loudness according to Zwicker method for\n stationary signals.\n Normatice reference:\n ISO 532:1975 (method B)\n DIN 45631:1991\n ISO 532-1:2017 (method 1)\n The code is based on BASIC program published in \"Program for\n calculating loudness according to DIN 45631 (ISO 532B)\", E.Zwicker\n and H.Fastl, J.A.S.J (E) 12, 1 (1991).\n Note that due to normative continuity, as defined in the\n preceeding standards, the method is in accordance with\n ISO 226:1987 equal loudness contours (instead of ISO 226:2003)\n\n Parameters\n ----------\n signal : numpy.array or DataTime object\n Signal time values [Pa]\n fs : float, optional\n Sampling frequency, can be omitted if the input is a DataTime\n object. Default to None\n field_type : str\n Type of soundfield corresponding to spec_third (\"free\" by\n default or \"diffuse\").\n is_sdt_output : Bool, optional\n If True, the outputs are returned as SciDataTool objects.\n Default to False\n\n Outputs\n -------\n N : float or numpy.array\n The overall loudness array [sones], size (Ntime,).\n N_specific : numpy.ndarray or DataFreq object\n The specific loudness array [sones/bark], size (Nbark, Ntime).\n bark_axis: numpy.array\n The Bark axis array, size (Nbark,).\n \"\"\"\n if DataTime is not None and isinstance(signal, DataTime):\n time = signal.get_along('time')['time']\n fs = 1 / (time[1] - time[0])\n signal = signal.get_along('time')[signal.symbol]\n spec_third, _ = noct_spectrum(signal, fs, fmin=24, fmax=12600)\n spec_third = amp2db(spec_third, ref=2e-05)\n Nm = _main_loudness(spec_third, field_type)\n N, N_specific = _calc_slopes(Nm)\n bark_axis = np.linspace(0.1, 24, int(24 / 0.1))\n if is_sdt_output:\n if DataLinspace is None:\n raise RuntimeError(\n \"In order to handle Data objects you need the 'SciDataTool' package.\"\n )\n else:\n bark_data = DataLinspace(name='Critical band rate', unit='Bark',\n initial=0, final=24, number=int(24 / 0.1), include_endpoint\n =True)\n N_specific = DataFreq(name=\n 'Specific loudness (Zwicker method for stationnary signal)',\n symbol=\"N'_{zwst}\", axes=[bark_data], values=N_specific,\n unit='sone/Bark')\n return N, N_specific, bark_axis\n", "<import token>\n<code token>\n<function token>\n" ]
false
794
0e9d0927e8d69b0c0fad98479d47f2409c95a751
n = int(input()) a = sorted([int(input()) for _ in range(n)]) x = a[:n//2] y = a[(n + 1)//2:] ans = 0 for i in range(len(x)): ans += abs(x[i] - y[i]) for i in range(1, len(y)): ans += abs(x[i - 1] - y[i]) if n % 2 == 1: ans += max( abs(a[n // 2] - x[-1]), abs(a[n // 2] - y[0]), ) print(ans)
[ "n = int(input())\na = sorted([int(input()) for _ in range(n)])\n\nx = a[:n//2]\ny = a[(n + 1)//2:]\n\nans = 0\nfor i in range(len(x)):\n ans += abs(x[i] - y[i])\nfor i in range(1, len(y)):\n ans += abs(x[i - 1] - y[i])\nif n % 2 == 1:\n ans += max(\n abs(a[n // 2] - x[-1]),\n abs(a[n // 2] - y[0]),\n )\nprint(ans)", "n = int(input())\na = sorted([int(input()) for _ in range(n)])\nx = a[:n // 2]\ny = a[(n + 1) // 2:]\nans = 0\nfor i in range(len(x)):\n ans += abs(x[i] - y[i])\nfor i in range(1, len(y)):\n ans += abs(x[i - 1] - y[i])\nif n % 2 == 1:\n ans += max(abs(a[n // 2] - x[-1]), abs(a[n // 2] - y[0]))\nprint(ans)\n", "<assignment token>\nfor i in range(len(x)):\n ans += abs(x[i] - y[i])\nfor i in range(1, len(y)):\n ans += abs(x[i - 1] - y[i])\nif n % 2 == 1:\n ans += max(abs(a[n // 2] - x[-1]), abs(a[n // 2] - y[0]))\nprint(ans)\n", "<assignment token>\n<code token>\n" ]
false
795
e3dece36ba3e5b3df763e7119c485f6ed2155098
# Core Packages import difflib import tkinter as tk from tkinter import * from tkinter import ttk from tkinter.scrolledtext import * import tkinter.filedialog import PyPDF2 from tkinter import filedialog import torch import json from transformers import T5Tokenizer, T5ForConditionalGeneration, T5Config # NLP Pkgs from spacy_summarization import text_summarizer from gensim.summarization import summarize from nltk_summarization import nltk_summarizer # Web Scraping Pkg from bs4 import BeautifulSoup from urllib.request import urlopen # Structure and Layout window = Tk() window.title("Summaryzer GUI") window.geometry("700x400") window.config(background='black') style = ttk.Style(window) style.configure('lefttab.TNotebook', tabposition='wn', ) # TAB LAYOUT tab_control = ttk.Notebook(window, style='lefttab.TNotebook') tab2 = ttk.Frame(tab_control) tab3 = ttk.Frame(tab_control) # ADD TABS TO NOTEBOOK tab_control.add(tab3, text=f'{"Extractive":^20s}') tab_control.add(tab2, text=f'{"Abstractive":^20s}') label1 = Label(tab3, text='Extractive Summrize', padx=5, pady=5) label1.grid(column=1, row=0) label2 = Label(tab2, text='Abstractive Summrize',padx=5, pady=5) label2.grid(column=0, row=0) tab_control.pack(expand=1, fill='both') def get_summary(): model = T5ForConditionalGeneration.from_pretrained ('t5-small') tokenizer = T5Tokenizer.from_pretrained ('t5-small') device = torch.device ('cpu') text = str(url_display1.get('1.0', tk.END)) preprocess_text = text.strip ().replace ("\n", "") t5_prepared_Text = "summarize: " + preprocess_text tokenized_text = tokenizer.encode (t5_prepared_Text, return_tensors="pt").to (device) summary_ids = model.generate (tokenized_text, num_beams=4, no_repeat_ngram_size=2, min_length=30, max_length=100, early_stopping=True) output = tokenizer.decode (summary_ids[0], skip_special_tokens=True) Str1 = text str2 = output printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100 edited = len(text)-len(output) Precision = (len(text)+len(output)+edited)/2 Precisioncalc = Precision / 100 result =("\n\nSummarized text: \n", output)," Precision = " , Precisioncalc , " similarity = " , printt tab2_display_text.insert(tk.END, result) def open_pdf(): open_file = filedialog.askopenfilename( initialdir="C:/gui/", title="Open PDF File", filetypes=( ("PDF Files", "*.pdf"), ("All Files", "."))) if open_file: pdf_file = PyPDF2.PdfFileReader(open_file) page = pdf_file.getPage(0) page_stuff = page.extractText() io = page_stuff.split() url_display.insert(3.0, io) def open_pdf1(): open_file = filedialog.askopenfilename( initialdir="C:/gui/", title="Open PDF File", filetypes=( ("PDF Files", "*.pdf"), ("All Files", "."))) if open_file: pdf_file = PyPDF2.PdfFileReader(open_file) page = pdf_file.getPage(0) page_stuff = page.extractText() io = page_stuff.split() url_display1.insert(3.0, io) def clear_display_result(): tab3_display_text.delete('1.0', END) # Clear For URL def clear_url_entry(): url_entry.delete(0, END) # Open File to Read and Process def openfiles(): file1 = tkinter.filedialog.askopenfilename(filetypes=(("Text Files", ".txt"), ("All files", "*"))) read_text = open(file1).read() url_display.insert(tk.END, read_text) def get_text(): raw_text = str(url_entry.get()) page = urlopen(raw_text) soup = BeautifulSoup(page) fetched_text = ' '.join(map(lambda p: p.text, soup.find_all('p'))) url_display.insert(tk.END, fetched_text) def get_url_summary(): raw_text = url_display.get('1.0', tk.END) final_text = text_summarizer(raw_text) result = '\nSummary:{}'.format(final_text) tab3_display_text.insert(tk.END, result) def use_spacy (): raw_text = url_display.get('1.0', tk.END) final_text = text_summarizer(raw_text) print(final_text) Str1 = raw_text str2 = text_summarizer(raw_text) printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100 Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text) Precisioncalc = Precision / 100 result = '\nSpacy Summary:{}\n'.format(final_text)," Precision = " , Precisioncalc , " similarity = " , printt tab3_display_text.insert(tk.END, result) def use_nltk(): raw_text = url_display.get ('1.0', tk.END) final_text = nltk_summarizer (raw_text) print (final_text) Str1 = raw_text str2 = nltk_summarizer(raw_text) printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100 Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text) Precisioncalc = Precision / 100 result = '\nNLTK Summary:{}\n'.format(final_text)," Precision = " , Precisioncalc , " similarity = " , printt tab3_display_text.insert(tk.END, result) def use_gensim(): raw_text = url_display.get ('1.0', tk.END) final_text = summarize(raw_text) print (final_text) Str1 = raw_text str2 = summarize(raw_text) printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100 Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text) Precisioncalc = Precision / 100 result ='\nGensim Summary:{}\n'.format(final_text)," Precision = " , Precisioncalc , " similarity = " , printt tab3_display_text.insert(tk.END, result) # URL TAB l1 = Label(tab3, text="Enter URL To Summarize") l1.grid(row=1, column=0) raw_entry = StringVar() url_entry = Entry(tab3, textvariable=raw_entry, width=50) url_entry.grid(row=1, column=1) # BUTTONS button1 = Button(tab3, text="Reset", command=clear_url_entry, width=12, bg='#03A9F4', fg='#fff') button1.grid(row=4, column=0, padx=10, pady=10) button2 = Button(tab3, text="Get Text", command=get_text, width=12, bg='#03A9F4', fg='#fff') button2.grid(row=4, column=1, padx=10, pady=10) button3 = Button(tab3, text="Open File", width=12, command=openfiles, bg='#c5cae9') button3.grid(row=5, column=0, padx=10, pady=10) button4 = Button(tab3, text="Open PDF", width=12, command=open_pdf, bg='#c5cae9') button4.grid(row=5, column=1, padx=10, pady=10) button5 = Button(tab3, text="SpaCy", command=use_spacy, width=12, bg='red', fg='#fff') button5.grid(row=8, column=0, padx=10, pady=10) button6 = Button(tab3, text="Clear Result", command=clear_display_result, width=12, bg='#03A9F4', fg='#fff') button6.grid(row=9, column=1, padx=10, pady=10) button7 = Button(tab3, text="NLTK", command=use_nltk, width=12, bg='#03A9F4', fg='#fff') button7.grid(row=8, column=1, padx=10, pady=10) button8 = Button(tab3, text="Gensim", command=use_gensim, width=12, bg='#03A9F4', fg='#fff') button8.grid(row=9, column=0, padx=10, pady=10) # Display Screen For Result url_display = ScrolledText(tab3, height=10) url_display.grid(row=7, column=0, columnspan=3, padx=5, pady=5) tab3_display_text = ScrolledText(tab3, height=10) tab3_display_text.grid(row=11, column=0, columnspan=3, padx=5, pady=5) l1 = Label(tab2, text="Enter URL To Summarize") l1.grid(row=1, column=0) raw_entry1 = StringVar() url_entry1 = Entry(tab2, textvariable=raw_entry, width=50) url_entry1.grid(row=1, column=1) # BUTTONS button9 = Button(tab2, text="Reset", command=clear_url_entry, width=12, bg='#03A9F4', fg='#fff') button9.grid(row=4, column=0, padx=10, pady=10) button10 = Button(tab2, text="Get Text", command=get_text, width=12, bg='#03A9F4', fg='#fff') button10.grid(row=4, column=1, padx=10, pady=10) button11 = Button(tab2, text="Open File", width=12, command=openfiles, bg='#c5cae9') button11.grid(row=5, column=0, padx=10, pady=10) button12 = Button(tab2, text="Open PDF", width=12, command=open_pdf1, bg='#c5cae9') button12.grid(row=5, column=1, padx=10, pady=10) button13 = Button(tab2, text="Clear Result", command=clear_display_result, width=12, bg='#03A9F4', fg='#fff') button13.grid(row=9, column=1, padx=10, pady=10) button14 = Button(tab2, text="Abstract", command=get_summary, width=12, bg='#03A9F4', fg='#fff') button14.grid(row=9, column=0, padx=10, pady=10) url_display1 = ScrolledText(tab2, height=10) url_display1.grid(row=7, column=0, columnspan=3, padx=5, pady=5) tab2_display_text = ScrolledText(tab2, height=10) tab2_display_text.grid(row=11, column=0, columnspan=3, padx=5, pady=5) window.mainloop()
[ "# Core Packages\r\nimport difflib\r\nimport tkinter as tk\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter.scrolledtext import *\r\nimport tkinter.filedialog\r\nimport PyPDF2\r\nfrom tkinter import filedialog\r\nimport torch\r\nimport json\r\nfrom transformers import T5Tokenizer, T5ForConditionalGeneration, T5Config\r\n\r\n# NLP Pkgs\r\nfrom spacy_summarization import text_summarizer\r\nfrom gensim.summarization import summarize\r\nfrom nltk_summarization import nltk_summarizer\r\n\r\n# Web Scraping Pkg\r\nfrom bs4 import BeautifulSoup\r\nfrom urllib.request import urlopen\r\n\r\n# Structure and Layout\r\nwindow = Tk()\r\nwindow.title(\"Summaryzer GUI\")\r\nwindow.geometry(\"700x400\")\r\nwindow.config(background='black')\r\n\r\nstyle = ttk.Style(window)\r\nstyle.configure('lefttab.TNotebook', tabposition='wn', )\r\n\r\n# TAB LAYOUT\r\ntab_control = ttk.Notebook(window, style='lefttab.TNotebook')\r\n\r\ntab2 = ttk.Frame(tab_control)\r\ntab3 = ttk.Frame(tab_control)\r\n\r\n# ADD TABS TO NOTEBOOK\r\ntab_control.add(tab3, text=f'{\"Extractive\":^20s}')\r\ntab_control.add(tab2, text=f'{\"Abstractive\":^20s}')\r\n\r\nlabel1 = Label(tab3, text='Extractive Summrize', padx=5, pady=5)\r\nlabel1.grid(column=1, row=0)\r\n\r\n\r\nlabel2 = Label(tab2, text='Abstractive Summrize',padx=5, pady=5)\r\nlabel2.grid(column=0, row=0)\r\n\r\ntab_control.pack(expand=1, fill='both')\r\n\r\ndef get_summary():\r\n model = T5ForConditionalGeneration.from_pretrained ('t5-small')\r\n tokenizer = T5Tokenizer.from_pretrained ('t5-small')\r\n device = torch.device ('cpu')\r\n text = str(url_display1.get('1.0', tk.END))\r\n preprocess_text = text.strip ().replace (\"\\n\", \"\")\r\n t5_prepared_Text = \"summarize: \" + preprocess_text\r\n tokenized_text = tokenizer.encode (t5_prepared_Text, return_tensors=\"pt\").to (device)\r\n\r\n summary_ids = model.generate (tokenized_text,\r\n num_beams=4,\r\n no_repeat_ngram_size=2,\r\n min_length=30,\r\n max_length=100,\r\n early_stopping=True)\r\n\r\n output = tokenizer.decode (summary_ids[0], skip_special_tokens=True)\r\n\r\n Str1 = text\r\n str2 = output\r\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\r\n\r\n edited = len(text)-len(output)\r\n Precision = (len(text)+len(output)+edited)/2\r\n Precisioncalc = Precision / 100\r\n\r\n result =(\"\\n\\nSummarized text: \\n\", output),\" Precision = \" , Precisioncalc , \" similarity = \" , printt\r\n\r\n tab2_display_text.insert(tk.END, result)\r\n\r\ndef open_pdf():\r\n open_file = filedialog.askopenfilename(\r\n initialdir=\"C:/gui/\",\r\n title=\"Open PDF File\",\r\n filetypes=(\r\n (\"PDF Files\", \"*.pdf\"),\r\n (\"All Files\", \".\")))\r\n\r\n if open_file:\r\n pdf_file = PyPDF2.PdfFileReader(open_file)\r\n page = pdf_file.getPage(0)\r\n page_stuff = page.extractText()\r\n io = page_stuff.split()\r\n url_display.insert(3.0, io)\r\n\r\n\r\ndef open_pdf1():\r\n open_file = filedialog.askopenfilename(\r\n initialdir=\"C:/gui/\",\r\n title=\"Open PDF File\",\r\n filetypes=(\r\n (\"PDF Files\", \"*.pdf\"),\r\n (\"All Files\", \".\")))\r\n\r\n if open_file:\r\n pdf_file = PyPDF2.PdfFileReader(open_file)\r\n page = pdf_file.getPage(0)\r\n page_stuff = page.extractText()\r\n io = page_stuff.split()\r\n url_display1.insert(3.0, io)\r\n\r\n\r\ndef clear_display_result():\r\n tab3_display_text.delete('1.0', END)\r\n\r\n# Clear For URL\r\ndef clear_url_entry():\r\n url_entry.delete(0, END)\r\n\r\n\r\n# Open File to Read and Process\r\ndef openfiles():\r\n file1 = tkinter.filedialog.askopenfilename(filetypes=((\"Text Files\", \".txt\"), (\"All files\", \"*\")))\r\n read_text = open(file1).read()\r\n url_display.insert(tk.END, read_text)\r\n\r\n\r\ndef get_text():\r\n raw_text = str(url_entry.get())\r\n page = urlopen(raw_text)\r\n soup = BeautifulSoup(page)\r\n fetched_text = ' '.join(map(lambda p: p.text, soup.find_all('p')))\r\n url_display.insert(tk.END, fetched_text)\r\n\r\n\r\ndef get_url_summary():\r\n raw_text = url_display.get('1.0', tk.END)\r\n final_text = text_summarizer(raw_text)\r\n result = '\\nSummary:{}'.format(final_text)\r\n tab3_display_text.insert(tk.END, result)\r\n\r\n\r\ndef use_spacy ():\r\n\r\n raw_text = url_display.get('1.0', tk.END)\r\n final_text = text_summarizer(raw_text)\r\n print(final_text)\r\n\r\n Str1 = raw_text\r\n str2 = text_summarizer(raw_text)\r\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\r\n\r\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\r\n Precisioncalc = Precision / 100\r\n result = '\\nSpacy Summary:{}\\n'.format(final_text),\" Precision = \" , Precisioncalc , \" similarity = \" , printt\r\n tab3_display_text.insert(tk.END, result)\r\n\r\n\r\ndef use_nltk():\r\n raw_text = url_display.get ('1.0', tk.END)\r\n final_text = nltk_summarizer (raw_text)\r\n print (final_text)\r\n\r\n Str1 = raw_text\r\n str2 = nltk_summarizer(raw_text)\r\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\r\n\r\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\r\n Precisioncalc = Precision / 100\r\n result = '\\nNLTK Summary:{}\\n'.format(final_text),\" Precision = \" , Precisioncalc , \" similarity = \" , printt\r\n tab3_display_text.insert(tk.END, result)\r\n\r\ndef use_gensim():\r\n raw_text = url_display.get ('1.0', tk.END)\r\n final_text = summarize(raw_text)\r\n print (final_text)\r\n Str1 = raw_text\r\n str2 = summarize(raw_text)\r\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\r\n\r\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\r\n Precisioncalc = Precision / 100\r\n result ='\\nGensim Summary:{}\\n'.format(final_text),\" Precision = \" , Precisioncalc , \" similarity = \" , printt\r\n tab3_display_text.insert(tk.END, result)\r\n\r\n\r\n# URL TAB\r\nl1 = Label(tab3, text=\"Enter URL To Summarize\")\r\nl1.grid(row=1, column=0)\r\n\r\nraw_entry = StringVar()\r\nurl_entry = Entry(tab3, textvariable=raw_entry, width=50)\r\nurl_entry.grid(row=1, column=1)\r\n\r\n# BUTTONS\r\nbutton1 = Button(tab3, text=\"Reset\", command=clear_url_entry, width=12, bg='#03A9F4', fg='#fff')\r\nbutton1.grid(row=4, column=0, padx=10, pady=10)\r\n\r\nbutton2 = Button(tab3, text=\"Get Text\", command=get_text, width=12, bg='#03A9F4', fg='#fff')\r\nbutton2.grid(row=4, column=1, padx=10, pady=10)\r\n\r\nbutton3 = Button(tab3, text=\"Open File\", width=12, command=openfiles, bg='#c5cae9')\r\nbutton3.grid(row=5, column=0, padx=10, pady=10)\r\n\r\nbutton4 = Button(tab3, text=\"Open PDF\", width=12, command=open_pdf, bg='#c5cae9')\r\nbutton4.grid(row=5, column=1, padx=10, pady=10)\r\n\r\nbutton5 = Button(tab3, text=\"SpaCy\", command=use_spacy, width=12, bg='red', fg='#fff')\r\nbutton5.grid(row=8, column=0, padx=10, pady=10)\r\n\r\nbutton6 = Button(tab3, text=\"Clear Result\", command=clear_display_result, width=12, bg='#03A9F4', fg='#fff')\r\nbutton6.grid(row=9, column=1, padx=10, pady=10)\r\n\r\nbutton7 = Button(tab3, text=\"NLTK\", command=use_nltk, width=12, bg='#03A9F4', fg='#fff')\r\nbutton7.grid(row=8, column=1, padx=10, pady=10)\r\n\r\nbutton8 = Button(tab3, text=\"Gensim\", command=use_gensim, width=12, bg='#03A9F4', fg='#fff')\r\nbutton8.grid(row=9, column=0, padx=10, pady=10)\r\n# Display Screen For Result\r\nurl_display = ScrolledText(tab3, height=10)\r\nurl_display.grid(row=7, column=0, columnspan=3, padx=5, pady=5)\r\n\r\ntab3_display_text = ScrolledText(tab3, height=10)\r\ntab3_display_text.grid(row=11, column=0, columnspan=3, padx=5, pady=5)\r\n\r\n\r\n\r\nl1 = Label(tab2, text=\"Enter URL To Summarize\")\r\nl1.grid(row=1, column=0)\r\n\r\nraw_entry1 = StringVar()\r\nurl_entry1 = Entry(tab2, textvariable=raw_entry, width=50)\r\nurl_entry1.grid(row=1, column=1)\r\n\r\n# BUTTONS\r\n\r\nbutton9 = Button(tab2, text=\"Reset\", command=clear_url_entry, width=12, bg='#03A9F4', fg='#fff')\r\nbutton9.grid(row=4, column=0, padx=10, pady=10)\r\n\r\nbutton10 = Button(tab2, text=\"Get Text\", command=get_text, width=12, bg='#03A9F4', fg='#fff')\r\nbutton10.grid(row=4, column=1, padx=10, pady=10)\r\n\r\nbutton11 = Button(tab2, text=\"Open File\", width=12, command=openfiles, bg='#c5cae9')\r\nbutton11.grid(row=5, column=0, padx=10, pady=10)\r\n\r\nbutton12 = Button(tab2, text=\"Open PDF\", width=12, command=open_pdf1, bg='#c5cae9')\r\nbutton12.grid(row=5, column=1, padx=10, pady=10)\r\n\r\nbutton13 = Button(tab2, text=\"Clear Result\", command=clear_display_result, width=12, bg='#03A9F4', fg='#fff')\r\nbutton13.grid(row=9, column=1, padx=10, pady=10)\r\n\r\nbutton14 = Button(tab2, text=\"Abstract\", command=get_summary, width=12, bg='#03A9F4', fg='#fff')\r\nbutton14.grid(row=9, column=0, padx=10, pady=10)\r\n\r\nurl_display1 = ScrolledText(tab2, height=10)\r\nurl_display1.grid(row=7, column=0, columnspan=3, padx=5, pady=5)\r\n\r\ntab2_display_text = ScrolledText(tab2, height=10)\r\ntab2_display_text.grid(row=11, column=0, columnspan=3, padx=5, pady=5)\r\n\r\nwindow.mainloop()\r\n\r\n", "import difflib\nimport tkinter as tk\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter.scrolledtext import *\nimport tkinter.filedialog\nimport PyPDF2\nfrom tkinter import filedialog\nimport torch\nimport json\nfrom transformers import T5Tokenizer, T5ForConditionalGeneration, T5Config\nfrom spacy_summarization import text_summarizer\nfrom gensim.summarization import summarize\nfrom nltk_summarization import nltk_summarizer\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nwindow = Tk()\nwindow.title('Summaryzer GUI')\nwindow.geometry('700x400')\nwindow.config(background='black')\nstyle = ttk.Style(window)\nstyle.configure('lefttab.TNotebook', tabposition='wn')\ntab_control = ttk.Notebook(window, style='lefttab.TNotebook')\ntab2 = ttk.Frame(tab_control)\ntab3 = ttk.Frame(tab_control)\ntab_control.add(tab3, text=f\"{'Extractive':^20s}\")\ntab_control.add(tab2, text=f\"{'Abstractive':^20s}\")\nlabel1 = Label(tab3, text='Extractive Summrize', padx=5, pady=5)\nlabel1.grid(column=1, row=0)\nlabel2 = Label(tab2, text='Abstractive Summrize', padx=5, pady=5)\nlabel2.grid(column=0, row=0)\ntab_control.pack(expand=1, fill='both')\n\n\ndef get_summary():\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\n device = torch.device('cpu')\n text = str(url_display1.get('1.0', tk.END))\n preprocess_text = text.strip().replace('\\n', '')\n t5_prepared_Text = 'summarize: ' + preprocess_text\n tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors='pt'\n ).to(device)\n summary_ids = model.generate(tokenized_text, num_beams=4,\n no_repeat_ngram_size=2, min_length=30, max_length=100,\n early_stopping=True)\n output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n Str1 = text\n str2 = output\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n edited = len(text) - len(output)\n Precision = (len(text) + len(output) + edited) / 2\n Precisioncalc = Precision / 100\n result = ('\\n\\nSummarized text: \\n', output\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab2_display_text.insert(tk.END, result)\n\n\ndef open_pdf():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display.insert(3.0, io)\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\ndef clear_url_entry():\n url_entry.delete(0, END)\n\n\ndef openfiles():\n file1 = tkinter.filedialog.askopenfilename(filetypes=(('Text Files',\n '.txt'), ('All files', '*')))\n read_text = open(file1).read()\n url_display.insert(tk.END, read_text)\n\n\ndef get_text():\n raw_text = str(url_entry.get())\n page = urlopen(raw_text)\n soup = BeautifulSoup(page)\n fetched_text = ' '.join(map(lambda p: p.text, soup.find_all('p')))\n url_display.insert(tk.END, fetched_text)\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_spacy():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = text_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nSpacy Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_nltk():\n raw_text = url_display.get('1.0', tk.END)\n final_text = nltk_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = nltk_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nNLTK Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_gensim():\n raw_text = url_display.get('1.0', tk.END)\n final_text = summarize(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = summarize(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nGensim Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\nl1 = Label(tab3, text='Enter URL To Summarize')\nl1.grid(row=1, column=0)\nraw_entry = StringVar()\nurl_entry = Entry(tab3, textvariable=raw_entry, width=50)\nurl_entry.grid(row=1, column=1)\nbutton1 = Button(tab3, text='Reset', command=clear_url_entry, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton1.grid(row=4, column=0, padx=10, pady=10)\nbutton2 = Button(tab3, text='Get Text', command=get_text, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton2.grid(row=4, column=1, padx=10, pady=10)\nbutton3 = Button(tab3, text='Open File', width=12, command=openfiles, bg=\n '#c5cae9')\nbutton3.grid(row=5, column=0, padx=10, pady=10)\nbutton4 = Button(tab3, text='Open PDF', width=12, command=open_pdf, bg=\n '#c5cae9')\nbutton4.grid(row=5, column=1, padx=10, pady=10)\nbutton5 = Button(tab3, text='SpaCy', command=use_spacy, width=12, bg='red',\n fg='#fff')\nbutton5.grid(row=8, column=0, padx=10, pady=10)\nbutton6 = Button(tab3, text='Clear Result', command=clear_display_result,\n width=12, bg='#03A9F4', fg='#fff')\nbutton6.grid(row=9, column=1, padx=10, pady=10)\nbutton7 = Button(tab3, text='NLTK', command=use_nltk, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton7.grid(row=8, column=1, padx=10, pady=10)\nbutton8 = Button(tab3, text='Gensim', command=use_gensim, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton8.grid(row=9, column=0, padx=10, pady=10)\nurl_display = ScrolledText(tab3, height=10)\nurl_display.grid(row=7, column=0, columnspan=3, padx=5, pady=5)\ntab3_display_text = ScrolledText(tab3, height=10)\ntab3_display_text.grid(row=11, column=0, columnspan=3, padx=5, pady=5)\nl1 = Label(tab2, text='Enter URL To Summarize')\nl1.grid(row=1, column=0)\nraw_entry1 = StringVar()\nurl_entry1 = Entry(tab2, textvariable=raw_entry, width=50)\nurl_entry1.grid(row=1, column=1)\nbutton9 = Button(tab2, text='Reset', command=clear_url_entry, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton9.grid(row=4, column=0, padx=10, pady=10)\nbutton10 = Button(tab2, text='Get Text', command=get_text, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton10.grid(row=4, column=1, padx=10, pady=10)\nbutton11 = Button(tab2, text='Open File', width=12, command=openfiles, bg=\n '#c5cae9')\nbutton11.grid(row=5, column=0, padx=10, pady=10)\nbutton12 = Button(tab2, text='Open PDF', width=12, command=open_pdf1, bg=\n '#c5cae9')\nbutton12.grid(row=5, column=1, padx=10, pady=10)\nbutton13 = Button(tab2, text='Clear Result', command=clear_display_result,\n width=12, bg='#03A9F4', fg='#fff')\nbutton13.grid(row=9, column=1, padx=10, pady=10)\nbutton14 = Button(tab2, text='Abstract', command=get_summary, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton14.grid(row=9, column=0, padx=10, pady=10)\nurl_display1 = ScrolledText(tab2, height=10)\nurl_display1.grid(row=7, column=0, columnspan=3, padx=5, pady=5)\ntab2_display_text = ScrolledText(tab2, height=10)\ntab2_display_text.grid(row=11, column=0, columnspan=3, padx=5, pady=5)\nwindow.mainloop()\n", "<import token>\nwindow = Tk()\nwindow.title('Summaryzer GUI')\nwindow.geometry('700x400')\nwindow.config(background='black')\nstyle = ttk.Style(window)\nstyle.configure('lefttab.TNotebook', tabposition='wn')\ntab_control = ttk.Notebook(window, style='lefttab.TNotebook')\ntab2 = ttk.Frame(tab_control)\ntab3 = ttk.Frame(tab_control)\ntab_control.add(tab3, text=f\"{'Extractive':^20s}\")\ntab_control.add(tab2, text=f\"{'Abstractive':^20s}\")\nlabel1 = Label(tab3, text='Extractive Summrize', padx=5, pady=5)\nlabel1.grid(column=1, row=0)\nlabel2 = Label(tab2, text='Abstractive Summrize', padx=5, pady=5)\nlabel2.grid(column=0, row=0)\ntab_control.pack(expand=1, fill='both')\n\n\ndef get_summary():\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\n device = torch.device('cpu')\n text = str(url_display1.get('1.0', tk.END))\n preprocess_text = text.strip().replace('\\n', '')\n t5_prepared_Text = 'summarize: ' + preprocess_text\n tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors='pt'\n ).to(device)\n summary_ids = model.generate(tokenized_text, num_beams=4,\n no_repeat_ngram_size=2, min_length=30, max_length=100,\n early_stopping=True)\n output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n Str1 = text\n str2 = output\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n edited = len(text) - len(output)\n Precision = (len(text) + len(output) + edited) / 2\n Precisioncalc = Precision / 100\n result = ('\\n\\nSummarized text: \\n', output\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab2_display_text.insert(tk.END, result)\n\n\ndef open_pdf():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display.insert(3.0, io)\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\ndef clear_url_entry():\n url_entry.delete(0, END)\n\n\ndef openfiles():\n file1 = tkinter.filedialog.askopenfilename(filetypes=(('Text Files',\n '.txt'), ('All files', '*')))\n read_text = open(file1).read()\n url_display.insert(tk.END, read_text)\n\n\ndef get_text():\n raw_text = str(url_entry.get())\n page = urlopen(raw_text)\n soup = BeautifulSoup(page)\n fetched_text = ' '.join(map(lambda p: p.text, soup.find_all('p')))\n url_display.insert(tk.END, fetched_text)\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_spacy():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = text_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nSpacy Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_nltk():\n raw_text = url_display.get('1.0', tk.END)\n final_text = nltk_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = nltk_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nNLTK Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_gensim():\n raw_text = url_display.get('1.0', tk.END)\n final_text = summarize(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = summarize(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nGensim Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\nl1 = Label(tab3, text='Enter URL To Summarize')\nl1.grid(row=1, column=0)\nraw_entry = StringVar()\nurl_entry = Entry(tab3, textvariable=raw_entry, width=50)\nurl_entry.grid(row=1, column=1)\nbutton1 = Button(tab3, text='Reset', command=clear_url_entry, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton1.grid(row=4, column=0, padx=10, pady=10)\nbutton2 = Button(tab3, text='Get Text', command=get_text, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton2.grid(row=4, column=1, padx=10, pady=10)\nbutton3 = Button(tab3, text='Open File', width=12, command=openfiles, bg=\n '#c5cae9')\nbutton3.grid(row=5, column=0, padx=10, pady=10)\nbutton4 = Button(tab3, text='Open PDF', width=12, command=open_pdf, bg=\n '#c5cae9')\nbutton4.grid(row=5, column=1, padx=10, pady=10)\nbutton5 = Button(tab3, text='SpaCy', command=use_spacy, width=12, bg='red',\n fg='#fff')\nbutton5.grid(row=8, column=0, padx=10, pady=10)\nbutton6 = Button(tab3, text='Clear Result', command=clear_display_result,\n width=12, bg='#03A9F4', fg='#fff')\nbutton6.grid(row=9, column=1, padx=10, pady=10)\nbutton7 = Button(tab3, text='NLTK', command=use_nltk, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton7.grid(row=8, column=1, padx=10, pady=10)\nbutton8 = Button(tab3, text='Gensim', command=use_gensim, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton8.grid(row=9, column=0, padx=10, pady=10)\nurl_display = ScrolledText(tab3, height=10)\nurl_display.grid(row=7, column=0, columnspan=3, padx=5, pady=5)\ntab3_display_text = ScrolledText(tab3, height=10)\ntab3_display_text.grid(row=11, column=0, columnspan=3, padx=5, pady=5)\nl1 = Label(tab2, text='Enter URL To Summarize')\nl1.grid(row=1, column=0)\nraw_entry1 = StringVar()\nurl_entry1 = Entry(tab2, textvariable=raw_entry, width=50)\nurl_entry1.grid(row=1, column=1)\nbutton9 = Button(tab2, text='Reset', command=clear_url_entry, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton9.grid(row=4, column=0, padx=10, pady=10)\nbutton10 = Button(tab2, text='Get Text', command=get_text, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton10.grid(row=4, column=1, padx=10, pady=10)\nbutton11 = Button(tab2, text='Open File', width=12, command=openfiles, bg=\n '#c5cae9')\nbutton11.grid(row=5, column=0, padx=10, pady=10)\nbutton12 = Button(tab2, text='Open PDF', width=12, command=open_pdf1, bg=\n '#c5cae9')\nbutton12.grid(row=5, column=1, padx=10, pady=10)\nbutton13 = Button(tab2, text='Clear Result', command=clear_display_result,\n width=12, bg='#03A9F4', fg='#fff')\nbutton13.grid(row=9, column=1, padx=10, pady=10)\nbutton14 = Button(tab2, text='Abstract', command=get_summary, width=12, bg=\n '#03A9F4', fg='#fff')\nbutton14.grid(row=9, column=0, padx=10, pady=10)\nurl_display1 = ScrolledText(tab2, height=10)\nurl_display1.grid(row=7, column=0, columnspan=3, padx=5, pady=5)\ntab2_display_text = ScrolledText(tab2, height=10)\ntab2_display_text.grid(row=11, column=0, columnspan=3, padx=5, pady=5)\nwindow.mainloop()\n", "<import token>\n<assignment token>\nwindow.title('Summaryzer GUI')\nwindow.geometry('700x400')\nwindow.config(background='black')\n<assignment token>\nstyle.configure('lefttab.TNotebook', tabposition='wn')\n<assignment token>\ntab_control.add(tab3, text=f\"{'Extractive':^20s}\")\ntab_control.add(tab2, text=f\"{'Abstractive':^20s}\")\n<assignment token>\nlabel1.grid(column=1, row=0)\n<assignment token>\nlabel2.grid(column=0, row=0)\ntab_control.pack(expand=1, fill='both')\n\n\ndef get_summary():\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\n device = torch.device('cpu')\n text = str(url_display1.get('1.0', tk.END))\n preprocess_text = text.strip().replace('\\n', '')\n t5_prepared_Text = 'summarize: ' + preprocess_text\n tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors='pt'\n ).to(device)\n summary_ids = model.generate(tokenized_text, num_beams=4,\n no_repeat_ngram_size=2, min_length=30, max_length=100,\n early_stopping=True)\n output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n Str1 = text\n str2 = output\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n edited = len(text) - len(output)\n Precision = (len(text) + len(output) + edited) / 2\n Precisioncalc = Precision / 100\n result = ('\\n\\nSummarized text: \\n', output\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab2_display_text.insert(tk.END, result)\n\n\ndef open_pdf():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display.insert(3.0, io)\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\ndef clear_url_entry():\n url_entry.delete(0, END)\n\n\ndef openfiles():\n file1 = tkinter.filedialog.askopenfilename(filetypes=(('Text Files',\n '.txt'), ('All files', '*')))\n read_text = open(file1).read()\n url_display.insert(tk.END, read_text)\n\n\ndef get_text():\n raw_text = str(url_entry.get())\n page = urlopen(raw_text)\n soup = BeautifulSoup(page)\n fetched_text = ' '.join(map(lambda p: p.text, soup.find_all('p')))\n url_display.insert(tk.END, fetched_text)\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_spacy():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = text_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nSpacy Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_nltk():\n raw_text = url_display.get('1.0', tk.END)\n final_text = nltk_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = nltk_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nNLTK Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_gensim():\n raw_text = url_display.get('1.0', tk.END)\n final_text = summarize(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = summarize(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nGensim Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\n<assignment token>\nl1.grid(row=1, column=0)\n<assignment token>\nurl_entry.grid(row=1, column=1)\n<assignment token>\nbutton1.grid(row=4, column=0, padx=10, pady=10)\n<assignment token>\nbutton2.grid(row=4, column=1, padx=10, pady=10)\n<assignment token>\nbutton3.grid(row=5, column=0, padx=10, pady=10)\n<assignment token>\nbutton4.grid(row=5, column=1, padx=10, pady=10)\n<assignment token>\nbutton5.grid(row=8, column=0, padx=10, pady=10)\n<assignment token>\nbutton6.grid(row=9, column=1, padx=10, pady=10)\n<assignment token>\nbutton7.grid(row=8, column=1, padx=10, pady=10)\n<assignment token>\nbutton8.grid(row=9, column=0, padx=10, pady=10)\n<assignment token>\nurl_display.grid(row=7, column=0, columnspan=3, padx=5, pady=5)\n<assignment token>\ntab3_display_text.grid(row=11, column=0, columnspan=3, padx=5, pady=5)\n<assignment token>\nl1.grid(row=1, column=0)\n<assignment token>\nurl_entry1.grid(row=1, column=1)\n<assignment token>\nbutton9.grid(row=4, column=0, padx=10, pady=10)\n<assignment token>\nbutton10.grid(row=4, column=1, padx=10, pady=10)\n<assignment token>\nbutton11.grid(row=5, column=0, padx=10, pady=10)\n<assignment token>\nbutton12.grid(row=5, column=1, padx=10, pady=10)\n<assignment token>\nbutton13.grid(row=9, column=1, padx=10, pady=10)\n<assignment token>\nbutton14.grid(row=9, column=0, padx=10, pady=10)\n<assignment token>\nurl_display1.grid(row=7, column=0, columnspan=3, padx=5, pady=5)\n<assignment token>\ntab2_display_text.grid(row=11, column=0, columnspan=3, padx=5, pady=5)\nwindow.mainloop()\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n\n\ndef get_summary():\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\n device = torch.device('cpu')\n text = str(url_display1.get('1.0', tk.END))\n preprocess_text = text.strip().replace('\\n', '')\n t5_prepared_Text = 'summarize: ' + preprocess_text\n tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors='pt'\n ).to(device)\n summary_ids = model.generate(tokenized_text, num_beams=4,\n no_repeat_ngram_size=2, min_length=30, max_length=100,\n early_stopping=True)\n output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n Str1 = text\n str2 = output\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n edited = len(text) - len(output)\n Precision = (len(text) + len(output) + edited) / 2\n Precisioncalc = Precision / 100\n result = ('\\n\\nSummarized text: \\n', output\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab2_display_text.insert(tk.END, result)\n\n\ndef open_pdf():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display.insert(3.0, io)\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\ndef clear_url_entry():\n url_entry.delete(0, END)\n\n\ndef openfiles():\n file1 = tkinter.filedialog.askopenfilename(filetypes=(('Text Files',\n '.txt'), ('All files', '*')))\n read_text = open(file1).read()\n url_display.insert(tk.END, read_text)\n\n\ndef get_text():\n raw_text = str(url_entry.get())\n page = urlopen(raw_text)\n soup = BeautifulSoup(page)\n fetched_text = ' '.join(map(lambda p: p.text, soup.find_all('p')))\n url_display.insert(tk.END, fetched_text)\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_spacy():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = text_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nSpacy Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_nltk():\n raw_text = url_display.get('1.0', tk.END)\n final_text = nltk_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = nltk_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nNLTK Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_gensim():\n raw_text = url_display.get('1.0', tk.END)\n final_text = summarize(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = summarize(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nGensim Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n\n\ndef get_summary():\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\n device = torch.device('cpu')\n text = str(url_display1.get('1.0', tk.END))\n preprocess_text = text.strip().replace('\\n', '')\n t5_prepared_Text = 'summarize: ' + preprocess_text\n tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors='pt'\n ).to(device)\n summary_ids = model.generate(tokenized_text, num_beams=4,\n no_repeat_ngram_size=2, min_length=30, max_length=100,\n early_stopping=True)\n output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n Str1 = text\n str2 = output\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n edited = len(text) - len(output)\n Precision = (len(text) + len(output) + edited) / 2\n Precisioncalc = Precision / 100\n result = ('\\n\\nSummarized text: \\n', output\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab2_display_text.insert(tk.END, result)\n\n\ndef open_pdf():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display.insert(3.0, io)\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\ndef clear_url_entry():\n url_entry.delete(0, END)\n\n\ndef openfiles():\n file1 = tkinter.filedialog.askopenfilename(filetypes=(('Text Files',\n '.txt'), ('All files', '*')))\n read_text = open(file1).read()\n url_display.insert(tk.END, read_text)\n\n\ndef get_text():\n raw_text = str(url_entry.get())\n page = urlopen(raw_text)\n soup = BeautifulSoup(page)\n fetched_text = ' '.join(map(lambda p: p.text, soup.find_all('p')))\n url_display.insert(tk.END, fetched_text)\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_spacy():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = text_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nSpacy Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_nltk():\n raw_text = url_display.get('1.0', tk.END)\n final_text = nltk_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = nltk_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nNLTK Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n\n\ndef get_summary():\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\n device = torch.device('cpu')\n text = str(url_display1.get('1.0', tk.END))\n preprocess_text = text.strip().replace('\\n', '')\n t5_prepared_Text = 'summarize: ' + preprocess_text\n tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors='pt'\n ).to(device)\n summary_ids = model.generate(tokenized_text, num_beams=4,\n no_repeat_ngram_size=2, min_length=30, max_length=100,\n early_stopping=True)\n output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n Str1 = text\n str2 = output\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n edited = len(text) - len(output)\n Precision = (len(text) + len(output) + edited) / 2\n Precisioncalc = Precision / 100\n result = ('\\n\\nSummarized text: \\n', output\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab2_display_text.insert(tk.END, result)\n\n\ndef open_pdf():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display.insert(3.0, io)\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\ndef clear_url_entry():\n url_entry.delete(0, END)\n\n\ndef openfiles():\n file1 = tkinter.filedialog.askopenfilename(filetypes=(('Text Files',\n '.txt'), ('All files', '*')))\n read_text = open(file1).read()\n url_display.insert(tk.END, read_text)\n\n\ndef get_text():\n raw_text = str(url_entry.get())\n page = urlopen(raw_text)\n soup = BeautifulSoup(page)\n fetched_text = ' '.join(map(lambda p: p.text, soup.find_all('p')))\n url_display.insert(tk.END, fetched_text)\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_spacy():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = text_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nSpacy Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n\n\ndef get_summary():\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\n device = torch.device('cpu')\n text = str(url_display1.get('1.0', tk.END))\n preprocess_text = text.strip().replace('\\n', '')\n t5_prepared_Text = 'summarize: ' + preprocess_text\n tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors='pt'\n ).to(device)\n summary_ids = model.generate(tokenized_text, num_beams=4,\n no_repeat_ngram_size=2, min_length=30, max_length=100,\n early_stopping=True)\n output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n Str1 = text\n str2 = output\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n edited = len(text) - len(output)\n Precision = (len(text) + len(output) + edited) / 2\n Precisioncalc = Precision / 100\n result = ('\\n\\nSummarized text: \\n', output\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab2_display_text.insert(tk.END, result)\n\n\n<function token>\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\ndef clear_url_entry():\n url_entry.delete(0, END)\n\n\ndef openfiles():\n file1 = tkinter.filedialog.askopenfilename(filetypes=(('Text Files',\n '.txt'), ('All files', '*')))\n read_text = open(file1).read()\n url_display.insert(tk.END, read_text)\n\n\ndef get_text():\n raw_text = str(url_entry.get())\n page = urlopen(raw_text)\n soup = BeautifulSoup(page)\n fetched_text = ' '.join(map(lambda p: p.text, soup.find_all('p')))\n url_display.insert(tk.END, fetched_text)\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_spacy():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = text_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nSpacy Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n\n\ndef get_summary():\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\n device = torch.device('cpu')\n text = str(url_display1.get('1.0', tk.END))\n preprocess_text = text.strip().replace('\\n', '')\n t5_prepared_Text = 'summarize: ' + preprocess_text\n tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors='pt'\n ).to(device)\n summary_ids = model.generate(tokenized_text, num_beams=4,\n no_repeat_ngram_size=2, min_length=30, max_length=100,\n early_stopping=True)\n output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n Str1 = text\n str2 = output\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n edited = len(text) - len(output)\n Precision = (len(text) + len(output) + edited) / 2\n Precisioncalc = Precision / 100\n result = ('\\n\\nSummarized text: \\n', output\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab2_display_text.insert(tk.END, result)\n\n\n<function token>\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\ndef clear_url_entry():\n url_entry.delete(0, END)\n\n\ndef openfiles():\n file1 = tkinter.filedialog.askopenfilename(filetypes=(('Text Files',\n '.txt'), ('All files', '*')))\n read_text = open(file1).read()\n url_display.insert(tk.END, read_text)\n\n\n<function token>\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_spacy():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = text_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nSpacy Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n\n\ndef get_summary():\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\n device = torch.device('cpu')\n text = str(url_display1.get('1.0', tk.END))\n preprocess_text = text.strip().replace('\\n', '')\n t5_prepared_Text = 'summarize: ' + preprocess_text\n tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors='pt'\n ).to(device)\n summary_ids = model.generate(tokenized_text, num_beams=4,\n no_repeat_ngram_size=2, min_length=30, max_length=100,\n early_stopping=True)\n output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n Str1 = text\n str2 = output\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n edited = len(text) - len(output)\n Precision = (len(text) + len(output) + edited) / 2\n Precisioncalc = Precision / 100\n result = ('\\n\\nSummarized text: \\n', output\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab2_display_text.insert(tk.END, result)\n\n\n<function token>\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\n<function token>\n\n\ndef openfiles():\n file1 = tkinter.filedialog.askopenfilename(filetypes=(('Text Files',\n '.txt'), ('All files', '*')))\n read_text = open(file1).read()\n url_display.insert(tk.END, read_text)\n\n\n<function token>\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_spacy():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = text_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nSpacy Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n\n\ndef get_summary():\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\n device = torch.device('cpu')\n text = str(url_display1.get('1.0', tk.END))\n preprocess_text = text.strip().replace('\\n', '')\n t5_prepared_Text = 'summarize: ' + preprocess_text\n tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors='pt'\n ).to(device)\n summary_ids = model.generate(tokenized_text, num_beams=4,\n no_repeat_ngram_size=2, min_length=30, max_length=100,\n early_stopping=True)\n output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n Str1 = text\n str2 = output\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n edited = len(text) - len(output)\n Precision = (len(text) + len(output) + edited) / 2\n Precisioncalc = Precision / 100\n result = ('\\n\\nSummarized text: \\n', output\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab2_display_text.insert(tk.END, result)\n\n\n<function token>\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\ndef use_spacy():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n print(final_text)\n Str1 = raw_text\n str2 = text_summarizer(raw_text)\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n Precision = len(raw_text) + len(nltk_summarizer(raw_text)) / len(raw_text)\n Precisioncalc = Precision / 100\n result = '\\nSpacy Summary:{}\\n'.format(final_text\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab3_display_text.insert(tk.END, result)\n\n\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n\n\ndef get_summary():\n model = T5ForConditionalGeneration.from_pretrained('t5-small')\n tokenizer = T5Tokenizer.from_pretrained('t5-small')\n device = torch.device('cpu')\n text = str(url_display1.get('1.0', tk.END))\n preprocess_text = text.strip().replace('\\n', '')\n t5_prepared_Text = 'summarize: ' + preprocess_text\n tokenized_text = tokenizer.encode(t5_prepared_Text, return_tensors='pt'\n ).to(device)\n summary_ids = model.generate(tokenized_text, num_beams=4,\n no_repeat_ngram_size=2, min_length=30, max_length=100,\n early_stopping=True)\n output = tokenizer.decode(summary_ids[0], skip_special_tokens=True)\n Str1 = text\n str2 = output\n printt = difflib.SequenceMatcher(None, Str1, str2, False).ratio() * 100\n edited = len(text) - len(output)\n Precision = (len(text) + len(output) + edited) / 2\n Precisioncalc = Precision / 100\n result = ('\\n\\nSummarized text: \\n', output\n ), ' Precision = ', Precisioncalc, ' similarity = ', printt\n tab2_display_text.insert(tk.END, result)\n\n\n<function token>\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<function token>\n<function token>\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\n<function token>\n<function token>\n<function token>\n\n\ndef get_url_summary():\n raw_text = url_display.get('1.0', tk.END)\n final_text = text_summarizer(raw_text)\n result = '\\nSummary:{}'.format(final_text)\n tab3_display_text.insert(tk.END, result)\n\n\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<function token>\n<function token>\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\ndef clear_display_result():\n tab3_display_text.delete('1.0', END)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<function token>\n<function token>\n\n\ndef open_pdf1():\n open_file = filedialog.askopenfilename(initialdir='C:/gui/', title=\n 'Open PDF File', filetypes=(('PDF Files', '*.pdf'), ('All Files', '.'))\n )\n if open_file:\n pdf_file = PyPDF2.PdfFileReader(open_file)\n page = pdf_file.getPage(0)\n page_stuff = page.extractText()\n io = page_stuff.split()\n url_display1.insert(3.0, io)\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n", "<import token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n<assignment token>\n<code token>\n" ]
false
796
64366e8532ffe05db7e7b7313e1d573c78a4e030
import packaging.requirements import pydantic import pytest from prefect.software.pip import PipRequirement, current_environment_requirements class TestPipRequirement: def is_packaging_subclass(self): r = PipRequirement("prefect") assert isinstance(r, packaging.requirements.Requirement) def test_can_be_used_in_pydantic_model(self): class MyModel(pydantic.BaseModel): req: PipRequirement inst = MyModel(req="prefect") assert inst.req == PipRequirement("prefect") assert isinstance(inst.req, PipRequirement) def test_equality(self): assert PipRequirement("prefect") == PipRequirement("prefect") assert PipRequirement("prefect") != PipRequirement("prefect>=2") # TODO: Add tests that mock the working set so we can make meaningful assertions def test_current_environment_requirements(): requirements = current_environment_requirements( on_uninstallable_requirement="ignore" ) assert all(isinstance(r, PipRequirement) for r in requirements) names = [r.name for r in requirements] assert "prefect" not in names # Editable install is excluded assert len(names) == len(set(names)), "Names should not be repeated" def test_current_environment_requirements_warns_about_editable_prefect(): with pytest.warns( UserWarning, match=r"prefect.*is an editable installation", ): requirements = current_environment_requirements( on_uninstallable_requirement="warn" ) assert all(isinstance(r, PipRequirement) for r in requirements) names = [r.name for r in requirements] assert "prefect" not in names assert len(names) == len(set(names)), "Names should not be repeated" def test_current_environment_requirements_raises_on_editable_prefect(): with pytest.raises( ValueError, match=r"prefect.*is an editable installation", ): current_environment_requirements(on_uninstallable_requirement="raise") def test_current_environment_requirements_raises_on_bad_mode(): with pytest.raises( ValueError, match=r"Unknown mode for `on_uninstallable_requirement`", ): current_environment_requirements(on_uninstallable_requirement="foo") def test_current_environment_requirements_top_level_only(): requirements = current_environment_requirements( exclude_nested=True, on_uninstallable_requirement="ignore" ) all_requirements = current_environment_requirements( on_uninstallable_requirement="ignore" ) assert {r.name for r in requirements}.issubset({r.name for r in all_requirements}) assert len(requirements) < len(all_requirements) assert all(isinstance(r, PipRequirement) for r in requirements)
[ "import packaging.requirements\nimport pydantic\nimport pytest\n\nfrom prefect.software.pip import PipRequirement, current_environment_requirements\n\n\nclass TestPipRequirement:\n def is_packaging_subclass(self):\n r = PipRequirement(\"prefect\")\n assert isinstance(r, packaging.requirements.Requirement)\n\n def test_can_be_used_in_pydantic_model(self):\n class MyModel(pydantic.BaseModel):\n req: PipRequirement\n\n inst = MyModel(req=\"prefect\")\n assert inst.req == PipRequirement(\"prefect\")\n assert isinstance(inst.req, PipRequirement)\n\n def test_equality(self):\n assert PipRequirement(\"prefect\") == PipRequirement(\"prefect\")\n assert PipRequirement(\"prefect\") != PipRequirement(\"prefect>=2\")\n\n\n# TODO: Add tests that mock the working set so we can make meaningful assertions\n\n\ndef test_current_environment_requirements():\n requirements = current_environment_requirements(\n on_uninstallable_requirement=\"ignore\"\n )\n assert all(isinstance(r, PipRequirement) for r in requirements)\n names = [r.name for r in requirements]\n assert \"prefect\" not in names # Editable install is excluded\n assert len(names) == len(set(names)), \"Names should not be repeated\"\n\n\ndef test_current_environment_requirements_warns_about_editable_prefect():\n with pytest.warns(\n UserWarning,\n match=r\"prefect.*is an editable installation\",\n ):\n requirements = current_environment_requirements(\n on_uninstallable_requirement=\"warn\"\n )\n assert all(isinstance(r, PipRequirement) for r in requirements)\n names = [r.name for r in requirements]\n assert \"prefect\" not in names\n assert len(names) == len(set(names)), \"Names should not be repeated\"\n\n\ndef test_current_environment_requirements_raises_on_editable_prefect():\n with pytest.raises(\n ValueError,\n match=r\"prefect.*is an editable installation\",\n ):\n current_environment_requirements(on_uninstallable_requirement=\"raise\")\n\n\ndef test_current_environment_requirements_raises_on_bad_mode():\n with pytest.raises(\n ValueError,\n match=r\"Unknown mode for `on_uninstallable_requirement`\",\n ):\n current_environment_requirements(on_uninstallable_requirement=\"foo\")\n\n\ndef test_current_environment_requirements_top_level_only():\n requirements = current_environment_requirements(\n exclude_nested=True, on_uninstallable_requirement=\"ignore\"\n )\n all_requirements = current_environment_requirements(\n on_uninstallable_requirement=\"ignore\"\n )\n assert {r.name for r in requirements}.issubset({r.name for r in all_requirements})\n assert len(requirements) < len(all_requirements)\n assert all(isinstance(r, PipRequirement) for r in requirements)\n", "import packaging.requirements\nimport pydantic\nimport pytest\nfrom prefect.software.pip import PipRequirement, current_environment_requirements\n\n\nclass TestPipRequirement:\n\n def is_packaging_subclass(self):\n r = PipRequirement('prefect')\n assert isinstance(r, packaging.requirements.Requirement)\n\n def test_can_be_used_in_pydantic_model(self):\n\n\n class MyModel(pydantic.BaseModel):\n req: PipRequirement\n inst = MyModel(req='prefect')\n assert inst.req == PipRequirement('prefect')\n assert isinstance(inst.req, PipRequirement)\n\n def test_equality(self):\n assert PipRequirement('prefect') == PipRequirement('prefect')\n assert PipRequirement('prefect') != PipRequirement('prefect>=2')\n\n\ndef test_current_environment_requirements():\n requirements = current_environment_requirements(\n on_uninstallable_requirement='ignore')\n assert all(isinstance(r, PipRequirement) for r in requirements)\n names = [r.name for r in requirements]\n assert 'prefect' not in names\n assert len(names) == len(set(names)), 'Names should not be repeated'\n\n\ndef test_current_environment_requirements_warns_about_editable_prefect():\n with pytest.warns(UserWarning, match='prefect.*is an editable installation'\n ):\n requirements = current_environment_requirements(\n on_uninstallable_requirement='warn')\n assert all(isinstance(r, PipRequirement) for r in requirements)\n names = [r.name for r in requirements]\n assert 'prefect' not in names\n assert len(names) == len(set(names)), 'Names should not be repeated'\n\n\ndef test_current_environment_requirements_raises_on_editable_prefect():\n with pytest.raises(ValueError, match='prefect.*is an editable installation'\n ):\n current_environment_requirements(on_uninstallable_requirement='raise')\n\n\ndef test_current_environment_requirements_raises_on_bad_mode():\n with pytest.raises(ValueError, match=\n 'Unknown mode for `on_uninstallable_requirement`'):\n current_environment_requirements(on_uninstallable_requirement='foo')\n\n\ndef test_current_environment_requirements_top_level_only():\n requirements = current_environment_requirements(exclude_nested=True,\n on_uninstallable_requirement='ignore')\n all_requirements = current_environment_requirements(\n on_uninstallable_requirement='ignore')\n assert {r.name for r in requirements}.issubset({r.name for r in\n all_requirements})\n assert len(requirements) < len(all_requirements)\n assert all(isinstance(r, PipRequirement) for r in requirements)\n", "<import token>\n\n\nclass TestPipRequirement:\n\n def is_packaging_subclass(self):\n r = PipRequirement('prefect')\n assert isinstance(r, packaging.requirements.Requirement)\n\n def test_can_be_used_in_pydantic_model(self):\n\n\n class MyModel(pydantic.BaseModel):\n req: PipRequirement\n inst = MyModel(req='prefect')\n assert inst.req == PipRequirement('prefect')\n assert isinstance(inst.req, PipRequirement)\n\n def test_equality(self):\n assert PipRequirement('prefect') == PipRequirement('prefect')\n assert PipRequirement('prefect') != PipRequirement('prefect>=2')\n\n\ndef test_current_environment_requirements():\n requirements = current_environment_requirements(\n on_uninstallable_requirement='ignore')\n assert all(isinstance(r, PipRequirement) for r in requirements)\n names = [r.name for r in requirements]\n assert 'prefect' not in names\n assert len(names) == len(set(names)), 'Names should not be repeated'\n\n\ndef test_current_environment_requirements_warns_about_editable_prefect():\n with pytest.warns(UserWarning, match='prefect.*is an editable installation'\n ):\n requirements = current_environment_requirements(\n on_uninstallable_requirement='warn')\n assert all(isinstance(r, PipRequirement) for r in requirements)\n names = [r.name for r in requirements]\n assert 'prefect' not in names\n assert len(names) == len(set(names)), 'Names should not be repeated'\n\n\ndef test_current_environment_requirements_raises_on_editable_prefect():\n with pytest.raises(ValueError, match='prefect.*is an editable installation'\n ):\n current_environment_requirements(on_uninstallable_requirement='raise')\n\n\ndef test_current_environment_requirements_raises_on_bad_mode():\n with pytest.raises(ValueError, match=\n 'Unknown mode for `on_uninstallable_requirement`'):\n current_environment_requirements(on_uninstallable_requirement='foo')\n\n\ndef test_current_environment_requirements_top_level_only():\n requirements = current_environment_requirements(exclude_nested=True,\n on_uninstallable_requirement='ignore')\n all_requirements = current_environment_requirements(\n on_uninstallable_requirement='ignore')\n assert {r.name for r in requirements}.issubset({r.name for r in\n all_requirements})\n assert len(requirements) < len(all_requirements)\n assert all(isinstance(r, PipRequirement) for r in requirements)\n", "<import token>\n\n\nclass TestPipRequirement:\n\n def is_packaging_subclass(self):\n r = PipRequirement('prefect')\n assert isinstance(r, packaging.requirements.Requirement)\n\n def test_can_be_used_in_pydantic_model(self):\n\n\n class MyModel(pydantic.BaseModel):\n req: PipRequirement\n inst = MyModel(req='prefect')\n assert inst.req == PipRequirement('prefect')\n assert isinstance(inst.req, PipRequirement)\n\n def test_equality(self):\n assert PipRequirement('prefect') == PipRequirement('prefect')\n assert PipRequirement('prefect') != PipRequirement('prefect>=2')\n\n\n<function token>\n\n\ndef test_current_environment_requirements_warns_about_editable_prefect():\n with pytest.warns(UserWarning, match='prefect.*is an editable installation'\n ):\n requirements = current_environment_requirements(\n on_uninstallable_requirement='warn')\n assert all(isinstance(r, PipRequirement) for r in requirements)\n names = [r.name for r in requirements]\n assert 'prefect' not in names\n assert len(names) == len(set(names)), 'Names should not be repeated'\n\n\ndef test_current_environment_requirements_raises_on_editable_prefect():\n with pytest.raises(ValueError, match='prefect.*is an editable installation'\n ):\n current_environment_requirements(on_uninstallable_requirement='raise')\n\n\ndef test_current_environment_requirements_raises_on_bad_mode():\n with pytest.raises(ValueError, match=\n 'Unknown mode for `on_uninstallable_requirement`'):\n current_environment_requirements(on_uninstallable_requirement='foo')\n\n\ndef test_current_environment_requirements_top_level_only():\n requirements = current_environment_requirements(exclude_nested=True,\n on_uninstallable_requirement='ignore')\n all_requirements = current_environment_requirements(\n on_uninstallable_requirement='ignore')\n assert {r.name for r in requirements}.issubset({r.name for r in\n all_requirements})\n assert len(requirements) < len(all_requirements)\n assert all(isinstance(r, PipRequirement) for r in requirements)\n", "<import token>\n\n\nclass TestPipRequirement:\n\n def is_packaging_subclass(self):\n r = PipRequirement('prefect')\n assert isinstance(r, packaging.requirements.Requirement)\n\n def test_can_be_used_in_pydantic_model(self):\n\n\n class MyModel(pydantic.BaseModel):\n req: PipRequirement\n inst = MyModel(req='prefect')\n assert inst.req == PipRequirement('prefect')\n assert isinstance(inst.req, PipRequirement)\n\n def test_equality(self):\n assert PipRequirement('prefect') == PipRequirement('prefect')\n assert PipRequirement('prefect') != PipRequirement('prefect>=2')\n\n\n<function token>\n\n\ndef test_current_environment_requirements_warns_about_editable_prefect():\n with pytest.warns(UserWarning, match='prefect.*is an editable installation'\n ):\n requirements = current_environment_requirements(\n on_uninstallable_requirement='warn')\n assert all(isinstance(r, PipRequirement) for r in requirements)\n names = [r.name for r in requirements]\n assert 'prefect' not in names\n assert len(names) == len(set(names)), 'Names should not be repeated'\n\n\ndef test_current_environment_requirements_raises_on_editable_prefect():\n with pytest.raises(ValueError, match='prefect.*is an editable installation'\n ):\n current_environment_requirements(on_uninstallable_requirement='raise')\n\n\ndef test_current_environment_requirements_raises_on_bad_mode():\n with pytest.raises(ValueError, match=\n 'Unknown mode for `on_uninstallable_requirement`'):\n current_environment_requirements(on_uninstallable_requirement='foo')\n\n\n<function token>\n", "<import token>\n\n\nclass TestPipRequirement:\n\n def is_packaging_subclass(self):\n r = PipRequirement('prefect')\n assert isinstance(r, packaging.requirements.Requirement)\n\n def test_can_be_used_in_pydantic_model(self):\n\n\n class MyModel(pydantic.BaseModel):\n req: PipRequirement\n inst = MyModel(req='prefect')\n assert inst.req == PipRequirement('prefect')\n assert isinstance(inst.req, PipRequirement)\n\n def test_equality(self):\n assert PipRequirement('prefect') == PipRequirement('prefect')\n assert PipRequirement('prefect') != PipRequirement('prefect>=2')\n\n\n<function token>\n<function token>\n\n\ndef test_current_environment_requirements_raises_on_editable_prefect():\n with pytest.raises(ValueError, match='prefect.*is an editable installation'\n ):\n current_environment_requirements(on_uninstallable_requirement='raise')\n\n\ndef test_current_environment_requirements_raises_on_bad_mode():\n with pytest.raises(ValueError, match=\n 'Unknown mode for `on_uninstallable_requirement`'):\n current_environment_requirements(on_uninstallable_requirement='foo')\n\n\n<function token>\n", "<import token>\n\n\nclass TestPipRequirement:\n\n def is_packaging_subclass(self):\n r = PipRequirement('prefect')\n assert isinstance(r, packaging.requirements.Requirement)\n\n def test_can_be_used_in_pydantic_model(self):\n\n\n class MyModel(pydantic.BaseModel):\n req: PipRequirement\n inst = MyModel(req='prefect')\n assert inst.req == PipRequirement('prefect')\n assert isinstance(inst.req, PipRequirement)\n\n def test_equality(self):\n assert PipRequirement('prefect') == PipRequirement('prefect')\n assert PipRequirement('prefect') != PipRequirement('prefect>=2')\n\n\n<function token>\n<function token>\n\n\ndef test_current_environment_requirements_raises_on_editable_prefect():\n with pytest.raises(ValueError, match='prefect.*is an editable installation'\n ):\n current_environment_requirements(on_uninstallable_requirement='raise')\n\n\n<function token>\n<function token>\n", "<import token>\n\n\nclass TestPipRequirement:\n\n def is_packaging_subclass(self):\n r = PipRequirement('prefect')\n assert isinstance(r, packaging.requirements.Requirement)\n\n def test_can_be_used_in_pydantic_model(self):\n\n\n class MyModel(pydantic.BaseModel):\n req: PipRequirement\n inst = MyModel(req='prefect')\n assert inst.req == PipRequirement('prefect')\n assert isinstance(inst.req, PipRequirement)\n\n def test_equality(self):\n assert PipRequirement('prefect') == PipRequirement('prefect')\n assert PipRequirement('prefect') != PipRequirement('prefect>=2')\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n\n\nclass TestPipRequirement:\n\n def is_packaging_subclass(self):\n r = PipRequirement('prefect')\n assert isinstance(r, packaging.requirements.Requirement)\n <function token>\n\n def test_equality(self):\n assert PipRequirement('prefect') == PipRequirement('prefect')\n assert PipRequirement('prefect') != PipRequirement('prefect>=2')\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n\n\nclass TestPipRequirement:\n\n def is_packaging_subclass(self):\n r = PipRequirement('prefect')\n assert isinstance(r, packaging.requirements.Requirement)\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n\n\nclass TestPipRequirement:\n <function token>\n <function token>\n <function token>\n\n\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n", "<import token>\n<class token>\n<function token>\n<function token>\n<function token>\n<function token>\n<function token>\n" ]
false
797
8c318d7152bfdf2bc472258eb87dfa499b743193
# coding:utf-8 def application(env,handle_headers): status="200" response_headers=[ ('Server','') ] return ""
[ "# coding:utf-8\n\n\ndef application(env,handle_headers):\n status=\"200\"\n response_headers=[\n ('Server','')\n ]\n return \"\"", "def application(env, handle_headers):\n status = '200'\n response_headers = [('Server', '')]\n return ''\n", "<function token>\n" ]
false
798
6a601d1c7c3c162c0902d03e6c39f8d75d4bcaf0
import numpy as np, argparse, sys, itertools, os, errno, warnings from mpi4py import MPI from enlib import enmap as en, powspec, utils from enlib.degrees_of_freedom import DOF, Arg from enlib.cg import CG warnings.filterwarnings("ignore") #from matplotlib.pylab import * parser = argparse.ArgumentParser() parser.add_argument("freqs") parser.add_argument("maps") parser.add_argument("noise") parser.add_argument("powspec") parser.add_argument("posfile") parser.add_argument("odir") parser.add_argument("-R", "--radius", type=float, default=30) parser.add_argument("--burnin", type=int, default=10) parser.add_argument("-n", "--nsamp", type=int, default=50) parser.add_argument("--dump", type=int, default=0) parser.add_argument("-v", "--verbose", action="store_true") parser.add_argument("-i", type=int, default=0) parser.add_argument("--nmax", type=int, default=0) parser.add_argument("--mindist-group", type=float, default=10) parser.add_argument("-c", "--cont", action="store_true") args = parser.parse_args() comm = MPI.COMM_WORLD myid = comm.rank nproc= comm.size r2c = 180/np.pi r2b = r2c*60*(8*np.log(2))**0.5 def read_maps(fmt, n, ntot=4): try: maps = en.read_map(fmt) if maps.ndim == ntot-1: maps = en.enmap([maps]*n,maps.wcs) if maps.ndim != ntot: raise ValueError("Map %s must have %d dimensions" % (fmt,ntot)) return maps except (IOError, OSError): maps = [en.read_map(fmt % i) for i in range(n)] maps = en.ndmap(maps, maps[0].wcs) if maps.ndim != ntot: maps = maps.reshape(maps.shape[:-2]+(1,)*(maps.ndim-ntot)+maps.shape[-2:]) return maps def flat_noise(shape, wcs, sigmas): res = en.zeros([len(sigmas),shape[-3],shape[-3],shape[-2],shape[-1]], wcs) for i,s in enumerate(sigmas): res[i] = (np.eye(shape[-3])*s**2)[:,:,None,None] return res def read_noise(info, shape, wcs, n): try: nmat = flat_noise(shape, wcs, parse_floats(info)) except ValueError: nmat = read_maps(info, n, 5) if len(nmat) != n: raise ValueError("Number of noise maps (%d) != number of signal maps (%d)!" % (len(nmat), n)) if np.any(nmat.shape[-2:] != shape[-2:]): raise ValueError("Noise and maps have inconsistent shape!") return nmat def parse_floats(strs): return np.array([float(w) for w in strs.split(",")]) def apodize(m, rad, apod_fun): scale = m.extent()/m.shape[-2:] y = np.arange(m.shape[-2])*scale[0] x = np.arange(m.shape[-1])*scale[1] yfun = apod_fun(y, rad)*apod_fun(y[-1]-y, rad) xfun = apod_fun(x, rad)*apod_fun(x[-1]-x, rad) a = yfun[:,None]*xfun[None,:] return m*a def apod_step(x, r): return x>r def apod_butter(x, r): return (1+(x/r)**-4)**-1 def apod_cos(x,r): return (1-np.cos(np.min(1,nx/r)*np.pi))/2 # Read our inputs freqs = parse_floats(args.freqs) maps = read_maps(args.maps, len(freqs)) ncomp = maps.shape[-3] nfreq = maps.shape[-4] noise = read_noise(args.noise, maps.shape, maps.wcs, len(freqs)) ps = powspec.read_spectrum(args.powspec, expand="diag")[:ncomp,:ncomp] poss = np.loadtxt(args.posfile)[:,:2]/r2c R = args.radius/r2c/60 beam_fiducial = 1.5/r2b beam_range = [0.8/r2b,3.0/r2b] beam_max_asym = 2 apod_rad = R/10 # We will cut out small mini-maps around each source candadate and # sample the CMB and source parameters jointly. But some candiates # are so near each other that they aren't independent. These must # be grouped into groups. def build_groups(poss): def dist(a,b): return np.sum((poss[a]-poss[b])**2)**0.5*180*60/np.pi rest = set(range(len(poss))) groups = [] while len(rest) > 0: group = [] tocheck = [rest.pop()] # Find distance to all other points while len(tocheck) > 0: current = tocheck.pop() rnew = set() while rest: other = rest.pop() if dist(current,other) < args.mindist_group: tocheck.append(other) else: rnew.add(other) rest = rnew group.append(current) groups.append(group) return groups groups = build_groups(poss) print "Found %d groups" % len(groups) # We will sample (cmb,A,pos,ibeam) jointly in gibbs fashion: # cmb,A <- P(cmb,A|data,A,pos,ibeam) # direct, but requires cr # pos,ibeam <- P(pos,ibeam|data,cmb,A) # MCMC # To take into account the nonperiodicity of each submap, we must introduce # a region of extra noise around the edge. class CMBSampler: """Draws samples from P(s,a|d,Cl,N,T), where T[ntemp,nfreq,ncomp,ny,nx] is a set of templates. a[ntemp] is the set of template amplitudes.""" def __init__(self, maps, inoise, ps, T=None): self.d = maps self.iN = inoise self.hN = en.multi_pow(inoise, 0.5, axes=[1,2]) self.iS = en.spec2flat(maps.shape[-3:], maps.wcs, ps, -1.0) self.hS = en.spec2flat(maps.shape[-3:], maps.wcs, ps, -0.5) self.ps = ps self.b, self.x = None, None # Prepare the preconditioner. It approximates the noise as the # same in every pixel, and ignores the cmb-template coupling. # See M(self,u) for details. iN_white = np.array(np.sum(np.mean(np.mean(self.iN,-1),-1),0)) # iN_white is now in pixel space, but the preconditioner needs it # in harmonic space, which introduces a #norm = np.prod((maps.box[1]-maps.box[0])/maps.shape[-2:]) #norm = 1./np.prod(maps.shape[-2:]) #iN_white /= norm self.S_prec = en.multi_pow(self.iS + iN_white[:,:,None,None], -1) # The template self.set_template(T) def set_template(self, T): if T is None: T = np.zeros((0,)+self.d.shape) self.T = T self.TT = np.einsum("aijyx,bijyx->ab",self.T,self.T) self.dof = DOF(Arg(default=self.d[0]), Arg(shape=T.shape[:1])) def P(self, u): s, a = self.dof.unzip(u) return s[None,:,:,:] + np.sum(self.T*a[:,None,None,None,None],0) def PT(self, d): return self.dof.zip(np.sum(d,0), np.einsum("qijyx,ijyx->q",self.T, d)) def A(self, u): s, a = self.dof.unzip(u) # U"u = [S"s, 0a] Uu = self.dof.zip(en.harm2map(en.map_mul(self.iS, en.map2harm(s))),a*0) # P'N"P u PNPu = self.PT(en.map_mul(self.iN, self.P(u))) return Uu + PNPu def M(self, u): # Multiplying things out, the full expression for A is: # [ S" + sum(N") sum(N"T) ] # [ sum(T'N") sum(T'T) ] # A reasonable approximation for this is # [ S" + sum(sigma^{-2}) 0 ] # [ 0 sum(T'T) ] # which can be directly inverted. s, a = self.dof.unzip(u) # Solve for the cmb signal component res_s = en.harm2map(en.map_mul(self.S_prec,en.map2harm(s))) res_a = np.linalg.solve(self.TT, a) return self.dof.zip(res_s, res_a) def calc_b(self): PNd = self.PT(en.map_mul(self.iN, self.d)) Uw1_s = en.harm2map(en.map_mul(self.hS, en.rand_gauss_harm(self.d.shape[-3:],self.d.wcs))) Uw1_a = np.zeros(self.T.shape[0]) Uw1 = self.dof.zip(Uw1_s, Uw1_a) PNw2 = self.PT(en.map_mul(self.hN, en.rand_gauss(self.d.shape, self.d.wcs))) return PNd + Uw1 + PNw2 def solve(self, b, x0, verbose=False): cg = CG(self.A, b, x0=x0*0, M=self.M) while cg.err > 1e-6: cg.step() if verbose: print "%5d %15.7e %15.7e" % (cg.i, cg.err, cg.err_true) #, self.dof.unzip(cg.x)[1] #if cg.i % 10 == 0: # s, a = self.dof.unzip(cg.x) # matshow(s[0]); colorbar(); show() return cg.x def sample(self, verbose=False): self.b = self.calc_b() if self.x is None: self.x = self.dof.zip(self.d[0], np.zeros(self.T.shape[0])) self.x = self.solve(self.b, self.x, verbose) return self.dof.unzip(self.x) class PtsrcModel: """This class converts from point source shape parameters to amplitude basis functions.""" def __init__(self, template): self.pos = template.posmap() self.nfreq, self.ncomp = template.shape[:2] self.nparam = self.nfreq*self.ncomp def get_templates(self, pos, irads): x = utils.rewind(self.pos - pos[:,None,None],0,2*np.pi) W = np.array([[irads[0],irads[2]],[irads[2],irads[1]]]) xWx = np.sum(np.einsum("ab,byx->ayx", W, x)*x,0) profile = np.exp(-0.5*xWx) bases = np.eye(self.nfreq*self.ncomp).reshape(self.nfreq*self.ncomp,self.nfreq,self.ncomp) return profile[None,None,None]*bases[:,:,:,None,None] def get_model(self, amps, pos, irads): return np.sum((self.get_templates(pos, irads).T*amps.T).T,0) class ShapeSampler: def __init__(self, maps, inoise, model, amps, pos, pos0, irads, nsamp=200, stepsize=0.02, maxdist=1.5*np.pi/180/60): self.maps = maps self.inoise = inoise self.model= model self.nsamp= nsamp self.stepsize = stepsize self.amps = amps self.pos, self.irads = pos, irads self.pos0 = pos0 self.maxdist=maxdist self.lik = self.getlik(self.amps, self.pos, self.irads) def getlik(self, amps, pos, irads): if irads[0] < 0 or irads[1] < 0: return np.inf if irads[0]*irads[1]-irads[2]**2 <= 0: return np.inf sigma, phi = expand_beam(irads) # The beam has a tendency to run off in unrealistic directions, # so we need a relatively strong prior on it. if np.min(sigma) < beam_range[0] or np.max(sigma) > beam_range[1] or np.max(sigma)/np.min(sigma) > beam_max_asym: return np.inf template = self.model.get_model(amps, pos, irads) residual = self.maps-template tmp = np.einsum("fabyx,abyx->fayx",self.inoise, residual) deviation = np.sum((pos-self.pos0)**2)**0.5/self.maxdist penalty = 1+max(deviation-1,0)**2 return 0.5*np.sum(tmp*residual)*penalty def newpos(self, pos): # Draw pos with gaussian prior centered on previous position # With a width given by the fiducial beam size. step = self.stepsize if np.random.uniform() < 0.1: step*100 # Sometimes try larger steps to break out of ruts return pos + np.random.standard_normal(2) * beam_fiducial * self.stepsize def newshape(self, irads): return irads + np.random.standard_normal(3) * 1.0/beam_fiducial**2 * self.stepsize * 0.5 def newamp(self, amps): return amps + np.random.standard_normal(len(amps)) * 1000 * self.stepsize def subsample(self, verbose=False): pos = self.newpos(self.pos) lik = self.getlik(self.amps, pos, self.irads) if np.random.uniform() < np.exp(self.lik-lik): self.pos, self.lik = pos, lik irads = self.newshape(self.irads) lik = self.getlik(self.amps, self.pos, irads) if np.random.uniform() < np.exp(self.lik-lik): self.irads, self.lik = irads, lik amps = self.newamp(self.amps) lik = self.getlik(amps, self.pos, self.irads) if np.random.uniform() < np.exp(self.lik-lik): self.amps, self.lik = amps, lik if verbose: sigma, phi = expand_beam(self.irads) print (" %9.2f"*len(self.amps)+" %10.5f %10.5f %8.3f %8.3f %8.3f") % (tuple(self.amps)+tuple(self.pos*r2c)+tuple(sigma*r2b)+(phi*r2c,)) return self.amps, self.pos, self.irads def sample(self, verbose=False): """Draw a new, uncorrelated sample.""" for i in range(self.nsamp): self.subsample(verbose) return self.amps, self.pos, self.irads class ShapeSamplerMulti: def __init__(self, maps, inoise, model, amps, pos, pos0, irads, nsamp=1500, stepsize=0.02, maxdist=1.5*np.pi/180/60): self.samplers = [ShapeSampler(maps, inoise, model, amp1, pos1, pos01, irads1, nsamp=1, stepsize=stepsize, maxdist=maxdist) for amp1, pos1, pos01, irads1 in zip(amps, pos, pos0, irads)] self.nsamp = nsamp def sample(self, verbose=False): for i in range(self.nsamp): for sampler in self.samplers: sampler.sample(verbose) amps = np.array([s.amps for s in self.samplers]) pos = np.array([s.pos for s in self.samplers]) irads= np.array([s.irads for s in self.samplers]) return amps, pos, irads class GibbsSampler: def __init__(self, maps, inoise, ps, pos0, amp0, irads0, cmb0): self.maps = maps self.inoise = inoise self.ps = ps self.src_model = PtsrcModel(maps) self.pos, self.amp, self.irads, self.cmb = pos0, amp0, irads0, cmb0 self.pos0 = pos0 self.cmb_sampler = CMBSampler(maps, inoise, ps) def sample(self, verbose=False): # First draw cmb,amp <- P(cmb,amp|data,pos,irads) src_template = self.src_model.get_templates(self.pos, self.irads) self.cmb_sampler.set_template(src_template) self.cmb, self.amp = self.cmb_sampler.sample(verbose) # Then draw pos,irads <- P(pos,irads|data,cmb,amp) maps_nocmb = self.maps - self.cmb[None,:,:,:] shape_sampler = ShapeSampler(maps_nocmb, self.inoise, self.src_model, self.amp, self.pos, self.pos0, self.irads) self.amp, self.pos, self.irads = shape_sampler.sample(verbose) return self.pos, self.amp, self.irads, self.cmb class GibbsSamplerMulti: """Like GibbsSampler, but samples multiple points jointly. This means that the source amplitude parameters will be arrays.""" def __init__(self, maps, inoise, ps, pos0, amp0, irads0, cmb0): self.maps = maps self.inoise = inoise self.ps = ps self.src_model = PtsrcModel(maps) self.pos, self.amp, self.irads, self.cmb = pos0, amp0, irads0, cmb0 self.pos0 = pos0 self.cmb_sampler = CMBSampler(maps, inoise, ps) def sample(self, verbose=False): # First draw cmb,amp <- P(cmb,amp|data,pos,irads) src_template = np.concatenate([self.src_model.get_templates(pos, irads) for pos,irads in zip(self.pos, self.irads)]) self.cmb_sampler.set_template(src_template) self.cmb, self.amp = self.cmb_sampler.sample(verbose) # Separate amps for each source self.amp = self.amp.reshape(self.pos.shape[0],-1) # Then draw pos,irads <- P(pos,irads|data,cmb,amp) maps_nocmb = self.maps - self.cmb[None,:,:,:] shape_sampler = ShapeSamplerMulti(maps_nocmb, self.inoise, self.src_model, self.amp, self.pos, self.pos0, self.irads) self.amp, self.pos, self.irads = shape_sampler.sample(verbose) return self.pos, self.amp, self.irads, self.cmb def expand_beam(irads): C = np.array([[irads[0],irads[2]],[irads[2],irads[1]]]) E, V = np.linalg.eigh(C) phi = np.arctan2(V[1,0],V[0,0]) sigma = E**-0.5 if sigma[1] > sigma[0]: sigma = sigma[::-1] phi += np.pi/2 phi %= np.pi return sigma, phi def smooth_gauss(m, sigma): l = np.sum(m.lmap()**2,0)**0.5 return np.real(en.ifft(en.fft(m)*np.exp(-0.5*(l*sigma)**2))) def get_startpoint(maps, inoise, ps, rad=5): # Filter away the CMB sampler = CMBSampler(maps, inoise, ps, maps[None][:0]) cmb, _ = sampler.sample() residual = maps - cmb[None] # Smooth based on fiducial beam residual = smooth_gauss(residual, beam_fiducial) # Extract best point near center cpix = np.array(residual.shape[-2:])/2 center = np.sum(np.sum((residual[:,:,cpix[0]-rad:cpix[0]+rad,cpix[1]-rad:cpix[1]+rad])**2,0),0) I = np.argmax(center) ipix = np.unravel_index(I, center.shape) pos = center.posmap()[:,ipix[0],ipix[1]] return pos def B(T,nu): c = 299792458.0 h = 6.62606957e-34 k = 1.3806488e-23 return 2*h*nu**3/c**2/(np.exp(h*nu/k/T)-1) def uK2mJ(amp,b1,b2): T0 = 2.73; nu=148e9 dB = B(T0+amp*1e-6,nu)-B(T0,nu) return dB*2*np.pi*b1*b2/1e-29 def output_dummy(id): with open(args.odir+"/samps%03d.txt" % id, "w") as ofile: pass utils.mkdir(args.odir) if args.nmax > 0: groups = groups[:args.nmax] for i in range(myid, len(groups), nproc): if i < args.i: continue group = groups[i] if args.cont: # If all our members are done, skip to next group try: lens = [len(np.loadtxt(args.odir + "/samps%03d.txt" % j)) for j in group] if np.min(lens) >= args.nsamp: continue except (IOError, OSError): pass print "%5d/%d %3d:" % (i+1, len(groups), myid), print (" %3d"*len(group)) % tuple(group) pos0 = np.array([poss[j] for j in group]) # Cut out a relevant region box = np.array([np.min(pos0,0)-R,np.max(pos0,0)+R]) submap = maps.submap(box) if submap.size == 0: for g in group: output_dummy(g) continue subnoise = apodize(noise.submap(box), apod_rad, apod_step) # Set up initial values for the sampler irads = np.tile(np.array([1/beam_fiducial**2,1/beam_fiducial**2,0]),(len(group),1)) amp = np.zeros([len(group),ncomp*nfreq]) cmb = submap[0] sampler = GibbsSamplerMulti(submap, subnoise, ps, pos0, amp, irads, cmb) # Open ofiles ofiles = [open(args.odir + "/samps%03d.txt" % j, "w") for j in group] for j in xrange(-args.burnin, args.nsamp): pos, amp, irad, cmb = sampler.sample(args.verbose) if j >= 0: for mypos, myamp, myirad, ofile, isrc in zip(pos, amp, irad, ofiles,group): sigma, phi = expand_beam(myirad) mJ = uK2mJ(myamp,sigma[0],sigma[1]) print >> ofile, (" %10.5f"*2 + " %6.1f"*len(myamp) + "%8.3f %8.3f %8.3f" + " %6.2f"*len(mJ)) % (tuple(mypos*r2c)+tuple(myamp)+tuple(sigma*r2b)+(phi*r2c,)+tuple(mJ)) ofile.flush() if args.dump > 0 and j % args.dump == 0: dumpdir = args.odir + "/dump%03d" % isrc utils.mkdir(dumpdir) src = sampler.src_model.get_model(myamp, mypos, myirad) residual = submap - src - cmb[None] # Cut out our area mybox = np.array([poss[isrc]-R,poss[isrc]+R]) mycmb, myres, mymod, mysub = [a.submap(mybox) for a in [cmb,residual,src,submap]] en.write_map(dumpdir + "/cmb%03d.hdf" % j, mycmb) en.write_map(dumpdir + "/residual%03d.hdf" % j, myres) en.write_map(dumpdir + "/model%03d.hdf" % j, mymod) en.write_map(dumpdir + "/submap.hdf", mysub)
[ "import numpy as np, argparse, sys, itertools, os, errno, warnings\nfrom mpi4py import MPI\nfrom enlib import enmap as en, powspec, utils\nfrom enlib.degrees_of_freedom import DOF, Arg\nfrom enlib.cg import CG\nwarnings.filterwarnings(\"ignore\")\n\n#from matplotlib.pylab import *\nparser = argparse.ArgumentParser()\nparser.add_argument(\"freqs\")\nparser.add_argument(\"maps\")\nparser.add_argument(\"noise\")\nparser.add_argument(\"powspec\")\nparser.add_argument(\"posfile\")\nparser.add_argument(\"odir\")\nparser.add_argument(\"-R\", \"--radius\", type=float, default=30)\nparser.add_argument(\"--burnin\", type=int, default=10)\nparser.add_argument(\"-n\", \"--nsamp\", type=int, default=50)\nparser.add_argument(\"--dump\", type=int, default=0)\nparser.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\nparser.add_argument(\"-i\", type=int, default=0)\nparser.add_argument(\"--nmax\", type=int, default=0)\nparser.add_argument(\"--mindist-group\", type=float, default=10)\nparser.add_argument(\"-c\", \"--cont\", action=\"store_true\")\nargs = parser.parse_args()\n\ncomm = MPI.COMM_WORLD\nmyid = comm.rank\nnproc= comm.size\nr2c = 180/np.pi\nr2b = r2c*60*(8*np.log(2))**0.5\n\ndef read_maps(fmt, n, ntot=4):\n\ttry:\n\t\tmaps = en.read_map(fmt)\n\t\tif maps.ndim == ntot-1: maps = en.enmap([maps]*n,maps.wcs)\n\t\tif maps.ndim != ntot: raise ValueError(\"Map %s must have %d dimensions\" % (fmt,ntot))\n\t\treturn maps\n\texcept (IOError, OSError):\n\t\tmaps = [en.read_map(fmt % i) for i in range(n)]\n\t\tmaps = en.ndmap(maps, maps[0].wcs)\n\t\tif maps.ndim != ntot: maps = maps.reshape(maps.shape[:-2]+(1,)*(maps.ndim-ntot)+maps.shape[-2:])\n\t\treturn maps\n\ndef flat_noise(shape, wcs, sigmas):\n\tres = en.zeros([len(sigmas),shape[-3],shape[-3],shape[-2],shape[-1]], wcs)\n\tfor i,s in enumerate(sigmas):\n\t\tres[i] = (np.eye(shape[-3])*s**2)[:,:,None,None]\n\treturn res\n\ndef read_noise(info, shape, wcs, n):\n\ttry:\n\t\tnmat = flat_noise(shape, wcs, parse_floats(info))\n\texcept ValueError:\n\t\tnmat = read_maps(info, n, 5)\n\tif len(nmat) != n: raise ValueError(\"Number of noise maps (%d) != number of signal maps (%d)!\" % (len(nmat), n))\n\tif np.any(nmat.shape[-2:] != shape[-2:]): raise ValueError(\"Noise and maps have inconsistent shape!\")\n\treturn nmat\n\ndef parse_floats(strs): return np.array([float(w) for w in strs.split(\",\")])\n\ndef apodize(m, rad, apod_fun):\n\tscale = m.extent()/m.shape[-2:]\n\ty = np.arange(m.shape[-2])*scale[0]\n\tx = np.arange(m.shape[-1])*scale[1]\n\tyfun = apod_fun(y, rad)*apod_fun(y[-1]-y, rad)\n\txfun = apod_fun(x, rad)*apod_fun(x[-1]-x, rad)\n\ta = yfun[:,None]*xfun[None,:]\n\treturn m*a\ndef apod_step(x, r): return x>r\ndef apod_butter(x, r): return (1+(x/r)**-4)**-1\ndef apod_cos(x,r): return (1-np.cos(np.min(1,nx/r)*np.pi))/2\n\n# Read our inputs\nfreqs = parse_floats(args.freqs)\nmaps = read_maps(args.maps, len(freqs))\nncomp = maps.shape[-3]\nnfreq = maps.shape[-4]\nnoise = read_noise(args.noise, maps.shape, maps.wcs, len(freqs))\nps = powspec.read_spectrum(args.powspec, expand=\"diag\")[:ncomp,:ncomp]\nposs = np.loadtxt(args.posfile)[:,:2]/r2c\nR = args.radius/r2c/60\nbeam_fiducial = 1.5/r2b\nbeam_range = [0.8/r2b,3.0/r2b]\nbeam_max_asym = 2\napod_rad = R/10\n\n# We will cut out small mini-maps around each source candadate and\n# sample the CMB and source parameters jointly. But some candiates\n# are so near each other that they aren't independent. These must\n# be grouped into groups.\ndef build_groups(poss):\n\tdef dist(a,b): return np.sum((poss[a]-poss[b])**2)**0.5*180*60/np.pi\n\trest = set(range(len(poss)))\n\tgroups = []\n\twhile len(rest) > 0:\n\t\tgroup = []\n\t\ttocheck = [rest.pop()]\n\t\t# Find distance to all other points\n\t\twhile len(tocheck) > 0:\n\t\t\tcurrent = tocheck.pop()\n\t\t\trnew = set()\n\t\t\twhile rest:\n\t\t\t\tother = rest.pop()\n\t\t\t\tif dist(current,other) < args.mindist_group:\n\t\t\t\t\ttocheck.append(other)\n\t\t\t\telse:\n\t\t\t\t\trnew.add(other)\n\t\t\trest = rnew\n\t\t\tgroup.append(current)\n\t\tgroups.append(group)\n\treturn groups\ngroups = build_groups(poss)\nprint \"Found %d groups\" % len(groups)\n\n# We will sample (cmb,A,pos,ibeam) jointly in gibbs fashion:\n# cmb,A <- P(cmb,A|data,A,pos,ibeam) # direct, but requires cr\n# pos,ibeam <- P(pos,ibeam|data,cmb,A) # MCMC\n# To take into account the nonperiodicity of each submap, we must introduce\n# a region of extra noise around the edge.\n\nclass CMBSampler:\n\t\"\"\"Draws samples from P(s,a|d,Cl,N,T), where T[ntemp,nfreq,ncomp,ny,nx] is a set of templates.\n\ta[ntemp] is the set of template amplitudes.\"\"\"\n\tdef __init__(self, maps, inoise, ps, T=None):\n\t\tself.d = maps\n\t\tself.iN = inoise\n\t\tself.hN = en.multi_pow(inoise, 0.5, axes=[1,2])\n\t\tself.iS = en.spec2flat(maps.shape[-3:], maps.wcs, ps, -1.0)\n\t\tself.hS = en.spec2flat(maps.shape[-3:], maps.wcs, ps, -0.5)\n\t\tself.ps = ps\n\t\tself.b, self.x = None, None\n\t\t# Prepare the preconditioner. It approximates the noise as the\n\t\t# same in every pixel, and ignores the cmb-template coupling.\n\t\t# See M(self,u) for details.\n\t\tiN_white = np.array(np.sum(np.mean(np.mean(self.iN,-1),-1),0))\n\t\t# iN_white is now in pixel space, but the preconditioner needs it\n\t\t# in harmonic space, which introduces a \n\t\t#norm = np.prod((maps.box[1]-maps.box[0])/maps.shape[-2:])\n\t\t#norm = 1./np.prod(maps.shape[-2:])\n\t\t#iN_white /= norm\n\t\tself.S_prec = en.multi_pow(self.iS + iN_white[:,:,None,None], -1)\n\n\t\t# The template\n\t\tself.set_template(T)\n\tdef set_template(self, T):\n\t\tif T is None: T = np.zeros((0,)+self.d.shape)\n\t\tself.T = T\n\t\tself.TT = np.einsum(\"aijyx,bijyx->ab\",self.T,self.T)\n\t\tself.dof = DOF(Arg(default=self.d[0]), Arg(shape=T.shape[:1]))\n\tdef P(self, u):\n\t\ts, a = self.dof.unzip(u)\n\t\treturn s[None,:,:,:] + np.sum(self.T*a[:,None,None,None,None],0)\n\tdef PT(self, d):\n\t\treturn self.dof.zip(np.sum(d,0), np.einsum(\"qijyx,ijyx->q\",self.T, d))\n\tdef A(self, u):\n\t\ts, a = self.dof.unzip(u)\n\t\t# U\"u = [S\"s, 0a]\n\t\tUu = self.dof.zip(en.harm2map(en.map_mul(self.iS, en.map2harm(s))),a*0)\n\t\t# P'N\"P u\n\t\tPNPu = self.PT(en.map_mul(self.iN, self.P(u)))\n\t\treturn Uu + PNPu\n\tdef M(self, u):\n\t\t# Multiplying things out, the full expression for A is:\n\t\t# [ S\" + sum(N\") sum(N\"T) ]\n\t\t# [ sum(T'N\") sum(T'T) ]\n\t\t# A reasonable approximation for this is\n\t\t# [ S\" + sum(sigma^{-2}) 0 ]\n\t\t# [ 0 sum(T'T) ]\n\t\t# which can be directly inverted.\n\t\ts, a = self.dof.unzip(u)\n\t\t# Solve for the cmb signal component\n\t\tres_s = en.harm2map(en.map_mul(self.S_prec,en.map2harm(s)))\n\t\tres_a = np.linalg.solve(self.TT, a)\n\t\treturn self.dof.zip(res_s, res_a)\n\tdef calc_b(self):\n\t\tPNd = self.PT(en.map_mul(self.iN, self.d))\n\t\tUw1_s = en.harm2map(en.map_mul(self.hS, en.rand_gauss_harm(self.d.shape[-3:],self.d.wcs)))\n\t\tUw1_a = np.zeros(self.T.shape[0])\n\t\tUw1 = self.dof.zip(Uw1_s, Uw1_a)\n\t\tPNw2 = self.PT(en.map_mul(self.hN, en.rand_gauss(self.d.shape, self.d.wcs)))\n\t\treturn PNd + Uw1 + PNw2\n\tdef solve(self, b, x0, verbose=False):\n\t\tcg = CG(self.A, b, x0=x0*0, M=self.M)\n\t\twhile cg.err > 1e-6:\n\t\t\tcg.step()\n\t\t\tif verbose:\n\t\t\t\tprint \"%5d %15.7e %15.7e\" % (cg.i, cg.err, cg.err_true) #, self.dof.unzip(cg.x)[1]\n\t\t\t#if cg.i % 10 == 0:\n\t\t\t#\ts, a = self.dof.unzip(cg.x)\n\t\t\t#\tmatshow(s[0]); colorbar(); show()\n\t\treturn cg.x\n\tdef sample(self, verbose=False):\n\t\tself.b = self.calc_b()\n\t\tif self.x is None: self.x = self.dof.zip(self.d[0], np.zeros(self.T.shape[0]))\n\t\tself.x = self.solve(self.b, self.x, verbose)\n\t\treturn self.dof.unzip(self.x)\n\nclass PtsrcModel:\n\t\"\"\"This class converts from point source shape parameters to amplitude\n\tbasis functions.\"\"\"\n\tdef __init__(self, template):\n\t\tself.pos = template.posmap()\n\t\tself.nfreq, self.ncomp = template.shape[:2]\n\t\tself.nparam = self.nfreq*self.ncomp\n\tdef get_templates(self, pos, irads):\n\t\tx = utils.rewind(self.pos - pos[:,None,None],0,2*np.pi)\n\t\tW = np.array([[irads[0],irads[2]],[irads[2],irads[1]]])\n\t\txWx = np.sum(np.einsum(\"ab,byx->ayx\", W, x)*x,0)\n\t\tprofile = np.exp(-0.5*xWx)\n\t\tbases = np.eye(self.nfreq*self.ncomp).reshape(self.nfreq*self.ncomp,self.nfreq,self.ncomp)\n\t\treturn profile[None,None,None]*bases[:,:,:,None,None]\n\tdef get_model(self, amps, pos, irads):\n\t\treturn np.sum((self.get_templates(pos, irads).T*amps.T).T,0)\n\nclass ShapeSampler:\n\tdef __init__(self, maps, inoise, model, amps, pos, pos0, irads, nsamp=200, stepsize=0.02, maxdist=1.5*np.pi/180/60):\n\t\tself.maps = maps\n\t\tself.inoise = inoise\n\t\tself.model= model\n\t\tself.nsamp= nsamp\n\t\tself.stepsize = stepsize\n\t\tself.amps = amps\n\t\tself.pos, self.irads = pos, irads\n\t\tself.pos0 = pos0\n\t\tself.maxdist=maxdist\n\t\tself.lik = self.getlik(self.amps, self.pos, self.irads)\n\tdef getlik(self, amps, pos, irads):\n\t\tif irads[0] < 0 or irads[1] < 0: return np.inf\n\t\tif irads[0]*irads[1]-irads[2]**2 <= 0: return np.inf\n\t\tsigma, phi = expand_beam(irads)\n\t\t# The beam has a tendency to run off in unrealistic directions,\n\t\t# so we need a relatively strong prior on it.\n\t\tif np.min(sigma) < beam_range[0] or np.max(sigma) > beam_range[1] or np.max(sigma)/np.min(sigma) > beam_max_asym: return np.inf\n\t\ttemplate = self.model.get_model(amps, pos, irads)\n\t\tresidual = self.maps-template\n\t\ttmp = np.einsum(\"fabyx,abyx->fayx\",self.inoise, residual)\n\t\tdeviation = np.sum((pos-self.pos0)**2)**0.5/self.maxdist\n\t\tpenalty = 1+max(deviation-1,0)**2\n\t\treturn 0.5*np.sum(tmp*residual)*penalty\n\tdef newpos(self, pos):\n\t\t# Draw pos with gaussian prior centered on previous position\n\t\t# With a width given by the fiducial beam size.\n\t\tstep = self.stepsize\n\t\tif np.random.uniform() < 0.1: step*100 # Sometimes try larger steps to break out of ruts\n\t\treturn pos + np.random.standard_normal(2) * beam_fiducial * self.stepsize\n\tdef newshape(self, irads):\n\t\treturn irads + np.random.standard_normal(3) * 1.0/beam_fiducial**2 * self.stepsize * 0.5\n\tdef newamp(self, amps):\n\t\treturn amps + np.random.standard_normal(len(amps)) * 1000 * self.stepsize\n\tdef subsample(self, verbose=False):\n\t\tpos = self.newpos(self.pos)\n\t\tlik = self.getlik(self.amps, pos, self.irads)\n\t\tif np.random.uniform() < np.exp(self.lik-lik):\n\t\t\tself.pos, self.lik = pos, lik\n\t\tirads = self.newshape(self.irads)\n\t\tlik = self.getlik(self.amps, self.pos, irads)\n\t\tif np.random.uniform() < np.exp(self.lik-lik):\n\t\t\tself.irads, self.lik = irads, lik\n\t\tamps = self.newamp(self.amps)\n\t\tlik = self.getlik(amps, self.pos, self.irads)\n\t\tif np.random.uniform() < np.exp(self.lik-lik):\n\t\t\tself.amps, self.lik = amps, lik\n\t\tif verbose:\n\t\t\tsigma, phi = expand_beam(self.irads)\n\t\t\tprint (\" %9.2f\"*len(self.amps)+\" %10.5f %10.5f %8.3f %8.3f %8.3f\") % (tuple(self.amps)+tuple(self.pos*r2c)+tuple(sigma*r2b)+(phi*r2c,))\n\t\treturn self.amps, self.pos, self.irads\n\tdef sample(self, verbose=False):\n\t\t\"\"\"Draw a new, uncorrelated sample.\"\"\"\n\t\tfor i in range(self.nsamp): self.subsample(verbose)\n\t\treturn self.amps, self.pos, self.irads\n\nclass ShapeSamplerMulti:\n\tdef __init__(self, maps, inoise, model, amps, pos, pos0, irads, nsamp=1500, stepsize=0.02, maxdist=1.5*np.pi/180/60):\n\t\tself.samplers = [ShapeSampler(maps, inoise, model, amp1, pos1, pos01, irads1, nsamp=1, stepsize=stepsize, maxdist=maxdist) for amp1, pos1, pos01, irads1 in zip(amps, pos, pos0, irads)]\n\t\tself.nsamp = nsamp\n\tdef sample(self, verbose=False):\n\t\tfor i in range(self.nsamp):\n\t\t\tfor sampler in self.samplers:\n\t\t\t\tsampler.sample(verbose)\n\t\tamps = np.array([s.amps for s in self.samplers])\n\t\tpos = np.array([s.pos for s in self.samplers])\n\t\tirads= np.array([s.irads for s in self.samplers])\n\t\treturn amps, pos, irads\n\nclass GibbsSampler:\n\tdef __init__(self, maps, inoise, ps, pos0, amp0, irads0, cmb0):\n\t\tself.maps = maps\n\t\tself.inoise = inoise\n\t\tself.ps = ps\n\t\tself.src_model = PtsrcModel(maps)\n\t\tself.pos, self.amp, self.irads, self.cmb = pos0, amp0, irads0, cmb0\n\t\tself.pos0 = pos0\n\t\tself.cmb_sampler = CMBSampler(maps, inoise, ps)\n\tdef sample(self, verbose=False):\n\t\t# First draw cmb,amp <- P(cmb,amp|data,pos,irads)\n\t\tsrc_template = self.src_model.get_templates(self.pos, self.irads)\n\t\tself.cmb_sampler.set_template(src_template)\n\t\tself.cmb, self.amp = self.cmb_sampler.sample(verbose)\n\t\t# Then draw pos,irads <- P(pos,irads|data,cmb,amp)\n\t\tmaps_nocmb = self.maps - self.cmb[None,:,:,:]\n\t\tshape_sampler = ShapeSampler(maps_nocmb, self.inoise, self.src_model, self.amp, self.pos, self.pos0, self.irads)\n\t\tself.amp, self.pos, self.irads = shape_sampler.sample(verbose)\n\t\treturn self.pos, self.amp, self.irads, self.cmb\n\nclass GibbsSamplerMulti:\n\t\"\"\"Like GibbsSampler, but samples multiple points jointly.\n\tThis means that the source amplitude parameters will be arrays.\"\"\"\n\tdef __init__(self, maps, inoise, ps, pos0, amp0, irads0, cmb0):\n\t\tself.maps = maps\n\t\tself.inoise = inoise\n\t\tself.ps = ps\n\t\tself.src_model = PtsrcModel(maps)\n\t\tself.pos, self.amp, self.irads, self.cmb = pos0, amp0, irads0, cmb0\n\t\tself.pos0 = pos0\n\t\tself.cmb_sampler = CMBSampler(maps, inoise, ps)\n\tdef sample(self, verbose=False):\n\t\t# First draw cmb,amp <- P(cmb,amp|data,pos,irads)\n\t\tsrc_template = np.concatenate([self.src_model.get_templates(pos, irads) for pos,irads in zip(self.pos, self.irads)])\n\t\tself.cmb_sampler.set_template(src_template)\n\t\tself.cmb, self.amp = self.cmb_sampler.sample(verbose)\n\t\t# Separate amps for each source\n\t\tself.amp = self.amp.reshape(self.pos.shape[0],-1)\n\t\t# Then draw pos,irads <- P(pos,irads|data,cmb,amp)\n\t\tmaps_nocmb = self.maps - self.cmb[None,:,:,:]\n\t\tshape_sampler = ShapeSamplerMulti(maps_nocmb, self.inoise, self.src_model, self.amp, self.pos, self.pos0, self.irads)\n\t\tself.amp, self.pos, self.irads = shape_sampler.sample(verbose)\n\t\treturn self.pos, self.amp, self.irads, self.cmb\n\ndef expand_beam(irads):\n\tC = np.array([[irads[0],irads[2]],[irads[2],irads[1]]])\n\tE, V = np.linalg.eigh(C)\n\tphi = np.arctan2(V[1,0],V[0,0])\n\tsigma = E**-0.5\n\tif sigma[1] > sigma[0]:\n\t\tsigma = sigma[::-1]\n\t\tphi += np.pi/2\n\tphi %= np.pi\n\treturn sigma, phi\n\ndef smooth_gauss(m, sigma):\n\tl = np.sum(m.lmap()**2,0)**0.5\n\treturn np.real(en.ifft(en.fft(m)*np.exp(-0.5*(l*sigma)**2)))\n\ndef get_startpoint(maps, inoise, ps, rad=5):\n\t# Filter away the CMB\n\tsampler = CMBSampler(maps, inoise, ps, maps[None][:0])\n\tcmb, _ = sampler.sample()\n\tresidual = maps - cmb[None]\n\t# Smooth based on fiducial beam\n\tresidual = smooth_gauss(residual, beam_fiducial)\n\t# Extract best point near center\n\tcpix = np.array(residual.shape[-2:])/2\n\tcenter = np.sum(np.sum((residual[:,:,cpix[0]-rad:cpix[0]+rad,cpix[1]-rad:cpix[1]+rad])**2,0),0)\n\tI = np.argmax(center)\n\tipix = np.unravel_index(I, center.shape)\n\tpos = center.posmap()[:,ipix[0],ipix[1]]\n\treturn pos\n\ndef B(T,nu):\n\tc = 299792458.0\n\th = 6.62606957e-34\n\tk = 1.3806488e-23\n\treturn 2*h*nu**3/c**2/(np.exp(h*nu/k/T)-1)\ndef uK2mJ(amp,b1,b2):\n\tT0 = 2.73; nu=148e9\n\tdB = B(T0+amp*1e-6,nu)-B(T0,nu)\n\treturn dB*2*np.pi*b1*b2/1e-29\n\ndef output_dummy(id):\n\twith open(args.odir+\"/samps%03d.txt\" % id, \"w\") as ofile:\n\t\tpass\n\nutils.mkdir(args.odir)\n\nif args.nmax > 0: groups = groups[:args.nmax]\n\nfor i in range(myid, len(groups), nproc):\n\tif i < args.i: continue\n\tgroup = groups[i]\n\tif args.cont:\n\t\t# If all our members are done, skip to next group\n\t\ttry:\n\t\t\tlens = [len(np.loadtxt(args.odir + \"/samps%03d.txt\" % j)) for j in group]\n\t\t\tif np.min(lens) >= args.nsamp:\n\t\t\t\tcontinue\n\t\texcept (IOError, OSError): pass\n\tprint \"%5d/%d %3d:\" % (i+1, len(groups), myid),\n\tprint (\" %3d\"*len(group)) % tuple(group)\n\tpos0 = np.array([poss[j] for j in group])\n\t# Cut out a relevant region\n\tbox = np.array([np.min(pos0,0)-R,np.max(pos0,0)+R])\n\tsubmap = maps.submap(box)\n\tif submap.size == 0:\n\t\tfor g in group:\n\t\t\toutput_dummy(g)\n\t\tcontinue\n\tsubnoise = apodize(noise.submap(box), apod_rad, apod_step)\n\t# Set up initial values for the sampler\n\tirads = np.tile(np.array([1/beam_fiducial**2,1/beam_fiducial**2,0]),(len(group),1))\n\tamp = np.zeros([len(group),ncomp*nfreq])\n\tcmb = submap[0]\n\tsampler = GibbsSamplerMulti(submap, subnoise, ps, pos0, amp, irads, cmb)\n\t# Open ofiles\n\tofiles = [open(args.odir + \"/samps%03d.txt\" % j, \"w\") for j in group]\n\tfor j in xrange(-args.burnin, args.nsamp):\n\t\tpos, amp, irad, cmb = sampler.sample(args.verbose)\n\t\tif j >= 0:\n\t\t\tfor mypos, myamp, myirad, ofile, isrc in zip(pos, amp, irad, ofiles,group):\n\t\t\t\tsigma, phi = expand_beam(myirad)\n\t\t\t\tmJ = uK2mJ(myamp,sigma[0],sigma[1])\n\t\t\t\tprint >> ofile, (\" %10.5f\"*2 + \" %6.1f\"*len(myamp) + \"%8.3f %8.3f %8.3f\" + \" %6.2f\"*len(mJ)) % (tuple(mypos*r2c)+tuple(myamp)+tuple(sigma*r2b)+(phi*r2c,)+tuple(mJ))\n\t\t\t\tofile.flush()\n\t\t\t\tif args.dump > 0 and j % args.dump == 0:\n\t\t\t\t\tdumpdir = args.odir + \"/dump%03d\" % isrc\n\t\t\t\t\tutils.mkdir(dumpdir)\n\t\t\t\t\tsrc = sampler.src_model.get_model(myamp, mypos, myirad)\n\t\t\t\t\tresidual = submap - src - cmb[None]\n\t\t\t\t\t# Cut out our area\n\t\t\t\t\tmybox = np.array([poss[isrc]-R,poss[isrc]+R])\n\t\t\t\t\tmycmb, myres, mymod, mysub = [a.submap(mybox) for a in [cmb,residual,src,submap]]\n\t\t\t\t\ten.write_map(dumpdir + \"/cmb%03d.hdf\" % j, mycmb)\n\t\t\t\t\ten.write_map(dumpdir + \"/residual%03d.hdf\" % j, myres)\n\t\t\t\t\ten.write_map(dumpdir + \"/model%03d.hdf\" % j, mymod)\n\t\t\t\t\ten.write_map(dumpdir + \"/submap.hdf\", mysub)\n" ]
true
799
af35075eaca9bba3d6bdb73353eaf944869cdede
# Software Name: MOON # Version: 5.4 # SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors # SPDX-License-Identifier: Apache-2.0 # This software is distributed under the 'Apache License 2.0', # the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' # or see the "LICENSE" file for more details. def update_pdp(pdp_id, value): from moon_manager.db_driver import PDPManager return PDPManager.update_pdp("", pdp_id, value) def delete_pdp(pdp_id): from moon_manager.db_driver import PDPManager PDPManager.delete_pdp("", pdp_id) def add_pdp(pdp_id=None, value=None): from moon_manager.db_driver import PDPManager return PDPManager.add_pdp("", pdp_id, value) def get_pdp(pdp_id=None): from moon_manager.db_driver import PDPManager return PDPManager.get_pdp("", pdp_id)
[ "# Software Name: MOON\n\n# Version: 5.4\n\n# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors\n# SPDX-License-Identifier: Apache-2.0\n\n# This software is distributed under the 'Apache License 2.0',\n# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt'\n# or see the \"LICENSE\" file for more details.\n\n\n\ndef update_pdp(pdp_id, value):\n from moon_manager.db_driver import PDPManager\n return PDPManager.update_pdp(\"\", pdp_id, value)\n\n\ndef delete_pdp(pdp_id):\n from moon_manager.db_driver import PDPManager\n PDPManager.delete_pdp(\"\", pdp_id)\n\n\ndef add_pdp(pdp_id=None, value=None):\n from moon_manager.db_driver import PDPManager\n return PDPManager.add_pdp(\"\", pdp_id, value)\n\n\ndef get_pdp(pdp_id=None):\n from moon_manager.db_driver import PDPManager\n return PDPManager.get_pdp(\"\", pdp_id)\n", "def update_pdp(pdp_id, value):\n from moon_manager.db_driver import PDPManager\n return PDPManager.update_pdp('', pdp_id, value)\n\n\ndef delete_pdp(pdp_id):\n from moon_manager.db_driver import PDPManager\n PDPManager.delete_pdp('', pdp_id)\n\n\ndef add_pdp(pdp_id=None, value=None):\n from moon_manager.db_driver import PDPManager\n return PDPManager.add_pdp('', pdp_id, value)\n\n\ndef get_pdp(pdp_id=None):\n from moon_manager.db_driver import PDPManager\n return PDPManager.get_pdp('', pdp_id)\n", "def update_pdp(pdp_id, value):\n from moon_manager.db_driver import PDPManager\n return PDPManager.update_pdp('', pdp_id, value)\n\n\ndef delete_pdp(pdp_id):\n from moon_manager.db_driver import PDPManager\n PDPManager.delete_pdp('', pdp_id)\n\n\n<function token>\n\n\ndef get_pdp(pdp_id=None):\n from moon_manager.db_driver import PDPManager\n return PDPManager.get_pdp('', pdp_id)\n", "<function token>\n\n\ndef delete_pdp(pdp_id):\n from moon_manager.db_driver import PDPManager\n PDPManager.delete_pdp('', pdp_id)\n\n\n<function token>\n\n\ndef get_pdp(pdp_id=None):\n from moon_manager.db_driver import PDPManager\n return PDPManager.get_pdp('', pdp_id)\n", "<function token>\n\n\ndef delete_pdp(pdp_id):\n from moon_manager.db_driver import PDPManager\n PDPManager.delete_pdp('', pdp_id)\n\n\n<function token>\n<function token>\n", "<function token>\n<function token>\n<function token>\n<function token>\n" ]
false