Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|># MONGO # # ================================================ def get_collection_pairs(db, args): if args.collection1 and args.collection2: print_single_pair_info(args.collection1, args.collection2) return [(args.collection1, args.collection2), ] collections = db.collection_names(include_system_collections=False) if args.collection_prefix: collections = [c for c in collections if c.startswith(args.collection_prefix)] if args.collection1: collections.sort() pairs = zip([args.collection1] * len(collections), collections) print_multiple_pairs_info(pairs) return pairs pairs = [p for p in itertools.combinations(sorted(collections), 2)] print_multiple_pairs_info(pairs) return pairs def index_collections(db, pairs): collections = sorted(list(set([c for tup in pairs for c in tup]))) fields = ['chain', 'prod'] logger.info('') logger.info('Creating indexes...') for c in collections: print(c) <|code_end|> , predict the next line using imports from the current file: from collections import Counter from StringIO import StringIO from abtools import log, mongodb import itertools import math import multiprocessing as mp import os import random import sqlite3 import subprocess as sp import sys import tempfile import time import urllib import uuid import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns import argparse and context including class names, function names, and sometimes code from other files: # Path: abtools/log.py # def setup_logging(logfile, print_log_location=True, debug=False): # def get_logger(name=None): # def add_stream_handler(logger): # def make_dir(d): # # Path: abtools/mongodb.py # def get_connection(ip='localhost', port=27017, user=None, password=None): # def get_db(db, ip='localhost', port=27017, user=None, password=None): # def get_collections(db, collection=None, prefix=None, suffix=None): # def rename_collection(db, collection, new_name): # def update(field, value, db, collection, match=None): # def unset(db, collection, field, match=None): # def mongoimport(json, database, # ip='localhost', port=27017, # user=None, password=None, # delim='_', delim1=None, delim2=None, # delim_occurance=1, delim1_occurance=1, delim2_occurance=1): # def index(db, collection, fields, directions=None, desc=False, background=False): # def remove_padding(db, collection, field='padding'): # def _get_import_collections(jsons, delim, delim_occurance, # delim1, delim1_occurance, # delim2, delim2_occurance): # def _print_mongoimport_info(logger): # def _print_remove_padding(): . Output only the next line.
mongodb.index(db, c, fields)
Based on the snippet: <|code_start|># furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING # BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # def abi_to_fasta(input, output): ''' Converts ABI or AB1 files to FASTA format. Args: input (str): Path to a file or directory containing abi/ab1 files or zip archives of abi/ab1 files output (str): Path to a directory for the output FASTA files ''' direcs = [input, ] # unzip any zip archives <|code_end|> , predict the immediate next line with the help of imports: from itertools import chain from zipfile import ZipFile from Bio import SeqIO from abtools.pipeline import list_files, make_dir import os and context (classes, functions, sometimes code) from other files: # Path: abtools/pipeline.py # def list_files(d, extension=None): # ''' # Lists files in a given directory. # # Args: # # d (str): Path to a directory. # # extension (str): If supplied, only files that contain the # specificied extension will be returned. Default is ``False``, # which returns all files in ``d``. # # Returns: # # list: A sorted list of file paths. # ''' # if os.path.isdir(d): # expanded_dir = os.path.expanduser(d) # files = sorted(glob.glob(expanded_dir + '/*')) # else: # files = [d, ] # if extension is not None: # if type(extension) in [str, unicode]: # extension = [extension, ] # files = [f for f in files if any([f.split('.')[-1] in extension, # f.split('.')[-1].upper() in extension, # f.split('.')[-1].lower() in extension])] # return files # # def make_dir(d): # ''' # Makes a directory, if it doesn't already exist. # # Args: # # d (str): Path to a directory. # ''' # if not os.path.exists(d): # os.makedirs(d) . Output only the next line.
zip_files = list_files(input, ['zip'])
Given snippet: <|code_start|> ''' Converts ABI or AB1 files to FASTA format. Args: input (str): Path to a file or directory containing abi/ab1 files or zip archives of abi/ab1 files output (str): Path to a directory for the output FASTA files ''' direcs = [input, ] # unzip any zip archives zip_files = list_files(input, ['zip']) if zip_files: direcs.extend(_process_zip_files(zip_files)) # convert files for d in direcs: files = list_files(d, ['ab1', 'abi']) seqs = [SeqIO.read(open(f, 'rb'), 'abi') for f in files] # seqs = list(chain.from_iterable(seqs)) fastas = ['>{}\n{}'.format(s.id, str(s.seq)) for s in seqs] ofile = os.path.basename(os.path.normpath(d)) + '.fasta' opath = os.path.join(output, ofile) open(opath, 'w').write('\n'.join(fastas)) def _process_zip_files(zip_files): out_dirs = [] for z in zip_files: out_path = '.'.join(z.split('.')[:-1]) <|code_end|> , continue by predicting the next line. Consider current file imports: from itertools import chain from zipfile import ZipFile from Bio import SeqIO from abtools.pipeline import list_files, make_dir import os and context: # Path: abtools/pipeline.py # def list_files(d, extension=None): # ''' # Lists files in a given directory. # # Args: # # d (str): Path to a directory. # # extension (str): If supplied, only files that contain the # specificied extension will be returned. Default is ``False``, # which returns all files in ``d``. # # Returns: # # list: A sorted list of file paths. # ''' # if os.path.isdir(d): # expanded_dir = os.path.expanduser(d) # files = sorted(glob.glob(expanded_dir + '/*')) # else: # files = [d, ] # if extension is not None: # if type(extension) in [str, unicode]: # extension = [extension, ] # files = [f for f in files if any([f.split('.')[-1] in extension, # f.split('.')[-1].upper() in extension, # f.split('.')[-1].lower() in extension])] # return files # # def make_dir(d): # ''' # Makes a directory, if it doesn't already exist. # # Args: # # d (str): Path to a directory. # ''' # if not os.path.exists(d): # os.makedirs(d) which might include code, classes, or functions. Output only the next line.
make_dir(out_path)
Next line prediction: <|code_start|> data: Can be one of three things: 1) Path to a single file 2) Path to a directory 3) A list of one or more paths to files or directories compressed_file (str): Path to the compressed file. Required. s3_path (str): The S3 path, with the filename omitted. The S3 filename will be the basename of the ``compressed_file``. For example:: compress_and_upload(data='/path/to/data', compressed_file='/path/to/compressed.tar.gz', s3_path='s3://my_bucket/path/to/') will result in an uploaded S3 path of ``s3://my_bucket/path/to/compressed.tar.gz`` method (str): Compression method. Options are ``'gz'`` (gzip) or ``'bz2'`` (bzip2). Default is ``'gz'``. delete (bool): If ``True``, the ``compressed_file`` will be deleted after upload to S3. Default is ``False``. access_key (str): AWS access key. secret_key (str): AWS secret key. ''' <|code_end|> . Use current file imports: (import os import subprocess as sp import tarfile from abtools import log) and context including class names, function names, or small code snippets from other files: # Path: abtools/log.py # def setup_logging(logfile, print_log_location=True, debug=False): # def get_logger(name=None): # def add_stream_handler(logger): # def make_dir(d): . Output only the next line.
logger = log.get_logger('s3')
Continue the code snippet: <|code_start|>def request(method, url, **kwargs): try: kwargs['slug'] = 'Pyston - file download' except ImportError: return request(method, url, **kwargs) class RequestDataTooBig(SuspiciousOperation): pass class InvalidResponseStatusCode(SuspiciousOperation): pass def get_content_type_from_filename(filename): return mimetypes.guess_type(filename)[0] def get_content_type_from_file_content(content): with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as m: mime_type = m.id_buffer(content.read(1024)) content.seek(0) return mime_type def get_filename_from_content_type(content_type): extensions = mimetypes.guess_all_extensions(content_type) <|code_end|> . Use current file imports: import os import cgi import mimetypes import magic # pylint: disable=E0401 from io import BytesIO from django.core.exceptions import SuspiciousOperation from pyston.conf import settings from security.transport.security_requests import request from requests import request and context (classes, functions, or code) from other files: # Path: pyston/conf.py # CONVERTERS = ( # 'pyston.converters.JsonConverter', # 'pyston.converters.XmlConverter', # 'pyston.converters.CsvConverter', # 'pyston.converters.TxtConverter', # ) # DEFAULT_FILENAMES = ( # (('pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv'), 'document'), # (('jpg', 'jpeg', 'png', 'gif', 'tiff', 'bmp', 'svg'), 'image'), # ) # DEFAULT_FILENAME = 'attachment' # DEFAULTS = { # 'CONVERTERS': CONVERTERS, # 'IGNORE_DUPE_MODELS': False, # 'CORS': False, # 'CORS_WHITELIST': (), # 'CORS_MAX_AGE': 60 * 30, # 'CORS_ALLOW_CREDENTIALS': True, # 'CORS_ALLOWED_HEADERS': ('X-Base', 'X-Offset', 'X-Fields', 'Origin', 'Content-Type', 'Accept'), # 'CORS_ALLOWED_EXPOSED_HEADERS': ('X-Total', 'X-Serialization-Format-Options', 'X-Fields-Options'), # 'JSON_CONVERTER_OPTIONS': { # 'indent': 4 # }, # 'PDF_EXPORT_TEMPLATE': 'default_pdf_table.html', # 'FILE_SIZE_LIMIT': 5000000, # 'AUTO_RELATED_REVERSE_FIELDS': True, # 'AUTO_RELATED_DIRECT_FIELDS': True, # 'PARTIAL_PUT_UPDATE': False, # 'PARTIAL_RELATED_UPDATE': False, # 'ERRORS_RESPONSE_CLASS': 'pyston.response.RestErrorsResponse', # 'ERROR_RESPONSE_CLASS': 'pyston.response.RestErrorResponse', # 'AUTO_REGISTER_RESOURCE': True, # 'ALLOW_TAGS': False, # 'DEFAULT_FILENAMES': DEFAULT_FILENAMES, # 'DEFAULT_FILENAME': DEFAULT_FILENAME, # 'NONE_HUMANIZED_VALUE': '--', # } # class Settings: # def __getattr__(self, attr): . Output only the next line.
known_extensions = [ext for exts, name in settings.DEFAULT_FILENAMES for ext in exts]
Next line prediction: <|code_start|> assert_equal(len(self.deserialize(resp)), min(max(int(resp['x-total']) - 2, 0), 5)) querystring = {'_offset': '2', '_base': '-5'} resp = self.get('%s?%s' % (self.USER_API_URL, urlencode(querystring))) assert_http_bad_request(resp) querystring = {'_offset': '-2', '_base': '5'} resp = self.get('%s?%s' % (self.USER_API_URL, urlencode(querystring))) assert_http_bad_request(resp) querystring = {'_offset': 'error', '_base': 'error'} resp = self.get('%s?%s' % (self.USER_API_URL, urlencode(querystring))) assert_http_bad_request(resp) @data_consumer('get_users_data') def test_read_user_with_more_headers_accept_types(self, number, data): resp = self.post(self.USER_API_URL, data=data) assert_valid_JSON_created_response(resp) pk = self.get_pk(resp) for accept_type in self.ACCEPT_TYPES: resp = self.get(self.USER_API_URL, headers={'HTTP_ACCEPT': accept_type}) assert_in(accept_type, resp['Content-Type']) resp = self.get('%s%s/' % (self.USER_API_URL, pk), headers={'HTTP_ACCEPT': accept_type}) assert_true(accept_type in resp['Content-Type']) resp = self.get('%s1050/' % self.USER_API_URL, headers={'HTTP_ACCEPT': accept_type}) assert_true(accept_type in resp['Content-Type']) assert_http_not_found(resp) @data_consumer('get_users_data') def test_read_user_with_more_querystring_accept_types(self, number, data): <|code_end|> . Use current file imports: (from six.moves.urllib.parse import urlencode from django.test.utils import override_settings from germanium.decorators import data_consumer from germanium.tools.trivials import assert_in, assert_equal, assert_true from germanium.tools.http import (assert_http_bad_request, assert_http_not_found, assert_http_method_not_allowed, assert_http_accepted) from germanium.tools.rest import assert_valid_JSON_created_response, assert_valid_JSON_response from .factories import UserFactory, IssueFactory from .test_case import PystonTestCase) and context including class names, function names, or small code snippets from other files: # Path: example/dj/apps/app/tests/factories.py # class UserFactory(factory.django.DjangoModelFactory): # # first_name = factory.Sequence(lambda n: 'John{0}'.format(n)) # last_name = factory.Sequence(lambda n: 'Doe{0}'.format(n)) # email = factory.Sequence(lambda n: 'customer_{0}@example.com'.format(n).lower()) # # class Meta: # model = models.User # # class IssueFactory(factory.django.DjangoModelFactory): # # name = factory.fuzzy.FuzzyText(length=100) # created_by = factory.SubFactory('app.tests.factories.UserFactory') # leader = factory.SubFactory('app.tests.factories.UserFactory') # # class Meta: # model = models.Issue # # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result . Output only the next line.
user = UserFactory()
Continue the code snippet: <|code_start|> querystring = {'_offset': '2', '_base': '-5'} resp = self.get('%s?%s' % (self.USER_API_URL, urlencode(querystring))) assert_http_bad_request(resp) querystring = {'_offset': '-2', '_base': '5'} resp = self.get('%s?%s' % (self.USER_API_URL, urlencode(querystring))) assert_http_bad_request(resp) querystring = {'_offset': 'error', '_base': 'error'} resp = self.get('%s?%s' % (self.USER_API_URL, urlencode(querystring))) assert_http_bad_request(resp) @data_consumer('get_users_data') def test_read_user_with_more_headers_accept_types(self, number, data): resp = self.post(self.USER_API_URL, data=data) assert_valid_JSON_created_response(resp) pk = self.get_pk(resp) for accept_type in self.ACCEPT_TYPES: resp = self.get(self.USER_API_URL, headers={'HTTP_ACCEPT': accept_type}) assert_in(accept_type, resp['Content-Type']) resp = self.get('%s%s/' % (self.USER_API_URL, pk), headers={'HTTP_ACCEPT': accept_type}) assert_true(accept_type in resp['Content-Type']) resp = self.get('%s1050/' % self.USER_API_URL, headers={'HTTP_ACCEPT': accept_type}) assert_true(accept_type in resp['Content-Type']) assert_http_not_found(resp) @data_consumer('get_users_data') def test_read_user_with_more_querystring_accept_types(self, number, data): user = UserFactory() <|code_end|> . Use current file imports: from six.moves.urllib.parse import urlencode from django.test.utils import override_settings from germanium.decorators import data_consumer from germanium.tools.trivials import assert_in, assert_equal, assert_true from germanium.tools.http import (assert_http_bad_request, assert_http_not_found, assert_http_method_not_allowed, assert_http_accepted) from germanium.tools.rest import assert_valid_JSON_created_response, assert_valid_JSON_response from .factories import UserFactory, IssueFactory from .test_case import PystonTestCase and context (classes, functions, or code) from other files: # Path: example/dj/apps/app/tests/factories.py # class UserFactory(factory.django.DjangoModelFactory): # # first_name = factory.Sequence(lambda n: 'John{0}'.format(n)) # last_name = factory.Sequence(lambda n: 'Doe{0}'.format(n)) # email = factory.Sequence(lambda n: 'customer_{0}@example.com'.format(n).lower()) # # class Meta: # model = models.User # # class IssueFactory(factory.django.DjangoModelFactory): # # name = factory.fuzzy.FuzzyText(length=100) # created_by = factory.SubFactory('app.tests.factories.UserFactory') # leader = factory.SubFactory('app.tests.factories.UserFactory') # # class Meta: # model = models.Issue # # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result . Output only the next line.
[issue.watched_by.add(user) for issue in (IssueFactory() for _ in range(10))]
Continue the code snippet: <|code_start|> class CompatibilityTestCase(TestCase): def test_is_relation(self): assert_true(is_relation(Issue, 'watched_by')) assert_true(is_relation(Issue, 'created_by')) assert_true(is_relation(Issue, 'solver')) assert_true(is_relation(Issue, 'leader')) assert_false(is_relation(Issue, 'name')) assert_false(is_relation(Issue, 'created_at')) assert_false(is_relation(Issue, 'invalid')) assert_true(is_relation(User, 'watched_issues')) assert_true(is_relation(User, 'created_issues')) assert_true(is_relation(User, 'solving_issue')) assert_true(is_relation(User, 'leading_issue')) def test_is_one_to_one(self): <|code_end|> . Use current file imports: from unittest.case import TestCase from django.core.exceptions import FieldError from germanium.tools import assert_true, assert_false, assert_raises, assert_equal, assert_is_none from pyston.utils.compatibility import ( is_relation, is_one_to_one, is_many_to_many, is_many_to_one, is_reverse_many_to_many, is_reverse_many_to_one, is_reverse_one_to_one, get_model_from_relation, get_model_from_relation_or_none, get_reverse_field_name ) from app.models import Issue, User and context (classes, functions, or code) from other files: # Path: pyston/utils/compatibility.py # def is_relation(model, field_name): # return ( # is_one_to_one(model, field_name) or # is_many_to_one(model, field_name) or # is_many_to_many(model, field_name) or # is_reverse_one_to_one(model, field_name) or # is_reverse_many_to_one(model, field_name) or # is_reverse_many_to_many(model, field_name) # ) # # def is_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.one_to_one # # def is_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_many # # def is_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_one # # def is_reverse_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.many_to_many # # def is_reverse_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_many # # def is_reverse_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_one # # def get_model_from_relation(model, field_name): # try: # related_model = model._meta.get_field(field_name).related_model # if related_model: # return related_model # else: # raise FieldError('field {} is not relation'.format(field_name)) # except FieldDoesNotExist: # raise FieldError('field {} is not relation'.format(field_name)) # # def get_model_from_relation_or_none(model, field_name): # try: # return get_model_from_relation(model, field_name) # except FieldError: # return None # # def get_reverse_field_name(model, field_name): # """ # Gets reverse field name, but for reverse fields must be set related_name, # therefore must be check if it was set by getting reverse field from the reverse model # """ # try: # model_field = model._meta.get_field(field_name) # reverse_field_name = model_field.remote_field.name # model_field.related_model._meta.get_field(reverse_field_name) # return reverse_field_name # except (FieldDoesNotExist, AttributeError): # raise FieldError('field {} is not relation'.format(field_name)) . Output only the next line.
assert_false(is_one_to_one(Issue, 'watched_by'))
Here is a snippet: <|code_start|> def test_is_one_to_one(self): assert_false(is_one_to_one(Issue, 'watched_by')) assert_false(is_one_to_one(Issue, 'created_by')) assert_true(is_one_to_one(Issue, 'solver')) assert_true(is_one_to_one(Issue, 'leader')) assert_false(is_one_to_one(Issue, 'name')) assert_false(is_one_to_one(Issue, 'created_at')) assert_false(is_one_to_one(Issue, 'invalid')) assert_false(is_one_to_one(User, 'watched_issues')) assert_false(is_one_to_one(User, 'created_issues')) assert_false(is_one_to_one(User, 'solving_issue')) assert_false(is_one_to_one(User, 'leading_issue')) def test_is_many_to_one(self): assert_false(is_many_to_one(Issue, 'watched_by')) assert_true(is_many_to_one(Issue, 'created_by')) assert_false(is_many_to_one(Issue, 'solver')) assert_false(is_many_to_one(Issue, 'leader')) assert_false(is_many_to_one(Issue, 'name')) assert_false(is_many_to_one(Issue, 'created_at')) assert_false(is_many_to_one(Issue, 'invalid')) assert_false(is_many_to_one(User, 'watched_issues')) assert_false(is_many_to_one(User, 'created_issues')) assert_false(is_many_to_one(User, 'solving_issue')) assert_false(is_many_to_one(User, 'leading_issue')) def test_is_many_to_many(self): <|code_end|> . Write the next line using the current file imports: from unittest.case import TestCase from django.core.exceptions import FieldError from germanium.tools import assert_true, assert_false, assert_raises, assert_equal, assert_is_none from pyston.utils.compatibility import ( is_relation, is_one_to_one, is_many_to_many, is_many_to_one, is_reverse_many_to_many, is_reverse_many_to_one, is_reverse_one_to_one, get_model_from_relation, get_model_from_relation_or_none, get_reverse_field_name ) from app.models import Issue, User and context from other files: # Path: pyston/utils/compatibility.py # def is_relation(model, field_name): # return ( # is_one_to_one(model, field_name) or # is_many_to_one(model, field_name) or # is_many_to_many(model, field_name) or # is_reverse_one_to_one(model, field_name) or # is_reverse_many_to_one(model, field_name) or # is_reverse_many_to_many(model, field_name) # ) # # def is_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.one_to_one # # def is_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_many # # def is_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_one # # def is_reverse_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.many_to_many # # def is_reverse_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_many # # def is_reverse_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_one # # def get_model_from_relation(model, field_name): # try: # related_model = model._meta.get_field(field_name).related_model # if related_model: # return related_model # else: # raise FieldError('field {} is not relation'.format(field_name)) # except FieldDoesNotExist: # raise FieldError('field {} is not relation'.format(field_name)) # # def get_model_from_relation_or_none(model, field_name): # try: # return get_model_from_relation(model, field_name) # except FieldError: # return None # # def get_reverse_field_name(model, field_name): # """ # Gets reverse field name, but for reverse fields must be set related_name, # therefore must be check if it was set by getting reverse field from the reverse model # """ # try: # model_field = model._meta.get_field(field_name) # reverse_field_name = model_field.remote_field.name # model_field.related_model._meta.get_field(reverse_field_name) # return reverse_field_name # except (FieldDoesNotExist, AttributeError): # raise FieldError('field {} is not relation'.format(field_name)) , which may include functions, classes, or code. Output only the next line.
assert_true(is_many_to_many(Issue, 'watched_by'))
Given the following code snippet before the placeholder: <|code_start|> def test_is_relation(self): assert_true(is_relation(Issue, 'watched_by')) assert_true(is_relation(Issue, 'created_by')) assert_true(is_relation(Issue, 'solver')) assert_true(is_relation(Issue, 'leader')) assert_false(is_relation(Issue, 'name')) assert_false(is_relation(Issue, 'created_at')) assert_false(is_relation(Issue, 'invalid')) assert_true(is_relation(User, 'watched_issues')) assert_true(is_relation(User, 'created_issues')) assert_true(is_relation(User, 'solving_issue')) assert_true(is_relation(User, 'leading_issue')) def test_is_one_to_one(self): assert_false(is_one_to_one(Issue, 'watched_by')) assert_false(is_one_to_one(Issue, 'created_by')) assert_true(is_one_to_one(Issue, 'solver')) assert_true(is_one_to_one(Issue, 'leader')) assert_false(is_one_to_one(Issue, 'name')) assert_false(is_one_to_one(Issue, 'created_at')) assert_false(is_one_to_one(Issue, 'invalid')) assert_false(is_one_to_one(User, 'watched_issues')) assert_false(is_one_to_one(User, 'created_issues')) assert_false(is_one_to_one(User, 'solving_issue')) assert_false(is_one_to_one(User, 'leading_issue')) def test_is_many_to_one(self): <|code_end|> , predict the next line using imports from the current file: from unittest.case import TestCase from django.core.exceptions import FieldError from germanium.tools import assert_true, assert_false, assert_raises, assert_equal, assert_is_none from pyston.utils.compatibility import ( is_relation, is_one_to_one, is_many_to_many, is_many_to_one, is_reverse_many_to_many, is_reverse_many_to_one, is_reverse_one_to_one, get_model_from_relation, get_model_from_relation_or_none, get_reverse_field_name ) from app.models import Issue, User and context including class names, function names, and sometimes code from other files: # Path: pyston/utils/compatibility.py # def is_relation(model, field_name): # return ( # is_one_to_one(model, field_name) or # is_many_to_one(model, field_name) or # is_many_to_many(model, field_name) or # is_reverse_one_to_one(model, field_name) or # is_reverse_many_to_one(model, field_name) or # is_reverse_many_to_many(model, field_name) # ) # # def is_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.one_to_one # # def is_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_many # # def is_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_one # # def is_reverse_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.many_to_many # # def is_reverse_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_many # # def is_reverse_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_one # # def get_model_from_relation(model, field_name): # try: # related_model = model._meta.get_field(field_name).related_model # if related_model: # return related_model # else: # raise FieldError('field {} is not relation'.format(field_name)) # except FieldDoesNotExist: # raise FieldError('field {} is not relation'.format(field_name)) # # def get_model_from_relation_or_none(model, field_name): # try: # return get_model_from_relation(model, field_name) # except FieldError: # return None # # def get_reverse_field_name(model, field_name): # """ # Gets reverse field name, but for reverse fields must be set related_name, # therefore must be check if it was set by getting reverse field from the reverse model # """ # try: # model_field = model._meta.get_field(field_name) # reverse_field_name = model_field.remote_field.name # model_field.related_model._meta.get_field(reverse_field_name) # return reverse_field_name # except (FieldDoesNotExist, AttributeError): # raise FieldError('field {} is not relation'.format(field_name)) . Output only the next line.
assert_false(is_many_to_one(Issue, 'watched_by'))
Predict the next line after this snippet: <|code_start|> def test_is_reverse_one_to_one(self): assert_false(is_reverse_one_to_one(Issue, 'watched_by')) assert_false(is_reverse_one_to_one(Issue, 'created_by')) assert_false(is_reverse_one_to_one(Issue, 'solver')) assert_false(is_reverse_one_to_one(Issue, 'leader')) assert_false(is_reverse_one_to_one(Issue, 'name')) assert_false(is_reverse_one_to_one(Issue, 'created_at')) assert_false(is_reverse_one_to_one(Issue, 'invalid')) assert_false(is_reverse_one_to_one(User, 'watched_issues')) assert_false(is_reverse_one_to_one(User, 'created_issues')) assert_true(is_reverse_one_to_one(User, 'solving_issue')) assert_true(is_reverse_one_to_one(User, 'leading_issue')) def test_is_reverse_many_to_one(self): assert_false(is_reverse_many_to_one(Issue, 'watched_by')) assert_false(is_reverse_many_to_one(Issue, 'created_by')) assert_false(is_reverse_many_to_one(Issue, 'solver')) assert_false(is_reverse_many_to_one(Issue, 'leader')) assert_false(is_reverse_many_to_one(Issue, 'name')) assert_false(is_reverse_many_to_one(Issue, 'created_at')) assert_false(is_reverse_many_to_one(Issue, 'invalid')) assert_false(is_reverse_many_to_one(User, 'watched_issues')) assert_true(is_reverse_many_to_one(User, 'created_issues')) assert_false(is_reverse_many_to_one(User, 'solving_issue')) assert_false(is_reverse_many_to_one(User, 'leading_issue')) def test_is_reverse_many_to_many(self): <|code_end|> using the current file's imports: from unittest.case import TestCase from django.core.exceptions import FieldError from germanium.tools import assert_true, assert_false, assert_raises, assert_equal, assert_is_none from pyston.utils.compatibility import ( is_relation, is_one_to_one, is_many_to_many, is_many_to_one, is_reverse_many_to_many, is_reverse_many_to_one, is_reverse_one_to_one, get_model_from_relation, get_model_from_relation_or_none, get_reverse_field_name ) from app.models import Issue, User and any relevant context from other files: # Path: pyston/utils/compatibility.py # def is_relation(model, field_name): # return ( # is_one_to_one(model, field_name) or # is_many_to_one(model, field_name) or # is_many_to_many(model, field_name) or # is_reverse_one_to_one(model, field_name) or # is_reverse_many_to_one(model, field_name) or # is_reverse_many_to_many(model, field_name) # ) # # def is_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.one_to_one # # def is_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_many # # def is_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_one # # def is_reverse_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.many_to_many # # def is_reverse_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_many # # def is_reverse_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_one # # def get_model_from_relation(model, field_name): # try: # related_model = model._meta.get_field(field_name).related_model # if related_model: # return related_model # else: # raise FieldError('field {} is not relation'.format(field_name)) # except FieldDoesNotExist: # raise FieldError('field {} is not relation'.format(field_name)) # # def get_model_from_relation_or_none(model, field_name): # try: # return get_model_from_relation(model, field_name) # except FieldError: # return None # # def get_reverse_field_name(model, field_name): # """ # Gets reverse field name, but for reverse fields must be set related_name, # therefore must be check if it was set by getting reverse field from the reverse model # """ # try: # model_field = model._meta.get_field(field_name) # reverse_field_name = model_field.remote_field.name # model_field.related_model._meta.get_field(reverse_field_name) # return reverse_field_name # except (FieldDoesNotExist, AttributeError): # raise FieldError('field {} is not relation'.format(field_name)) . Output only the next line.
assert_false(is_reverse_many_to_many(Issue, 'watched_by'))
Next line prediction: <|code_start|> def test_is_many_to_many(self): assert_true(is_many_to_many(Issue, 'watched_by')) assert_false(is_many_to_many(Issue, 'created_by')) assert_false(is_many_to_many(Issue, 'solver')) assert_false(is_many_to_many(Issue, 'leader')) assert_false(is_many_to_many(Issue, 'name')) assert_false(is_many_to_many(Issue, 'created_at')) assert_false(is_many_to_many(Issue, 'invalid')) assert_false(is_many_to_many(User, 'watched_issues')) assert_false(is_many_to_many(User, 'created_issues')) assert_false(is_many_to_many(User, 'solving_issue')) assert_false(is_many_to_many(User, 'leading_issue')) def test_is_reverse_one_to_one(self): assert_false(is_reverse_one_to_one(Issue, 'watched_by')) assert_false(is_reverse_one_to_one(Issue, 'created_by')) assert_false(is_reverse_one_to_one(Issue, 'solver')) assert_false(is_reverse_one_to_one(Issue, 'leader')) assert_false(is_reverse_one_to_one(Issue, 'name')) assert_false(is_reverse_one_to_one(Issue, 'created_at')) assert_false(is_reverse_one_to_one(Issue, 'invalid')) assert_false(is_reverse_one_to_one(User, 'watched_issues')) assert_false(is_reverse_one_to_one(User, 'created_issues')) assert_true(is_reverse_one_to_one(User, 'solving_issue')) assert_true(is_reverse_one_to_one(User, 'leading_issue')) def test_is_reverse_many_to_one(self): <|code_end|> . Use current file imports: (from unittest.case import TestCase from django.core.exceptions import FieldError from germanium.tools import assert_true, assert_false, assert_raises, assert_equal, assert_is_none from pyston.utils.compatibility import ( is_relation, is_one_to_one, is_many_to_many, is_many_to_one, is_reverse_many_to_many, is_reverse_many_to_one, is_reverse_one_to_one, get_model_from_relation, get_model_from_relation_or_none, get_reverse_field_name ) from app.models import Issue, User) and context including class names, function names, or small code snippets from other files: # Path: pyston/utils/compatibility.py # def is_relation(model, field_name): # return ( # is_one_to_one(model, field_name) or # is_many_to_one(model, field_name) or # is_many_to_many(model, field_name) or # is_reverse_one_to_one(model, field_name) or # is_reverse_many_to_one(model, field_name) or # is_reverse_many_to_many(model, field_name) # ) # # def is_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.one_to_one # # def is_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_many # # def is_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_one # # def is_reverse_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.many_to_many # # def is_reverse_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_many # # def is_reverse_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_one # # def get_model_from_relation(model, field_name): # try: # related_model = model._meta.get_field(field_name).related_model # if related_model: # return related_model # else: # raise FieldError('field {} is not relation'.format(field_name)) # except FieldDoesNotExist: # raise FieldError('field {} is not relation'.format(field_name)) # # def get_model_from_relation_or_none(model, field_name): # try: # return get_model_from_relation(model, field_name) # except FieldError: # return None # # def get_reverse_field_name(model, field_name): # """ # Gets reverse field name, but for reverse fields must be set related_name, # therefore must be check if it was set by getting reverse field from the reverse model # """ # try: # model_field = model._meta.get_field(field_name) # reverse_field_name = model_field.remote_field.name # model_field.related_model._meta.get_field(reverse_field_name) # return reverse_field_name # except (FieldDoesNotExist, AttributeError): # raise FieldError('field {} is not relation'.format(field_name)) . Output only the next line.
assert_false(is_reverse_many_to_one(Issue, 'watched_by'))
Next line prediction: <|code_start|> def test_is_many_to_one(self): assert_false(is_many_to_one(Issue, 'watched_by')) assert_true(is_many_to_one(Issue, 'created_by')) assert_false(is_many_to_one(Issue, 'solver')) assert_false(is_many_to_one(Issue, 'leader')) assert_false(is_many_to_one(Issue, 'name')) assert_false(is_many_to_one(Issue, 'created_at')) assert_false(is_many_to_one(Issue, 'invalid')) assert_false(is_many_to_one(User, 'watched_issues')) assert_false(is_many_to_one(User, 'created_issues')) assert_false(is_many_to_one(User, 'solving_issue')) assert_false(is_many_to_one(User, 'leading_issue')) def test_is_many_to_many(self): assert_true(is_many_to_many(Issue, 'watched_by')) assert_false(is_many_to_many(Issue, 'created_by')) assert_false(is_many_to_many(Issue, 'solver')) assert_false(is_many_to_many(Issue, 'leader')) assert_false(is_many_to_many(Issue, 'name')) assert_false(is_many_to_many(Issue, 'created_at')) assert_false(is_many_to_many(Issue, 'invalid')) assert_false(is_many_to_many(User, 'watched_issues')) assert_false(is_many_to_many(User, 'created_issues')) assert_false(is_many_to_many(User, 'solving_issue')) assert_false(is_many_to_many(User, 'leading_issue')) def test_is_reverse_one_to_one(self): <|code_end|> . Use current file imports: (from unittest.case import TestCase from django.core.exceptions import FieldError from germanium.tools import assert_true, assert_false, assert_raises, assert_equal, assert_is_none from pyston.utils.compatibility import ( is_relation, is_one_to_one, is_many_to_many, is_many_to_one, is_reverse_many_to_many, is_reverse_many_to_one, is_reverse_one_to_one, get_model_from_relation, get_model_from_relation_or_none, get_reverse_field_name ) from app.models import Issue, User) and context including class names, function names, or small code snippets from other files: # Path: pyston/utils/compatibility.py # def is_relation(model, field_name): # return ( # is_one_to_one(model, field_name) or # is_many_to_one(model, field_name) or # is_many_to_many(model, field_name) or # is_reverse_one_to_one(model, field_name) or # is_reverse_many_to_one(model, field_name) or # is_reverse_many_to_many(model, field_name) # ) # # def is_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.one_to_one # # def is_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_many # # def is_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_one # # def is_reverse_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.many_to_many # # def is_reverse_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_many # # def is_reverse_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_one # # def get_model_from_relation(model, field_name): # try: # related_model = model._meta.get_field(field_name).related_model # if related_model: # return related_model # else: # raise FieldError('field {} is not relation'.format(field_name)) # except FieldDoesNotExist: # raise FieldError('field {} is not relation'.format(field_name)) # # def get_model_from_relation_or_none(model, field_name): # try: # return get_model_from_relation(model, field_name) # except FieldError: # return None # # def get_reverse_field_name(model, field_name): # """ # Gets reverse field name, but for reverse fields must be set related_name, # therefore must be check if it was set by getting reverse field from the reverse model # """ # try: # model_field = model._meta.get_field(field_name) # reverse_field_name = model_field.remote_field.name # model_field.related_model._meta.get_field(reverse_field_name) # return reverse_field_name # except (FieldDoesNotExist, AttributeError): # raise FieldError('field {} is not relation'.format(field_name)) . Output only the next line.
assert_false(is_reverse_one_to_one(Issue, 'watched_by'))
Using the snippet: <|code_start|> def test_is_reverse_many_to_one(self): assert_false(is_reverse_many_to_one(Issue, 'watched_by')) assert_false(is_reverse_many_to_one(Issue, 'created_by')) assert_false(is_reverse_many_to_one(Issue, 'solver')) assert_false(is_reverse_many_to_one(Issue, 'leader')) assert_false(is_reverse_many_to_one(Issue, 'name')) assert_false(is_reverse_many_to_one(Issue, 'created_at')) assert_false(is_reverse_many_to_one(Issue, 'invalid')) assert_false(is_reverse_many_to_one(User, 'watched_issues')) assert_true(is_reverse_many_to_one(User, 'created_issues')) assert_false(is_reverse_many_to_one(User, 'solving_issue')) assert_false(is_reverse_many_to_one(User, 'leading_issue')) def test_is_reverse_many_to_many(self): assert_false(is_reverse_many_to_many(Issue, 'watched_by')) assert_false(is_reverse_many_to_many(Issue, 'created_by')) assert_false(is_reverse_many_to_many(Issue, 'solver')) assert_false(is_reverse_many_to_many(Issue, 'leader')) assert_false(is_reverse_many_to_many(Issue, 'name')) assert_false(is_reverse_many_to_many(Issue, 'created_at')) assert_false(is_reverse_many_to_many(Issue, 'invalid')) assert_true(is_reverse_many_to_many(User, 'watched_issues')) assert_false(is_reverse_many_to_many(User, 'created_issues')) assert_false(is_reverse_many_to_many(User, 'solving_issue')) assert_false(is_reverse_many_to_many(User, 'leading_issue')) def test_get_model_from_relation(self): <|code_end|> , determine the next line of code. You have imports: from unittest.case import TestCase from django.core.exceptions import FieldError from germanium.tools import assert_true, assert_false, assert_raises, assert_equal, assert_is_none from pyston.utils.compatibility import ( is_relation, is_one_to_one, is_many_to_many, is_many_to_one, is_reverse_many_to_many, is_reverse_many_to_one, is_reverse_one_to_one, get_model_from_relation, get_model_from_relation_or_none, get_reverse_field_name ) from app.models import Issue, User and context (class names, function names, or code) available: # Path: pyston/utils/compatibility.py # def is_relation(model, field_name): # return ( # is_one_to_one(model, field_name) or # is_many_to_one(model, field_name) or # is_many_to_many(model, field_name) or # is_reverse_one_to_one(model, field_name) or # is_reverse_many_to_one(model, field_name) or # is_reverse_many_to_many(model, field_name) # ) # # def is_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.one_to_one # # def is_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_many # # def is_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_one # # def is_reverse_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.many_to_many # # def is_reverse_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_many # # def is_reverse_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_one # # def get_model_from_relation(model, field_name): # try: # related_model = model._meta.get_field(field_name).related_model # if related_model: # return related_model # else: # raise FieldError('field {} is not relation'.format(field_name)) # except FieldDoesNotExist: # raise FieldError('field {} is not relation'.format(field_name)) # # def get_model_from_relation_or_none(model, field_name): # try: # return get_model_from_relation(model, field_name) # except FieldError: # return None # # def get_reverse_field_name(model, field_name): # """ # Gets reverse field name, but for reverse fields must be set related_name, # therefore must be check if it was set by getting reverse field from the reverse model # """ # try: # model_field = model._meta.get_field(field_name) # reverse_field_name = model_field.remote_field.name # model_field.related_model._meta.get_field(reverse_field_name) # return reverse_field_name # except (FieldDoesNotExist, AttributeError): # raise FieldError('field {} is not relation'.format(field_name)) . Output only the next line.
assert_equal(get_model_from_relation(Issue, 'watched_by'), User)
Continue the code snippet: <|code_start|> def test_is_reverse_many_to_many(self): assert_false(is_reverse_many_to_many(Issue, 'watched_by')) assert_false(is_reverse_many_to_many(Issue, 'created_by')) assert_false(is_reverse_many_to_many(Issue, 'solver')) assert_false(is_reverse_many_to_many(Issue, 'leader')) assert_false(is_reverse_many_to_many(Issue, 'name')) assert_false(is_reverse_many_to_many(Issue, 'created_at')) assert_false(is_reverse_many_to_many(Issue, 'invalid')) assert_true(is_reverse_many_to_many(User, 'watched_issues')) assert_false(is_reverse_many_to_many(User, 'created_issues')) assert_false(is_reverse_many_to_many(User, 'solving_issue')) assert_false(is_reverse_many_to_many(User, 'leading_issue')) def test_get_model_from_relation(self): assert_equal(get_model_from_relation(Issue, 'watched_by'), User) assert_equal(get_model_from_relation(Issue, 'created_by'), User) assert_equal(get_model_from_relation(Issue, 'solver'), User) assert_equal(get_model_from_relation(Issue, 'leader'), User) assert_raises(FieldError, get_model_from_relation, Issue, 'name') assert_raises(FieldError, get_model_from_relation, Issue, 'created_at') assert_raises(FieldError, get_model_from_relation, Issue, 'invalid') assert_equal(get_model_from_relation(User, 'watched_issues'), Issue) assert_equal(get_model_from_relation(User, 'created_issues'), Issue) assert_equal(get_model_from_relation(User, 'solving_issue'), Issue) assert_equal(get_model_from_relation(User, 'leading_issue'), Issue) def test_get_model_from_relation_or_none(self): <|code_end|> . Use current file imports: from unittest.case import TestCase from django.core.exceptions import FieldError from germanium.tools import assert_true, assert_false, assert_raises, assert_equal, assert_is_none from pyston.utils.compatibility import ( is_relation, is_one_to_one, is_many_to_many, is_many_to_one, is_reverse_many_to_many, is_reverse_many_to_one, is_reverse_one_to_one, get_model_from_relation, get_model_from_relation_or_none, get_reverse_field_name ) from app.models import Issue, User and context (classes, functions, or code) from other files: # Path: pyston/utils/compatibility.py # def is_relation(model, field_name): # return ( # is_one_to_one(model, field_name) or # is_many_to_one(model, field_name) or # is_many_to_many(model, field_name) or # is_reverse_one_to_one(model, field_name) or # is_reverse_many_to_one(model, field_name) or # is_reverse_many_to_many(model, field_name) # ) # # def is_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.one_to_one # # def is_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_many # # def is_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_one # # def is_reverse_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.many_to_many # # def is_reverse_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_many # # def is_reverse_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_one # # def get_model_from_relation(model, field_name): # try: # related_model = model._meta.get_field(field_name).related_model # if related_model: # return related_model # else: # raise FieldError('field {} is not relation'.format(field_name)) # except FieldDoesNotExist: # raise FieldError('field {} is not relation'.format(field_name)) # # def get_model_from_relation_or_none(model, field_name): # try: # return get_model_from_relation(model, field_name) # except FieldError: # return None # # def get_reverse_field_name(model, field_name): # """ # Gets reverse field name, but for reverse fields must be set related_name, # therefore must be check if it was set by getting reverse field from the reverse model # """ # try: # model_field = model._meta.get_field(field_name) # reverse_field_name = model_field.remote_field.name # model_field.related_model._meta.get_field(reverse_field_name) # return reverse_field_name # except (FieldDoesNotExist, AttributeError): # raise FieldError('field {} is not relation'.format(field_name)) . Output only the next line.
assert_equal(get_model_from_relation_or_none(Issue, 'watched_by'), User)
Here is a snippet: <|code_start|> def test_get_model_from_relation(self): assert_equal(get_model_from_relation(Issue, 'watched_by'), User) assert_equal(get_model_from_relation(Issue, 'created_by'), User) assert_equal(get_model_from_relation(Issue, 'solver'), User) assert_equal(get_model_from_relation(Issue, 'leader'), User) assert_raises(FieldError, get_model_from_relation, Issue, 'name') assert_raises(FieldError, get_model_from_relation, Issue, 'created_at') assert_raises(FieldError, get_model_from_relation, Issue, 'invalid') assert_equal(get_model_from_relation(User, 'watched_issues'), Issue) assert_equal(get_model_from_relation(User, 'created_issues'), Issue) assert_equal(get_model_from_relation(User, 'solving_issue'), Issue) assert_equal(get_model_from_relation(User, 'leading_issue'), Issue) def test_get_model_from_relation_or_none(self): assert_equal(get_model_from_relation_or_none(Issue, 'watched_by'), User) assert_equal(get_model_from_relation_or_none(Issue, 'created_by'), User) assert_equal(get_model_from_relation_or_none(Issue, 'solver'), User) assert_equal(get_model_from_relation_or_none(Issue, 'leader'), User) assert_is_none(get_model_from_relation_or_none(Issue, 'name')) assert_is_none(get_model_from_relation_or_none(Issue, 'created_at')) assert_is_none(get_model_from_relation_or_none(Issue, 'invalid')) assert_equal(get_model_from_relation_or_none(User, 'watched_issues'), Issue) assert_equal(get_model_from_relation_or_none(User, 'created_issues'), Issue) assert_equal(get_model_from_relation_or_none(User, 'solving_issue'), Issue) assert_equal(get_model_from_relation_or_none(User, 'leading_issue'), Issue) def test_get_reverse_field_name(self): <|code_end|> . Write the next line using the current file imports: from unittest.case import TestCase from django.core.exceptions import FieldError from germanium.tools import assert_true, assert_false, assert_raises, assert_equal, assert_is_none from pyston.utils.compatibility import ( is_relation, is_one_to_one, is_many_to_many, is_many_to_one, is_reverse_many_to_many, is_reverse_many_to_one, is_reverse_one_to_one, get_model_from_relation, get_model_from_relation_or_none, get_reverse_field_name ) from app.models import Issue, User and context from other files: # Path: pyston/utils/compatibility.py # def is_relation(model, field_name): # return ( # is_one_to_one(model, field_name) or # is_many_to_one(model, field_name) or # is_many_to_many(model, field_name) or # is_reverse_one_to_one(model, field_name) or # is_reverse_many_to_one(model, field_name) or # is_reverse_many_to_many(model, field_name) # ) # # def is_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.one_to_one # # def is_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_many # # def is_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and not field.auto_created and field.many_to_one # # def is_reverse_many_to_many(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.many_to_many # # def is_reverse_many_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_many # # def is_reverse_one_to_one(model, field_name): # field = get_field_or_none(model, field_name) # return field and field.auto_created and field.one_to_one # # def get_model_from_relation(model, field_name): # try: # related_model = model._meta.get_field(field_name).related_model # if related_model: # return related_model # else: # raise FieldError('field {} is not relation'.format(field_name)) # except FieldDoesNotExist: # raise FieldError('field {} is not relation'.format(field_name)) # # def get_model_from_relation_or_none(model, field_name): # try: # return get_model_from_relation(model, field_name) # except FieldError: # return None # # def get_reverse_field_name(model, field_name): # """ # Gets reverse field name, but for reverse fields must be set related_name, # therefore must be check if it was set by getting reverse field from the reverse model # """ # try: # model_field = model._meta.get_field(field_name) # reverse_field_name = model_field.remote_field.name # model_field.related_model._meta.get_field(reverse_field_name) # return reverse_field_name # except (FieldDoesNotExist, AttributeError): # raise FieldError('field {} is not relation'.format(field_name)) , which may include functions, classes, or code. Output only the next line.
assert_equal(get_reverse_field_name(Issue, 'watched_by'), 'watched_issues')
Given the code snippet: <|code_start|> class DynamoSorter(BaseSorter): def get_order_term(self): return self.direction == DIRECTION.ASC <|code_end|> , generate the next line using the imports in this file: from pyston.order.sorters import BaseSorter from pyston.order.managers import BaseParserModelOrderManager from pyston.order.utils import DIRECTION and context (functions, classes, or occasionally code) from other files: # Path: pyston/order/sorters.py # class BaseSorter: # # def __init__(self, identifiers, direction): # self.identifiers = identifiers # self.direction = direction # # def update_queryset(self, qs): # return qs # # def get_order_term(self): # raise NotImplementedError # # Path: pyston/order/managers.py # class BaseParserModelOrderManager(BaseModelOrderManager): # # parsers = [DefaultOrderParser()] # # def _get_sorters(self, parsed_order_terms, resource, request): # """ # Converts order terms to sorter classes # """ # sorters = [] # for ordering_term in parsed_order_terms: # try: # sorters.append(self.get_sorter(ordering_term.identifiers, ordering_term.direction, resource, request)) # except OrderIdentifierError: # raise RestException( # mark_safe(ugettext('Invalid identifier of ordering "{}"').format(ordering_term.source)) # ) # return sorters # # def _convert_order_terms(self, sorters): # """ # Converts sorters to the django query order strings. # """ # return [sorter.get_order_term() for sorter in sorters] # # def _update_queryset(self, qs, sorters): # """ # Update queryset for extra sorter class (it is used for annotations before ordering) # """ # for sorter in sorters: # qs = sorter.update_queryset(qs) # return qs # # def _sort_queryset(self, qs, terms): # raise NotImplementedError # # def _sort_with_parser(self, parser, resource, qs, request): # try: # parsed_order_terms = parser.parse(request) # sorters = self._get_sorters(parsed_order_terms or (), resource, request) # qs = self._update_queryset(qs, sorters) # return self._sort_queryset(qs, self._convert_order_terms(sorters)) if sorters else qs # except OrderParserError as ex: # raise RestException(ex) # # def sort(self, resource, qs, request): # for parser in self.parsers: # qs = self._sort_with_parser(parser, resource, qs, request) # return qs # # Path: pyston/order/utils.py # DIRECTION = Enum( # 'ASC', # 'DESC', # ) . Output only the next line.
class DynamoOrderManager(BaseParserModelOrderManager):
Next line prediction: <|code_start|> class CountIssuesPerUserTable(Serializable): def serialize(self, serialization_format, **kwargs): return [ { 'email': user.email, 'created_issues_count': user.created_issues.count(), } for user in User.objects.all() ] <|code_end|> . Use current file imports: (from pyston.serializer import Serializable, SerializableObj from .models import User) and context including class names, function names, or small code snippets from other files: # Path: pyston/serializer.py # class Serializable: # # def serialize(self, serialization_format, **kwargs): # raise NotImplementedError # # class SerializableObj(Serializable, metaclass=SerializableObjMetaClass): # # resource_typemapper = {} # # def _get_value(self, field, serialization_format, request, **kwargs): # val = getattr(self, field) # return get_serializer( # val, request=request, resource_typemapper=self.resource_typemapper # ).serialize(val, serialization_format, **kwargs) # # def serialize(self, serialization_format, request=None, requested_fieldset=None, **kwargs): # return { # field_name: self._get_value( # field_name, # serialization_format, # request, # requested_fieldset=requested_fieldset.get(field_name).subfieldset if requested_fieldset else None, # **kwargs # ) # for field_name in self.get_fields() # if not requested_fieldset or field_name in requested_fieldset # } # # def get_fields(self): # return self.RestMeta.fields # # Path: example/dj/apps/app/models.py # class User(models.Model): # # created_at = models.DateTimeField(verbose_name=_('created at'), null=False, blank=False, auto_now_add=True) # email = models.EmailField(verbose_name=_('email'), null=False, blank=False, unique=True, # filter=OnlyContainsStringFieldFilter) # contract = models.FileField(_('file'), null=True, blank=True, upload_to='documents/') # is_superuser = models.BooleanField(_('is superuser'), default=True) # first_name = models.CharField(_('first name'), null=True, blank=True, max_length=100) # last_name = models.CharField(_('last name'), null=True, blank=True, max_length=100) # manual_created_date = models.DateTimeField(verbose_name=_('manual created date'), null=True, blank=True) # # @filter_class(WatchedIssuesCountMethodFilter) # @sorter_class(WatchedIssuesCountSorter) # def watched_issues_count(self): # return self.watched_issues.count() # # def __str__(self): # return 'user: %s' % self.email # # class RestMeta: # fields = ('created_at', 'email', 'contract', 'solving_issue', 'first_name', 'last_name', 'is_superuser', # 'manual_created_date', 'watched_issues_count') # detailed_fields = ('created_at', '_obj_name', 'email', 'contract', 'solving_issue', 'first_name', 'last_name', # 'watched_issues__name', 'watched_issues__id', 'manual_created_date') # general_fields = ('email', 'first_name', 'last_name', 'watched_issues__name', 'watched_issues__id', # 'manual_created_date', 'watched_issues_count') # direct_serialization_fields = ('created_at', 'email', 'contract', 'solving_issue', 'first_name', 'last_name', # 'manual_created_date') # order_fields = ('email', 'solving_issue', 'watched_issues_count') # extra_order_fields = ('created_at',) # filter_fields = ('email', 'first_name', 'last_name', 'is_superuser', 'created_issues', 'watched_issues_count') # extra_filter_fields = ('created_at',) . Output only the next line.
class CountWatchersPerIssue(SerializableObj):
Given snippet: <|code_start|> class CountIssuesPerUserTable(Serializable): def serialize(self, serialization_format, **kwargs): return [ { 'email': user.email, 'created_issues_count': user.created_issues.count(), } <|code_end|> , continue by predicting the next line. Consider current file imports: from pyston.serializer import Serializable, SerializableObj from .models import User and context: # Path: pyston/serializer.py # class Serializable: # # def serialize(self, serialization_format, **kwargs): # raise NotImplementedError # # class SerializableObj(Serializable, metaclass=SerializableObjMetaClass): # # resource_typemapper = {} # # def _get_value(self, field, serialization_format, request, **kwargs): # val = getattr(self, field) # return get_serializer( # val, request=request, resource_typemapper=self.resource_typemapper # ).serialize(val, serialization_format, **kwargs) # # def serialize(self, serialization_format, request=None, requested_fieldset=None, **kwargs): # return { # field_name: self._get_value( # field_name, # serialization_format, # request, # requested_fieldset=requested_fieldset.get(field_name).subfieldset if requested_fieldset else None, # **kwargs # ) # for field_name in self.get_fields() # if not requested_fieldset or field_name in requested_fieldset # } # # def get_fields(self): # return self.RestMeta.fields # # Path: example/dj/apps/app/models.py # class User(models.Model): # # created_at = models.DateTimeField(verbose_name=_('created at'), null=False, blank=False, auto_now_add=True) # email = models.EmailField(verbose_name=_('email'), null=False, blank=False, unique=True, # filter=OnlyContainsStringFieldFilter) # contract = models.FileField(_('file'), null=True, blank=True, upload_to='documents/') # is_superuser = models.BooleanField(_('is superuser'), default=True) # first_name = models.CharField(_('first name'), null=True, blank=True, max_length=100) # last_name = models.CharField(_('last name'), null=True, blank=True, max_length=100) # manual_created_date = models.DateTimeField(verbose_name=_('manual created date'), null=True, blank=True) # # @filter_class(WatchedIssuesCountMethodFilter) # @sorter_class(WatchedIssuesCountSorter) # def watched_issues_count(self): # return self.watched_issues.count() # # def __str__(self): # return 'user: %s' % self.email # # class RestMeta: # fields = ('created_at', 'email', 'contract', 'solving_issue', 'first_name', 'last_name', 'is_superuser', # 'manual_created_date', 'watched_issues_count') # detailed_fields = ('created_at', '_obj_name', 'email', 'contract', 'solving_issue', 'first_name', 'last_name', # 'watched_issues__name', 'watched_issues__id', 'manual_created_date') # general_fields = ('email', 'first_name', 'last_name', 'watched_issues__name', 'watched_issues__id', # 'manual_created_date', 'watched_issues_count') # direct_serialization_fields = ('created_at', 'email', 'contract', 'solving_issue', 'first_name', 'last_name', # 'manual_created_date') # order_fields = ('email', 'solving_issue', 'watched_issues_count') # extra_order_fields = ('created_at',) # filter_fields = ('email', 'first_name', 'last_name', 'is_superuser', 'created_issues', 'watched_issues_count') # extra_filter_fields = ('created_at',) which might include code, classes, or functions. Output only the next line.
for user in User.objects.all()
Given snippet: <|code_start|>class FilterParser: """ Abstract filter parser. """ def parse(self, request): """ :param request: Django HTTP request. :return: returns conditions tree or None. """ raise NotImplementedError class DefaultFilterParser(FilterParser): """ Parser for complex filter terms. E.q.: /api/user?filter=created_at__moth=5 AND NOT (contract=null OR first_name='Petr') """ ALLOWED_OPERATORS = ( '=', '!=', '>=', '<=', '>', '<', '[a-z]+' ) OPERATORS_MAPPING = { <|code_end|> , continue by predicting the next line. Consider current file imports: import re import pyparsing as pp from django.utils.safestring import mark_safe from django.utils.translation import ugettext from .filters import OPERATORS from .utils import LOGICAL_OPERATORS and context: # Path: pyston/filters/filters.py # OPERATORS = Enum( # ('GT', 'gt'), # ('LT', 'lt'), # ('EQ', 'eq'), # ('NEQ', 'neq'), # ('LTE', 'lte'), # ('GTE', 'gte'), # ('CONTAINS', 'contains'), # ('ICONTAINS', 'icontains'), # ('RANGE', 'range'), # ('EXACT', 'exact'), # ('IEXACT', 'iexact'), # ('STARTSWITH', 'startswith'), # ('ISTARTSWITH', 'istartswith'), # ('ENDSWITH', 'endswith'), # ('IENDSWITH', 'iendswith'), # ('IN', 'in'), # ('RANGE', 'range'), # ('ALL', 'all'), # ('ISNULL', 'isnull'), # ) # # Path: pyston/filters/utils.py # LOGICAL_OPERATORS = Enum( # 'AND', # 'OR', # 'NOT', # ) which might include code, classes, or functions. Output only the next line.
'=': OPERATORS.EQ,
Using the snippet: <|code_start|> '>=', '<=', '>', '<', '[a-z]+' ) OPERATORS_MAPPING = { '=': OPERATORS.EQ, '!=': OPERATORS.NEQ, '<': OPERATORS.LT, '>': OPERATORS.GT, '>=': OPERATORS.GTE, '<=': OPERATORS.LTE, } VALUE_MAPPERS = { 'null': None } DELIMITER = '__' def _clean_value(self, value): if isinstance(value, list): return [self._clean_value(v) for v in value] else: return self.VALUE_MAPPERS.get(value, value) def _clean_operator(self, operator_slug): return self.OPERATORS_MAPPING.get(operator_slug, operator_slug.lower()) def _parse_to_conditions(self, parsed_result_list, condition_positions, condition, input): def _parse_to_conditions_recursive(term): <|code_end|> , determine the next line of code. You have imports: import re import pyparsing as pp from django.utils.safestring import mark_safe from django.utils.translation import ugettext from .filters import OPERATORS from .utils import LOGICAL_OPERATORS and context (class names, function names, or code) available: # Path: pyston/filters/filters.py # OPERATORS = Enum( # ('GT', 'gt'), # ('LT', 'lt'), # ('EQ', 'eq'), # ('NEQ', 'neq'), # ('LTE', 'lte'), # ('GTE', 'gte'), # ('CONTAINS', 'contains'), # ('ICONTAINS', 'icontains'), # ('RANGE', 'range'), # ('EXACT', 'exact'), # ('IEXACT', 'iexact'), # ('STARTSWITH', 'startswith'), # ('ISTARTSWITH', 'istartswith'), # ('ENDSWITH', 'endswith'), # ('IENDSWITH', 'iendswith'), # ('IN', 'in'), # ('RANGE', 'range'), # ('ALL', 'all'), # ('ISNULL', 'isnull'), # ) # # Path: pyston/filters/utils.py # LOGICAL_OPERATORS = Enum( # 'AND', # 'OR', # 'NOT', # ) . Output only the next line.
if len(term) == 2 and term[0] == LOGICAL_OPERATORS.NOT:
Using the snippet: <|code_start|> class ModelRequestedFieldsManager: parser = None def get_requested_fields(self, resource, request): try: parsed_requested_rfs = self.parser.parse(request) if parsed_requested_rfs is None: return None else: return parsed_requested_rfs <|code_end|> , determine the next line of code. You have imports: from pyston.exception import RestException from .parser import DefaultRequestedFieldsParser and context (class names, function names, or code) available: # Path: pyston/exception.py # class RestException(Exception): # message = None # # def __init__(self, message=None): # super().__init__() # self.message = message or self.message # # @property # def errors(self): # return {'error': self.message} # # Path: pyston/requested_fields/parser.py # class DefaultRequestedFieldsParser: # """ # Default fields parserr. # E.q.: # /api/user?_filter=first_name,last_name,issues(id) # """ # # def parse(self, request): # input = request._rest_context.get('fields') # if input is None: # return None # return RFS.create_from_string(input) . Output only the next line.
except RestException as ex:
Here is a snippet: <|code_start|> class ModelRequestedFieldsManager: parser = None def get_requested_fields(self, resource, request): try: parsed_requested_rfs = self.parser.parse(request) if parsed_requested_rfs is None: return None else: return parsed_requested_rfs except RestException as ex: raise RestException(ex) class DefaultRequestedFieldsManager(ModelRequestedFieldsManager): """ Default requested fields manager. """ <|code_end|> . Write the next line using the current file imports: from pyston.exception import RestException from .parser import DefaultRequestedFieldsParser and context from other files: # Path: pyston/exception.py # class RestException(Exception): # message = None # # def __init__(self, message=None): # super().__init__() # self.message = message or self.message # # @property # def errors(self): # return {'error': self.message} # # Path: pyston/requested_fields/parser.py # class DefaultRequestedFieldsParser: # """ # Default fields parserr. # E.q.: # /api/user?_filter=first_name,last_name,issues(id) # """ # # def parse(self, request): # input = request._rest_context.get('fields') # if input is None: # return None # return RFS.create_from_string(input) , which may include functions, classes, or code. Output only the next line.
parser = DefaultRequestedFieldsParser()
Here is a snippet: <|code_start|> def merge_iterable(a, b): c = list(a) + list(b) return sorted(set(c), key=lambda x: c.index(x)) class RestOptions(Options): model_class = models.Model meta_class_name = 'RestMeta' meta_name = '_rest_meta' attributes = {} def __init__(self, model): super().__init__(model) <|code_end|> . Write the next line using the current file imports: from chamber.patch import Options from django.db import models from django.db.models.fields import Field from django.db.models.fields.related import ForeignKey, ManyToManyField, ForeignObjectRel from pyston.utils.compatibility import get_last_parent_pk_field_name import django.db.models.options as options and context from other files: # Path: pyston/utils/compatibility.py # def get_last_parent_pk_field_name(obj): # for field in obj._meta.fields: # if field.primary_key and (not field.is_relation or not field.auto_created): # return field.name # raise RuntimeError('Last parent field name was not found (cannot happen)') , which may include functions, classes, or code. Output only the next line.
pk_field_name = get_last_parent_pk_field_name(model)
Predict the next line after this snippet: <|code_start|> class DirectSerializationTestCase(TestCase): def test_serialization(self): for i in range(10): User.objects.create(is_superuser=True, email='test{}@test.cz'.format(i)) <|code_end|> using the current file's imports: import json import xml.dom.minidom from decimal import Decimal from uuid import uuid4 from datetime import date, datetime, time, timedelta from collections import OrderedDict from germanium.tools import assert_true, assert_equal from unittest.case import TestCase from app.models import User from pyston.serializer import serialize and any relevant context from other files: # Path: pyston/serializer.py # def serialize(self, serialization_format, **kwargs): # raise NotImplementedError . Output only the next line.
assert_true(isinstance(json.loads((serialize(User.objects.all()))), list))
Given snippet: <|code_start|> FOO_DOMAIN = 'http://foo.pyston.net' BAR_DOMAIN = 'http://bar.pyston.net' class CorsTestCase(PystonTestCase): @override_settings(PYSTON_CORS=False) @data_consumer('get_users_data') def test_with_turned_off_cors_headers_is_not_included(self, number, data): resp = self.options(self.USER_API_URL) <|code_end|> , continue by predicting the next line. Consider current file imports: from six.moves.urllib.parse import urlencode from django.test import TestCase from django.test.utils import override_settings from germanium.test_cases.rest import RestTestCase from germanium.tools.trivials import assert_true, assert_false, assert_equal from germanium.decorators import data_consumer from pyston.resource import (ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_MAX_AGE) from .test_case import PystonTestCase and context: # Path: pyston/resource.py # ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin' # # ACCESS_CONTROL_EXPOSE_HEADERS = 'Access-Control-Expose-Headers' # # ACCESS_CONTROL_ALLOW_CREDENTIALS = 'Access-Control-Allow-Credentials' # # ACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers' # # ACCESS_CONTROL_ALLOW_METHODS = 'Access-Control-Allow-Methods' # # ACCESS_CONTROL_MAX_AGE = 'Access-Control-Max-Age' # # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result which might include code, classes, or functions. Output only the next line.
assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_ORIGIN))
Based on the snippet: <|code_start|> FOO_DOMAIN = 'http://foo.pyston.net' BAR_DOMAIN = 'http://bar.pyston.net' class CorsTestCase(PystonTestCase): @override_settings(PYSTON_CORS=False) @data_consumer('get_users_data') def test_with_turned_off_cors_headers_is_not_included(self, number, data): resp = self.options(self.USER_API_URL) assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_ORIGIN)) <|code_end|> , predict the immediate next line with the help of imports: from six.moves.urllib.parse import urlencode from django.test import TestCase from django.test.utils import override_settings from germanium.test_cases.rest import RestTestCase from germanium.tools.trivials import assert_true, assert_false, assert_equal from germanium.decorators import data_consumer from pyston.resource import (ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_MAX_AGE) from .test_case import PystonTestCase and context (classes, functions, sometimes code) from other files: # Path: pyston/resource.py # ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin' # # ACCESS_CONTROL_EXPOSE_HEADERS = 'Access-Control-Expose-Headers' # # ACCESS_CONTROL_ALLOW_CREDENTIALS = 'Access-Control-Allow-Credentials' # # ACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers' # # ACCESS_CONTROL_ALLOW_METHODS = 'Access-Control-Allow-Methods' # # ACCESS_CONTROL_MAX_AGE = 'Access-Control-Max-Age' # # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result . Output only the next line.
assert_false(resp.has_header(ACCESS_CONTROL_EXPOSE_HEADERS))
Given the code snippet: <|code_start|> FOO_DOMAIN = 'http://foo.pyston.net' BAR_DOMAIN = 'http://bar.pyston.net' class CorsTestCase(PystonTestCase): @override_settings(PYSTON_CORS=False) @data_consumer('get_users_data') def test_with_turned_off_cors_headers_is_not_included(self, number, data): resp = self.options(self.USER_API_URL) assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_ORIGIN)) assert_false(resp.has_header(ACCESS_CONTROL_EXPOSE_HEADERS)) <|code_end|> , generate the next line using the imports in this file: from six.moves.urllib.parse import urlencode from django.test import TestCase from django.test.utils import override_settings from germanium.test_cases.rest import RestTestCase from germanium.tools.trivials import assert_true, assert_false, assert_equal from germanium.decorators import data_consumer from pyston.resource import (ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_MAX_AGE) from .test_case import PystonTestCase and context (functions, classes, or occasionally code) from other files: # Path: pyston/resource.py # ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin' # # ACCESS_CONTROL_EXPOSE_HEADERS = 'Access-Control-Expose-Headers' # # ACCESS_CONTROL_ALLOW_CREDENTIALS = 'Access-Control-Allow-Credentials' # # ACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers' # # ACCESS_CONTROL_ALLOW_METHODS = 'Access-Control-Allow-Methods' # # ACCESS_CONTROL_MAX_AGE = 'Access-Control-Max-Age' # # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result . Output only the next line.
assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_CREDENTIALS))
Based on the snippet: <|code_start|> FOO_DOMAIN = 'http://foo.pyston.net' BAR_DOMAIN = 'http://bar.pyston.net' class CorsTestCase(PystonTestCase): @override_settings(PYSTON_CORS=False) @data_consumer('get_users_data') def test_with_turned_off_cors_headers_is_not_included(self, number, data): resp = self.options(self.USER_API_URL) assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_ORIGIN)) assert_false(resp.has_header(ACCESS_CONTROL_EXPOSE_HEADERS)) assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_CREDENTIALS)) <|code_end|> , predict the immediate next line with the help of imports: from six.moves.urllib.parse import urlencode from django.test import TestCase from django.test.utils import override_settings from germanium.test_cases.rest import RestTestCase from germanium.tools.trivials import assert_true, assert_false, assert_equal from germanium.decorators import data_consumer from pyston.resource import (ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_MAX_AGE) from .test_case import PystonTestCase and context (classes, functions, sometimes code) from other files: # Path: pyston/resource.py # ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin' # # ACCESS_CONTROL_EXPOSE_HEADERS = 'Access-Control-Expose-Headers' # # ACCESS_CONTROL_ALLOW_CREDENTIALS = 'Access-Control-Allow-Credentials' # # ACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers' # # ACCESS_CONTROL_ALLOW_METHODS = 'Access-Control-Allow-Methods' # # ACCESS_CONTROL_MAX_AGE = 'Access-Control-Max-Age' # # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result . Output only the next line.
assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_HEADERS))
Given the code snippet: <|code_start|> FOO_DOMAIN = 'http://foo.pyston.net' BAR_DOMAIN = 'http://bar.pyston.net' class CorsTestCase(PystonTestCase): @override_settings(PYSTON_CORS=False) @data_consumer('get_users_data') def test_with_turned_off_cors_headers_is_not_included(self, number, data): resp = self.options(self.USER_API_URL) assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_ORIGIN)) assert_false(resp.has_header(ACCESS_CONTROL_EXPOSE_HEADERS)) assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_CREDENTIALS)) assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_HEADERS)) <|code_end|> , generate the next line using the imports in this file: from six.moves.urllib.parse import urlencode from django.test import TestCase from django.test.utils import override_settings from germanium.test_cases.rest import RestTestCase from germanium.tools.trivials import assert_true, assert_false, assert_equal from germanium.decorators import data_consumer from pyston.resource import (ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_MAX_AGE) from .test_case import PystonTestCase and context (functions, classes, or occasionally code) from other files: # Path: pyston/resource.py # ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin' # # ACCESS_CONTROL_EXPOSE_HEADERS = 'Access-Control-Expose-Headers' # # ACCESS_CONTROL_ALLOW_CREDENTIALS = 'Access-Control-Allow-Credentials' # # ACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers' # # ACCESS_CONTROL_ALLOW_METHODS = 'Access-Control-Allow-Methods' # # ACCESS_CONTROL_MAX_AGE = 'Access-Control-Max-Age' # # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result . Output only the next line.
assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_METHODS))
Based on the snippet: <|code_start|> FOO_DOMAIN = 'http://foo.pyston.net' BAR_DOMAIN = 'http://bar.pyston.net' class CorsTestCase(PystonTestCase): @override_settings(PYSTON_CORS=False) @data_consumer('get_users_data') def test_with_turned_off_cors_headers_is_not_included(self, number, data): resp = self.options(self.USER_API_URL) assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_ORIGIN)) assert_false(resp.has_header(ACCESS_CONTROL_EXPOSE_HEADERS)) assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_CREDENTIALS)) assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_HEADERS)) assert_false(resp.has_header(ACCESS_CONTROL_ALLOW_METHODS)) <|code_end|> , predict the immediate next line with the help of imports: from six.moves.urllib.parse import urlencode from django.test import TestCase from django.test.utils import override_settings from germanium.test_cases.rest import RestTestCase from germanium.tools.trivials import assert_true, assert_false, assert_equal from germanium.decorators import data_consumer from pyston.resource import (ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_MAX_AGE) from .test_case import PystonTestCase and context (classes, functions, sometimes code) from other files: # Path: pyston/resource.py # ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin' # # ACCESS_CONTROL_EXPOSE_HEADERS = 'Access-Control-Expose-Headers' # # ACCESS_CONTROL_ALLOW_CREDENTIALS = 'Access-Control-Allow-Credentials' # # ACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers' # # ACCESS_CONTROL_ALLOW_METHODS = 'Access-Control-Allow-Methods' # # ACCESS_CONTROL_MAX_AGE = 'Access-Control-Max-Age' # # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result . Output only the next line.
assert_false(resp.has_header(ACCESS_CONTROL_MAX_AGE))
Here is a snippet: <|code_start|> class ExtraResourceTestCase(PystonTestCase): def test_not_supported_message_for_put_post_and_delete(self): resp = self.put(self.EXTRA_API_URL, data={}) assert_http_method_not_allowed(resp) resp = self.post(self.EXTRA_API_URL, data={}) assert_http_method_not_allowed(resp) resp = self.delete(self.EXTRA_API_URL) assert_http_method_not_allowed(resp) def test_should_return_data_for_get(self): resp = self.get(self.EXTRA_API_URL) assert_valid_JSON_response(resp) def test_resource_with_serializable_result(self): <|code_end|> . Write the next line using the current file imports: from germanium.tools.trivials import assert_equal from germanium.tools.http import assert_http_method_not_allowed from germanium.tools.rest import assert_valid_JSON_response from .test_case import PystonTestCase from .factories import UserFactory, IssueFactory and context from other files: # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result # # Path: example/dj/apps/app/tests/factories.py # class UserFactory(factory.django.DjangoModelFactory): # # first_name = factory.Sequence(lambda n: 'John{0}'.format(n)) # last_name = factory.Sequence(lambda n: 'Doe{0}'.format(n)) # email = factory.Sequence(lambda n: 'customer_{0}@example.com'.format(n).lower()) # # class Meta: # model = models.User # # class IssueFactory(factory.django.DjangoModelFactory): # # name = factory.fuzzy.FuzzyText(length=100) # created_by = factory.SubFactory('app.tests.factories.UserFactory') # leader = factory.SubFactory('app.tests.factories.UserFactory') # # class Meta: # model = models.Issue , which may include functions, classes, or code. Output only the next line.
[IssueFactory(solver=UserFactory()) for _ in range(10)]
Given snippet: <|code_start|> class ExtraResourceTestCase(PystonTestCase): def test_not_supported_message_for_put_post_and_delete(self): resp = self.put(self.EXTRA_API_URL, data={}) assert_http_method_not_allowed(resp) resp = self.post(self.EXTRA_API_URL, data={}) assert_http_method_not_allowed(resp) resp = self.delete(self.EXTRA_API_URL) assert_http_method_not_allowed(resp) def test_should_return_data_for_get(self): resp = self.get(self.EXTRA_API_URL) assert_valid_JSON_response(resp) def test_resource_with_serializable_result(self): <|code_end|> , continue by predicting the next line. Consider current file imports: from germanium.tools.trivials import assert_equal from germanium.tools.http import assert_http_method_not_allowed from germanium.tools.rest import assert_valid_JSON_response from .test_case import PystonTestCase from .factories import UserFactory, IssueFactory and context: # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result # # Path: example/dj/apps/app/tests/factories.py # class UserFactory(factory.django.DjangoModelFactory): # # first_name = factory.Sequence(lambda n: 'John{0}'.format(n)) # last_name = factory.Sequence(lambda n: 'Doe{0}'.format(n)) # email = factory.Sequence(lambda n: 'customer_{0}@example.com'.format(n).lower()) # # class Meta: # model = models.User # # class IssueFactory(factory.django.DjangoModelFactory): # # name = factory.fuzzy.FuzzyText(length=100) # created_by = factory.SubFactory('app.tests.factories.UserFactory') # leader = factory.SubFactory('app.tests.factories.UserFactory') # # class Meta: # model = models.Issue which might include code, classes, or functions. Output only the next line.
[IssueFactory(solver=UserFactory()) for _ in range(10)]
Given the following code snippet before the placeholder: <|code_start|> class DynamoCursorBasedPaginator(BasePaginator): def __init__(self, default_base=20, max_base=100): self.default_base = default_base self.max_base = max_base def get_response(self, qs, request): base = self._get_base(request) cursor = self._get_cursor(request) if cursor is not None: qs = qs.set_last_evaluated_key(cursor) qs = qs.set_limit(base) return HeadersResponse( qs, self.get_headers(self.get_next_cursor(qs)) ) def _get_base(self, request): base = request._rest_context.get('base') if not base: return self.default_base elif base.isdigit(): base_int = int(base) if base_int > self.max_base: <|code_end|> , predict the next line using imports from the current file: import base64 import json from django.utils.translation import ugettext from pyston.exception import RestException from pyston.paginator import BasePaginator from pyston.response import HeadersResponse and context including class names, function names, and sometimes code from other files: # Path: pyston/exception.py # class RestException(Exception): # message = None # # def __init__(self, message=None): # super().__init__() # self.message = message or self.message # # @property # def errors(self): # return {'error': self.message} # # Path: pyston/paginator.py # class BasePaginator: # # def get_response(self, qs, request): # raise NotImplementedError # # Path: pyston/response.py # class HeadersResponse: # # fieldset = True # # def __init__(self, result, http_headers=None, code=200): # http_headers = {} if http_headers is None else http_headers # self.result = result # self.http_headers = http_headers # self.status_code = code . Output only the next line.
raise RestException(ugettext('Base must lower or equal to {}').format(self.max_base))
Predict the next line for this snippet: <|code_start|> class DynamoCursorBasedPaginator(BasePaginator): def __init__(self, default_base=20, max_base=100): self.default_base = default_base self.max_base = max_base def get_response(self, qs, request): base = self._get_base(request) cursor = self._get_cursor(request) if cursor is not None: qs = qs.set_last_evaluated_key(cursor) qs = qs.set_limit(base) <|code_end|> with the help of current file imports: import base64 import json from django.utils.translation import ugettext from pyston.exception import RestException from pyston.paginator import BasePaginator from pyston.response import HeadersResponse and context from other files: # Path: pyston/exception.py # class RestException(Exception): # message = None # # def __init__(self, message=None): # super().__init__() # self.message = message or self.message # # @property # def errors(self): # return {'error': self.message} # # Path: pyston/paginator.py # class BasePaginator: # # def get_response(self, qs, request): # raise NotImplementedError # # Path: pyston/response.py # class HeadersResponse: # # fieldset = True # # def __init__(self, result, http_headers=None, code=200): # http_headers = {} if http_headers is None else http_headers # self.result = result # self.http_headers = http_headers # self.status_code = code , which may contain function names, class names, or code. Output only the next line.
return HeadersResponse(
Using the snippet: <|code_start|> return r elif isinstance(data, datetime.date): return data.isoformat() elif isinstance(data, datetime.time): if is_aware(data): raise ValueError("JSON can't represent timezone-aware times.") r = data.isoformat() if data.microsecond: r = r[:12] return r elif isinstance(data, datetime.timedelta): return duration_iso_string(data) elif isinstance(data, (decimal.Decimal, uuid.UUID, Promise)): return str(data) else: return data def str_to_class(class_string): module_name, class_name = class_string.rsplit('.', 1) # load the module, will raise ImportError if module cannot be loaded m = __import__(module_name, globals(), locals(), str(class_name)) # get the class, will raise AttributeError if class cannot be found c = getattr(m, class_name) return c def get_field_or_none(model, field_name): try: return model._meta.get_field(field_name) <|code_end|> , determine the next line of code. You have imports: import types import sys import datetime import decimal import uuid from io import BytesIO from django.utils.encoding import force_bytes from django.conf import settings from django.utils.duration import duration_iso_string from django.utils.functional import Promise from django.utils.timezone import is_aware from chamber.utils import get_class_method from .compatibility import FieldDoesNotExist from pyston.serializer import LAZY_SERIALIZERS and context (class names, function names, or code) available: # Path: pyston/utils/compatibility.py # def get_field_or_none(model, field_name): # def get_all_related_objects_from_model(model): # def get_concrete_field(model, field_name): # def is_reverse_many_to_one(model, field_name): # def is_reverse_one_to_one(model, field_name): # def is_reverse_many_to_many(model, field_name): # def is_many_to_one(model, field_name): # def is_one_to_one(model, field_name): # def is_many_to_many(model, field_name): # def is_relation(model, field_name): # def get_model_from_relation(model, field_name): # def get_model_from_relation_or_none(model, field_name): # def get_reverse_field_name(model, field_name): # def get_last_parent_pk_field_name(obj): # def delete_cached_value(instance, field_name): . Output only the next line.
except FieldDoesNotExist:
Here is a snippet: <|code_start|> if header: for col, head in enumerate(header): ws.write(row, col, force_text(head)) row += 1 for data_row in data: for col, val in enumerate(data_row): if isinstance(val, datetime): ws.write(row, col, val.replace(tzinfo=None), datetime_format) elif isinstance(val, date): ws.write(row, col, val, date_format) elif isinstance(val, (Decimal, float)): ws.write(row, col, val, decimal_format) elif isinstance(val, str): val = self._prepare_value(val) ws.write(row, col, val) else: ws.write(row, col, val) row += 1 wb.close() if pisa: class PdfGenerator: encoding = 'utf-8' def generate(self, header, data, output_stream): def fetch_resources(uri, rel): urls = { <|code_end|> . Write the next line using the current file imports: import os import csv import codecs import xlsxwriter from datetime import datetime, date from decimal import Decimal from django.conf import settings as django_settings from django.utils.encoding import force_text from django.template.loader import get_template from xhtml2pdf import pisa from pyston.conf import settings and context from other files: # Path: pyston/conf.py # CONVERTERS = ( # 'pyston.converters.JsonConverter', # 'pyston.converters.XmlConverter', # 'pyston.converters.CsvConverter', # 'pyston.converters.TxtConverter', # ) # DEFAULT_FILENAMES = ( # (('pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv'), 'document'), # (('jpg', 'jpeg', 'png', 'gif', 'tiff', 'bmp', 'svg'), 'image'), # ) # DEFAULT_FILENAME = 'attachment' # DEFAULTS = { # 'CONVERTERS': CONVERTERS, # 'IGNORE_DUPE_MODELS': False, # 'CORS': False, # 'CORS_WHITELIST': (), # 'CORS_MAX_AGE': 60 * 30, # 'CORS_ALLOW_CREDENTIALS': True, # 'CORS_ALLOWED_HEADERS': ('X-Base', 'X-Offset', 'X-Fields', 'Origin', 'Content-Type', 'Accept'), # 'CORS_ALLOWED_EXPOSED_HEADERS': ('X-Total', 'X-Serialization-Format-Options', 'X-Fields-Options'), # 'JSON_CONVERTER_OPTIONS': { # 'indent': 4 # }, # 'PDF_EXPORT_TEMPLATE': 'default_pdf_table.html', # 'FILE_SIZE_LIMIT': 5000000, # 'AUTO_RELATED_REVERSE_FIELDS': True, # 'AUTO_RELATED_DIRECT_FIELDS': True, # 'PARTIAL_PUT_UPDATE': False, # 'PARTIAL_RELATED_UPDATE': False, # 'ERRORS_RESPONSE_CLASS': 'pyston.response.RestErrorsResponse', # 'ERROR_RESPONSE_CLASS': 'pyston.response.RestErrorResponse', # 'AUTO_REGISTER_RESOURCE': True, # 'ALLOW_TAGS': False, # 'DEFAULT_FILENAMES': DEFAULT_FILENAMES, # 'DEFAULT_FILENAME': DEFAULT_FILENAME, # 'NONE_HUMANIZED_VALUE': '--', # } # class Settings: # def __getattr__(self, attr): , which may include functions, classes, or code. Output only the next line.
django_settings.MEDIA_ROOT: settings.MEDIA_URL,
Using the snippet: <|code_start|> class OrderTestCase(PystonTestCase): def test_order_by_decorator(self): [IssueFactory(description=str(i)) for i in range(10)] data = self.deserialize(self.get(build_url(self.ISSUE_API_URL, order='short_description'))) assert_equal([v['short_description'] for v in data], [str(i) for i in range(10)]) data = self.deserialize(self.get(build_url(self.ISSUE_API_URL, order='-short_description'))) assert_equal([v['short_description'] for v in data], [str(i) for i in range(10)][::-1]) assert_valid_JSON_response(self.get(build_url(self.USER_API_URL, order='solving_issue__short_description'))) assert_valid_JSON_response(self.get(build_url(self.USER_API_URL, order='-solving_issue__short_description'))) assert_http_bad_request(self.get(build_url(self.ISSUE_API_URL, order='description'))) def test_override_extra_order_fields(self): assert_http_bad_request(self.get(build_url(self.USER_API_URL, order='created_at'))) assert_valid_JSON_response( self.get(build_url(self.USER_API_URL, order='email,-solving_issue__short_description')) ) def test_issue_can_order_only_with_readable_fields_and_extra_field(self): assert_valid_JSON_response(self.get(build_url(self.ISSUE_API_URL, order='solver__created_at'))) assert_valid_JSON_response(self.get(build_url(self.ISSUE_API_URL, order='created_at'))) assert_http_bad_request(self.get(build_url(self.ISSUE_API_URL, order='solver__manual_created_date'))) def test_extra_sorter(self): <|code_end|> , determine the next line of code. You have imports: from germanium.tools.trivials import assert_equal from germanium.tools.http import assert_http_bad_request, build_url from germanium.tools.rest import assert_valid_JSON_response from .factories import IssueFactory, UserFactory from .test_case import PystonTestCase and context (class names, function names, or code) available: # Path: example/dj/apps/app/tests/factories.py # class IssueFactory(factory.django.DjangoModelFactory): # # name = factory.fuzzy.FuzzyText(length=100) # created_by = factory.SubFactory('app.tests.factories.UserFactory') # leader = factory.SubFactory('app.tests.factories.UserFactory') # # class Meta: # model = models.Issue # # class UserFactory(factory.django.DjangoModelFactory): # # first_name = factory.Sequence(lambda n: 'John{0}'.format(n)) # last_name = factory.Sequence(lambda n: 'Doe{0}'.format(n)) # email = factory.Sequence(lambda n: 'customer_{0}@example.com'.format(n).lower()) # # class Meta: # model = models.User # # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result . Output only the next line.
user1 = UserFactory()
Using the snippet: <|code_start|> class UserIDFilter(BaseDynamoFilter): allowed_operators = (OPERATORS.EQ,) def get_filter_term(self, value, operator_slug, request): return {'user_id__startswith': value} <|code_end|> , determine the next line of code. You have imports: from pyston.filters.filters import OPERATORS from pyston.contrib.dynamo.resource import BaseDynamoResource from pyston.contrib.dynamo.filter import BaseDynamoFilter from .models import Comment and context (class names, function names, or code) available: # Path: pyston/filters/filters.py # OPERATORS = Enum( # ('GT', 'gt'), # ('LT', 'lt'), # ('EQ', 'eq'), # ('NEQ', 'neq'), # ('LTE', 'lte'), # ('GTE', 'gte'), # ('CONTAINS', 'contains'), # ('ICONTAINS', 'icontains'), # ('RANGE', 'range'), # ('EXACT', 'exact'), # ('IEXACT', 'iexact'), # ('STARTSWITH', 'startswith'), # ('ISTARTSWITH', 'istartswith'), # ('ENDSWITH', 'endswith'), # ('IENDSWITH', 'iendswith'), # ('IN', 'in'), # ('RANGE', 'range'), # ('ALL', 'all'), # ('ISNULL', 'isnull'), # ) # # Path: pyston/contrib/dynamo/resource.py # class BaseDynamoResource(BaseModelResource): # # register = True # abstract = True # # allowed_methods = ('get', 'head', 'options') # paginator = DynamoCursorBasedPaginator() # serializer = DynamoResourceSerializer # order_manager = DynamoOrderManager() # filter_manager = DynamoFilterManager() # # range_key = None # # def _get_hash_key(self): # raise NotImplementedError # # def _get_obj_or_none(self, pk=None): # if not pk: # return None # try: # return self.model.get(self._get_hash_key(), pk) # except self.model.DoesNotExist: # return None # # def _get_queryset(self): # return self.model.objects.set_hash_key(self._get_hash_key()) # # def get_range_key(self): # return self.range_key # # Path: pyston/contrib/dynamo/filter.py # class BaseDynamoFilter(Filter): # # allowed_operators = None # # def get_allowed_operators(self): # return self.allowed_operators # # def clean_value(self, value, operator_slug, request): # return value # # def get_q(self, value, operator_slug, request): # if operator_slug not in self.get_allowed_operators(): # raise OperatorFilterError # else: # return self.get_filter_term(self.clean_value(value, operator_slug, request), operator_slug, request) # # def get_filter_term(self, value, operator_slug, request): # raise NotImplementedError # # Path: example/dj/apps/app/dynamo/models.py # class Comment(DynamoModel): # # issue_id = UnicodeAttribute(hash_key=True) # user_id = UnicodeAttribute(range_key=True) # content = UnicodeAttribute() # is_public = BooleanAttribute() # priority = NumberAttribute() # # def __str__(self): # return self.id # # class Meta: # table_name = 'comment' . Output only the next line.
class CommentDynamoResource(BaseDynamoResource):
Here is a snippet: <|code_start|> class UserIDFilter(BaseDynamoFilter): allowed_operators = (OPERATORS.EQ,) def get_filter_term(self, value, operator_slug, request): return {'user_id__startswith': value} class CommentDynamoResource(BaseDynamoResource): <|code_end|> . Write the next line using the current file imports: from pyston.filters.filters import OPERATORS from pyston.contrib.dynamo.resource import BaseDynamoResource from pyston.contrib.dynamo.filter import BaseDynamoFilter from .models import Comment and context from other files: # Path: pyston/filters/filters.py # OPERATORS = Enum( # ('GT', 'gt'), # ('LT', 'lt'), # ('EQ', 'eq'), # ('NEQ', 'neq'), # ('LTE', 'lte'), # ('GTE', 'gte'), # ('CONTAINS', 'contains'), # ('ICONTAINS', 'icontains'), # ('RANGE', 'range'), # ('EXACT', 'exact'), # ('IEXACT', 'iexact'), # ('STARTSWITH', 'startswith'), # ('ISTARTSWITH', 'istartswith'), # ('ENDSWITH', 'endswith'), # ('IENDSWITH', 'iendswith'), # ('IN', 'in'), # ('RANGE', 'range'), # ('ALL', 'all'), # ('ISNULL', 'isnull'), # ) # # Path: pyston/contrib/dynamo/resource.py # class BaseDynamoResource(BaseModelResource): # # register = True # abstract = True # # allowed_methods = ('get', 'head', 'options') # paginator = DynamoCursorBasedPaginator() # serializer = DynamoResourceSerializer # order_manager = DynamoOrderManager() # filter_manager = DynamoFilterManager() # # range_key = None # # def _get_hash_key(self): # raise NotImplementedError # # def _get_obj_or_none(self, pk=None): # if not pk: # return None # try: # return self.model.get(self._get_hash_key(), pk) # except self.model.DoesNotExist: # return None # # def _get_queryset(self): # return self.model.objects.set_hash_key(self._get_hash_key()) # # def get_range_key(self): # return self.range_key # # Path: pyston/contrib/dynamo/filter.py # class BaseDynamoFilter(Filter): # # allowed_operators = None # # def get_allowed_operators(self): # return self.allowed_operators # # def clean_value(self, value, operator_slug, request): # return value # # def get_q(self, value, operator_slug, request): # if operator_slug not in self.get_allowed_operators(): # raise OperatorFilterError # else: # return self.get_filter_term(self.clean_value(value, operator_slug, request), operator_slug, request) # # def get_filter_term(self, value, operator_slug, request): # raise NotImplementedError # # Path: example/dj/apps/app/dynamo/models.py # class Comment(DynamoModel): # # issue_id = UnicodeAttribute(hash_key=True) # user_id = UnicodeAttribute(range_key=True) # content = UnicodeAttribute() # is_public = BooleanAttribute() # priority = NumberAttribute() # # def __str__(self): # return self.id # # class Meta: # table_name = 'comment' , which may include functions, classes, or code. Output only the next line.
model = Comment
Here is a snippet: <|code_start|> assert_equal(len(self.deserialize(resp)), 5) resp = self.get( build_url( self.ISSUE_API_URL, filter='(created_at__day = "{}" AND created_at__year = "{}") OR (created_at > "{}")'.format( now.day + 1, now.year, now.isoformat() ) ) ) assert_equal(len(self.deserialize(resp)), 5) def test_filter_issue_by_datetime_querystring_filter_parser(self): now = datetime.now() [IssueFactory() for _ in range(5)] resp = self.get( build_url( self.ISSUE_API_URL, created_at__day=now.day, created_at__year=now.year ) ) assert_equal(len(self.deserialize(resp)), 5) resp = self.get( build_url( self.ISSUE_API_URL, created_at__day=now.day + 1, created_at__year=now.year ) ) assert_equal(len(self.deserialize(resp)), 0) def test_boolean_filter(self): <|code_end|> . Write the next line using the current file imports: from datetime import datetime from germanium.tools.trivials import assert_equal from germanium.tools.http import assert_http_bad_request, build_url from germanium.tools.rest import assert_valid_JSON_response from .factories import UserFactory, IssueFactory from .test_case import PystonTestCase and context from other files: # Path: example/dj/apps/app/tests/factories.py # class UserFactory(factory.django.DjangoModelFactory): # # first_name = factory.Sequence(lambda n: 'John{0}'.format(n)) # last_name = factory.Sequence(lambda n: 'Doe{0}'.format(n)) # email = factory.Sequence(lambda n: 'customer_{0}@example.com'.format(n).lower()) # # class Meta: # model = models.User # # class IssueFactory(factory.django.DjangoModelFactory): # # name = factory.fuzzy.FuzzyText(length=100) # created_by = factory.SubFactory('app.tests.factories.UserFactory') # leader = factory.SubFactory('app.tests.factories.UserFactory') # # class Meta: # model = models.Issue # # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result , which may include functions, classes, or code. Output only the next line.
user = UserFactory(is_superuser=False)
Continue the code snippet: <|code_start|> class FilterTestCase(PystonTestCase): def test_override_extra_filter_fields(self): assert_http_bad_request(self.get(build_url(self.USER_API_URL, filter='created_at__gt="1.1.1980"'))) assert_valid_JSON_response( self.get(build_url(self.USER_API_URL, filter='email contains "test@test.cz"')) ) def test_invalid_filter_format(self): assert_http_bad_request(self.get(build_url(self.USER_API_URL, filter='email="test@test.cz" AND'))) assert_http_bad_request(self.get(build_url(self.USER_API_URL, filter='invalid'))) assert_http_bad_request(self.get(build_url(self.USER_API_URL, filter='email="test@test.cz" AND OR email="test@test.cz"'))) def test_issue_can_filter_only_with_readable_fields_and_extra_field(self): assert_valid_JSON_response( self.get(build_url(self.ISSUE_API_URL, filter='solver__created_at="1.1.2017"')) ) assert_valid_JSON_response(self.get(build_url(self.ISSUE_API_URL, filter='created_at>"1.1.2017"'))) assert_http_bad_request( self.get(build_url(self.ISSUE_API_URL, filter='solver__manual_created_date>"1.1.2017"')) ) def test_filter_issue_by_datetime(self): now = datetime.now() <|code_end|> . Use current file imports: from datetime import datetime from germanium.tools.trivials import assert_equal from germanium.tools.http import assert_http_bad_request, build_url from germanium.tools.rest import assert_valid_JSON_response from .factories import UserFactory, IssueFactory from .test_case import PystonTestCase and context (classes, functions, or code) from other files: # Path: example/dj/apps/app/tests/factories.py # class UserFactory(factory.django.DjangoModelFactory): # # first_name = factory.Sequence(lambda n: 'John{0}'.format(n)) # last_name = factory.Sequence(lambda n: 'Doe{0}'.format(n)) # email = factory.Sequence(lambda n: 'customer_{0}@example.com'.format(n).lower()) # # class Meta: # model = models.User # # class IssueFactory(factory.django.DjangoModelFactory): # # name = factory.fuzzy.FuzzyText(length=100) # created_by = factory.SubFactory('app.tests.factories.UserFactory') # leader = factory.SubFactory('app.tests.factories.UserFactory') # # class Meta: # model = models.Issue # # Path: example/dj/apps/app/tests/test_case.py # class PystonTestCase(RestTestCase): # # USER_API_URL = '/api/user/' # USER_WITH_FORM_API_URL = '/api/user-form/' # ISSUE_API_URL = '/api/issue/' # ISSUE_WITH_FORM_API_URL = '/api/issue-form/' # EXTRA_API_URL = '/api/extra/' # COUNT_ISSUES_PER_USER = '/api/count-issues-per-user/' # COUNT_WATCHERS_PER_ISSUE = '/api/count-watchers-per-issue/' # TEST_CC_API_URL = '/api/test-cc/' # # user_id = 0 # issue_id = 0 # # DATA_AMOUNT = 10 # # def get_pk(self, resp): # return self.deserialize(resp).get('id') # # def get_pk_list(self, resp, only_pks=None): # return [obj.get('id') for obj in self.deserialize(resp) if not only_pks or obj.get('id') in only_pks] # # def get_user_data(self, prefix='', **kwargs): # result = {'email': '%suser_%s@test.cz' % (prefix, self.user_id)} # self.user_id += 1 # result.update(kwargs) # return result # # def get_issue_data(self, prefix='', **kwargs): # result = {'name': 'Issue %s' % self.issue_id, 'created_by': self.get_user_data(prefix), # 'leader': self.get_user_data(prefix)} # self.issue_id += 1 # result.update(kwargs) # return result # # def get_users_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # if flat: # result.append(self.get_user_data(prefix)) # else: # result.append((i, self.get_user_data(prefix))) # return result # # def get_issues_data(self, prefix='', flat=False): # result = [] # for i in range(self.DATA_AMOUNT): # result.append((i, self.get_issue_data(prefix))) # return result # # def get_issues_and_users_data(self, prefix=''): # result = [] # for i in range(self.DATA_AMOUNT): # issue_data = self.get_issue_data(prefix) # user_data = issue_data['created_by'] # del issue_data['created_by'] # result.append((i, issue_data, user_data)) # return result . Output only the next line.
[IssueFactory() for _ in range(5)]
Given the code snippet: <|code_start|> ) class WatchedIssuesCountMethodFilter(IntegerFilterMixin, SimpleMethodEqualFilter): def get_filter_term(self, value, operator, request): return { 'pk__in': User.objects.annotate( watched_issues_count=Count('watched_issues') ).filter(watched_issues_count=value).values('pk') } class WatchedIssuesCountSorter(ExtraDjangoSorter): def update_queryset(self, qs): return qs.annotate(**{self._get_order_string(): Count('watched_issues')}) class User(models.Model): created_at = models.DateTimeField(verbose_name=_('created at'), null=False, blank=False, auto_now_add=True) email = models.EmailField(verbose_name=_('email'), null=False, blank=False, unique=True, filter=OnlyContainsStringFieldFilter) contract = models.FileField(_('file'), null=True, blank=True, upload_to='documents/') is_superuser = models.BooleanField(_('is superuser'), default=True) first_name = models.CharField(_('first name'), null=True, blank=True, max_length=100) last_name = models.CharField(_('last name'), null=True, blank=True, max_length=100) manual_created_date = models.DateTimeField(verbose_name=_('manual created date'), null=True, blank=True) <|code_end|> , generate the next line using the imports in this file: from django.db import models from django.db.models import Count from django.utils.translation import ugettext_lazy as _ from pyston.utils.decorators import order_by, filter_class, filter_by, allow_tags, sorter_class from pyston.filters.filters import OPERATORS, IntegerFilterMixin from pyston.filters.django_filters import CONTAINS, StringFieldFilter, SimpleMethodEqualFilter from pyston.order.django_sorters import ExtraDjangoSorter and context (functions, classes, or occasionally code) from other files: # Path: pyston/utils/decorators.py # def order_by(field_name): # """Sets 'field name' (this is used for grid ordering)""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.order_by = field_name # return func # return decorator # # def filter_class(filter_class): # """Sets 'filter' class (this attribute is used inside grid and rest).""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.filter = filter_class # return func # return decorator # # def filter_by(field_name): # """Sets 'field name' (this is used for grid filtering)""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.filter_by = field_name # return func # return decorator # # def allow_tags(func): # """Allows HTML tags to be returned from resource without escaping""" # if isinstance(func, property): # func = func.fget # func.allow_tags = True # return func # # def sorter_class(sorter_class): # """Sets 'sorter' class (this attribute is used inside grid and rest).""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.sorter = sorter_class # return func # return decorator # # Path: pyston/filters/filters.py # OPERATORS = Enum( # ('GT', 'gt'), # ('LT', 'lt'), # ('EQ', 'eq'), # ('NEQ', 'neq'), # ('LTE', 'lte'), # ('GTE', 'gte'), # ('CONTAINS', 'contains'), # ('ICONTAINS', 'icontains'), # ('RANGE', 'range'), # ('EXACT', 'exact'), # ('IEXACT', 'iexact'), # ('STARTSWITH', 'startswith'), # ('ISTARTSWITH', 'istartswith'), # ('ENDSWITH', 'endswith'), # ('IENDSWITH', 'iendswith'), # ('IN', 'in'), # ('RANGE', 'range'), # ('ALL', 'all'), # ('ISNULL', 'isnull'), # ) # # class IntegerFilterMixin: # """ # Helper that contains cleaner for integer input values. # """ # # def clean_value(self, value, operator_slug, request): # if value is None: # return value # try: # return int(value) # except (ValueError, TypeError): # raise FilterValueError(ugettext('Value must be integer')) # # Path: pyston/filters/django_filters.py # CONTAINS = SimpleOperator('contains') # # class StringFieldFilter(OperatorsModelFieldFilter): # # operators = ( # (OPERATORS.ICONTAINS, ICONTAINS), # (OPERATORS.CONTAINS, CONTAINS), # (OPERATORS.EXACT, EXACT), # (OPERATORS.IEXACT, IEXACT), # (OPERATORS.STARTSWITH, STARTSWITH), # (OPERATORS.ISTARTSWITH, ISTARTSWITH), # (OPERATORS.ENDSWITH, ENDSWITH), # (OPERATORS.IENDSWITH, IENDSWITH), # (OPERATORS.EQ, EQ), # (OPERATORS.NEQ, NEQ), # (OPERATORS.LT, LT), # (OPERATORS.GT, GT), # (OPERATORS.LTE, LTE), # (OPERATORS.GTE, GTE), # (OPERATORS.IN, IN), # ) # # class SimpleMethodEqualFilter(SimpleEqualFilterMixin, MethodFilter): # """ # Combination of simple equal filter and method filter used for custom method filters. # """ # pass # # Path: pyston/order/django_sorters.py # class ExtraDjangoSorter(DjangoSorter): # """ # Special type of sorter that updates queryset using annotate or extra queryset method. # For this purpose must be implement updated_queryset method which returns queryset with new column # that is used for ordering. # """ # # def _get_order_string(self): # return LOOKUP_SEP.join(chain(('extra_order',), self.identifiers)) # # def update_queryset(self, qs): # raise NotImplementedError . Output only the next line.
@filter_class(WatchedIssuesCountMethodFilter)
Based on the snippet: <|code_start|> class WatchedIssuesCountMethodFilter(IntegerFilterMixin, SimpleMethodEqualFilter): def get_filter_term(self, value, operator, request): return { 'pk__in': User.objects.annotate( watched_issues_count=Count('watched_issues') ).filter(watched_issues_count=value).values('pk') } class WatchedIssuesCountSorter(ExtraDjangoSorter): def update_queryset(self, qs): return qs.annotate(**{self._get_order_string(): Count('watched_issues')}) class User(models.Model): created_at = models.DateTimeField(verbose_name=_('created at'), null=False, blank=False, auto_now_add=True) email = models.EmailField(verbose_name=_('email'), null=False, blank=False, unique=True, filter=OnlyContainsStringFieldFilter) contract = models.FileField(_('file'), null=True, blank=True, upload_to='documents/') is_superuser = models.BooleanField(_('is superuser'), default=True) first_name = models.CharField(_('first name'), null=True, blank=True, max_length=100) last_name = models.CharField(_('last name'), null=True, blank=True, max_length=100) manual_created_date = models.DateTimeField(verbose_name=_('manual created date'), null=True, blank=True) @filter_class(WatchedIssuesCountMethodFilter) <|code_end|> , predict the immediate next line with the help of imports: from django.db import models from django.db.models import Count from django.utils.translation import ugettext_lazy as _ from pyston.utils.decorators import order_by, filter_class, filter_by, allow_tags, sorter_class from pyston.filters.filters import OPERATORS, IntegerFilterMixin from pyston.filters.django_filters import CONTAINS, StringFieldFilter, SimpleMethodEqualFilter from pyston.order.django_sorters import ExtraDjangoSorter and context (classes, functions, sometimes code) from other files: # Path: pyston/utils/decorators.py # def order_by(field_name): # """Sets 'field name' (this is used for grid ordering)""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.order_by = field_name # return func # return decorator # # def filter_class(filter_class): # """Sets 'filter' class (this attribute is used inside grid and rest).""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.filter = filter_class # return func # return decorator # # def filter_by(field_name): # """Sets 'field name' (this is used for grid filtering)""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.filter_by = field_name # return func # return decorator # # def allow_tags(func): # """Allows HTML tags to be returned from resource without escaping""" # if isinstance(func, property): # func = func.fget # func.allow_tags = True # return func # # def sorter_class(sorter_class): # """Sets 'sorter' class (this attribute is used inside grid and rest).""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.sorter = sorter_class # return func # return decorator # # Path: pyston/filters/filters.py # OPERATORS = Enum( # ('GT', 'gt'), # ('LT', 'lt'), # ('EQ', 'eq'), # ('NEQ', 'neq'), # ('LTE', 'lte'), # ('GTE', 'gte'), # ('CONTAINS', 'contains'), # ('ICONTAINS', 'icontains'), # ('RANGE', 'range'), # ('EXACT', 'exact'), # ('IEXACT', 'iexact'), # ('STARTSWITH', 'startswith'), # ('ISTARTSWITH', 'istartswith'), # ('ENDSWITH', 'endswith'), # ('IENDSWITH', 'iendswith'), # ('IN', 'in'), # ('RANGE', 'range'), # ('ALL', 'all'), # ('ISNULL', 'isnull'), # ) # # class IntegerFilterMixin: # """ # Helper that contains cleaner for integer input values. # """ # # def clean_value(self, value, operator_slug, request): # if value is None: # return value # try: # return int(value) # except (ValueError, TypeError): # raise FilterValueError(ugettext('Value must be integer')) # # Path: pyston/filters/django_filters.py # CONTAINS = SimpleOperator('contains') # # class StringFieldFilter(OperatorsModelFieldFilter): # # operators = ( # (OPERATORS.ICONTAINS, ICONTAINS), # (OPERATORS.CONTAINS, CONTAINS), # (OPERATORS.EXACT, EXACT), # (OPERATORS.IEXACT, IEXACT), # (OPERATORS.STARTSWITH, STARTSWITH), # (OPERATORS.ISTARTSWITH, ISTARTSWITH), # (OPERATORS.ENDSWITH, ENDSWITH), # (OPERATORS.IENDSWITH, IENDSWITH), # (OPERATORS.EQ, EQ), # (OPERATORS.NEQ, NEQ), # (OPERATORS.LT, LT), # (OPERATORS.GT, GT), # (OPERATORS.LTE, LTE), # (OPERATORS.GTE, GTE), # (OPERATORS.IN, IN), # ) # # class SimpleMethodEqualFilter(SimpleEqualFilterMixin, MethodFilter): # """ # Combination of simple equal filter and method filter used for custom method filters. # """ # pass # # Path: pyston/order/django_sorters.py # class ExtraDjangoSorter(DjangoSorter): # """ # Special type of sorter that updates queryset using annotate or extra queryset method. # For this purpose must be implement updated_queryset method which returns queryset with new column # that is used for ordering. # """ # # def _get_order_string(self): # return LOOKUP_SEP.join(chain(('extra_order',), self.identifiers)) # # def update_queryset(self, qs): # raise NotImplementedError . Output only the next line.
@sorter_class(WatchedIssuesCountSorter)
Predict the next line for this snippet: <|code_start|> class OnlyContainsStringFieldFilter(StringFieldFilter): operators = ( (OPERATORS.CONTAINS, CONTAINS), ) <|code_end|> with the help of current file imports: from django.db import models from django.db.models import Count from django.utils.translation import ugettext_lazy as _ from pyston.utils.decorators import order_by, filter_class, filter_by, allow_tags, sorter_class from pyston.filters.filters import OPERATORS, IntegerFilterMixin from pyston.filters.django_filters import CONTAINS, StringFieldFilter, SimpleMethodEqualFilter from pyston.order.django_sorters import ExtraDjangoSorter and context from other files: # Path: pyston/utils/decorators.py # def order_by(field_name): # """Sets 'field name' (this is used for grid ordering)""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.order_by = field_name # return func # return decorator # # def filter_class(filter_class): # """Sets 'filter' class (this attribute is used inside grid and rest).""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.filter = filter_class # return func # return decorator # # def filter_by(field_name): # """Sets 'field name' (this is used for grid filtering)""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.filter_by = field_name # return func # return decorator # # def allow_tags(func): # """Allows HTML tags to be returned from resource without escaping""" # if isinstance(func, property): # func = func.fget # func.allow_tags = True # return func # # def sorter_class(sorter_class): # """Sets 'sorter' class (this attribute is used inside grid and rest).""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.sorter = sorter_class # return func # return decorator # # Path: pyston/filters/filters.py # OPERATORS = Enum( # ('GT', 'gt'), # ('LT', 'lt'), # ('EQ', 'eq'), # ('NEQ', 'neq'), # ('LTE', 'lte'), # ('GTE', 'gte'), # ('CONTAINS', 'contains'), # ('ICONTAINS', 'icontains'), # ('RANGE', 'range'), # ('EXACT', 'exact'), # ('IEXACT', 'iexact'), # ('STARTSWITH', 'startswith'), # ('ISTARTSWITH', 'istartswith'), # ('ENDSWITH', 'endswith'), # ('IENDSWITH', 'iendswith'), # ('IN', 'in'), # ('RANGE', 'range'), # ('ALL', 'all'), # ('ISNULL', 'isnull'), # ) # # class IntegerFilterMixin: # """ # Helper that contains cleaner for integer input values. # """ # # def clean_value(self, value, operator_slug, request): # if value is None: # return value # try: # return int(value) # except (ValueError, TypeError): # raise FilterValueError(ugettext('Value must be integer')) # # Path: pyston/filters/django_filters.py # CONTAINS = SimpleOperator('contains') # # class StringFieldFilter(OperatorsModelFieldFilter): # # operators = ( # (OPERATORS.ICONTAINS, ICONTAINS), # (OPERATORS.CONTAINS, CONTAINS), # (OPERATORS.EXACT, EXACT), # (OPERATORS.IEXACT, IEXACT), # (OPERATORS.STARTSWITH, STARTSWITH), # (OPERATORS.ISTARTSWITH, ISTARTSWITH), # (OPERATORS.ENDSWITH, ENDSWITH), # (OPERATORS.IENDSWITH, IENDSWITH), # (OPERATORS.EQ, EQ), # (OPERATORS.NEQ, NEQ), # (OPERATORS.LT, LT), # (OPERATORS.GT, GT), # (OPERATORS.LTE, LTE), # (OPERATORS.GTE, GTE), # (OPERATORS.IN, IN), # ) # # class SimpleMethodEqualFilter(SimpleEqualFilterMixin, MethodFilter): # """ # Combination of simple equal filter and method filter used for custom method filters. # """ # pass # # Path: pyston/order/django_sorters.py # class ExtraDjangoSorter(DjangoSorter): # """ # Special type of sorter that updates queryset using annotate or extra queryset method. # For this purpose must be implement updated_queryset method which returns queryset with new column # that is used for ordering. # """ # # def _get_order_string(self): # return LOOKUP_SEP.join(chain(('extra_order',), self.identifiers)) # # def update_queryset(self, qs): # raise NotImplementedError , which may contain function names, class names, or code. Output only the next line.
class WatchedIssuesCountMethodFilter(IntegerFilterMixin, SimpleMethodEqualFilter):
Based on the snippet: <|code_start|> class OnlyContainsStringFieldFilter(StringFieldFilter): operators = ( (OPERATORS.CONTAINS, CONTAINS), ) <|code_end|> , predict the immediate next line with the help of imports: from django.db import models from django.db.models import Count from django.utils.translation import ugettext_lazy as _ from pyston.utils.decorators import order_by, filter_class, filter_by, allow_tags, sorter_class from pyston.filters.filters import OPERATORS, IntegerFilterMixin from pyston.filters.django_filters import CONTAINS, StringFieldFilter, SimpleMethodEqualFilter from pyston.order.django_sorters import ExtraDjangoSorter and context (classes, functions, sometimes code) from other files: # Path: pyston/utils/decorators.py # def order_by(field_name): # """Sets 'field name' (this is used for grid ordering)""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.order_by = field_name # return func # return decorator # # def filter_class(filter_class): # """Sets 'filter' class (this attribute is used inside grid and rest).""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.filter = filter_class # return func # return decorator # # def filter_by(field_name): # """Sets 'field name' (this is used for grid filtering)""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.filter_by = field_name # return func # return decorator # # def allow_tags(func): # """Allows HTML tags to be returned from resource without escaping""" # if isinstance(func, property): # func = func.fget # func.allow_tags = True # return func # # def sorter_class(sorter_class): # """Sets 'sorter' class (this attribute is used inside grid and rest).""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.sorter = sorter_class # return func # return decorator # # Path: pyston/filters/filters.py # OPERATORS = Enum( # ('GT', 'gt'), # ('LT', 'lt'), # ('EQ', 'eq'), # ('NEQ', 'neq'), # ('LTE', 'lte'), # ('GTE', 'gte'), # ('CONTAINS', 'contains'), # ('ICONTAINS', 'icontains'), # ('RANGE', 'range'), # ('EXACT', 'exact'), # ('IEXACT', 'iexact'), # ('STARTSWITH', 'startswith'), # ('ISTARTSWITH', 'istartswith'), # ('ENDSWITH', 'endswith'), # ('IENDSWITH', 'iendswith'), # ('IN', 'in'), # ('RANGE', 'range'), # ('ALL', 'all'), # ('ISNULL', 'isnull'), # ) # # class IntegerFilterMixin: # """ # Helper that contains cleaner for integer input values. # """ # # def clean_value(self, value, operator_slug, request): # if value is None: # return value # try: # return int(value) # except (ValueError, TypeError): # raise FilterValueError(ugettext('Value must be integer')) # # Path: pyston/filters/django_filters.py # CONTAINS = SimpleOperator('contains') # # class StringFieldFilter(OperatorsModelFieldFilter): # # operators = ( # (OPERATORS.ICONTAINS, ICONTAINS), # (OPERATORS.CONTAINS, CONTAINS), # (OPERATORS.EXACT, EXACT), # (OPERATORS.IEXACT, IEXACT), # (OPERATORS.STARTSWITH, STARTSWITH), # (OPERATORS.ISTARTSWITH, ISTARTSWITH), # (OPERATORS.ENDSWITH, ENDSWITH), # (OPERATORS.IENDSWITH, IENDSWITH), # (OPERATORS.EQ, EQ), # (OPERATORS.NEQ, NEQ), # (OPERATORS.LT, LT), # (OPERATORS.GT, GT), # (OPERATORS.LTE, LTE), # (OPERATORS.GTE, GTE), # (OPERATORS.IN, IN), # ) # # class SimpleMethodEqualFilter(SimpleEqualFilterMixin, MethodFilter): # """ # Combination of simple equal filter and method filter used for custom method filters. # """ # pass # # Path: pyston/order/django_sorters.py # class ExtraDjangoSorter(DjangoSorter): # """ # Special type of sorter that updates queryset using annotate or extra queryset method. # For this purpose must be implement updated_queryset method which returns queryset with new column # that is used for ordering. # """ # # def _get_order_string(self): # return LOOKUP_SEP.join(chain(('extra_order',), self.identifiers)) # # def update_queryset(self, qs): # raise NotImplementedError . Output only the next line.
class WatchedIssuesCountMethodFilter(IntegerFilterMixin, SimpleMethodEqualFilter):
Next line prediction: <|code_start|> class OnlyContainsStringFieldFilter(StringFieldFilter): operators = ( (OPERATORS.CONTAINS, CONTAINS), ) class WatchedIssuesCountMethodFilter(IntegerFilterMixin, SimpleMethodEqualFilter): def get_filter_term(self, value, operator, request): return { 'pk__in': User.objects.annotate( watched_issues_count=Count('watched_issues') ).filter(watched_issues_count=value).values('pk') } <|code_end|> . Use current file imports: (from django.db import models from django.db.models import Count from django.utils.translation import ugettext_lazy as _ from pyston.utils.decorators import order_by, filter_class, filter_by, allow_tags, sorter_class from pyston.filters.filters import OPERATORS, IntegerFilterMixin from pyston.filters.django_filters import CONTAINS, StringFieldFilter, SimpleMethodEqualFilter from pyston.order.django_sorters import ExtraDjangoSorter) and context including class names, function names, or small code snippets from other files: # Path: pyston/utils/decorators.py # def order_by(field_name): # """Sets 'field name' (this is used for grid ordering)""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.order_by = field_name # return func # return decorator # # def filter_class(filter_class): # """Sets 'filter' class (this attribute is used inside grid and rest).""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.filter = filter_class # return func # return decorator # # def filter_by(field_name): # """Sets 'field name' (this is used for grid filtering)""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.filter_by = field_name # return func # return decorator # # def allow_tags(func): # """Allows HTML tags to be returned from resource without escaping""" # if isinstance(func, property): # func = func.fget # func.allow_tags = True # return func # # def sorter_class(sorter_class): # """Sets 'sorter' class (this attribute is used inside grid and rest).""" # def decorator(func): # if isinstance(func, property): # func = func.fget # func.sorter = sorter_class # return func # return decorator # # Path: pyston/filters/filters.py # OPERATORS = Enum( # ('GT', 'gt'), # ('LT', 'lt'), # ('EQ', 'eq'), # ('NEQ', 'neq'), # ('LTE', 'lte'), # ('GTE', 'gte'), # ('CONTAINS', 'contains'), # ('ICONTAINS', 'icontains'), # ('RANGE', 'range'), # ('EXACT', 'exact'), # ('IEXACT', 'iexact'), # ('STARTSWITH', 'startswith'), # ('ISTARTSWITH', 'istartswith'), # ('ENDSWITH', 'endswith'), # ('IENDSWITH', 'iendswith'), # ('IN', 'in'), # ('RANGE', 'range'), # ('ALL', 'all'), # ('ISNULL', 'isnull'), # ) # # class IntegerFilterMixin: # """ # Helper that contains cleaner for integer input values. # """ # # def clean_value(self, value, operator_slug, request): # if value is None: # return value # try: # return int(value) # except (ValueError, TypeError): # raise FilterValueError(ugettext('Value must be integer')) # # Path: pyston/filters/django_filters.py # CONTAINS = SimpleOperator('contains') # # class StringFieldFilter(OperatorsModelFieldFilter): # # operators = ( # (OPERATORS.ICONTAINS, ICONTAINS), # (OPERATORS.CONTAINS, CONTAINS), # (OPERATORS.EXACT, EXACT), # (OPERATORS.IEXACT, IEXACT), # (OPERATORS.STARTSWITH, STARTSWITH), # (OPERATORS.ISTARTSWITH, ISTARTSWITH), # (OPERATORS.ENDSWITH, ENDSWITH), # (OPERATORS.IENDSWITH, IENDSWITH), # (OPERATORS.EQ, EQ), # (OPERATORS.NEQ, NEQ), # (OPERATORS.LT, LT), # (OPERATORS.GT, GT), # (OPERATORS.LTE, LTE), # (OPERATORS.GTE, GTE), # (OPERATORS.IN, IN), # ) # # class SimpleMethodEqualFilter(SimpleEqualFilterMixin, MethodFilter): # """ # Combination of simple equal filter and method filter used for custom method filters. # """ # pass # # Path: pyston/order/django_sorters.py # class ExtraDjangoSorter(DjangoSorter): # """ # Special type of sorter that updates queryset using annotate or extra queryset method. # For this purpose must be implement updated_queryset method which returns queryset with new column # that is used for ordering. # """ # # def _get_order_string(self): # return LOOKUP_SEP.join(chain(('extra_order',), self.identifiers)) # # def update_queryset(self, qs): # raise NotImplementedError . Output only the next line.
class WatchedIssuesCountSorter(ExtraDjangoSorter):
Given the following code snippet before the placeholder: <|code_start|>''' class Text(object): template = Template("""&${code} = ${description} #project: ${project} #atf: lang ${language} % for child in children: ${child.serialize()} % endfor""") def __init__(self): self.children = [] self.composite = False self.links = [] self.score = None self.code = None self.description = None self.project = None self.language = None def __str__(self): return Text.template.render_unicode(**vars(self)) def serialize(self): return Text.template.render_unicode(**vars(self)) def objects(self): <|code_end|> , predict the next line using imports from the current file: from mako.template import Template from .oraccobject import OraccObject and context including class names, function names, and sometimes code from other files: # Path: pyoracc/model/oraccobject.py # class OraccObject(object): # # template = Template(r"""@${objecttype} # % for child in children: # ${child.serialize()} # % endfor""", output_encoding='utf-8') # # def __init__(self, objecttype): # self.objecttype = objecttype # self.children = [] # self.query = False # self.broken = False # self.remarkable = False # self.collated = False # # def __str__(self): # return OraccObject.template.render_unicode(**vars(self)) # # def serialize(self): # return OraccObject.template.render_unicode(**vars(self)) . Output only the next line.
return [x for x in self.children if isinstance(x, OraccObject)]
Given the code snippet: <|code_start|>(at your option) any later version. PyORACC 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 PyORACC. If not, see <http://www.gnu.org/licenses/>. ''' from __future__ import print_function class Corpus(object): def __init__(self, **kwargs): self.texts = [] self.failures = 0 self.successes = 0 self.atftype = kwargs['atftype'] self.source = kwargs['source'] if 'source' in kwargs: for dirpath, _, files in os.walk(self.source): for filename in files: if filename.endswith('.atf'): try: path = os.path.join(dirpath, filename) print("Parsing file", path, "... ", end="") content = codecs.open(path, encoding='utf-8-sig').read() <|code_end|> , generate the next line using the imports in this file: import sys import os import codecs from pyoracc.atf.common.atffile import AtfFile and context (functions, classes, or occasionally code) from other files: # Path: pyoracc/atf/common/atffile.py # class AtfFile(object): # template = Template("${text.serialize()}") # # def __init__(self, content, atftype='oracc', debug=False): # skipinvalid = False # if content[-1] != '\n': # content += "\n" # if atftype == 'cdli': # lexer = AtfCDLILexer(debug=debug, skipinvalid=skipinvalid, # log=log).lexer # parser = AtfCDLIParser(debug=debug, log=log).parser # elif atftype == 'oracc': # lexer = AtfOraccLexer(debug=debug, skipinvalid=skipinvalid, # log=log).lexer # parser = AtfOraccParser(debug=debug, log=log).parser # else: # lexer = AtfLexer(debug=debug, skipinvalid=skipinvalid, # log=log).lexer # parser = AtfParser(debug=debug, log=log).parser # if debug: # self.text = parser.parse(content, lexer=lexer, debug=log) # else: # self.text = parser.parse(content, lexer=lexer) # # def __str__(self): # return AtfFile.template.render_unicode(**vars(self)) # # def serialize(self): # return AtfFile.template.render_unicode(**vars(self)) # # def to_json(self, skip_empty=True, **kwargs): # '''Return a JSON representation of the parsed file. # # The optional skip_empty argument determines whether keys # with empty values are included in the output. Set it to # False to see all possible object members. # # Otherwise it accepts the same optional arguments as # json.dumps().''' # def _make_serializable(obj): # '''Construct a dict representation of an object. # # This is necessary to handle our custom objects # which json.JSONEncoder doesn't know how to # serialize.''' # # return {k: v # for k, v in vars(obj).items() # if not str(k).startswith('_') and not ( # skip_empty and not v and not isinstance(v, Number) # )} # # kwargs.setdefault('indent', 2) # kwargs.setdefault('default', _make_serializable) # return json.dumps(self.text, **kwargs) . Output only the next line.
self.texts.append(AtfFile(content, self.atftype))
Given snippet: <|code_start|>''' Copyright 2015, 2016 University College London. This file is part of PyORACC. PyORACC 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. PyORACC 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 PyORACC. If not, see <http://www.gnu.org/licenses/>. ''' <|code_end|> , continue by predicting the next line. Consider current file imports: from .oraccobject import OraccObject and context: # Path: pyoracc/model/oraccobject.py # class OraccObject(object): # # template = Template(r"""@${objecttype} # % for child in children: # ${child.serialize()} # % endfor""", output_encoding='utf-8') # # def __init__(self, objecttype): # self.objecttype = objecttype # self.children = [] # self.query = False # self.broken = False # self.remarkable = False # self.collated = False # # def __str__(self): # return OraccObject.template.render_unicode(**vars(self)) # # def serialize(self): # return OraccObject.template.render_unicode(**vars(self)) which might include code, classes, or functions. Output only the next line.
class OraccNamedObject(OraccObject):
Based on the snippet: <|code_start|> def check_and_process(pathname, atftype, verbose=False): mode = os.stat(pathname)[ST_MODE] if S_ISREG(mode) and pathname.lower().endswith('.atf'): # It's a file, call the callback function if verbose: click.echo('Info: Parsing {0}.'.format(pathname)) <|code_end|> , predict the immediate next line with the help of imports: import os import click from stat import ST_MODE, S_ISREG from pyoracc.atf.common.atffile import check_atf and context (classes, functions, sometimes code) from other files: # Path: pyoracc/atf/common/atffile.py # def check_atf(infile, atftype, verbose=False): # content = codecs.open(infile, # encoding='utf-8-sig').read() # AtfFile(content, atftype, verbose) . Output only the next line.
check_atf(pathname, atftype, verbose)
Continue the code snippet: <|code_start|># encoding: utf-8 """ @author: monitor1379 @contact: yy4f5da2@hotmail.com @site: www.monitor1379.com @version: 1.0 @license: GNU General Public License(Version 3) @file: check_gradient.py @time: 2016/10/4 9:59 """ def check_LinearGate(): x = np.random.randn(10, 4).astype(np.double) dy = np.random.randn(10, 4).astype(np.double) <|code_end|> . Use current file imports: from hamaa.gates import * from hamaa.layers import * from hamaa.utils.np_utils import eval_numerical_gradient_array, sum_abs_err and context (classes, functions, or code) from other files: # Path: hamaa/utils/np_utils.py # def eval_numerical_gradient_array(f, x, df=None, verbose=False, h=1e-4): # it = np.nditer(x, flags=['multi_index']) # grad = np.zeros_like(x) # while not it.finished: # xi = it.multi_index # old_val = x[xi] # # x[xi] = old_val + h # y_top = f(x) # # x[xi] = old_val - h # y_bottom = f(x) # # if df is not None: # grad[xi] = np.sum((y_top - y_bottom) * df) / (2 * h) # else: # grad[xi] = np.sum(y_top - y_bottom) / (2 * h) # # if verbose: # print it.multi_index, grad[xi] # x[xi] = old_val # it.iternext() # # return grad # # def sum_abs_err(u, v): # return np.sum(np.abs(u - v)) . Output only the next line.
grad_x = eval_numerical_gradient_array(LinearGate.forward, x, dy)
Using the snippet: <|code_start|> x = np.random.randn(10, 4).astype(np.double) dy = np.random.randn(10, 4).astype(np.double) grad_x = eval_numerical_gradient_array(LinearGate.forward, x, dy) dx = LinearGate.backward(x, dy) print grad_x print dx print np.sum(np.abs(grad_x - dx)) def check_MultiGate(): x = np.random.randn(10, 4) w = np.random.randn(4, 6) df = np.random.randn(10, 6) grad_x = eval_numerical_gradient_array(lambda a: MulGate.forward(w, a), x, df) grad_w = eval_numerical_gradient_array(lambda b: MulGate.forward(b, x), w, df) dw, dx = MulGate.backward(w, x, df) print np.sum(np.abs(grad_x - dx)) print np.sum(np.abs(grad_w - dw)) def check_AddGate(): x = np.random.randn(10, 3) # b = np.random.randn(1, 3) b = np.random.randn(1, 1) df = np.random.randn(10, 3) grad_x = eval_numerical_gradient_array(lambda t: AddGate.forward(t, b), x, df) grad_b = eval_numerical_gradient_array(lambda t: AddGate.forward(x, t), b, df) dx, db = AddGate.backward(x, b, df) <|code_end|> , determine the next line of code. You have imports: from hamaa.gates import * from hamaa.layers import * from hamaa.utils.np_utils import eval_numerical_gradient_array, sum_abs_err and context (class names, function names, or code) available: # Path: hamaa/utils/np_utils.py # def eval_numerical_gradient_array(f, x, df=None, verbose=False, h=1e-4): # it = np.nditer(x, flags=['multi_index']) # grad = np.zeros_like(x) # while not it.finished: # xi = it.multi_index # old_val = x[xi] # # x[xi] = old_val + h # y_top = f(x) # # x[xi] = old_val - h # y_bottom = f(x) # # if df is not None: # grad[xi] = np.sum((y_top - y_bottom) * df) / (2 * h) # else: # grad[xi] = np.sum(y_top - y_bottom) / (2 * h) # # if verbose: # print it.multi_index, grad[xi] # x[xi] = old_val # it.iternext() # # return grad # # def sum_abs_err(u, v): # return np.sum(np.abs(u - v)) . Output only the next line.
print sum_abs_err(grad_x, dx)
Given snippet: <|code_start|>@site: www.monitor1379.com @version: 1.0 @license: GNU General Public License(Version 3) @file: objectives.py @time: 2016/9/11 12:07 损失函数 """ class MeanSquareError: @staticmethod def loss(y_real, y_pred): return np.mean(np.square(y_real - y_pred)) @staticmethod def diff(y_real, y_pred): return - (y_real - y_pred) / y_real.shape[0] class CategoricalCrossEntropy: @staticmethod def loss(y_real, y_pred): probs = y_pred <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from .gates import SoftmaxGate from .utils import np_utils and context: # Path: hamaa/gates.py # class SoftmaxGate: # """softmax单元""" # # @staticmethod # def forward(x): # ex = np.exp(x - np.max(x, axis=1, keepdims=True)) # return ex / np.sum(ex, axis=1, keepdims=True) # # @staticmethod # def backward(x, z, d_z): # # Because softmax is usually used together with crossentropy cost function, # # so the backpropagation part of softmax is calculated in the BP of crossentropy. # # Here just pass through the derivatives. # return np.array(d_z) # # @staticmethod # def naive_backward(x, z, d_z): # import warnings # warnings.warn('Do not use SoftmaxGate.backward() when backpropagation!') # n, m = x.shape # d_x = np.empty_like(x) # eyemat = np.eye(m) # for i in xrange(n): # z_i = z[i].reshape(1, m) # d_x[i] = np.dot(d_z[i], (eyemat - z_i) * z_i.T) # return d_x # # Path: hamaa/utils/np_utils.py # def to_one_hot(y, nb_class): # def to_categorical(y): # def split_training_data(data, nb_validation=None, split_ratio=None): # def padding(images, pad_size): # def rot180(images): # def eval_numerical_gradient_array(f, x, df=None, verbose=False, h=1e-4): # def sum_abs_err(u, v): which might include code, classes, or functions. Output only the next line.
categorical_y_real = np_utils.to_categorical(y_real)
Predict the next line for this snippet: <|code_start|># encoding: utf-8 """ @author: monitor1379 @contact: yy4f5da2@hotmail.com @site: www.monitor1379.com @version: 1.0 @license: GNU General Public License(Version 3) @file: activations.py @time: 2016/10/9 20:29 """ <|code_end|> with the help of current file imports: from .gates import SigmoidGate, TanhGate, ReLUGate, LinearGate, SoftmaxGate and context from other files: # Path: hamaa/gates.py # class SigmoidGate: # """sigmoid单元""" # # @staticmethod # def forward(x): # z = 1.0 / (1.0 + np.exp(-x)) # return z # # @staticmethod # def backward(x, z, d_z): # d_x = z * (1 - z) * d_z # return d_x # # class TanhGate: # """tanh单元""" # # @staticmethod # def forward(x): # e1 = np.exp(x) # e2 = np.exp(-x) # return (e1 - e2) / (e1 + e2) # # @staticmethod # def backward(x, z, d_z): # d_x = (1 - z**2) * d_z # return d_x # # class ReLUGate: # """relu单元""" # @staticmethod # def forward(x): # z = np.array(x) # z[z < 0] = 0 # return z # # @staticmethod # def backward(x, z, d_z): # d_x = np.ones_like(x) # d_x[x < 0] = 0 # return d_x * d_z # # class LinearGate: # """线性计算单元""" # # @staticmethod # def forward(x): # return np.array(x) # # @staticmethod # def backward(x, d_z): # return np.ones_like(x) * d_z # # class SoftmaxGate: # """softmax单元""" # # @staticmethod # def forward(x): # ex = np.exp(x - np.max(x, axis=1, keepdims=True)) # return ex / np.sum(ex, axis=1, keepdims=True) # # @staticmethod # def backward(x, z, d_z): # # Because softmax is usually used together with crossentropy cost function, # # so the backpropagation part of softmax is calculated in the BP of crossentropy. # # Here just pass through the derivatives. # return np.array(d_z) # # @staticmethod # def naive_backward(x, z, d_z): # import warnings # warnings.warn('Do not use SoftmaxGate.backward() when backpropagation!') # n, m = x.shape # d_x = np.empty_like(x) # eyemat = np.eye(m) # for i in xrange(n): # z_i = z[i].reshape(1, m) # d_x[i] = np.dot(d_z[i], (eyemat - z_i) * z_i.T) # return d_x , which may contain function names, class names, or code. Output only the next line.
_dict = {'sigmoid': SigmoidGate,
Based on the snippet: <|code_start|># encoding: utf-8 """ @author: monitor1379 @contact: yy4f5da2@hotmail.com @site: www.monitor1379.com @version: 1.0 @license: GNU General Public License(Version 3) @file: activations.py @time: 2016/10/9 20:29 """ _dict = {'sigmoid': SigmoidGate, <|code_end|> , predict the immediate next line with the help of imports: from .gates import SigmoidGate, TanhGate, ReLUGate, LinearGate, SoftmaxGate and context (classes, functions, sometimes code) from other files: # Path: hamaa/gates.py # class SigmoidGate: # """sigmoid单元""" # # @staticmethod # def forward(x): # z = 1.0 / (1.0 + np.exp(-x)) # return z # # @staticmethod # def backward(x, z, d_z): # d_x = z * (1 - z) * d_z # return d_x # # class TanhGate: # """tanh单元""" # # @staticmethod # def forward(x): # e1 = np.exp(x) # e2 = np.exp(-x) # return (e1 - e2) / (e1 + e2) # # @staticmethod # def backward(x, z, d_z): # d_x = (1 - z**2) * d_z # return d_x # # class ReLUGate: # """relu单元""" # @staticmethod # def forward(x): # z = np.array(x) # z[z < 0] = 0 # return z # # @staticmethod # def backward(x, z, d_z): # d_x = np.ones_like(x) # d_x[x < 0] = 0 # return d_x * d_z # # class LinearGate: # """线性计算单元""" # # @staticmethod # def forward(x): # return np.array(x) # # @staticmethod # def backward(x, d_z): # return np.ones_like(x) * d_z # # class SoftmaxGate: # """softmax单元""" # # @staticmethod # def forward(x): # ex = np.exp(x - np.max(x, axis=1, keepdims=True)) # return ex / np.sum(ex, axis=1, keepdims=True) # # @staticmethod # def backward(x, z, d_z): # # Because softmax is usually used together with crossentropy cost function, # # so the backpropagation part of softmax is calculated in the BP of crossentropy. # # Here just pass through the derivatives. # return np.array(d_z) # # @staticmethod # def naive_backward(x, z, d_z): # import warnings # warnings.warn('Do not use SoftmaxGate.backward() when backpropagation!') # n, m = x.shape # d_x = np.empty_like(x) # eyemat = np.eye(m) # for i in xrange(n): # z_i = z[i].reshape(1, m) # d_x[i] = np.dot(d_z[i], (eyemat - z_i) * z_i.T) # return d_x . Output only the next line.
'tanh': TanhGate,
Predict the next line after this snippet: <|code_start|># encoding: utf-8 """ @author: monitor1379 @contact: yy4f5da2@hotmail.com @site: www.monitor1379.com @version: 1.0 @license: GNU General Public License(Version 3) @file: activations.py @time: 2016/10/9 20:29 """ _dict = {'sigmoid': SigmoidGate, 'tanh': TanhGate, <|code_end|> using the current file's imports: from .gates import SigmoidGate, TanhGate, ReLUGate, LinearGate, SoftmaxGate and any relevant context from other files: # Path: hamaa/gates.py # class SigmoidGate: # """sigmoid单元""" # # @staticmethod # def forward(x): # z = 1.0 / (1.0 + np.exp(-x)) # return z # # @staticmethod # def backward(x, z, d_z): # d_x = z * (1 - z) * d_z # return d_x # # class TanhGate: # """tanh单元""" # # @staticmethod # def forward(x): # e1 = np.exp(x) # e2 = np.exp(-x) # return (e1 - e2) / (e1 + e2) # # @staticmethod # def backward(x, z, d_z): # d_x = (1 - z**2) * d_z # return d_x # # class ReLUGate: # """relu单元""" # @staticmethod # def forward(x): # z = np.array(x) # z[z < 0] = 0 # return z # # @staticmethod # def backward(x, z, d_z): # d_x = np.ones_like(x) # d_x[x < 0] = 0 # return d_x * d_z # # class LinearGate: # """线性计算单元""" # # @staticmethod # def forward(x): # return np.array(x) # # @staticmethod # def backward(x, d_z): # return np.ones_like(x) * d_z # # class SoftmaxGate: # """softmax单元""" # # @staticmethod # def forward(x): # ex = np.exp(x - np.max(x, axis=1, keepdims=True)) # return ex / np.sum(ex, axis=1, keepdims=True) # # @staticmethod # def backward(x, z, d_z): # # Because softmax is usually used together with crossentropy cost function, # # so the backpropagation part of softmax is calculated in the BP of crossentropy. # # Here just pass through the derivatives. # return np.array(d_z) # # @staticmethod # def naive_backward(x, z, d_z): # import warnings # warnings.warn('Do not use SoftmaxGate.backward() when backpropagation!') # n, m = x.shape # d_x = np.empty_like(x) # eyemat = np.eye(m) # for i in xrange(n): # z_i = z[i].reshape(1, m) # d_x[i] = np.dot(d_z[i], (eyemat - z_i) * z_i.T) # return d_x . Output only the next line.
'relu': ReLUGate,
Given snippet: <|code_start|># encoding: utf-8 """ @author: monitor1379 @contact: yy4f5da2@hotmail.com @site: www.monitor1379.com @version: 1.0 @license: GNU General Public License(Version 3) @file: activations.py @time: 2016/10/9 20:29 """ _dict = {'sigmoid': SigmoidGate, 'tanh': TanhGate, 'relu': ReLUGate, <|code_end|> , continue by predicting the next line. Consider current file imports: from .gates import SigmoidGate, TanhGate, ReLUGate, LinearGate, SoftmaxGate and context: # Path: hamaa/gates.py # class SigmoidGate: # """sigmoid单元""" # # @staticmethod # def forward(x): # z = 1.0 / (1.0 + np.exp(-x)) # return z # # @staticmethod # def backward(x, z, d_z): # d_x = z * (1 - z) * d_z # return d_x # # class TanhGate: # """tanh单元""" # # @staticmethod # def forward(x): # e1 = np.exp(x) # e2 = np.exp(-x) # return (e1 - e2) / (e1 + e2) # # @staticmethod # def backward(x, z, d_z): # d_x = (1 - z**2) * d_z # return d_x # # class ReLUGate: # """relu单元""" # @staticmethod # def forward(x): # z = np.array(x) # z[z < 0] = 0 # return z # # @staticmethod # def backward(x, z, d_z): # d_x = np.ones_like(x) # d_x[x < 0] = 0 # return d_x * d_z # # class LinearGate: # """线性计算单元""" # # @staticmethod # def forward(x): # return np.array(x) # # @staticmethod # def backward(x, d_z): # return np.ones_like(x) * d_z # # class SoftmaxGate: # """softmax单元""" # # @staticmethod # def forward(x): # ex = np.exp(x - np.max(x, axis=1, keepdims=True)) # return ex / np.sum(ex, axis=1, keepdims=True) # # @staticmethod # def backward(x, z, d_z): # # Because softmax is usually used together with crossentropy cost function, # # so the backpropagation part of softmax is calculated in the BP of crossentropy. # # Here just pass through the derivatives. # return np.array(d_z) # # @staticmethod # def naive_backward(x, z, d_z): # import warnings # warnings.warn('Do not use SoftmaxGate.backward() when backpropagation!') # n, m = x.shape # d_x = np.empty_like(x) # eyemat = np.eye(m) # for i in xrange(n): # z_i = z[i].reshape(1, m) # d_x[i] = np.dot(d_z[i], (eyemat - z_i) * z_i.T) # return d_x which might include code, classes, or functions. Output only the next line.
'linear': LinearGate,
Here is a snippet: <|code_start|># encoding: utf-8 """ @author: monitor1379 @contact: yy4f5da2@hotmail.com @site: www.monitor1379.com @version: 1.0 @license: GNU General Public License(Version 3) @file: activations.py @time: 2016/10/9 20:29 """ _dict = {'sigmoid': SigmoidGate, 'tanh': TanhGate, 'relu': ReLUGate, 'linear': LinearGate, <|code_end|> . Write the next line using the current file imports: from .gates import SigmoidGate, TanhGate, ReLUGate, LinearGate, SoftmaxGate and context from other files: # Path: hamaa/gates.py # class SigmoidGate: # """sigmoid单元""" # # @staticmethod # def forward(x): # z = 1.0 / (1.0 + np.exp(-x)) # return z # # @staticmethod # def backward(x, z, d_z): # d_x = z * (1 - z) * d_z # return d_x # # class TanhGate: # """tanh单元""" # # @staticmethod # def forward(x): # e1 = np.exp(x) # e2 = np.exp(-x) # return (e1 - e2) / (e1 + e2) # # @staticmethod # def backward(x, z, d_z): # d_x = (1 - z**2) * d_z # return d_x # # class ReLUGate: # """relu单元""" # @staticmethod # def forward(x): # z = np.array(x) # z[z < 0] = 0 # return z # # @staticmethod # def backward(x, z, d_z): # d_x = np.ones_like(x) # d_x[x < 0] = 0 # return d_x * d_z # # class LinearGate: # """线性计算单元""" # # @staticmethod # def forward(x): # return np.array(x) # # @staticmethod # def backward(x, d_z): # return np.ones_like(x) * d_z # # class SoftmaxGate: # """softmax单元""" # # @staticmethod # def forward(x): # ex = np.exp(x - np.max(x, axis=1, keepdims=True)) # return ex / np.sum(ex, axis=1, keepdims=True) # # @staticmethod # def backward(x, z, d_z): # # Because softmax is usually used together with crossentropy cost function, # # so the backpropagation part of softmax is calculated in the BP of crossentropy. # # Here just pass through the derivatives. # return np.array(d_z) # # @staticmethod # def naive_backward(x, z, d_z): # import warnings # warnings.warn('Do not use SoftmaxGate.backward() when backpropagation!') # n, m = x.shape # d_x = np.empty_like(x) # eyemat = np.eye(m) # for i in xrange(n): # z_i = z[i].reshape(1, m) # d_x[i] = np.dot(d_z[i], (eyemat - z_i) * z_i.T) # return d_x , which may include functions, classes, or code. Output only the next line.
'softmax': SoftmaxGate,
Predict the next line after this snippet: <|code_start|> plt.scatter(epoch, training_acc, marker='*') if validation_acc: plt.plot(epoch, validation_acc, label='validation') plt.scatter(epoch, validation_acc, marker='*') plt.legend(loc=0) # 绘画损失函数值随着训练周期的折线图 plt.subplot(313) if validation_acc: top = max(np.max(training_loss), np.max(validation_loss)) else: top = np.max(training_loss) plt.xlim([1, epoch[-1]]) plt.ylim([0, 0.1 + top]) plt.xlabel('epoch') plt.ylabel('loss') plt.plot(epoch, training_loss, label='training') plt.scatter(epoch, training_loss, marker='*') if validation_loss: plt.plot(epoch, validation_loss, label='validation') plt.scatter(epoch, validation_loss, marker='*') plt.legend(loc=0) plt.show() def plot_prediction(self, model, data): """绘画出决策边界。只适用于数据维数为2的情况。""" x, y = data # 如果y是one-hot,则重置为categorical if np.shape(y)[1] != 1: <|code_end|> using the current file's imports: import sys import time import warnings import matplotlib.pyplot as plt import numpy as np from .utils import np_utils from .utils.time_utils import ProgressBar and any relevant context from other files: # Path: hamaa/utils/np_utils.py # def to_one_hot(y, nb_class): # def to_categorical(y): # def split_training_data(data, nb_validation=None, split_ratio=None): # def padding(images, pad_size): # def rot180(images): # def eval_numerical_gradient_array(f, x, df=None, verbose=False, h=1e-4): # def sum_abs_err(u, v): # # Path: hamaa/utils/time_utils.py # class ProgressBar: # """控制台进度条类""" # # def __init__(self, total=0, width=20): # """ # :param total: 进度最大值,整数类型 # :param width: 进图条显示宽度,单位为一个字符占位格 # """ # # 当前轮数,类型为整数值 # self.current = 0 # self.total = total # self.width = width # self.timestamp = None # self.one_move_time = 0 # # def move(self, step=1): # self.current += step # if self.timestamp: # self.one_move_time = (time.time() - self.timestamp) / step # self.timestamp = time.time() # # def clear(self): # """清空进度条""" # sys.stdout.write('\r') # sys.stdout.write(' ' * (100)) # sys.stdout.write('\r') # sys.stdout.flush() # # def reset(self): # """重置进度条进度""" # self.current = 0 # # def show(self, head='', message=''): # self.clear() # # 计算当前进度百分比 # percent = self.current * 1.0 / self.total # # 根据百分比以及进度条总长度,计算当前进度的占位符宽度 # progress = int(math.ceil(self.width * percent)) # if progress == self.width: # progress -= 1 # # 估计剩余耗时 # remaining_time = (self.total - self.current) * self.one_move_time # # 打印进度条头 # sys.stdout.write(head + ', {0:3}/{1}: '.format(self.current, self.total)) # # 打印进度条 # sys.stdout.write('[' + '='*progress + '>' + ' '*(self.width - progress - 1) + '] remaining time: %.2fs' % remaining_time) # # 打印尾随信息 # sys.stdout.write(message) # sys.stdout.flush() # # # 如果进度完成,则输出换行符(永久打印在控制台上) # # if self.current == self.total: # # sys.stdout.write('\n') # # sys.stdout.flush() . Output only the next line.
y = np_utils.to_categorical(y)
Given the following code snippet before the placeholder: <|code_start|> for i in xrange(batch_times): # 对于每次批量计算 batch_range = random_idx[i * mini_batch_size:(i + 1) * mini_batch_size] batch_training_x = training_x[batch_range] batch_training_y = training_y[batch_range] self.train_by_batch(model, (batch_training_x, batch_training_y)) print 'epoch:{}, loss:{}'.format(epoch, model.evaluate_loss(training_x, training_y)) def train(self, model, training_data, nb_epochs, mini_batch_size, verbose=1, log_epoch=1, validation_data=None, shuffle=True, evaluate_batch_size=100, **kwargs): """训练模型.TODO""" assert log_epoch > 0, 'log_epoch:{} must be larger than zero!'.format(log_epoch) assert verbose in [0, 1, 2], 'invalid verbose:{}'.format(verbose) # 当log_epoch不为1时,不推荐使用进度条功能。 if log_epoch != 1 and verbose == 2: raise Exception('Invalid log_epoch and verbose: verbose为2时log_epoch只能为1!\n' '原因:进图条功能用于在控制台显示每个epoch的完成进度,\n' '如果log_epoch > 1,说明控制台每隔log_epoch个epoch才显示一次,\n' '会和进图条的显示功能产生冲突。') training_x, training_y = training_data n = training_x.shape[0] random_idx = range(n) batch_times = np.ceil(n * 1.0 / mini_batch_size).astype(np.int32) # logger负责记录训练过程,同时统计两次log之间的时间间隔 self.reset_logger() self.logger['need_to_refresh_start_time'] = True <|code_end|> , predict the next line using imports from the current file: import sys import time import warnings import matplotlib.pyplot as plt import numpy as np from .utils import np_utils from .utils.time_utils import ProgressBar and context including class names, function names, and sometimes code from other files: # Path: hamaa/utils/np_utils.py # def to_one_hot(y, nb_class): # def to_categorical(y): # def split_training_data(data, nb_validation=None, split_ratio=None): # def padding(images, pad_size): # def rot180(images): # def eval_numerical_gradient_array(f, x, df=None, verbose=False, h=1e-4): # def sum_abs_err(u, v): # # Path: hamaa/utils/time_utils.py # class ProgressBar: # """控制台进度条类""" # # def __init__(self, total=0, width=20): # """ # :param total: 进度最大值,整数类型 # :param width: 进图条显示宽度,单位为一个字符占位格 # """ # # 当前轮数,类型为整数值 # self.current = 0 # self.total = total # self.width = width # self.timestamp = None # self.one_move_time = 0 # # def move(self, step=1): # self.current += step # if self.timestamp: # self.one_move_time = (time.time() - self.timestamp) / step # self.timestamp = time.time() # # def clear(self): # """清空进度条""" # sys.stdout.write('\r') # sys.stdout.write(' ' * (100)) # sys.stdout.write('\r') # sys.stdout.flush() # # def reset(self): # """重置进度条进度""" # self.current = 0 # # def show(self, head='', message=''): # self.clear() # # 计算当前进度百分比 # percent = self.current * 1.0 / self.total # # 根据百分比以及进度条总长度,计算当前进度的占位符宽度 # progress = int(math.ceil(self.width * percent)) # if progress == self.width: # progress -= 1 # # 估计剩余耗时 # remaining_time = (self.total - self.current) * self.one_move_time # # 打印进度条头 # sys.stdout.write(head + ', {0:3}/{1}: '.format(self.current, self.total)) # # 打印进度条 # sys.stdout.write('[' + '='*progress + '>' + ' '*(self.width - progress - 1) + '] remaining time: %.2fs' % remaining_time) # # 打印尾随信息 # sys.stdout.write(message) # sys.stdout.flush() # # # 如果进度完成,则输出换行符(永久打印在控制台上) # # if self.current == self.total: # # sys.stdout.write('\n') # # sys.stdout.flush() . Output only the next line.
bar = ProgressBar(total=n, width=20)
Predict the next line for this snippet: <|code_start|> # 如果不存在bin文件夹,则解压mnist的gz压缩包 # 创建解压文件夹,存放地点为hamaa/datasets/mnist/bin mnist_bin_dir = module_path + os.sep + 'mnist' + os.sep + 'bin' + os.sep # 检查是否缺失解压后的数据文件 miss_bin_file = False for filename in filenames: file_path = mnist_bin_dir + filename.split('.')[0] if not os.path.exists(file_path): miss_bin_file = True break if not os.path.exists(mnist_bin_dir) or miss_bin_file: if not os.path.exists(mnist_bin_dir): os.mkdir(mnist_bin_dir) # 开始解压 for filename in filenames: print 'unzip ' + filename + ' ...' fn = filename.split() in_file = gzip.GzipFile(mnist_gz_dir + filename, 'rb') out_file = open(mnist_bin_dir + filename.split('.')[0], 'wb') out_file.write(in_file.read()) in_file.close() out_file.close() def load_mnist_data(nb_training, nb_test, preprocess=False, flatten=True, one_hot=True): # 自动检查数据,如果数据文件不存在则会先自动下载 download_mnist_data() <|code_end|> with the help of current file imports: import gzip import os import urllib import numpy as np from PIL import Image from .mnist import mnist_decoder from ..utils import np_utils and context from other files: # Path: hamaa/datasets/mnist/mnist_decoder.py # def decode_idx3_ubyte(idx3_ubyte_file, num_data=-1): # def decode_idx1_ubyte(idx1_ubyte_file, num_data=-1): # def load_train_images(idx_ubyte_file=train_images_idx3_ubyte_file, num_data=-1): # def load_train_labels(idx_ubyte_file=train_labels_idx1_ubyte_file, num_data=-1): # def load_test_images(idx_ubyte_file=test_images_idx3_ubyte_file, num_data=-1): # def load_test_labels(idx_ubyte_file=test_labels_idx1_ubyte_file, num_data=-1): # def run(): # # Path: hamaa/utils/np_utils.py # def to_one_hot(y, nb_class): # def to_categorical(y): # def split_training_data(data, nb_validation=None, split_ratio=None): # def padding(images, pad_size): # def rot180(images): # def eval_numerical_gradient_array(f, x, df=None, verbose=False, h=1e-4): # def sum_abs_err(u, v): , which may contain function names, class names, or code. Output only the next line.
training_x = mnist_decoder.load_train_images(num_data=nb_training)
Continue the code snippet: <|code_start|># encoding: utf-8 """ @author: monitor1379 @contact: yy4f5da2@hotmail.com @site: www.monitor1379.com @version: 1.0 @license: GNU General Public License(Version 3) @file: datasets.py @time: 2016/9/11 9:00 数据集加载文件 """ def load_or_data(one_hot=True): x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) y = np.array([0, 1, 1, 1]) if one_hot: <|code_end|> . Use current file imports: import gzip import os import urllib import numpy as np from PIL import Image from .mnist import mnist_decoder from ..utils import np_utils and context (classes, functions, or code) from other files: # Path: hamaa/datasets/mnist/mnist_decoder.py # def decode_idx3_ubyte(idx3_ubyte_file, num_data=-1): # def decode_idx1_ubyte(idx1_ubyte_file, num_data=-1): # def load_train_images(idx_ubyte_file=train_images_idx3_ubyte_file, num_data=-1): # def load_train_labels(idx_ubyte_file=train_labels_idx1_ubyte_file, num_data=-1): # def load_test_images(idx_ubyte_file=test_images_idx3_ubyte_file, num_data=-1): # def load_test_labels(idx_ubyte_file=test_labels_idx1_ubyte_file, num_data=-1): # def run(): # # Path: hamaa/utils/np_utils.py # def to_one_hot(y, nb_class): # def to_categorical(y): # def split_training_data(data, nb_validation=None, split_ratio=None): # def padding(images, pad_size): # def rot180(images): # def eval_numerical_gradient_array(f, x, df=None, verbose=False, h=1e-4): # def sum_abs_err(u, v): . Output only the next line.
y = np_utils.to_one_hot(y, 2)
Continue the code snippet: <|code_start|> class RemoveEntityOnDeath(Leaf): """ Will remove the parent from the dungeon when parent Entity dies. """ def __init__(self): super(RemoveEntityOnDeath, self).__init__() self.component_type = "remove_on_death" def after_tick(self, time): if self.parent.health.is_dead(): self.parent.dungeon_level.value self.parent.mover.try_remove_from_dungeon() class PrintDeathMessageOnDeath(Leaf): """ Will print death message when parent Entity dies. """ def __init__(self): super(PrintDeathMessageOnDeath, self).__init__() self.component_type = "print_death_message_on_death" def on_tick(self, time): if self.parent.health.is_dead(): <|code_end|> . Use current file imports: import random import spawner from compositecore import Leaf from messenger import msg and context (classes, functions, or code) from other files: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: messenger.py # EQUIP_MESSAGE = "%(source_entity)s equips %(item)s." # UNEQUIP_MESSAGE = "%(source_entity)s puts away %(item)s." # HEAL_MESSAGE = "%(source_entity)s heals %(target_entity)s for %(health)s health." # HEALTH_POTION_MESSAGE = "The health potion heals %(target_entity)s for %(health)s health." # DISSOLVE_MESSAGE = "%(source_entity)s dissolves %(target_entity)s for %(damage)s damage." # HIT_MESSAGE = "%(source_entity)s hits %(target_entity)s for %(damage)s damage." # MISS_MESSAGE = "%(source_entity)s misses %(target_entity)s." # CRIT_MESSAGE = "%(source_entity)s critically hits %(target_entity)s for %(damage)s damage." # HAUNT_MESSAGE = "%(source_entity)s haunts the %(target_entity)s!" # HEART_STOP_MESSAGE = "%(target_entity)s clutches its heart." # DARKNESS_MESSAGE = "An unnatural darkness fills the dungeon." # PICK_UP_MESSAGE = "You pick up %(item)s." # POISON_MESSAGE = "%(target_entity)s takes %(damage)s in poison damage." # BLEED_MESSAGE = "%(target_entity)s is bleeding out %(damage)s damage." # DOWN_STAIRS_HEAL_MESSAGE = "Your feel vitalized by your progress, you regain %(health)s health." # FALL_DOWN_MESSAGE = "You take a damage of %(damage)s from the fall." # DRINK_FOUNTAIN_MESSAGE = "You drink from the fountain, your max health increases by %(health)s." # HURT_BY_EXPLOSION = "The explosion blasts %(target_entity)s for %(damage)s damage." # HURT_BY_FIRE = "The fire burns %(target_entity)s for %(damage)s damage." # WONT_BREAK_OUT_OF_WEB_MESSAGE = "%(target_entity)s is stuck in the spider web." # BREAKS_OUT_OF_WEB_MESSAGE = "%(target_entity)s breaks free." # WANT_TO_JUMP_DOWN_CHASM = "Are you sure you want to drop down the chasm?" # PRESS_ENTER_TO_ACCEPT = "Press ENTER to accept, another key to reject." # PLAYER_TELEPORT_MESSAGE = "Your surroundings seem different." # PLAYER_SWITCH_MESSAGE = "Your surrounding is replaced." # PLAYER_MAP_MESSAGE = "You surroundings suddenly seem familiar." # PLAYER_PUSH_SCROLL_MESSAGE = "You as you form the words of the scroll your voice turns into a strong wind." # GLASS_TURNING_MESSAGE = "You surroundings suddenly seem more transparent." # SWAP_DEVICE_MESSAGE = "Your surroundings has changed." # ZAP_DEVICE_MESSAGE = "%(source_entity)s zaps %(target_entity)s for %(damage)s damage!" # HEALTH_DEVICE_MESSAGE = "%(target_entity)s is healed by the device for %(health)s health." # STARE_PARALYZE_MESSAGE = "%(source_entity)s stares at %(target_entity)s, it's paralyzed!." # NO_LONGER_PARALYZED_MESSAGE = "%(source_entity)s is no longer paralyzed." # FROST_POTION_DRINK_MESSAGE = "That potion was cold as ice! You feel yourself slow down." # FROST_POTION_BREAKS_MESSAGE = "The potion smashes to the ground and creates a freezing cloud of mist!" # POTION_SMASHES_AGAINST_FLOOR_MESSAGE = "The potion smashes to the ground and breaks into pieces." # FLAME_POTION_DRINK_MESSAGE = "As you drink the potion the liquid ignites!" # FLAME_POTION_BREAKS_MESSAGE = "The potion smashes to the ground and creates a roaring fire!" # POISON_POTION_DRINK_MESSAGE = "The potion tastes really nasty, you feel sick!" # POISON_POTION_BREAK_MESSAGE = "The potion smashes to the ground and creates a poisonous cloud of gas!" # POTION_SMASH_TO_GROUND = "The %(target_entity)s smashes to the ground and breaks into pieces." # ITEM_HITS_THE_GROUND_HEAVY = "The %(target_entity)s hits the ground with a thud." # ITEM_HITS_THE_GROUND_LIGHT = "The %(target_entity)s falls to the ground." # ITEM_FALLS_DOWN_CHASM = "The %(target_entity)s falls into the chasm and disappears." # ENTITY_EXPLODES = "%(target_entity)s explodes!" # class Messenger(object): # class Message(object): # def __init__(self): # def has_new_message(self): # def has_new_message(self, value): # def send_visual_message(self, new_message, position): # def send_global_message(self, new_message): # def _message(self, new_message): # def tail(self, length): # def clear(self): # def __init__(self, message): # def increase(self): # def tick(self): # def __str__(self): . Output only the next line.
msg.send_visual_message(self.parent.entity_messages.death, self.parent.position.value)
Here is a snippet: <|code_start|> # Arguments: SOURCE_ENTITY = "source_entity" TARGET_ENTITY = "target_entity" GAME_STATE = "game_state" TARGET_POSITION = "target_position" EQUIPMENT_SLOT = "equipment_slot" ACTION = "action" DESTINATION = "destination" #TODO: Replace with target_position? <|code_end|> . Write the next line using the current file imports: import gametime from compositecore import Leaf and context from other files: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) , which may include functions, classes, or code. Output only the next line.
class Action(Leaf):
Based on the snippet: <|code_start|> class TestComposition(unittest.TestCase): def setUp(self): pass def test_other_side_of_point_direction_should_return_right_when_target_on_left(self): """ 1, 2, r ..... .12r. ..... """ p1 = (-1, 0) p2 = (0, 0) expected_r = (1, 0) <|code_end|> , predict the immediate next line with the help of imports: import unittest from geometry import other_side_of_point_direction, other_side_of_point and context (classes, functions, sometimes code) from other files: # Path: geometry.py # def other_side_of_point_direction(point1, point2): # far_behind_point = sub_2d(point2, point1) # direction = element_wise_round(normalize(far_behind_point)) # return direction # # def other_side_of_point(point1, point2): # """ # returns the point right behind point2 as seen by point1. # 1 = point1 # 2 = point2 # r = result # ..1.. # ..... # ..... # ...2. # ...r. # """ # direction = other_side_of_point_direction(point1, point2) # return add_2d(point2, direction) . Output only the next line.
self.assertEqual(other_side_of_point_direction(p1, p2), expected_r)
Using the snippet: <|code_start|> """ p1 = (1, -1) p2 = (0, 0) expected_r = (-1, 1) self.assertEqual(other_side_of_point_direction(p1, p2), expected_r) def test_other_side_of_point_direction_should_return_down_left_when_target_up_right(self): """ 1, 2, r ...1. ..2.. .r... """ p1 = (1, -1) p2 = (0, 0) expected_r = (-1, 1) self.assertEqual(other_side_of_point_direction(p1, p2), expected_r) def test_other_side_of_point_should_return_down_when_target_is_up(self): """ 1, 2, r ...1. ..... ..... ..2.. ..r.. """ p1 = (1, -3) p2 = (0, 0) expected_r = (0, 1) <|code_end|> , determine the next line of code. You have imports: import unittest from geometry import other_side_of_point_direction, other_side_of_point and context (class names, function names, or code) available: # Path: geometry.py # def other_side_of_point_direction(point1, point2): # far_behind_point = sub_2d(point2, point1) # direction = element_wise_round(normalize(far_behind_point)) # return direction # # def other_side_of_point(point1, point2): # """ # returns the point right behind point2 as seen by point1. # 1 = point1 # 2 = point2 # r = result # ..1.. # ..... # ..... # ...2. # ...r. # """ # direction = other_side_of_point_direction(point1, point2) # return add_2d(point2, direction) . Output only the next line.
self.assertEqual(other_side_of_point(p1, p2), expected_r)
Given the code snippet: <|code_start|> __author__ = 'co' def start_accept_reject_prompt(state_stack, game_state, message): prompt = menu.AcceptRejectPrompt(state_stack, message) game_state.start_prompt(state.UIState(prompt)) return prompt.result <|code_end|> , generate the next line using the imports in this file: from compositecore import Leaf import menu import state and context (functions, classes, or occasionally code) from other files: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) . Output only the next line.
class PromptPlayer(Leaf):
Continue the code snippet: <|code_start|> class TestComposition(unittest.TestCase): def setUp(self): pass def test_get_horizontal_with_same_start_and_destination_is_length_one(self): <|code_end|> . Use current file imports: import unittest from util import get_path and context (classes, functions, or code) from other files: # Path: util.py # def get_path(start, destination): # result = [start] # sx, sy = start # dx, dy = destination # libtcod.line_init(sx, sy, dx, dy) # x, y = libtcod.line_step() # while not x is None: # result.append((x, y)) # x, y = libtcod.line_step() # return result . Output only the next line.
path = get_path((2, 4), (2, 4))
Given snippet: <|code_start|> RING = 3 AMULET = 4 # Weapons MELEE_WEAPON = 5 RANGED_WEAPON = 6 ALL = [HEADGEAR, ARMOR, BOOTS, RING, AMULET, MELEE_WEAPON, RANGED_WEAPON] class EquipmentSlots(object): # Weapons MELEE_WEAPON = EquipmentSlot("Melee Weapon", EquipmentTypes.MELEE_WEAPON, icon.SWORD) RANGED_WEAPON = EquipmentSlot("Ranged Weapon", EquipmentTypes.RANGED_WEAPON, icon.GUN) # Armor HEADGEAR = EquipmentSlot("Headgear", EquipmentTypes.HEADGEAR, icon.HELM) ARMOR = EquipmentSlot("Armor", EquipmentTypes.ARMOR, icon.ARMOR) BOOTS = EquipmentSlot("Boots", EquipmentTypes.BOOTS, icon.BOOTS) # Jewelry RIGHT_RING = EquipmentSlot("Right Ring", EquipmentTypes.RING, icon.RING) LEFT_RING = EquipmentSlot("Left Ring", EquipmentTypes.RING, icon.RING) AMULET = EquipmentSlot("Amulet", EquipmentTypes.AMULET, icon.AMULET) ALL = [MELEE_WEAPON, RANGED_WEAPON, HEADGEAR, ARMOR, BOOTS, RIGHT_RING, LEFT_RING, AMULET] <|code_end|> , continue by predicting the next line. Consider current file imports: import icon from compositecore import Leaf and context: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) which might include code, classes, or functions. Output only the next line.
class Equipment(Leaf):
Given the following code snippet before the placeholder: <|code_start|> # Do not shuffle public constants! directions = list(direction.DIRECTIONS) random.shuffle(directions) for d in directions: destination = geometry.add_2d(d, new_position) if self.try_move(destination, new_dungeon_level): return True return False def try_move(self, new_position, new_dungeon_level=None): """ Tries to move parent to new position. Returns true if it is successful, false otherwise. """ if new_dungeon_level is None: new_dungeon_level = self.parent.dungeon_level.value if self.can_move(new_position, new_dungeon_level): self._move(new_position, new_dungeon_level) return True return False def _move(self, new_position, dungeon_level): """ Moves parent to new position, assumes that it fits there. """ self._remove_from_old_tile() dungeon_level.get_tile(new_position).add(self.parent) self.parent.position.value = new_position if not self.has_sibling("dungeon_level"): <|code_end|> , predict the next line using imports from the current file: import random import Status import direction import geometry import trigger from compositecore import Leaf from position import DungeonLevel from stats import max_instances_of_composite_on_tile, IntelligenceLevel from statusflags import StatusFlags and context including class names, function names, and sometimes code from other files: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: position.py # class DungeonLevel(Leaf): # """ # Composites holding this is in a DungeonLevel. # """ # def __init__(self): # super(DungeonLevel, self).__init__() # self.component_type = "dungeon_level" # self._value = None # self.last_dungeon_level = None # # @property # def value(self): # """ # Gets the dungeon_level the entity is currently in. # """ # return self._value # # @value.setter # def value(self, new_dungeon_level): # """ # Sets current dungeon_level of the entity. # Also updates the visibility/solidity of the dungeon_level tiles. # """ # if not self._value is new_dungeon_level: # old_dungeon_level = self._value # self._value = new_dungeon_level # self._signal_dungeon_level_changed() # if(not old_dungeon_level is None and # self.has_sibling("actor")): # old_dungeon_level.remove_actor_if_present(self.parent) # self.last_dungeon_level = old_dungeon_level # if self.last_dungeon_level is None: # self.last_dungeon_level = new_dungeon_level # # def _signal_dungeon_level_changed(self): # """ # Is called when dungeon level has changed. # """ # if self.has_parent() and not self.value is None: # self.parent.send_message(CompositeMessage.DUNGEON_LEVEL_CHANGED) # if self.has_sibling("actor"): # self.value.add_actor_if_not_present(self.parent) # if self.has_sibling("is_dungeon_feature"): # self.value.add_dungeon_feature_if_not_present(self.parent) # # def on_parent_changed(self): # """ # When the parent changes try to add it to the dungeon. # """ # self._signal_dungeon_level_changed() # # Path: stats.py # def max_instances_of_composite_on_tile(composite): # return GamePieceTypes.MAX_INSTANCES_ON_TILE[composite.game_piece_type.value] # # class IntelligenceLevel(DataPoint): # MINDLESS = 0 # PLANT = 1 # ANIMAL = 2 # NORMAL = 3 # HIGH = 4 # # Path: statusflags.py # class StatusFlags(Leaf): # """ # Composites holding this has status flags, describing their behaviour. # """ # INVISIBILE = 0 # SEE_INVISIBILITY = 1 # FLYING = 2 # IS_ALIVE = 3 # CAN_OPEN_DOORS = 4 # HAS_HEART = 5 # # def __init__(self, status_flags=[]): # super(StatusFlags, self).__init__() # self.component_type = "status_flags" # self._status_flags = set(status_flags) # self._temp_status_flags = set() # # def has_status(self, status): # """ # Returns True if parent entity has the status given. # """ # if not self.next is None: # return (status in self._status_flags or # status in self._temp_status_flags or # next.has_status(status)) # else: # return (status in self._status_flags or # status in self._temp_status_flags) # # def add_temp_status(self, status): # """ # Adds a temporary status that will be removed the next tick. # """ # self._temp_status_flags.add(status) # # def before_tick(self, time): # self._temp_status_flags = set() . Output only the next line.
self.parent.set_child(DungeonLevel())
Predict the next line after this snippet: <|code_start|> Moves parent to new position, assumes that it fits there. """ self._remove_from_old_tile() dungeon_level.get_tile(new_position).add(self.parent) self.parent.position.value = new_position if not self.has_sibling("dungeon_level"): self.parent.set_child(DungeonLevel()) self.parent.dungeon_level.value = dungeon_level def replace_move(self, new_position, new_dungeon_level=None): """ Moves parent to new position and replaces what was already there. """ if new_dungeon_level is None: new_dungeon_level = self.parent.dungeon_level.value if not new_dungeon_level.has_tile(new_position): return False new_tile = new_dungeon_level.get_tile(new_position) self._remove_from_old_tile() piece_type = self.parent.game_piece_type.value new_place = new_tile.game_pieces[piece_type] for piece in new_place: piece.mover.try_remove_from_dungeon() return self.try_move(new_position, new_dungeon_level) def _can_fit_on_tile(self, tile): """ Checks if the parent can fit on the tile. """ piece_type = self.parent.game_piece_type <|code_end|> using the current file's imports: import random import Status import direction import geometry import trigger from compositecore import Leaf from position import DungeonLevel from stats import max_instances_of_composite_on_tile, IntelligenceLevel from statusflags import StatusFlags and any relevant context from other files: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: position.py # class DungeonLevel(Leaf): # """ # Composites holding this is in a DungeonLevel. # """ # def __init__(self): # super(DungeonLevel, self).__init__() # self.component_type = "dungeon_level" # self._value = None # self.last_dungeon_level = None # # @property # def value(self): # """ # Gets the dungeon_level the entity is currently in. # """ # return self._value # # @value.setter # def value(self, new_dungeon_level): # """ # Sets current dungeon_level of the entity. # Also updates the visibility/solidity of the dungeon_level tiles. # """ # if not self._value is new_dungeon_level: # old_dungeon_level = self._value # self._value = new_dungeon_level # self._signal_dungeon_level_changed() # if(not old_dungeon_level is None and # self.has_sibling("actor")): # old_dungeon_level.remove_actor_if_present(self.parent) # self.last_dungeon_level = old_dungeon_level # if self.last_dungeon_level is None: # self.last_dungeon_level = new_dungeon_level # # def _signal_dungeon_level_changed(self): # """ # Is called when dungeon level has changed. # """ # if self.has_parent() and not self.value is None: # self.parent.send_message(CompositeMessage.DUNGEON_LEVEL_CHANGED) # if self.has_sibling("actor"): # self.value.add_actor_if_not_present(self.parent) # if self.has_sibling("is_dungeon_feature"): # self.value.add_dungeon_feature_if_not_present(self.parent) # # def on_parent_changed(self): # """ # When the parent changes try to add it to the dungeon. # """ # self._signal_dungeon_level_changed() # # Path: stats.py # def max_instances_of_composite_on_tile(composite): # return GamePieceTypes.MAX_INSTANCES_ON_TILE[composite.game_piece_type.value] # # class IntelligenceLevel(DataPoint): # MINDLESS = 0 # PLANT = 1 # ANIMAL = 2 # NORMAL = 3 # HIGH = 4 # # Path: statusflags.py # class StatusFlags(Leaf): # """ # Composites holding this has status flags, describing their behaviour. # """ # INVISIBILE = 0 # SEE_INVISIBILITY = 1 # FLYING = 2 # IS_ALIVE = 3 # CAN_OPEN_DOORS = 4 # HAS_HEART = 5 # # def __init__(self, status_flags=[]): # super(StatusFlags, self).__init__() # self.component_type = "status_flags" # self._status_flags = set(status_flags) # self._temp_status_flags = set() # # def has_status(self, status): # """ # Returns True if parent entity has the status given. # """ # if not self.next is None: # return (status in self._status_flags or # status in self._temp_status_flags or # next.has_status(status)) # else: # return (status in self._status_flags or # status in self._temp_status_flags) # # def add_temp_status(self, status): # """ # Adds a temporary status that will be removed the next tick. # """ # self._temp_status_flags.add(status) # # def before_tick(self, time): # self._temp_status_flags = set() . Output only the next line.
return len(tile.game_pieces[piece_type.value]) < max_instances_of_composite_on_tile(self.parent)
Here is a snippet: <|code_start|> return False def try_attack(self, position): entity = (self.parent.dungeon_level.value.get_tile(position).get_first_entity()) if self.parent.has("melee_attacker") and entity: return self.parent.melee_attacker.try_hit(entity) def try_move_or_bump(self, position): """ Tries to move the entity to a position. If there is a unfriendly entity in the way hit it instead. If there is a door in the way try to open it. If an action is taken return True otherwise return False. Args: position (int, int): The position the entity tries to move to. Returns: Energy spent """ if self.try_bump_terrain(position): return self.parent.movement_speed.value if self.try_attack(position): return self.parent.melee_speed.value if self._try_move_to_destination(position): return self.parent.movement_speed.value return 0 def is_tile_dangerous(tile, entity): <|code_end|> . Write the next line using the current file imports: import random import Status import direction import geometry import trigger from compositecore import Leaf from position import DungeonLevel from stats import max_instances_of_composite_on_tile, IntelligenceLevel from statusflags import StatusFlags and context from other files: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: position.py # class DungeonLevel(Leaf): # """ # Composites holding this is in a DungeonLevel. # """ # def __init__(self): # super(DungeonLevel, self).__init__() # self.component_type = "dungeon_level" # self._value = None # self.last_dungeon_level = None # # @property # def value(self): # """ # Gets the dungeon_level the entity is currently in. # """ # return self._value # # @value.setter # def value(self, new_dungeon_level): # """ # Sets current dungeon_level of the entity. # Also updates the visibility/solidity of the dungeon_level tiles. # """ # if not self._value is new_dungeon_level: # old_dungeon_level = self._value # self._value = new_dungeon_level # self._signal_dungeon_level_changed() # if(not old_dungeon_level is None and # self.has_sibling("actor")): # old_dungeon_level.remove_actor_if_present(self.parent) # self.last_dungeon_level = old_dungeon_level # if self.last_dungeon_level is None: # self.last_dungeon_level = new_dungeon_level # # def _signal_dungeon_level_changed(self): # """ # Is called when dungeon level has changed. # """ # if self.has_parent() and not self.value is None: # self.parent.send_message(CompositeMessage.DUNGEON_LEVEL_CHANGED) # if self.has_sibling("actor"): # self.value.add_actor_if_not_present(self.parent) # if self.has_sibling("is_dungeon_feature"): # self.value.add_dungeon_feature_if_not_present(self.parent) # # def on_parent_changed(self): # """ # When the parent changes try to add it to the dungeon. # """ # self._signal_dungeon_level_changed() # # Path: stats.py # def max_instances_of_composite_on_tile(composite): # return GamePieceTypes.MAX_INSTANCES_ON_TILE[composite.game_piece_type.value] # # class IntelligenceLevel(DataPoint): # MINDLESS = 0 # PLANT = 1 # ANIMAL = 2 # NORMAL = 3 # HIGH = 4 # # Path: statusflags.py # class StatusFlags(Leaf): # """ # Composites holding this has status flags, describing their behaviour. # """ # INVISIBILE = 0 # SEE_INVISIBILITY = 1 # FLYING = 2 # IS_ALIVE = 3 # CAN_OPEN_DOORS = 4 # HAS_HEART = 5 # # def __init__(self, status_flags=[]): # super(StatusFlags, self).__init__() # self.component_type = "status_flags" # self._status_flags = set(status_flags) # self._temp_status_flags = set() # # def has_status(self, status): # """ # Returns True if parent entity has the status given. # """ # if not self.next is None: # return (status in self._status_flags or # status in self._temp_status_flags or # next.has_status(status)) # else: # return (status in self._status_flags or # status in self._temp_status_flags) # # def add_temp_status(self, status): # """ # Adds a temporary status that will be removed the next tick. # """ # self._temp_status_flags.add(status) # # def before_tick(self, time): # self._temp_status_flags = set() , which may include functions, classes, or code. Output only the next line.
if entity.intelligence.value == IntelligenceLevel.PLANT:
Predict the next line for this snippet: <|code_start|> self._remove_from_old_tile() piece_type = self.parent.game_piece_type.value new_place = new_tile.game_pieces[piece_type] for piece in new_place: piece.mover.try_remove_from_dungeon() return self.try_move(new_position, new_dungeon_level) def _can_fit_on_tile(self, tile): """ Checks if the parent can fit on the tile. """ piece_type = self.parent.game_piece_type return len(tile.game_pieces[piece_type.value]) < max_instances_of_composite_on_tile(self.parent) def can_move_to_terrain(self, terrain_to_pass): if terrain_to_pass is None or terrain_to_pass.has("is_chasm"): return True elif terrain_to_pass.has("is_solid"): return False else: return self.can_pass_terrain(terrain_to_pass) def can_pass_terrain(self, terrain_to_pass): """ Checks if the parent can move through a terrain. """ if terrain_to_pass is None: return True if self.has_sibling("status_flags"): status_flags = self.parent.status_flags <|code_end|> with the help of current file imports: import random import Status import direction import geometry import trigger from compositecore import Leaf from position import DungeonLevel from stats import max_instances_of_composite_on_tile, IntelligenceLevel from statusflags import StatusFlags and context from other files: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: position.py # class DungeonLevel(Leaf): # """ # Composites holding this is in a DungeonLevel. # """ # def __init__(self): # super(DungeonLevel, self).__init__() # self.component_type = "dungeon_level" # self._value = None # self.last_dungeon_level = None # # @property # def value(self): # """ # Gets the dungeon_level the entity is currently in. # """ # return self._value # # @value.setter # def value(self, new_dungeon_level): # """ # Sets current dungeon_level of the entity. # Also updates the visibility/solidity of the dungeon_level tiles. # """ # if not self._value is new_dungeon_level: # old_dungeon_level = self._value # self._value = new_dungeon_level # self._signal_dungeon_level_changed() # if(not old_dungeon_level is None and # self.has_sibling("actor")): # old_dungeon_level.remove_actor_if_present(self.parent) # self.last_dungeon_level = old_dungeon_level # if self.last_dungeon_level is None: # self.last_dungeon_level = new_dungeon_level # # def _signal_dungeon_level_changed(self): # """ # Is called when dungeon level has changed. # """ # if self.has_parent() and not self.value is None: # self.parent.send_message(CompositeMessage.DUNGEON_LEVEL_CHANGED) # if self.has_sibling("actor"): # self.value.add_actor_if_not_present(self.parent) # if self.has_sibling("is_dungeon_feature"): # self.value.add_dungeon_feature_if_not_present(self.parent) # # def on_parent_changed(self): # """ # When the parent changes try to add it to the dungeon. # """ # self._signal_dungeon_level_changed() # # Path: stats.py # def max_instances_of_composite_on_tile(composite): # return GamePieceTypes.MAX_INSTANCES_ON_TILE[composite.game_piece_type.value] # # class IntelligenceLevel(DataPoint): # MINDLESS = 0 # PLANT = 1 # ANIMAL = 2 # NORMAL = 3 # HIGH = 4 # # Path: statusflags.py # class StatusFlags(Leaf): # """ # Composites holding this has status flags, describing their behaviour. # """ # INVISIBILE = 0 # SEE_INVISIBILITY = 1 # FLYING = 2 # IS_ALIVE = 3 # CAN_OPEN_DOORS = 4 # HAS_HEART = 5 # # def __init__(self, status_flags=[]): # super(StatusFlags, self).__init__() # self.component_type = "status_flags" # self._status_flags = set(status_flags) # self._temp_status_flags = set() # # def has_status(self, status): # """ # Returns True if parent entity has the status given. # """ # if not self.next is None: # return (status in self._status_flags or # status in self._temp_status_flags or # next.has_status(status)) # else: # return (status in self._status_flags or # status in self._temp_status_flags) # # def add_temp_status(self, status): # """ # Adds a temporary status that will be removed the next tick. # """ # self._temp_status_flags.add(status) # # def before_tick(self, time): # self._temp_status_flags = set() , which may contain function names, class names, or code. Output only the next line.
if terrain_to_pass.has("is_chasm") and status_flags.has_status(StatusFlags.FLYING):
Predict the next line after this snippet: <|code_start|> self.game_state = game_state def get_dungeon_level(self, depth): if depth >= self.level_count: self.game_state.has_won = True return None while len(self._dungeon_levels) <= depth: self._dungeon_levels.append(self._generate_dungeon_level(len(self._dungeon_levels))) return self._dungeon_levels[depth] def __getstate__(self): return dict(self.__dict__) def __setstate__(self, state): self.__dict__.update(state) def _generate_dungeon_level(self, depth): self.game_state.draw_loading_screen("Generating Dungeon...") size = 600 + depth * 20 dungeon_level = time_it("dungeon_level_generation", (lambda: dungeongenerator.generate_dungeon_floor(size, depth))) minimum_monsters = int(4 + depth * 1.2) monsters_to_spawn = random.randrange(minimum_monsters, minimum_monsters + 3) monsters = from_table_pick_n_items_for_depth(dungeon_table, monsters_to_spawn, depth, self.game_state) print monsters for monster in monsters: sleep_chance = 0.25 if sleep_chance > random.random(): <|code_end|> using the current file's imports: import random import dungeongenerator import spawner from monsteractor import TryPutToSleep from monstertables import from_table_pick_n_items_for_depth, dungeon_table, dungeon_equipment_table, dungeon_usable_item_table from tools import time_it and any relevant context from other files: # Path: monsteractor.py # class TryPutToSleep(Leaf): # def __init__(self): # super(TryPutToSleep, self).__init__() # self.component_type = "try_put_to_sleep" # # def first_tick(self, time): # if self.parent_may_sleep(): # self.parent.set_child(SleepingEntity()) # self.parent.remove_component(self) # # def parent_may_sleep(self): # return self.parent.status_flags.has_status(StatusFlags.IS_ALIVE) # # Path: monstertables.py # class DungeonTableItem(object): # def __init__(self, creator): # def filter_monster_table_by_depth(table, depth): # def from_table_pick_n_items_for_depth(table, n, depth, game_state): # # Path: tools.py # def time_it(name, func): # start = time.clock() # result = func() # elapsed = time.clock() - start # print name + ": " + str(elapsed) # return result . Output only the next line.
monster.set_child(TryPutToSleep())
Here is a snippet: <|code_start|> class Dungeon(object): def __init__(self, game_state): self.level_count = 10 self._dungeon_levels = [None] self.game_state = game_state def get_dungeon_level(self, depth): if depth >= self.level_count: self.game_state.has_won = True return None while len(self._dungeon_levels) <= depth: self._dungeon_levels.append(self._generate_dungeon_level(len(self._dungeon_levels))) return self._dungeon_levels[depth] def __getstate__(self): return dict(self.__dict__) def __setstate__(self, state): self.__dict__.update(state) def _generate_dungeon_level(self, depth): self.game_state.draw_loading_screen("Generating Dungeon...") size = 600 + depth * 20 dungeon_level = time_it("dungeon_level_generation", (lambda: dungeongenerator.generate_dungeon_floor(size, depth))) minimum_monsters = int(4 + depth * 1.2) monsters_to_spawn = random.randrange(minimum_monsters, minimum_monsters + 3) <|code_end|> . Write the next line using the current file imports: import random import dungeongenerator import spawner from monsteractor import TryPutToSleep from monstertables import from_table_pick_n_items_for_depth, dungeon_table, dungeon_equipment_table, dungeon_usable_item_table from tools import time_it and context from other files: # Path: monsteractor.py # class TryPutToSleep(Leaf): # def __init__(self): # super(TryPutToSleep, self).__init__() # self.component_type = "try_put_to_sleep" # # def first_tick(self, time): # if self.parent_may_sleep(): # self.parent.set_child(SleepingEntity()) # self.parent.remove_component(self) # # def parent_may_sleep(self): # return self.parent.status_flags.has_status(StatusFlags.IS_ALIVE) # # Path: monstertables.py # class DungeonTableItem(object): # def __init__(self, creator): # def filter_monster_table_by_depth(table, depth): # def from_table_pick_n_items_for_depth(table, n, depth, game_state): # # Path: tools.py # def time_it(name, func): # start = time.clock() # result = func() # elapsed = time.clock() - start # print name + ": " + str(elapsed) # return result , which may include functions, classes, or code. Output only the next line.
monsters = from_table_pick_n_items_for_depth(dungeon_table, monsters_to_spawn,
Predict the next line after this snippet: <|code_start|> class Dungeon(object): def __init__(self, game_state): self.level_count = 10 self._dungeon_levels = [None] self.game_state = game_state def get_dungeon_level(self, depth): if depth >= self.level_count: self.game_state.has_won = True return None while len(self._dungeon_levels) <= depth: self._dungeon_levels.append(self._generate_dungeon_level(len(self._dungeon_levels))) return self._dungeon_levels[depth] def __getstate__(self): return dict(self.__dict__) def __setstate__(self, state): self.__dict__.update(state) def _generate_dungeon_level(self, depth): self.game_state.draw_loading_screen("Generating Dungeon...") size = 600 + depth * 20 dungeon_level = time_it("dungeon_level_generation", (lambda: dungeongenerator.generate_dungeon_floor(size, depth))) minimum_monsters = int(4 + depth * 1.2) monsters_to_spawn = random.randrange(minimum_monsters, minimum_monsters + 3) <|code_end|> using the current file's imports: import random import dungeongenerator import spawner from monsteractor import TryPutToSleep from monstertables import from_table_pick_n_items_for_depth, dungeon_table, dungeon_equipment_table, dungeon_usable_item_table from tools import time_it and any relevant context from other files: # Path: monsteractor.py # class TryPutToSleep(Leaf): # def __init__(self): # super(TryPutToSleep, self).__init__() # self.component_type = "try_put_to_sleep" # # def first_tick(self, time): # if self.parent_may_sleep(): # self.parent.set_child(SleepingEntity()) # self.parent.remove_component(self) # # def parent_may_sleep(self): # return self.parent.status_flags.has_status(StatusFlags.IS_ALIVE) # # Path: monstertables.py # class DungeonTableItem(object): # def __init__(self, creator): # def filter_monster_table_by_depth(table, depth): # def from_table_pick_n_items_for_depth(table, n, depth, game_state): # # Path: tools.py # def time_it(name, func): # start = time.clock() # result = func() # elapsed = time.clock() - start # print name + ": " + str(elapsed) # return result . Output only the next line.
monsters = from_table_pick_n_items_for_depth(dungeon_table, monsters_to_spawn,
Next line prediction: <|code_start|> self.game_state.draw_loading_screen("Generating Dungeon...") size = 600 + depth * 20 dungeon_level = time_it("dungeon_level_generation", (lambda: dungeongenerator.generate_dungeon_floor(size, depth))) minimum_monsters = int(4 + depth * 1.2) monsters_to_spawn = random.randrange(minimum_monsters, minimum_monsters + 3) monsters = from_table_pick_n_items_for_depth(dungeon_table, monsters_to_spawn, depth, self.game_state) print monsters for monster in monsters: sleep_chance = 0.25 if sleep_chance > random.random(): monster.set_child(TryPutToSleep()) spawner.place_piece_on_random_walkable_tile(monster, dungeon_level) if depth == (len(self._dungeon_levels) - 1): jericho = monster.new_jericho(self.game_state) spawner.place_piece_on_random_walkable_tile(jericho, dungeon_level) place_items_in_dungeon(dungeon_level, self.game_state) #dungeon_level.print_statistics() dungeon_level.dungeon = self return dungeon_level def place_items_in_dungeon(dungeon_level, game_state): spawner.place_health_potions(dungeon_level, game_state) <|code_end|> . Use current file imports: (import random import dungeongenerator import spawner from monsteractor import TryPutToSleep from monstertables import from_table_pick_n_items_for_depth, dungeon_table, dungeon_equipment_table, dungeon_usable_item_table from tools import time_it) and context including class names, function names, or small code snippets from other files: # Path: monsteractor.py # class TryPutToSleep(Leaf): # def __init__(self): # super(TryPutToSleep, self).__init__() # self.component_type = "try_put_to_sleep" # # def first_tick(self, time): # if self.parent_may_sleep(): # self.parent.set_child(SleepingEntity()) # self.parent.remove_component(self) # # def parent_may_sleep(self): # return self.parent.status_flags.has_status(StatusFlags.IS_ALIVE) # # Path: monstertables.py # class DungeonTableItem(object): # def __init__(self, creator): # def filter_monster_table_by_depth(table, depth): # def from_table_pick_n_items_for_depth(table, n, depth, game_state): # # Path: tools.py # def time_it(name, func): # start = time.clock() # result = func() # elapsed = time.clock() - start # print name + ": " + str(elapsed) # return result . Output only the next line.
equipments = from_table_pick_n_items_for_depth(dungeon_equipment_table,
Predict the next line for this snippet: <|code_start|> dungeon_level = time_it("dungeon_level_generation", (lambda: dungeongenerator.generate_dungeon_floor(size, depth))) minimum_monsters = int(4 + depth * 1.2) monsters_to_spawn = random.randrange(minimum_monsters, minimum_monsters + 3) monsters = from_table_pick_n_items_for_depth(dungeon_table, monsters_to_spawn, depth, self.game_state) print monsters for monster in monsters: sleep_chance = 0.25 if sleep_chance > random.random(): monster.set_child(TryPutToSleep()) spawner.place_piece_on_random_walkable_tile(monster, dungeon_level) if depth == (len(self._dungeon_levels) - 1): jericho = monster.new_jericho(self.game_state) spawner.place_piece_on_random_walkable_tile(jericho, dungeon_level) place_items_in_dungeon(dungeon_level, self.game_state) #dungeon_level.print_statistics() dungeon_level.dungeon = self return dungeon_level def place_items_in_dungeon(dungeon_level, game_state): spawner.place_health_potions(dungeon_level, game_state) equipments = from_table_pick_n_items_for_depth(dungeon_equipment_table, random.randrange(int(2 + dungeon_level.depth * 0.5)), dungeon_level.depth, game_state) <|code_end|> with the help of current file imports: import random import dungeongenerator import spawner from monsteractor import TryPutToSleep from monstertables import from_table_pick_n_items_for_depth, dungeon_table, dungeon_equipment_table, dungeon_usable_item_table from tools import time_it and context from other files: # Path: monsteractor.py # class TryPutToSleep(Leaf): # def __init__(self): # super(TryPutToSleep, self).__init__() # self.component_type = "try_put_to_sleep" # # def first_tick(self, time): # if self.parent_may_sleep(): # self.parent.set_child(SleepingEntity()) # self.parent.remove_component(self) # # def parent_may_sleep(self): # return self.parent.status_flags.has_status(StatusFlags.IS_ALIVE) # # Path: monstertables.py # class DungeonTableItem(object): # def __init__(self, creator): # def filter_monster_table_by_depth(table, depth): # def from_table_pick_n_items_for_depth(table, n, depth, game_state): # # Path: tools.py # def time_it(name, func): # start = time.clock() # result = func() # elapsed = time.clock() - start # print name + ": " + str(elapsed) # return result , which may contain function names, class names, or code. Output only the next line.
usable_items = from_table_pick_n_items_for_depth(dungeon_usable_item_table,
Based on the snippet: <|code_start|> class Dungeon(object): def __init__(self, game_state): self.level_count = 10 self._dungeon_levels = [None] self.game_state = game_state def get_dungeon_level(self, depth): if depth >= self.level_count: self.game_state.has_won = True return None while len(self._dungeon_levels) <= depth: self._dungeon_levels.append(self._generate_dungeon_level(len(self._dungeon_levels))) return self._dungeon_levels[depth] def __getstate__(self): return dict(self.__dict__) def __setstate__(self, state): self.__dict__.update(state) def _generate_dungeon_level(self, depth): self.game_state.draw_loading_screen("Generating Dungeon...") size = 600 + depth * 20 <|code_end|> , predict the immediate next line with the help of imports: import random import dungeongenerator import spawner from monsteractor import TryPutToSleep from monstertables import from_table_pick_n_items_for_depth, dungeon_table, dungeon_equipment_table, dungeon_usable_item_table from tools import time_it and context (classes, functions, sometimes code) from other files: # Path: monsteractor.py # class TryPutToSleep(Leaf): # def __init__(self): # super(TryPutToSleep, self).__init__() # self.component_type = "try_put_to_sleep" # # def first_tick(self, time): # if self.parent_may_sleep(): # self.parent.set_child(SleepingEntity()) # self.parent.remove_component(self) # # def parent_may_sleep(self): # return self.parent.status_flags.has_status(StatusFlags.IS_ALIVE) # # Path: monstertables.py # class DungeonTableItem(object): # def __init__(self, creator): # def filter_monster_table_by_depth(table, depth): # def from_table_pick_n_items_for_depth(table, n, depth, game_state): # # Path: tools.py # def time_it(name, func): # start = time.clock() # result = func() # elapsed = time.clock() - start # print name + ": " + str(elapsed) # return result . Output only the next line.
dungeon_level = time_it("dungeon_level_generation",
Given the code snippet: <|code_start|> class Tile(object): def __init__(self): self.game_pieces = { <|code_end|> , generate the next line using the imports in this file: import colors import compositecore import frame import terrain from graphic import CharPrinter from stats import GamePieceTypes, DataPoint, DataTypes and context (functions, classes, or occasionally code) from other files: # Path: graphic.py # class CharPrinter(Leaf): # def __init__(self): # super(CharPrinter, self).__init__() # self.component_type = "char_printer" # self._temp_animation_frames = [] # # def _tick_animation(self): # frame = None # if len(self._temp_animation_frames) > 0: # frame = self._temp_animation_frames.pop(0) # return frame # # def clear_animation(self): # self._temp_animation_frames = [] # # def draw(self, position, the_console=0): # """ # Draws the char on the given position on the console. # """ # animation_frame = self._tick_animation() # if animation_frame: # return draw_graphic_char_to_console(position, animation_frame, the_console) # draw_graphic_char_to_console(position, self.parent.graphic_char, the_console) # # def draw_unseen(self, screen_position, the_console=0): # """ # Draws the char as it looks like outside the field of view. # """ # self._tick_animation() # console.console.set_colors_and_symbol(screen_position, # colors.UNSEEN_FG, # colors.UNSEEN_BG, # self.parent.graphic_char.icon, # console=the_console) # def draw_unvisited(self, screen_position, the_console=0): # """ # Draws the char as it looks like outside the field of view. # """ # self._tick_animation() # console.console.set_colors_and_symbol(screen_position, # colors.DARK_PURPLE, # colors.UNSEEN_BG, # self.parent.graphic_char.icon, # console=the_console) # # def append_graphic_char_temporary_frames(self, graphic_char_frames, animation_delay=settings.ANIMATION_DELAY): # """ # Appends frames to the graphic char animation frame queue. # # These chars will be drawn as an effect, # the regular chars won't be drawn until the animation frame queue is empty. # """ # frames = _expand_frames(graphic_char_frames, animation_delay) # self._temp_animation_frames.extend(frames) # # def append_fg_color_blink_frames(self, frame_colors, animation_delay=settings.ANIMATION_DELAY): # """ # Appends frames to the graphic char animation frame queue. With only fg_color changed. # # These chars will be drawn as an effect, # the regular chars won't be drawn until the animation frame queue is empty. # """ # color_bg = self.parent.graphic_char.color_bg # symbol = self.parent.graphic_char.icon # frames = [GraphicChar(color_bg, color, symbol) for color in frame_colors] # self.append_graphic_char_temporary_frames(frames, animation_delay) # # def append_default_graphic_frame(self, frames=settings.ANIMATION_DELAY): # self.append_graphic_char_temporary_frames([self.parent.graphic_char], frames) # # def copy(self): # """ # Makes a copy of this component. # """ # copy = CharPrinter() # copy._temp_animation_frames = self._temp_animation_frames # return copy # # Path: stats.py # class GamePieceTypes(DataPoint): # ENTITY = 0 # CLOUD = 1 # ITEM = 2 # DUNGEON_FEATURE = 3 # DUNGEON_TRASH = 4 # TERRAIN = 5 # # MAX_INSTANCES_ON_TILE = {ENTITY: 1, # CLOUD: 1, # ITEM: 1, # DUNGEON_FEATURE: 1, # DUNGEON_TRASH: 1, # TERRAIN: 1} # # class DataPoint(Leaf): # """ # Class for components holding a single data point. # """ # def __init__(self, component_type, value, tags=[]): # super(DataPoint, self).__init__() # self.tags |= set(tags) # self.component_type = component_type # self.value = value # # class DataTypes: # CLASS = "job" # RACE = "race" # # ENERGY = "energy" # CRIT_MULTIPLIER = "crit_multiplier" # UNARMED_CRIT_CHANCE = "unarmed_crit_chance" # CRIT_CHANCE = "crit_chance" # CRIT_CHANCE_WEAPON = "crit_chance_weapon_effect" # STRENGTH = "strength" # ARMOR = "armor" # ACCURACY = "accuracy" # DAMAGE = "damage" # STEALTH = "stealth" # AWARENESS = "awareness" # EVASION = "evasion" # # COUNTER_ATTACK_CHANCE = "counter_attack_chance" # OFFENCIVE_ATTACK_CHANCE = "offencive_attack_chance" # DEFENCIVE_ATTACK_CHANCE = "defencive_attack_chance" # # MELEE_SPEED = "melee_speed" # SHOOT_SPEED = "shoot_speed" # THROW_SPEED = "throw_speed" # THROW_ITEM_SPEED = "throw_item_speed" # CAST_SPEED = "cast_speed" # # MELEE_DAMAGE_MULTIPLIER = "melee_damage_multiplier" # THROW_DAMAGE_MULTIPLIER = "throw_damage_multiplier" # # INTELLIGENCE = "intelligence" # GAME_PIECE_TYPE = "game_piece_type" # MOVEMENT_SPEED = "movement_speed" # FACTION = "faction" # # WEIGHT = "weight" # WEAPON_RANGE = "weapon_range" # # SIGHT_RADIUS = "sight_radius" # SKIP_ACTION_CHANCE = "skip_action_chance" # # DENSITY = "density" # CLOUD_TYPE = "cloud_type" # CLONE_FUNCTION = "clone_function" # # MINIMUM_DEPTH = "minimum_depth" # # GAME_STATE = "game_state" . Output only the next line.
GamePieceTypes.ENTITY: [],
Predict the next line for this snippet: <|code_start|> __author__ = 'co' def load_first_game(): save_file = open(get_save_files()[0], 'rb') print save_file <|code_end|> with the help of current file imports: import cPickle as pickle import os from genericpath import isfile from os import getcwd, listdir from tools import time_it and context from other files: # Path: tools.py # def time_it(name, func): # start = time.clock() # result = func() # elapsed = time.clock() - start # print name + ": " + str(elapsed) # return result , which may contain function names, class names, or code. Output only the next line.
game_state = time_it("load", (lambda: pickle.load(save_file)))
Predict the next line for this snippet: <|code_start|> def _get_walkable_neighbors(entity, position, dungeon_level): result_positions = [] for direction_ in direction.DIRECTIONS: neighbor_position = geo.add_2d(position, direction_) try: neighbor = dungeon_level.get_tile(neighbor_position) if entity.mover.can_pass_terrain(neighbor.get_terrain()): result_positions.append(neighbor_position) except IndexError: pass return result_positions def _get_walkable_neighbors_or_unseen(position, entity, dungeon_level): result_positions = [] for direction_ in direction.DIRECTIONS: neighbor_position = geo.add_2d(position, direction_) try: neighbor = dungeon_level.get_tile(neighbor_position) if (entity.mover.can_pass_terrain(neighbor.get_terrain()) or not entity.memory_map.has_seen_position(neighbor_position)): result_positions.append(neighbor_position) except IndexError: pass return result_positions def entity_skip_turn(source_entity, target_entity): <|code_end|> with the help of current file imports: from actor import DoNothingActor, StunnedActor from entityeffect import AddSpoofChild from mover import ImmobileStepper import gametime import libtcodpy as libtcod import turn import direction import geometry as geo and context from other files: # Path: actor.py # class DoNothingActor(Actor): # """ # Entities with this actor will do nothing. # """ # def __init__(self): # super(DoNothingActor, self).__init__() # # def act(self): # """ # Just returns energy spent, nothing is done. # """ # return gametime.single_turn # # class StunnedActor(Actor): # """ # Entities with this actor will do nothing. # """ # def __init__(self): # super(StunnedActor, self).__init__() # # def on_tick(self, time): # if self.parent.has("status_bar"): # self.parent.status_bar.add(Status.STUNNED_STATUS_DESCRIPTION) # # def act(self): # """ # Just returns energy spent, shows it's stunned. # """ # self.parent.char_printer.append_fg_color_blink_frames([colors.CHAMPAGNE]) # return gametime.single_turn # # Path: entityeffect.py # class AddSpoofChild(EntityEffect): # def __init__(self, source_entity, spoof_child, time_to_live, message_effect=None, meld_id=None, effect_id=None, # status_description=None): # super(AddSpoofChild, self).__init__(source_entity=source_entity, # effect_type=EffectTypes.ADD_SPOOF_CHILD, # time_to_live=time_to_live, # meld_id=meld_id, # effect_id=effect_id) # self.status_description = status_description # self.message_effect = message_effect # self.spoof_child = spoof_child # # def update(self, time_spent): # self.target_entity.add_spoof_child(self.spoof_child) # if self.message_effect: # self.message() # self.update_status_icon() # self.tick(time_spent) # # def update_status_icon(self): # if self.status_description and self.target_entity.has("status_bar"): # self.target_entity.status_bar.add(self.status_description) # # def message(self): # messenger.msg.send_visual_message( # self.message_effect % {"source_entity": self.source_entity.description.long_name, # "target_entity": self.target_entity.description.long_name}, # self.target_entity.position.value) # # Path: mover.py # class ImmobileStepper(Stepper): # def __init__(self): # super(ImmobileStepper, self).__init__() # self.component_type = "stepper" # # def try_move_or_bump(self, position): # return self.parent.movement_speed.value , which may contain function names, class names, or code. Output only the next line.
add_spoof_effect = AddSpoofChild(source_entity, DoNothingActor(), gametime.single_turn)
Continue the code snippet: <|code_start|> neighbor_position = geo.add_2d(position, direction_) try: neighbor = dungeon_level.get_tile(neighbor_position) if entity.mover.can_pass_terrain(neighbor.get_terrain()): result_positions.append(neighbor_position) except IndexError: pass return result_positions def _get_walkable_neighbors_or_unseen(position, entity, dungeon_level): result_positions = [] for direction_ in direction.DIRECTIONS: neighbor_position = geo.add_2d(position, direction_) try: neighbor = dungeon_level.get_tile(neighbor_position) if (entity.mover.can_pass_terrain(neighbor.get_terrain()) or not entity.memory_map.has_seen_position(neighbor_position)): result_positions.append(neighbor_position) except IndexError: pass return result_positions def entity_skip_turn(source_entity, target_entity): add_spoof_effect = AddSpoofChild(source_entity, DoNothingActor(), gametime.single_turn) target_entity.effect_queue.add(add_spoof_effect) def entity_stunned_turn(source_entity, target_entity): <|code_end|> . Use current file imports: from actor import DoNothingActor, StunnedActor from entityeffect import AddSpoofChild from mover import ImmobileStepper import gametime import libtcodpy as libtcod import turn import direction import geometry as geo and context (classes, functions, or code) from other files: # Path: actor.py # class DoNothingActor(Actor): # """ # Entities with this actor will do nothing. # """ # def __init__(self): # super(DoNothingActor, self).__init__() # # def act(self): # """ # Just returns energy spent, nothing is done. # """ # return gametime.single_turn # # class StunnedActor(Actor): # """ # Entities with this actor will do nothing. # """ # def __init__(self): # super(StunnedActor, self).__init__() # # def on_tick(self, time): # if self.parent.has("status_bar"): # self.parent.status_bar.add(Status.STUNNED_STATUS_DESCRIPTION) # # def act(self): # """ # Just returns energy spent, shows it's stunned. # """ # self.parent.char_printer.append_fg_color_blink_frames([colors.CHAMPAGNE]) # return gametime.single_turn # # Path: entityeffect.py # class AddSpoofChild(EntityEffect): # def __init__(self, source_entity, spoof_child, time_to_live, message_effect=None, meld_id=None, effect_id=None, # status_description=None): # super(AddSpoofChild, self).__init__(source_entity=source_entity, # effect_type=EffectTypes.ADD_SPOOF_CHILD, # time_to_live=time_to_live, # meld_id=meld_id, # effect_id=effect_id) # self.status_description = status_description # self.message_effect = message_effect # self.spoof_child = spoof_child # # def update(self, time_spent): # self.target_entity.add_spoof_child(self.spoof_child) # if self.message_effect: # self.message() # self.update_status_icon() # self.tick(time_spent) # # def update_status_icon(self): # if self.status_description and self.target_entity.has("status_bar"): # self.target_entity.status_bar.add(self.status_description) # # def message(self): # messenger.msg.send_visual_message( # self.message_effect % {"source_entity": self.source_entity.description.long_name, # "target_entity": self.target_entity.description.long_name}, # self.target_entity.position.value) # # Path: mover.py # class ImmobileStepper(Stepper): # def __init__(self): # super(ImmobileStepper, self).__init__() # self.component_type = "stepper" # # def try_move_or_bump(self, position): # return self.parent.movement_speed.value . Output only the next line.
add_spoof_effect = AddSpoofChild(source_entity, StunnedActor(), gametime.single_turn)
Predict the next line for this snippet: <|code_start|> def _get_walkable_neighbors(entity, position, dungeon_level): result_positions = [] for direction_ in direction.DIRECTIONS: neighbor_position = geo.add_2d(position, direction_) try: neighbor = dungeon_level.get_tile(neighbor_position) if entity.mover.can_pass_terrain(neighbor.get_terrain()): result_positions.append(neighbor_position) except IndexError: pass return result_positions def _get_walkable_neighbors_or_unseen(position, entity, dungeon_level): result_positions = [] for direction_ in direction.DIRECTIONS: neighbor_position = geo.add_2d(position, direction_) try: neighbor = dungeon_level.get_tile(neighbor_position) if (entity.mover.can_pass_terrain(neighbor.get_terrain()) or not entity.memory_map.has_seen_position(neighbor_position)): result_positions.append(neighbor_position) except IndexError: pass return result_positions def entity_skip_turn(source_entity, target_entity): <|code_end|> with the help of current file imports: from actor import DoNothingActor, StunnedActor from entityeffect import AddSpoofChild from mover import ImmobileStepper import gametime import libtcodpy as libtcod import turn import direction import geometry as geo and context from other files: # Path: actor.py # class DoNothingActor(Actor): # """ # Entities with this actor will do nothing. # """ # def __init__(self): # super(DoNothingActor, self).__init__() # # def act(self): # """ # Just returns energy spent, nothing is done. # """ # return gametime.single_turn # # class StunnedActor(Actor): # """ # Entities with this actor will do nothing. # """ # def __init__(self): # super(StunnedActor, self).__init__() # # def on_tick(self, time): # if self.parent.has("status_bar"): # self.parent.status_bar.add(Status.STUNNED_STATUS_DESCRIPTION) # # def act(self): # """ # Just returns energy spent, shows it's stunned. # """ # self.parent.char_printer.append_fg_color_blink_frames([colors.CHAMPAGNE]) # return gametime.single_turn # # Path: entityeffect.py # class AddSpoofChild(EntityEffect): # def __init__(self, source_entity, spoof_child, time_to_live, message_effect=None, meld_id=None, effect_id=None, # status_description=None): # super(AddSpoofChild, self).__init__(source_entity=source_entity, # effect_type=EffectTypes.ADD_SPOOF_CHILD, # time_to_live=time_to_live, # meld_id=meld_id, # effect_id=effect_id) # self.status_description = status_description # self.message_effect = message_effect # self.spoof_child = spoof_child # # def update(self, time_spent): # self.target_entity.add_spoof_child(self.spoof_child) # if self.message_effect: # self.message() # self.update_status_icon() # self.tick(time_spent) # # def update_status_icon(self): # if self.status_description and self.target_entity.has("status_bar"): # self.target_entity.status_bar.add(self.status_description) # # def message(self): # messenger.msg.send_visual_message( # self.message_effect % {"source_entity": self.source_entity.description.long_name, # "target_entity": self.target_entity.description.long_name}, # self.target_entity.position.value) # # Path: mover.py # class ImmobileStepper(Stepper): # def __init__(self): # super(ImmobileStepper, self).__init__() # self.component_type = "stepper" # # def try_move_or_bump(self, position): # return self.parent.movement_speed.value , which may contain function names, class names, or code. Output only the next line.
add_spoof_effect = AddSpoofChild(source_entity, DoNothingActor(), gametime.single_turn)
Based on the snippet: <|code_start|> except IndexError: pass return result_positions def _get_walkable_neighbors_or_unseen(position, entity, dungeon_level): result_positions = [] for direction_ in direction.DIRECTIONS: neighbor_position = geo.add_2d(position, direction_) try: neighbor = dungeon_level.get_tile(neighbor_position) if (entity.mover.can_pass_terrain(neighbor.get_terrain()) or not entity.memory_map.has_seen_position(neighbor_position)): result_positions.append(neighbor_position) except IndexError: pass return result_positions def entity_skip_turn(source_entity, target_entity): add_spoof_effect = AddSpoofChild(source_entity, DoNothingActor(), gametime.single_turn) target_entity.effect_queue.add(add_spoof_effect) def entity_stunned_turn(source_entity, target_entity): add_spoof_effect = AddSpoofChild(source_entity, StunnedActor(), gametime.single_turn) target_entity.effect_queue.add(add_spoof_effect) def entity_skip_step(source_entity, target_entity): <|code_end|> , predict the immediate next line with the help of imports: from actor import DoNothingActor, StunnedActor from entityeffect import AddSpoofChild from mover import ImmobileStepper import gametime import libtcodpy as libtcod import turn import direction import geometry as geo and context (classes, functions, sometimes code) from other files: # Path: actor.py # class DoNothingActor(Actor): # """ # Entities with this actor will do nothing. # """ # def __init__(self): # super(DoNothingActor, self).__init__() # # def act(self): # """ # Just returns energy spent, nothing is done. # """ # return gametime.single_turn # # class StunnedActor(Actor): # """ # Entities with this actor will do nothing. # """ # def __init__(self): # super(StunnedActor, self).__init__() # # def on_tick(self, time): # if self.parent.has("status_bar"): # self.parent.status_bar.add(Status.STUNNED_STATUS_DESCRIPTION) # # def act(self): # """ # Just returns energy spent, shows it's stunned. # """ # self.parent.char_printer.append_fg_color_blink_frames([colors.CHAMPAGNE]) # return gametime.single_turn # # Path: entityeffect.py # class AddSpoofChild(EntityEffect): # def __init__(self, source_entity, spoof_child, time_to_live, message_effect=None, meld_id=None, effect_id=None, # status_description=None): # super(AddSpoofChild, self).__init__(source_entity=source_entity, # effect_type=EffectTypes.ADD_SPOOF_CHILD, # time_to_live=time_to_live, # meld_id=meld_id, # effect_id=effect_id) # self.status_description = status_description # self.message_effect = message_effect # self.spoof_child = spoof_child # # def update(self, time_spent): # self.target_entity.add_spoof_child(self.spoof_child) # if self.message_effect: # self.message() # self.update_status_icon() # self.tick(time_spent) # # def update_status_icon(self): # if self.status_description and self.target_entity.has("status_bar"): # self.target_entity.status_bar.add(self.status_description) # # def message(self): # messenger.msg.send_visual_message( # self.message_effect % {"source_entity": self.source_entity.description.long_name, # "target_entity": self.target_entity.description.long_name}, # self.target_entity.position.value) # # Path: mover.py # class ImmobileStepper(Stepper): # def __init__(self): # super(ImmobileStepper, self).__init__() # self.component_type = "stepper" # # def try_move_or_bump(self, position): # return self.parent.movement_speed.value . Output only the next line.
add_spoof_effect = AddSpoofChild(source_entity, ImmobileStepper(), gametime.single_turn)
Using the snippet: <|code_start|> class StatusDescription(object): def __init__(self, name, graphic_char, description): self.graphic_char = graphic_char self.name = name self.description = description <|code_end|> , determine the next line of code. You have imports: import colors import icon from compositecore import Leaf from graphic import GraphicChar and context (class names, function names, or code) available: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) . Output only the next line.
class StatusDescriptionBar(Leaf):
Using the snippet: <|code_start|> class StatusDescription(object): def __init__(self, name, graphic_char, description): self.graphic_char = graphic_char self.name = name self.description = description class StatusDescriptionBar(Leaf): def __init__(self): super(StatusDescriptionBar, self).__init__() self.component_type = "status_bar" self.statuses = [] def clear(self): self.statuses = [] def add(self, status_icon): self.statuses.append(status_icon) def first_tick(self, time): self.clear() <|code_end|> , determine the next line of code. You have imports: import colors import icon from compositecore import Leaf from graphic import GraphicChar and context (class names, function names, or code) available: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) . Output only the next line.
FIRE_STATUS_DESCRIPTION = StatusDescription("Fire", GraphicChar(None, colors.RED, icon.FIRE), "You are standing in flames, taking heavy fire damage each turn spent in the flames.")
Given the code snippet: <|code_start|> __author__ = 'co' STEP_NEXT_TO_ENEMY_TRIGGER_TAG = "step_next_to_enemy_trigger" ENEMY_STEPPING_NEXT_TO_ME_TRIGGER_TAG = "enemy_stepping_next_to_me_trigger" ON_ATTACKED_TRIGGER_TAG = "on_attacked_trigger" <|code_end|> , generate the next line using the imports in this file: from compositecore import Leaf and context (functions, classes, or occasionally code) from other files: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) . Output only the next line.
class Trigger(Leaf):
Given the code snippet: <|code_start|> class InstantAnimation(object): def __init__(self, game_state): self.game_state = game_state def run_animation(self): pass class MissileAnimation(InstantAnimation): def __init__(self, game_state, symbol, color_fg, path): super(MissileAnimation, self).__init__(game_state) self.symbol = symbol self.color_fg = color_fg self.path = path self.camera = game_state.camera self.player = game_state.player def run_animation(self): for point in self.path: if not self.player.dungeon_mask.can_see_point(point): continue self.game_state.prepare_draw() self.draw_missile_at_point(point) for _ in range(settings.MISSILE_ANIMATION_DELAY): <|code_end|> , generate the next line using the imports in this file: from console import console from graphic import GraphicChar import icon import settings and context (functions, classes, or occasionally code) from other files: # Path: console.py # class ConsoleVisual(object): # def __init__(self, width, height): # def get_color_fg(self, position): # def get_color_bg(self, position): # def get_symbol(self, position): # def get_default_color_fg(self): # def get_default_color_bg(self): # def set_default_color_fg(self, color, console=0): # def set_default_color_bg(self, color, console=0): # def set_symbol(self, position, icon, console=0): # def set_color_fg(self, position, color, console=0): # def set_color_bg(self, position, color, effect=libtcod.BKGND_SET, console=0): # def print_text(self, position, text): # def print_text_vertical(self, position, text): # def set_colors_and_symbol(self, position, color_fg, color_bg, icon, console=0): # def print_char_big(self, icon_position, destination, console=0): # def flush(self): # def print_screen(self): # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) . Output only the next line.
console.flush()
Predict the next line for this snippet: <|code_start|> console.flush() def draw_missile_at_point(self, point): x, y = self.camera.dungeon_to_screen_position(point) console.set_color_fg((x, y), self.color_fg) console.set_symbol((x, y), self.symbol) def animate_flight(game_state, path, symbol_char, color_fg): flight_animation = MissileAnimation(game_state, symbol_char, color_fg, path) flight_animation.run_animation() def animate_point(game_state, position, graphic_chars): if not game_state.player.dungeon_mask.can_see_point(position): return camera = game_state.camera x, y = camera.dungeon_to_screen_position(position) for graphic_char in graphic_chars: game_state.prepare_draw() console.set_color_fg((x, y), graphic_char.color_fg) console.set_symbol((x, y), graphic_char.icon) for _ in range(settings.MISSILE_ANIMATION_DELAY): console.flush() def animate_fall_sync(target_entity): color_fg = target_entity.graphic_char.color_fg target_entity.game_state.value.force_draw() graphic_chars = [target_entity.graphic_char, <|code_end|> with the help of current file imports: from console import console from graphic import GraphicChar import icon import settings and context from other files: # Path: console.py # class ConsoleVisual(object): # def __init__(self, width, height): # def get_color_fg(self, position): # def get_color_bg(self, position): # def get_symbol(self, position): # def get_default_color_fg(self): # def get_default_color_bg(self): # def set_default_color_fg(self, color, console=0): # def set_default_color_bg(self, color, console=0): # def set_symbol(self, position, icon, console=0): # def set_color_fg(self, position, color, console=0): # def set_color_bg(self, position, color, effect=libtcod.BKGND_SET, console=0): # def print_text(self, position, text): # def print_text_vertical(self, position, text): # def set_colors_and_symbol(self, position, color_fg, color_bg, icon, console=0): # def print_char_big(self, icon_position, destination, console=0): # def flush(self): # def print_screen(self): # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) , which may contain function names, class names, or code. Output only the next line.
GraphicChar(None, color_fg, icon.BIG_CENTER_DOT),
Next line prediction: <|code_start|> if key in inputhandler.move_controls: dx, dy = inputhandler.move_controls[key] self.offset_cursor_position((dx * step_size, dy * step_size)) elif key in inputhandler.vi_move_controls: dx, dy = inputhandler.vi_move_controls[key] self.offset_cursor_position((dx * step_size, dy * step_size)) def offset_cursor_position(self, offset): old_x, old_y = self.cursor_position[0], self.cursor_position[1] new_x = min_max(old_x + offset[0], self.start_position[0] - self.max_distance, self.start_position[0] + self.max_distance) new_y = min_max(old_y + offset[1], self.start_position[1] - self.max_distance, self.start_position[1] + self.max_distance) self.cursor_position = (new_x, new_y) def _handle_escape(self, key): if key == inputhandler.ESCAPE: self._exit() def _handle_enter(self, key): if key == inputhandler.ENTER: self._exit() def _handle_tab(self, key): pass def _draw_background(self): if not self._background_state is None: self._background_state.prepare_draw() def _draw_cursor(self): position = self.camera.dungeon_to_screen_position(self.cursor_position) <|code_end|> . Use current file imports: (import geometry as geo import gui import icon import libtcodpy as libtcod import colors import inputhandler import settings import state from console import console) and context including class names, function names, or small code snippets from other files: # Path: console.py # class ConsoleVisual(object): # def __init__(self, width, height): # def get_color_fg(self, position): # def get_color_bg(self, position): # def get_symbol(self, position): # def get_default_color_fg(self): # def get_default_color_bg(self): # def set_default_color_fg(self, color, console=0): # def set_default_color_bg(self, color, console=0): # def set_symbol(self, position, icon, console=0): # def set_color_fg(self, position, color, console=0): # def set_color_bg(self, position, color, effect=libtcod.BKGND_SET, console=0): # def print_text(self, position, text): # def print_text_vertical(self, position, text): # def set_colors_and_symbol(self, position, color_fg, color_bg, icon, console=0): # def print_char_big(self, icon_position, destination, console=0): # def flush(self): # def print_screen(self): . Output only the next line.
console.set_symbol(position, self.cursor_symbol)
Using the snippet: <|code_start|> elif len(self._dirty_point_list) > 0: for point in self._dirty_point_list: x, y = point self.update_dungeon_map_point(x, y) self._dirty_point_list = [] self.update_fov() def update_dungeon_map_point(self, x, y): dungeon_level = self.parent.dungeon_level.value terrain = dungeon_level.get_tile_or_unknown((x, y)).get_terrain() dungeon_feature = dungeon_level.get_tile_or_unknown((x, y)).get_dungeon_feature() is_opaque = terrain.has("is_opaque") or (dungeon_feature and dungeon_feature.has("is_opaque")) libtcod.map_set_properties(self.dungeon_map, x, y, 0 if is_opaque else 1, self.parent.mover.can_pass_terrain(terrain)) def update_dungeon_map(self): """ Updates the dungeon map. """ dungeon_level = self.parent.dungeon_level.value for y in range(dungeon_level.height): for x in range(dungeon_level.width): self.update_dungeon_map_point(x, y) self.dungeon_map_needs_total_update = False self._dirty_point_list = [] def send_message(self, message): """ Handles received messages. """ <|code_end|> , determine the next line of code. You have imports: import random import time import colors import direction import geometry import icon import libtcodpy as libtcod import turn from compositecore import Leaf, CompositeMessage from console import console and context (class names, function names, or code) available: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # class CompositeMessage(object): # """ # Enumerator defining class. Defines all messages that may be sent. # """ # DUNGEON_LEVEL_CHANGED = 0 # POSITION_CHANGED = 1 # # def __init__(self): # """ # Should not be initiated. # """ # raise # # Path: console.py # class ConsoleVisual(object): # def __init__(self, width, height): # def get_color_fg(self, position): # def get_color_bg(self, position): # def get_symbol(self, position): # def get_default_color_fg(self): # def get_default_color_bg(self): # def set_default_color_fg(self, color, console=0): # def set_default_color_bg(self, color, console=0): # def set_symbol(self, position, icon, console=0): # def set_color_fg(self, position, color, console=0): # def set_color_bg(self, position, color, effect=libtcod.BKGND_SET, console=0): # def print_text(self, position, text): # def print_text_vertical(self, position, text): # def set_colors_and_symbol(self, position, color_fg, color_bg, icon, console=0): # def print_char_big(self, icon_position, destination, console=0): # def flush(self): # def print_screen(self): . Output only the next line.
if message == CompositeMessage.DUNGEON_LEVEL_CHANGED:
Here is a snippet: <|code_start|> sx, sy = self.parent.position.value dx, dy = destination libtcod.path_compute(self.path, sx, sy, dx, dy) self.clear() x, y = libtcod.path_walk(self.path, True) while not x is None: self.position_list.insert(0, (x, y)) x, y = libtcod.path_walk(self.path, True) def set_line_path(self, destination): sx, sy = self.parent.position.value dx, dy = destination libtcod.line_init(sx, sy, dx, dy) self.clear() x, y = libtcod.line_step() while not x is None: self.position_list.insert(0, (x, y)) x, y = libtcod.line_step() def clear(self): self.position_list = [] def draw(self, camera): points = list(self.position_list) points.reverse() point = None for point in points: if not self.parent.mover.can_pass_terrain( self.parent.dungeon_level.value.get_tile_or_unknown(point).get_terrain()): break <|code_end|> . Write the next line using the current file imports: import random import time import colors import direction import geometry import icon import libtcodpy as libtcod import turn from compositecore import Leaf, CompositeMessage from console import console and context from other files: # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # class CompositeMessage(object): # """ # Enumerator defining class. Defines all messages that may be sent. # """ # DUNGEON_LEVEL_CHANGED = 0 # POSITION_CHANGED = 1 # # def __init__(self): # """ # Should not be initiated. # """ # raise # # Path: console.py # class ConsoleVisual(object): # def __init__(self, width, height): # def get_color_fg(self, position): # def get_color_bg(self, position): # def get_symbol(self, position): # def get_default_color_fg(self): # def get_default_color_bg(self): # def set_default_color_fg(self, color, console=0): # def set_default_color_bg(self, color, console=0): # def set_symbol(self, position, icon, console=0): # def set_color_fg(self, position, color, console=0): # def set_color_bg(self, position, color, effect=libtcod.BKGND_SET, console=0): # def print_text(self, position, text): # def print_text_vertical(self, position, text): # def set_colors_and_symbol(self, position, color_fg, color_bg, icon, console=0): # def print_char_big(self, icon_position, destination, console=0): # def flush(self): # def print_screen(self): , which may include functions, classes, or code. Output only the next line.
console.set_symbol(camera.dungeon_to_screen_position(point), icon.FOOT_STEPS)
Here is a snippet: <|code_start|> class HealthModifier(Leaf): def __init__(self): super(HealthModifier, self).__init__() self.component_type = "health_modifier" def hurt(self, damage, entity=None, damage_types=[]): """ Damages the entity by reducing hp by damage. """ if damage == 0 and rng.coin_flip(): damage = 1 # You should never be completely safe if damage == 0: return damage self.parent.health.hp.decrease(damage) self._animate_hurt(damage_types) if self.parent.health.is_dead(): self.parent.health.killer = entity self._call_damage_taken_effect(damage, entity, damage_types) return damage def _animate_hurt(self, damage_types): """ Adds a blink animation to hurt entity. """ frame_length = max(settings.ANIMATION_DELAY / 2, 1) hurt_colors = self._get_hurt_colors(damage_types) self.parent.char_printer.append_fg_color_blink_frames(hurt_colors, frame_length) def _get_hurt_colors(self, damage_types): <|code_end|> . Write the next line using the current file imports: import logging import counter import colors import entityeffect import geometry import icon import rng import settings import shapegenerator from attacker import DamageTypes from compositecore import Leaf from dungeontrash import PoolOfBlood from graphic import GraphicChar from messenger import NO_LONGER_PARALYZED_MESSAGE and context from other files: # Path: attacker.py # class DamageTypes(object): # PHYSICAL = "physical_damage_type" # MAGIC = "magic_damage_type" # BLUNT = "blunt_damage_type" # PIERCING = "piercing_damage_type" # CUTTING = "cutting_damage_type" # BLEED = "bleed_damage_type" # ACID = "acid_damage_type" # POISON = "poison_damage_type" # LIGHTNING = "lightning_damage_type" # FIRE = "fire_damage_type" # REFLECT = "reflect_damage_type" # # IGNORE_ARMOR = "ignore_armor_damage_type" # # FALL = "fall_damage_type" # # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: dungeontrash.py # class PoolOfBlood(Composite): # """ # A pool of blood. Totally useless but looks nice # and gives the user feedback when a monster is hurt. # """ # def __init__(self): # super(PoolOfBlood, self).__init__() # self.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.DUNGEON_TRASH)) # self.set_child(Position()) # self.set_child(DungeonLevel()) # self.set_child(Description("A pool of blood.", "A pool of blood.")) # self.set_child(GraphicChar(None, colors.RED, random.choice(icon.BLOOD_ICONS))) # self.set_child(CharPrinter()) # self.set_child(Mover()) # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) # # Path: messenger.py # NO_LONGER_PARALYZED_MESSAGE = "%(source_entity)s is no longer paralyzed." , which may include functions, classes, or code. Output only the next line.
if DamageTypes.POISON in damage_types:
Given the code snippet: <|code_start|> point_behind = self._get_point_behind_unless_solid(source_entity.position.value, 1, dungeon_level) shape = shapegenerator.random_explosion_not_through_solid(point_behind, 2, dungeon_level) for point in shape: self.put_blood_on_tile(dungeon_level, point) if damage / float(self.parent.health.hp.max_value) > 0.8: point_behind = self._get_point_behind_unless_solid(source_entity.position.value, 2, dungeon_level) shape = shapegenerator.random_explosion_not_through_solid(point_behind, min(damage / 2, 7), dungeon_level) for point in shape: self.put_blood_on_tile(dungeon_level, point) def _get_point_behind_unless_solid(self, enemy_position, distance, dungeon_level): """ Gets point right behind me seen from my enemy. """ right_behind_direction = geometry.other_side_of_point_direction(enemy_position, self.parent.position.value) last_result = self.parent.position.value for _ in range(distance): result = geometry.add_2d(right_behind_direction, last_result) if position_is_solid(result, dungeon_level): return last_result last_result = result return result def position_is_solid(position, dungeon_level): return dungeon_level.get_tile_or_unknown(position).get_terrain().has("is_solid") def spawn_blood_on_position(position, dungeon_level): <|code_end|> , generate the next line using the imports in this file: import logging import counter import colors import entityeffect import geometry import icon import rng import settings import shapegenerator from attacker import DamageTypes from compositecore import Leaf from dungeontrash import PoolOfBlood from graphic import GraphicChar from messenger import NO_LONGER_PARALYZED_MESSAGE and context (functions, classes, or occasionally code) from other files: # Path: attacker.py # class DamageTypes(object): # PHYSICAL = "physical_damage_type" # MAGIC = "magic_damage_type" # BLUNT = "blunt_damage_type" # PIERCING = "piercing_damage_type" # CUTTING = "cutting_damage_type" # BLEED = "bleed_damage_type" # ACID = "acid_damage_type" # POISON = "poison_damage_type" # LIGHTNING = "lightning_damage_type" # FIRE = "fire_damage_type" # REFLECT = "reflect_damage_type" # # IGNORE_ARMOR = "ignore_armor_damage_type" # # FALL = "fall_damage_type" # # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: dungeontrash.py # class PoolOfBlood(Composite): # """ # A pool of blood. Totally useless but looks nice # and gives the user feedback when a monster is hurt. # """ # def __init__(self): # super(PoolOfBlood, self).__init__() # self.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.DUNGEON_TRASH)) # self.set_child(Position()) # self.set_child(DungeonLevel()) # self.set_child(Description("A pool of blood.", "A pool of blood.")) # self.set_child(GraphicChar(None, colors.RED, random.choice(icon.BLOOD_ICONS))) # self.set_child(CharPrinter()) # self.set_child(Mover()) # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) # # Path: messenger.py # NO_LONGER_PARALYZED_MESSAGE = "%(source_entity)s is no longer paralyzed." . Output only the next line.
corpse = PoolOfBlood()
Here is a snippet: <|code_start|> self.parent.health.hp.decrease(damage) self._animate_hurt(damage_types) if self.parent.health.is_dead(): self.parent.health.killer = entity self._call_damage_taken_effect(damage, entity, damage_types) return damage def _animate_hurt(self, damage_types): """ Adds a blink animation to hurt entity. """ frame_length = max(settings.ANIMATION_DELAY / 2, 1) hurt_colors = self._get_hurt_colors(damage_types) self.parent.char_printer.append_fg_color_blink_frames(hurt_colors, frame_length) def _get_hurt_colors(self, damage_types): if DamageTypes.POISON in damage_types: return [colors.GREEN, colors.GREEN_D] return [colors.LIGHT_PINK, colors.RED] def heal(self, health): """ Heals increases the current hp by health. """ if not self.parent.health.hp.value == self.parent.health.hp.max_value: self.parent.health.hp.increase(health) self._animate_heal() return health def _animate_heal(self): <|code_end|> . Write the next line using the current file imports: import logging import counter import colors import entityeffect import geometry import icon import rng import settings import shapegenerator from attacker import DamageTypes from compositecore import Leaf from dungeontrash import PoolOfBlood from graphic import GraphicChar from messenger import NO_LONGER_PARALYZED_MESSAGE and context from other files: # Path: attacker.py # class DamageTypes(object): # PHYSICAL = "physical_damage_type" # MAGIC = "magic_damage_type" # BLUNT = "blunt_damage_type" # PIERCING = "piercing_damage_type" # CUTTING = "cutting_damage_type" # BLEED = "bleed_damage_type" # ACID = "acid_damage_type" # POISON = "poison_damage_type" # LIGHTNING = "lightning_damage_type" # FIRE = "fire_damage_type" # REFLECT = "reflect_damage_type" # # IGNORE_ARMOR = "ignore_armor_damage_type" # # FALL = "fall_damage_type" # # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: dungeontrash.py # class PoolOfBlood(Composite): # """ # A pool of blood. Totally useless but looks nice # and gives the user feedback when a monster is hurt. # """ # def __init__(self): # super(PoolOfBlood, self).__init__() # self.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.DUNGEON_TRASH)) # self.set_child(Position()) # self.set_child(DungeonLevel()) # self.set_child(Description("A pool of blood.", "A pool of blood.")) # self.set_child(GraphicChar(None, colors.RED, random.choice(icon.BLOOD_ICONS))) # self.set_child(CharPrinter()) # self.set_child(Mover()) # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) # # Path: messenger.py # NO_LONGER_PARALYZED_MESSAGE = "%(source_entity)s is no longer paralyzed." , which may include functions, classes, or code. Output only the next line.
heart_graphic_char = GraphicChar(None, colors.RED, icon.HEALTH_GAIN_ICON)
Continue the code snippet: <|code_start|> def effect(self, damage, source_entity, damage_types=[]): pass class ReflectDamageTakenEffect(DamageTakenEffect): def __init__(self): super(ReflectDamageTakenEffect, self).__init__() self.component_type = "reflect_damage" self.damage = 1 def effect(self, damage, source_entity, damage_types=[]): if (damage >= 1 and source_entity and source_entity.has("health_modifier") and not DamageTypes.REFLECT in damage_types and source_entity != self.parent and rng.coin_flip()): damage_effect = entityeffect.UndodgeableAttackEntityEffect(self.parent, self.damage, [DamageTypes.MAGIC, DamageTypes.REFLECT]) source_entity.effect_queue.add(damage_effect) class LoseParalyzeWhenDamaged(DamageTakenEffect): def __init__(self): super(LoseParalyzeWhenDamaged, self).__init__() self.component_type = "lose_paralyze_when_damaged" def effect(self, damage, source_entity, damage_types=[]): if rng.coin_flip(): <|code_end|> . Use current file imports: import logging import counter import colors import entityeffect import geometry import icon import rng import settings import shapegenerator from attacker import DamageTypes from compositecore import Leaf from dungeontrash import PoolOfBlood from graphic import GraphicChar from messenger import NO_LONGER_PARALYZED_MESSAGE and context (classes, functions, or code) from other files: # Path: attacker.py # class DamageTypes(object): # PHYSICAL = "physical_damage_type" # MAGIC = "magic_damage_type" # BLUNT = "blunt_damage_type" # PIERCING = "piercing_damage_type" # CUTTING = "cutting_damage_type" # BLEED = "bleed_damage_type" # ACID = "acid_damage_type" # POISON = "poison_damage_type" # LIGHTNING = "lightning_damage_type" # FIRE = "fire_damage_type" # REFLECT = "reflect_damage_type" # # IGNORE_ARMOR = "ignore_armor_damage_type" # # FALL = "fall_damage_type" # # Path: compositecore.py # class Leaf(Component): # """ # Abstract leaf class of composite design pattern. # # Component classes of leaf type should inherit from this class. # """ # # def __init__(self): # super(Leaf, self).__init__() # # def get_relative_of_type(self, component_type): # return self.parent.get_child_or_ancestor(component_type) # # def has_relative_of_type(self, component_type): # return self.parent.has_child_or_ancestor(component_type) # # Path: dungeontrash.py # class PoolOfBlood(Composite): # """ # A pool of blood. Totally useless but looks nice # and gives the user feedback when a monster is hurt. # """ # def __init__(self): # super(PoolOfBlood, self).__init__() # self.set_child(DataPoint(DataTypes.GAME_PIECE_TYPE, GamePieceTypes.DUNGEON_TRASH)) # self.set_child(Position()) # self.set_child(DungeonLevel()) # self.set_child(Description("A pool of blood.", "A pool of blood.")) # self.set_child(GraphicChar(None, colors.RED, random.choice(icon.BLOOD_ICONS))) # self.set_child(CharPrinter()) # self.set_child(Mover()) # # Path: graphic.py # class GraphicChar(Leaf): # """ # Composites holding this has a graphical representation as a char. # """ # # def __init__(self, color_bg, color_fg, icon): # super(GraphicChar, self).__init__() # self.component_type = "graphic_char" # self._color_bg = color_bg # self._color_fg = color_fg # self._icon = icon # # @property # def color_bg(self): # if self._color_bg: # return self._color_bg # elif self.next: # return self.next.color_bg # return None # # # @color_bg.setter # def color_bg(self, value): # self._color_bg = value # # @property # def color_fg(self): # if self._color_fg: # return self._color_fg # elif self.next: # return self.next.color_fg # return None # # @color_fg.setter # def color_fg(self, value): # self._color_fg = value # # @property # def icon(self): # if self._icon: # return self._icon # elif self.next: # return self.next.icon # return None # # @icon.setter # def icon(self, value): # self._icon = value # # def copy(self): # """ # Makes a copy of this component. # """ # return GraphicChar(self.color_bg, self.color_fg, self.icon) # # Path: messenger.py # NO_LONGER_PARALYZED_MESSAGE = "%(source_entity)s is no longer paralyzed." . Output only the next line.
self.parent.effect_queue.add(entityeffect.EffectRemover(self.parent, "paralyze", message=NO_LONGER_PARALYZED_MESSAGE))
Here is a snippet: <|code_start|> def dungeon_to_screen_position(self, position): return geo.add_2d(geo.sub_2d(position, self.camera_offset), self.screen_position) def screen_to_dungeon_position(self, position): return geo.sub_2d(geo.add_2d(position, self.camera_offset), self.screen_position) def scroll_graze_delta(self, position): x_delta = 0 y_delta = 0 x_delta += max(0, self.x_graze_edge[0] - position[0]) x_delta -= max(0, position[0] - self.x_graze_edge[1]) y_delta += max(0, self.y_graze_edge[0] - position[1]) y_delta -= max(0, position[1] - self.y_graze_edge[1]) return - x_delta, - y_delta def update(self, player): position = player.position.value delta = self.scroll_graze_delta(self.dungeon_to_screen_position(position)) self.camera_offset = geo.add_2d(self.camera_offset, delta) def center_on_entity(self, entity): position = entity.position.value delta = geo.sub_2d(position, self.screen_center_position) self.camera_offset = geo.add_2d(self.camera_offset, delta) def draw_graze_rect(self): for x in range(self.x_graze_edge[0], self.x_graze_edge[1]): <|code_end|> . Write the next line using the current file imports: import colors import constants import geometry as geo import settings from console import console and context from other files: # Path: console.py # class ConsoleVisual(object): # def __init__(self, width, height): # def get_color_fg(self, position): # def get_color_bg(self, position): # def get_symbol(self, position): # def get_default_color_fg(self): # def get_default_color_bg(self): # def set_default_color_fg(self, color, console=0): # def set_default_color_bg(self, color, console=0): # def set_symbol(self, position, icon, console=0): # def set_color_fg(self, position, color, console=0): # def set_color_bg(self, position, color, effect=libtcod.BKGND_SET, console=0): # def print_text(self, position, text): # def print_text_vertical(self, position, text): # def set_colors_and_symbol(self, position, color_fg, color_bg, icon, console=0): # def print_char_big(self, icon_position, destination, console=0): # def flush(self): # def print_screen(self): , which may include functions, classes, or code. Output only the next line.
console.set_color_bg((x, self.y_graze_edge[0]), colors.YELLOW)
Given the code snippet: <|code_start|> class DungeonCreatorVisualizer(state.State): def __init__(self): super(DungeonCreatorVisualizer, self).__init__() self.dungeon_level = dgen.get_full_wall_dungeon(70, 55, 0) self.camera = camera.Camera(geo.zero2d(), geo.zero2d(), self) def fill_dungeon(self): width = self.dungeon_level.width height = self.dungeon_level.height self.dungeon_level = dgen.get_full_wall_dungeon(width, height, 0) def draw(self): self.dungeon_level.draw_everything(self.camera) <|code_end|> , generate the next line using the imports in this file: import dungeongenerator as dgen import geometry as geo import camera import direction import inputhandler import state import terrain from console import console and context (functions, classes, or occasionally code) from other files: # Path: console.py # class ConsoleVisual(object): # def __init__(self, width, height): # def get_color_fg(self, position): # def get_color_bg(self, position): # def get_symbol(self, position): # def get_default_color_fg(self): # def get_default_color_bg(self): # def set_default_color_fg(self, color, console=0): # def set_default_color_bg(self, color, console=0): # def set_symbol(self, position, icon, console=0): # def set_color_fg(self, position, color, console=0): # def set_color_bg(self, position, color, effect=libtcod.BKGND_SET, console=0): # def print_text(self, position, text): # def print_text_vertical(self, position, text): # def set_colors_and_symbol(self, position, color_fg, color_bg, icon, console=0): # def print_char_big(self, icon_position, destination, console=0): # def flush(self): # def print_screen(self): . Output only the next line.
console.flush()