Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Here is a snippet: <|code_start|> class AnalysisRequest(db.Document): analysis_system = ReferenceField(AnalysisSystem, required=True) sample = ReferenceField(Sample, required=True) analysis_requested = DateTimeField(default=TimeFunctions.get_timestamp, required=True) priority = IntField(default=0, required=True) meta = { 'ordering': ['-analysis_requested'], 'indexes': ['analysis_requested'] } <|code_end|> . Write the next line using the current file imports: from mass_flask_config.app import db from .analysis_system import AnalysisSystem from .sample import Sample from mongoengine import DateTimeField, ReferenceField, IntField from mass_flask_core.utils import TimeFunctions and context from other files: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/models/analysis_system.py # class AnalysisSystem(db.Document): # identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True) # verbose_name = StringField(max_length=200, required=True) # information_text = StringField() # tag_filter_expression = StringField(max_length=400, required=True, default='') # # meta = { # 'ordering': ['identifier_name'], # 'indexes': ['identifier_name'] # } # # def __repr__(self): # return '[AnalysisSystem] {}'.format(self.identifier_name) # # def __str__(self): # return self.__repr__() # # Path: mass_flask_core/models/sample.py # class Sample(db.Document, CommentsMixin): # delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True) # first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True) # tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$')) # dispatched_to = ListField(ReferenceField(AnalysisSystem)) # created_by = GenericReferenceField() # tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True) # # meta = { # 'allow_inheritance': True, # 'ordering': ['-delivery_date'], # 'indexes': ['delivery_date'], # 'queryset_class': SampleQuerySet # } # # def __repr__(self): # return '[{}] {}'.format(str(self.__class__.__name__), str(self.id)) # # def __str__(self): # return self.__repr__() # # @property # def title(self): # return self.id # # def add_tags(self, tags): # self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags) # self.save() # # def _update(self, **kwargs): # if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen: # self.first_seen = kwargs['first_seen'] # if 'tlp_level' in kwargs and not self.tlp_level: # self.tlp_level = kwargs['tlp_level'] # if current_authenticated_entity.is_authenticated and not self.created_by: # self.created_by = current_authenticated_entity._get_current_object() # if 'tags' in kwargs: # tags = kwargs['tags'] # else: # tags = [] # self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags) # # @classmethod # def create_or_update(cls, **kwargs): # raise ValidationError('Samples of the base type Sample should not be instantiated directly.') # # Path: mass_flask_core/utils/time_functions.py # class TimeFunctions: # @staticmethod # def get_timestamp(): # # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision # return datetime.now(utc).replace(microsecond=0) , which may include functions, classes, or code. Output only the next line.
def __repr__(self):
Predict the next line for this snippet: <|code_start|> def _gen_uuid(): return str(uuid4()) class AnalysisSystemInstance(db.Document, AbstractAuthEntity): @property def is_authenticated(self): return True def get_roles(self): return ['analysis_system_instance'] @property def max_tlp_level(self): return TLPLevelField.TLP_LEVEL_WHITE analysis_system = ReferenceField(AnalysisSystem, required=True) uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid) last_seen = DateTimeField() meta = { 'ordering': ['analysis_system', 'uuid'], 'indexes': [('analysis_system', 'uuid')] } <|code_end|> with the help of current file imports: from uuid import uuid4 from flask_modular_auth import AbstractAuthEntity from mass_flask_config.app import db from mongoengine import StringField, DateTimeField, ReferenceField from mass_flask_core.utils import TimeFunctions from .analysis_system import AnalysisSystem from .tlp_level import TLPLevelField import datetime and context from other files: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/utils/time_functions.py # class TimeFunctions: # @staticmethod # def get_timestamp(): # # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision # return datetime.now(utc).replace(microsecond=0) # # Path: mass_flask_core/models/analysis_system.py # class AnalysisSystem(db.Document): # identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True) # verbose_name = StringField(max_length=200, required=True) # information_text = StringField() # tag_filter_expression = StringField(max_length=400, required=True, default='') # # meta = { # 'ordering': ['identifier_name'], # 'indexes': ['identifier_name'] # } # # def __repr__(self): # return '[AnalysisSystem] {}'.format(self.identifier_name) # # def __str__(self): # return self.__repr__() # # Path: mass_flask_core/models/tlp_level.py # class TLPLevelField(IntField): # TLP_LEVEL_WHITE = 0 # Access without login # TLP_LEVEL_GREEN = 1 # Access with login # TLP_LEVEL_AMBER = 2 # Access only for especially authorized users of same group # TLP_LEVEL_RED = 3 # Access only for explicitly mentioned users/groups # # def __init__(self, *args, **kwargs): # kwargs['choices'] = [ # TLPLevelField.TLP_LEVEL_WHITE, # TLPLevelField.TLP_LEVEL_GREEN, # TLPLevelField.TLP_LEVEL_AMBER, # TLPLevelField.TLP_LEVEL_RED # ] # super(TLPLevelField, self).__init__(*args, **kwargs) , which may contain function names, class names, or code. Output only the next line.
def __repr__(self):
Next line prediction: <|code_start|> def _gen_uuid(): return str(uuid4()) class AnalysisSystemInstance(db.Document, AbstractAuthEntity): @property def is_authenticated(self): return True def get_roles(self): return ['analysis_system_instance'] @property def max_tlp_level(self): return TLPLevelField.TLP_LEVEL_WHITE analysis_system = ReferenceField(AnalysisSystem, required=True) uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid) last_seen = DateTimeField() meta = { 'ordering': ['analysis_system', 'uuid'], 'indexes': [('analysis_system', 'uuid')] <|code_end|> . Use current file imports: (from uuid import uuid4 from flask_modular_auth import AbstractAuthEntity from mass_flask_config.app import db from mongoengine import StringField, DateTimeField, ReferenceField from mass_flask_core.utils import TimeFunctions from .analysis_system import AnalysisSystem from .tlp_level import TLPLevelField import datetime) and context including class names, function names, or small code snippets from other files: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/utils/time_functions.py # class TimeFunctions: # @staticmethod # def get_timestamp(): # # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision # return datetime.now(utc).replace(microsecond=0) # # Path: mass_flask_core/models/analysis_system.py # class AnalysisSystem(db.Document): # identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True) # verbose_name = StringField(max_length=200, required=True) # information_text = StringField() # tag_filter_expression = StringField(max_length=400, required=True, default='') # # meta = { # 'ordering': ['identifier_name'], # 'indexes': ['identifier_name'] # } # # def __repr__(self): # return '[AnalysisSystem] {}'.format(self.identifier_name) # # def __str__(self): # return self.__repr__() # # Path: mass_flask_core/models/tlp_level.py # class TLPLevelField(IntField): # TLP_LEVEL_WHITE = 0 # Access without login # TLP_LEVEL_GREEN = 1 # Access with login # TLP_LEVEL_AMBER = 2 # Access only for especially authorized users of same group # TLP_LEVEL_RED = 3 # Access only for explicitly mentioned users/groups # # def __init__(self, *args, **kwargs): # kwargs['choices'] = [ # TLPLevelField.TLP_LEVEL_WHITE, # TLPLevelField.TLP_LEVEL_GREEN, # TLPLevelField.TLP_LEVEL_AMBER, # TLPLevelField.TLP_LEVEL_RED # ] # super(TLPLevelField, self).__init__(*args, **kwargs) . Output only the next line.
}
Given snippet: <|code_start|> def _gen_uuid(): return str(uuid4()) class AnalysisSystemInstance(db.Document, AbstractAuthEntity): @property def is_authenticated(self): return True def get_roles(self): return ['analysis_system_instance'] @property def max_tlp_level(self): return TLPLevelField.TLP_LEVEL_WHITE analysis_system = ReferenceField(AnalysisSystem, required=True) uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid) last_seen = DateTimeField() meta = { 'ordering': ['analysis_system', 'uuid'], 'indexes': [('analysis_system', 'uuid')] } def __repr__(self): return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid) def __str__(self): <|code_end|> , continue by predicting the next line. Consider current file imports: from uuid import uuid4 from flask_modular_auth import AbstractAuthEntity from mass_flask_config.app import db from mongoengine import StringField, DateTimeField, ReferenceField from mass_flask_core.utils import TimeFunctions from .analysis_system import AnalysisSystem from .tlp_level import TLPLevelField import datetime and context: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/utils/time_functions.py # class TimeFunctions: # @staticmethod # def get_timestamp(): # # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision # return datetime.now(utc).replace(microsecond=0) # # Path: mass_flask_core/models/analysis_system.py # class AnalysisSystem(db.Document): # identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True) # verbose_name = StringField(max_length=200, required=True) # information_text = StringField() # tag_filter_expression = StringField(max_length=400, required=True, default='') # # meta = { # 'ordering': ['identifier_name'], # 'indexes': ['identifier_name'] # } # # def __repr__(self): # return '[AnalysisSystem] {}'.format(self.identifier_name) # # def __str__(self): # return self.__repr__() # # Path: mass_flask_core/models/tlp_level.py # class TLPLevelField(IntField): # TLP_LEVEL_WHITE = 0 # Access without login # TLP_LEVEL_GREEN = 1 # Access with login # TLP_LEVEL_AMBER = 2 # Access only for especially authorized users of same group # TLP_LEVEL_RED = 3 # Access only for explicitly mentioned users/groups # # def __init__(self, *args, **kwargs): # kwargs['choices'] = [ # TLPLevelField.TLP_LEVEL_WHITE, # TLPLevelField.TLP_LEVEL_GREEN, # TLPLevelField.TLP_LEVEL_AMBER, # TLPLevelField.TLP_LEVEL_RED # ] # super(TLPLevelField, self).__init__(*args, **kwargs) which might include code, classes, or functions. Output only the next line.
return self.__repr__()
Continue the code snippet: <|code_start|> return str(uuid4()) class AnalysisSystemInstance(db.Document, AbstractAuthEntity): @property def is_authenticated(self): return True def get_roles(self): return ['analysis_system_instance'] @property def max_tlp_level(self): return TLPLevelField.TLP_LEVEL_WHITE analysis_system = ReferenceField(AnalysisSystem, required=True) uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid) last_seen = DateTimeField() meta = { 'ordering': ['analysis_system', 'uuid'], 'indexes': [('analysis_system', 'uuid')] } def __repr__(self): return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid) def __str__(self): return self.__repr__() <|code_end|> . Use current file imports: from uuid import uuid4 from flask_modular_auth import AbstractAuthEntity from mass_flask_config.app import db from mongoengine import StringField, DateTimeField, ReferenceField from mass_flask_core.utils import TimeFunctions from .analysis_system import AnalysisSystem from .tlp_level import TLPLevelField import datetime and context (classes, functions, or code) from other files: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/utils/time_functions.py # class TimeFunctions: # @staticmethod # def get_timestamp(): # # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision # return datetime.now(utc).replace(microsecond=0) # # Path: mass_flask_core/models/analysis_system.py # class AnalysisSystem(db.Document): # identifier_name = StringField(min_length=3, max_length=50, unique=True, required=True) # verbose_name = StringField(max_length=200, required=True) # information_text = StringField() # tag_filter_expression = StringField(max_length=400, required=True, default='') # # meta = { # 'ordering': ['identifier_name'], # 'indexes': ['identifier_name'] # } # # def __repr__(self): # return '[AnalysisSystem] {}'.format(self.identifier_name) # # def __str__(self): # return self.__repr__() # # Path: mass_flask_core/models/tlp_level.py # class TLPLevelField(IntField): # TLP_LEVEL_WHITE = 0 # Access without login # TLP_LEVEL_GREEN = 1 # Access with login # TLP_LEVEL_AMBER = 2 # Access only for especially authorized users of same group # TLP_LEVEL_RED = 3 # Access only for explicitly mentioned users/groups # # def __init__(self, *args, **kwargs): # kwargs['choices'] = [ # TLPLevelField.TLP_LEVEL_WHITE, # TLPLevelField.TLP_LEVEL_GREEN, # TLPLevelField.TLP_LEVEL_AMBER, # TLPLevelField.TLP_LEVEL_RED # ] # super(TLPLevelField, self).__init__(*args, **kwargs) . Output only the next line.
def update_last_seen(self):
Predict the next line for this snippet: <|code_start|> class UserMixin(AbstractAuthEntity): user_level = UserLevel.USER_LEVEL_ANONYMOUS def get_roles(self): roles = [] if self.is_user: roles.append('user') if self.is_privileged: roles.append('privileged') if self.is_manager: roles.append('manager') if self.is_admin: roles.append('admin') return roles def is_authenticated(self): return False @property def is_anonymous(self): return self.user_level == UserLevel.USER_LEVEL_ANONYMOUS @property def is_user(self): return self.user_level >= UserLevel.USER_LEVEL_USER @property def is_privileged(self): <|code_end|> with the help of current file imports: from flask_modular_auth import AbstractAuthEntity from mongoengine import StringField, BooleanField, IntField from werkzeug.security import generate_password_hash, check_password_hash from bson import ObjectId from mass_flask_config.app import db, setup_session_auth, auth_manager from .tlp_level import TLPLevelField and context from other files: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/models/tlp_level.py # class TLPLevelField(IntField): # TLP_LEVEL_WHITE = 0 # Access without login # TLP_LEVEL_GREEN = 1 # Access with login # TLP_LEVEL_AMBER = 2 # Access only for especially authorized users of same group # TLP_LEVEL_RED = 3 # Access only for explicitly mentioned users/groups # # def __init__(self, *args, **kwargs): # kwargs['choices'] = [ # TLPLevelField.TLP_LEVEL_WHITE, # TLPLevelField.TLP_LEVEL_GREEN, # TLPLevelField.TLP_LEVEL_AMBER, # TLPLevelField.TLP_LEVEL_RED # ] # super(TLPLevelField, self).__init__(*args, **kwargs) , which may contain function names, class names, or code. Output only the next line.
return self.user_level >= UserLevel.USER_LEVEL_PRIVILEGED
Based on the snippet: <|code_start|> USER_LEVEL_ADMIN = 4 class UserLevelField(IntField): def __init__(self, *args, **kwargs): kwargs['choices'] = [ UserLevel.USER_LEVEL_ANONYMOUS, UserLevel.USER_LEVEL_USER, UserLevel.USER_LEVEL_PRIVILEGED, UserLevel.USER_LEVEL_MANAGER, UserLevel.USER_LEVEL_ADMIN ] super(UserLevelField, self).__init__(*args, **kwargs) class UserMixin(AbstractAuthEntity): user_level = UserLevel.USER_LEVEL_ANONYMOUS def get_roles(self): roles = [] if self.is_user: roles.append('user') if self.is_privileged: roles.append('privileged') if self.is_manager: roles.append('manager') if self.is_admin: roles.append('admin') return roles <|code_end|> , predict the immediate next line with the help of imports: from flask_modular_auth import AbstractAuthEntity from mongoengine import StringField, BooleanField, IntField from werkzeug.security import generate_password_hash, check_password_hash from bson import ObjectId from mass_flask_config.app import db, setup_session_auth, auth_manager from .tlp_level import TLPLevelField and context (classes, functions, sometimes code) from other files: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/models/tlp_level.py # class TLPLevelField(IntField): # TLP_LEVEL_WHITE = 0 # Access without login # TLP_LEVEL_GREEN = 1 # Access with login # TLP_LEVEL_AMBER = 2 # Access only for especially authorized users of same group # TLP_LEVEL_RED = 3 # Access only for explicitly mentioned users/groups # # def __init__(self, *args, **kwargs): # kwargs['choices'] = [ # TLPLevelField.TLP_LEVEL_WHITE, # TLPLevelField.TLP_LEVEL_GREEN, # TLPLevelField.TLP_LEVEL_AMBER, # TLPLevelField.TLP_LEVEL_RED # ] # super(TLPLevelField, self).__init__(*args, **kwargs) . Output only the next line.
def is_authenticated(self):
Predict the next line for this snippet: <|code_start|> username = StringField(min_length=3, max_length=50, unique=True, required=True) password_hash = StringField(min_length=5, max_length=200) user_level = UserLevelField(default=UserLevel.USER_LEVEL_USER, required=True) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) def get_id(self): return str(self.id) @staticmethod def user_loader(**kwargs): if 'username' in kwargs and 'password' in kwargs: user = User.objects(username=kwargs['username']).first() if user and user.check_password(kwargs['password']): return user else: return None elif 'id' in kwargs and kwargs['id']: return User.objects(id=ObjectId(kwargs['id'])).first() else: raise RuntimeError('This access method is not supported by the user loader.') class AnonymousUser(UserMixin): @property def is_authenticated(self): <|code_end|> with the help of current file imports: from flask_modular_auth import AbstractAuthEntity from mongoengine import StringField, BooleanField, IntField from werkzeug.security import generate_password_hash, check_password_hash from bson import ObjectId from mass_flask_config.app import db, setup_session_auth, auth_manager from .tlp_level import TLPLevelField and context from other files: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/models/tlp_level.py # class TLPLevelField(IntField): # TLP_LEVEL_WHITE = 0 # Access without login # TLP_LEVEL_GREEN = 1 # Access with login # TLP_LEVEL_AMBER = 2 # Access only for especially authorized users of same group # TLP_LEVEL_RED = 3 # Access only for explicitly mentioned users/groups # # def __init__(self, *args, **kwargs): # kwargs['choices'] = [ # TLPLevelField.TLP_LEVEL_WHITE, # TLPLevelField.TLP_LEVEL_GREEN, # TLPLevelField.TLP_LEVEL_AMBER, # TLPLevelField.TLP_LEVEL_RED # ] # super(TLPLevelField, self).__init__(*args, **kwargs) , which may contain function names, class names, or code. Output only the next line.
return False
Next line prediction: <|code_start|> roles.append('admin') return roles def is_authenticated(self): return False @property def is_anonymous(self): return self.user_level == UserLevel.USER_LEVEL_ANONYMOUS @property def is_user(self): return self.user_level >= UserLevel.USER_LEVEL_USER @property def is_privileged(self): return self.user_level >= UserLevel.USER_LEVEL_PRIVILEGED @property def is_manager(self): return self.user_level >= UserLevel.USER_LEVEL_MANAGER @property def is_admin(self): return self.user_level >= UserLevel.USER_LEVEL_ADMIN @property def max_tlp_level(self): if self.is_admin: return TLPLevelField.TLP_LEVEL_RED <|code_end|> . Use current file imports: (from flask_modular_auth import AbstractAuthEntity from mongoengine import StringField, BooleanField, IntField from werkzeug.security import generate_password_hash, check_password_hash from bson import ObjectId from mass_flask_config.app import db, setup_session_auth, auth_manager from .tlp_level import TLPLevelField) and context including class names, function names, or small code snippets from other files: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/models/tlp_level.py # class TLPLevelField(IntField): # TLP_LEVEL_WHITE = 0 # Access without login # TLP_LEVEL_GREEN = 1 # Access with login # TLP_LEVEL_AMBER = 2 # Access only for especially authorized users of same group # TLP_LEVEL_RED = 3 # Access only for explicitly mentioned users/groups # # def __init__(self, *args, **kwargs): # kwargs['choices'] = [ # TLPLevelField.TLP_LEVEL_WHITE, # TLPLevelField.TLP_LEVEL_GREEN, # TLPLevelField.TLP_LEVEL_AMBER, # TLPLevelField.TLP_LEVEL_RED # ] # super(TLPLevelField, self).__init__(*args, **kwargs) . Output only the next line.
elif self.is_privileged:
Given the code snippet: <|code_start|> class ScheduledAnalysis(db.Document): analysis_system_instance = ReferenceField(AnalysisSystemInstance, required=True) sample = ReferenceField(Sample, required=True) analysis_scheduled = DateTimeField(default=TimeFunctions.get_timestamp, required=True) priority = IntField(default=0, required=True) <|code_end|> , generate the next line using the imports in this file: from mass_flask_config.app import db from mongoengine import DateTimeField, ReferenceField, IntField from .analysis_system_instance import AnalysisSystemInstance from .sample import Sample from mass_flask_core.utils import TimeFunctions and context (functions, classes, or occasionally code) from other files: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/models/analysis_system_instance.py # class AnalysisSystemInstance(db.Document, AbstractAuthEntity): # @property # def is_authenticated(self): # return True # # def get_roles(self): # return ['analysis_system_instance'] # # @property # def max_tlp_level(self): # return TLPLevelField.TLP_LEVEL_WHITE # # analysis_system = ReferenceField(AnalysisSystem, required=True) # uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid) # last_seen = DateTimeField() # # meta = { # 'ordering': ['analysis_system', 'uuid'], # 'indexes': [('analysis_system', 'uuid')] # } # # def __repr__(self): # return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid) # # def __str__(self): # return self.__repr__() # # def update_last_seen(self): # self.last_seen = TimeFunctions.get_timestamp() # self.save() # # @property # def is_online(self): # if self.last_seen is None: # return False # # difference = TimeFunctions.get_timestamp() - self.last_seen # return difference < datetime.timedelta(minutes=10) # # Path: mass_flask_core/models/sample.py # class Sample(db.Document, CommentsMixin): # delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True) # first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True) # tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$')) # dispatched_to = ListField(ReferenceField(AnalysisSystem)) # created_by = GenericReferenceField() # tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True) # # meta = { # 'allow_inheritance': True, # 'ordering': ['-delivery_date'], # 'indexes': ['delivery_date'], # 'queryset_class': SampleQuerySet # } # # def __repr__(self): # return '[{}] {}'.format(str(self.__class__.__name__), str(self.id)) # # def __str__(self): # return self.__repr__() # # @property # def title(self): # return self.id # # def add_tags(self, tags): # self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags) # self.save() # # def _update(self, **kwargs): # if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen: # self.first_seen = kwargs['first_seen'] # if 'tlp_level' in kwargs and not self.tlp_level: # self.tlp_level = kwargs['tlp_level'] # if current_authenticated_entity.is_authenticated and not self.created_by: # self.created_by = current_authenticated_entity._get_current_object() # if 'tags' in kwargs: # tags = kwargs['tags'] # else: # tags = [] # self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags) # # @classmethod # def create_or_update(cls, **kwargs): # raise ValidationError('Samples of the base type Sample should not be instantiated directly.') # # Path: mass_flask_core/utils/time_functions.py # class TimeFunctions: # @staticmethod # def get_timestamp(): # # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision # return datetime.now(utc).replace(microsecond=0) . Output only the next line.
meta = {
Predict the next line for this snippet: <|code_start|> class ScheduledAnalysis(db.Document): analysis_system_instance = ReferenceField(AnalysisSystemInstance, required=True) sample = ReferenceField(Sample, required=True) analysis_scheduled = DateTimeField(default=TimeFunctions.get_timestamp, required=True) <|code_end|> with the help of current file imports: from mass_flask_config.app import db from mongoengine import DateTimeField, ReferenceField, IntField from .analysis_system_instance import AnalysisSystemInstance from .sample import Sample from mass_flask_core.utils import TimeFunctions and context from other files: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/models/analysis_system_instance.py # class AnalysisSystemInstance(db.Document, AbstractAuthEntity): # @property # def is_authenticated(self): # return True # # def get_roles(self): # return ['analysis_system_instance'] # # @property # def max_tlp_level(self): # return TLPLevelField.TLP_LEVEL_WHITE # # analysis_system = ReferenceField(AnalysisSystem, required=True) # uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid) # last_seen = DateTimeField() # # meta = { # 'ordering': ['analysis_system', 'uuid'], # 'indexes': [('analysis_system', 'uuid')] # } # # def __repr__(self): # return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid) # # def __str__(self): # return self.__repr__() # # def update_last_seen(self): # self.last_seen = TimeFunctions.get_timestamp() # self.save() # # @property # def is_online(self): # if self.last_seen is None: # return False # # difference = TimeFunctions.get_timestamp() - self.last_seen # return difference < datetime.timedelta(minutes=10) # # Path: mass_flask_core/models/sample.py # class Sample(db.Document, CommentsMixin): # delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True) # first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True) # tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$')) # dispatched_to = ListField(ReferenceField(AnalysisSystem)) # created_by = GenericReferenceField() # tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True) # # meta = { # 'allow_inheritance': True, # 'ordering': ['-delivery_date'], # 'indexes': ['delivery_date'], # 'queryset_class': SampleQuerySet # } # # def __repr__(self): # return '[{}] {}'.format(str(self.__class__.__name__), str(self.id)) # # def __str__(self): # return self.__repr__() # # @property # def title(self): # return self.id # # def add_tags(self, tags): # self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags) # self.save() # # def _update(self, **kwargs): # if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen: # self.first_seen = kwargs['first_seen'] # if 'tlp_level' in kwargs and not self.tlp_level: # self.tlp_level = kwargs['tlp_level'] # if current_authenticated_entity.is_authenticated and not self.created_by: # self.created_by = current_authenticated_entity._get_current_object() # if 'tags' in kwargs: # tags = kwargs['tags'] # else: # tags = [] # self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags) # # @classmethod # def create_or_update(cls, **kwargs): # raise ValidationError('Samples of the base type Sample should not be instantiated directly.') # # Path: mass_flask_core/utils/time_functions.py # class TimeFunctions: # @staticmethod # def get_timestamp(): # # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision # return datetime.now(utc).replace(microsecond=0) , which may contain function names, class names, or code. Output only the next line.
priority = IntField(default=0, required=True)
Given the code snippet: <|code_start|> class ScheduledAnalysis(db.Document): analysis_system_instance = ReferenceField(AnalysisSystemInstance, required=True) sample = ReferenceField(Sample, required=True) analysis_scheduled = DateTimeField(default=TimeFunctions.get_timestamp, required=True) priority = IntField(default=0, required=True) meta = { 'ordering': ['-analysis_scheduled'], 'indexes': ['analysis_scheduled'] <|code_end|> , generate the next line using the imports in this file: from mass_flask_config.app import db from mongoengine import DateTimeField, ReferenceField, IntField from .analysis_system_instance import AnalysisSystemInstance from .sample import Sample from mass_flask_core.utils import TimeFunctions and context (functions, classes, or occasionally code) from other files: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/models/analysis_system_instance.py # class AnalysisSystemInstance(db.Document, AbstractAuthEntity): # @property # def is_authenticated(self): # return True # # def get_roles(self): # return ['analysis_system_instance'] # # @property # def max_tlp_level(self): # return TLPLevelField.TLP_LEVEL_WHITE # # analysis_system = ReferenceField(AnalysisSystem, required=True) # uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid) # last_seen = DateTimeField() # # meta = { # 'ordering': ['analysis_system', 'uuid'], # 'indexes': [('analysis_system', 'uuid')] # } # # def __repr__(self): # return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid) # # def __str__(self): # return self.__repr__() # # def update_last_seen(self): # self.last_seen = TimeFunctions.get_timestamp() # self.save() # # @property # def is_online(self): # if self.last_seen is None: # return False # # difference = TimeFunctions.get_timestamp() - self.last_seen # return difference < datetime.timedelta(minutes=10) # # Path: mass_flask_core/models/sample.py # class Sample(db.Document, CommentsMixin): # delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True) # first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True) # tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$')) # dispatched_to = ListField(ReferenceField(AnalysisSystem)) # created_by = GenericReferenceField() # tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True) # # meta = { # 'allow_inheritance': True, # 'ordering': ['-delivery_date'], # 'indexes': ['delivery_date'], # 'queryset_class': SampleQuerySet # } # # def __repr__(self): # return '[{}] {}'.format(str(self.__class__.__name__), str(self.id)) # # def __str__(self): # return self.__repr__() # # @property # def title(self): # return self.id # # def add_tags(self, tags): # self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags) # self.save() # # def _update(self, **kwargs): # if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen: # self.first_seen = kwargs['first_seen'] # if 'tlp_level' in kwargs and not self.tlp_level: # self.tlp_level = kwargs['tlp_level'] # if current_authenticated_entity.is_authenticated and not self.created_by: # self.created_by = current_authenticated_entity._get_current_object() # if 'tags' in kwargs: # tags = kwargs['tags'] # else: # tags = [] # self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags) # # @classmethod # def create_or_update(cls, **kwargs): # raise ValidationError('Samples of the base type Sample should not be instantiated directly.') # # Path: mass_flask_core/utils/time_functions.py # class TimeFunctions: # @staticmethod # def get_timestamp(): # # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision # return datetime.now(utc).replace(microsecond=0) . Output only the next line.
}
Using the snippet: <|code_start|> class ScheduledAnalysis(db.Document): analysis_system_instance = ReferenceField(AnalysisSystemInstance, required=True) sample = ReferenceField(Sample, required=True) analysis_scheduled = DateTimeField(default=TimeFunctions.get_timestamp, required=True) priority = IntField(default=0, required=True) meta = { <|code_end|> , determine the next line of code. You have imports: from mass_flask_config.app import db from mongoengine import DateTimeField, ReferenceField, IntField from .analysis_system_instance import AnalysisSystemInstance from .sample import Sample from mass_flask_core.utils import TimeFunctions and context (class names, function names, or code) available: # Path: mass_flask_config/app.py # BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt') # def setup_session_auth(user_loader): # def setup_key_based_auth(key_loader): # def unauthorized_callback(): # # Path: mass_flask_core/models/analysis_system_instance.py # class AnalysisSystemInstance(db.Document, AbstractAuthEntity): # @property # def is_authenticated(self): # return True # # def get_roles(self): # return ['analysis_system_instance'] # # @property # def max_tlp_level(self): # return TLPLevelField.TLP_LEVEL_WHITE # # analysis_system = ReferenceField(AnalysisSystem, required=True) # uuid = StringField(max_length=36, required=True, unique=True, default=_gen_uuid) # last_seen = DateTimeField() # # meta = { # 'ordering': ['analysis_system', 'uuid'], # 'indexes': [('analysis_system', 'uuid')] # } # # def __repr__(self): # return '[AnalysisSystemInstance] {} {}'.format(self.analysis_system.identifier_name, self.uuid) # # def __str__(self): # return self.__repr__() # # def update_last_seen(self): # self.last_seen = TimeFunctions.get_timestamp() # self.save() # # @property # def is_online(self): # if self.last_seen is None: # return False # # difference = TimeFunctions.get_timestamp() - self.last_seen # return difference < datetime.timedelta(minutes=10) # # Path: mass_flask_core/models/sample.py # class Sample(db.Document, CommentsMixin): # delivery_date = DateTimeField(default=TimeFunctions.get_timestamp, required=True) # first_seen = DateTimeField(default=TimeFunctions.get_timestamp, required=True) # tags = ListField(StringField(regex=r'^[\w:\-\_\/\+\.]+$')) # dispatched_to = ListField(ReferenceField(AnalysisSystem)) # created_by = GenericReferenceField() # tlp_level = TLPLevelField(verbose_name='TLP Level', help_text='Privacy level of this sample', required=True) # # meta = { # 'allow_inheritance': True, # 'ordering': ['-delivery_date'], # 'indexes': ['delivery_date'], # 'queryset_class': SampleQuerySet # } # # def __repr__(self): # return '[{}] {}'.format(str(self.__class__.__name__), str(self.id)) # # def __str__(self): # return self.__repr__() # # @property # def title(self): # return self.id # # def add_tags(self, tags): # self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags) # self.save() # # def _update(self, **kwargs): # if 'first_seen' in kwargs and kwargs['first_seen'] < self.first_seen: # self.first_seen = kwargs['first_seen'] # if 'tlp_level' in kwargs and not self.tlp_level: # self.tlp_level = kwargs['tlp_level'] # if current_authenticated_entity.is_authenticated and not self.created_by: # self.created_by = current_authenticated_entity._get_current_object() # if 'tags' in kwargs: # tags = kwargs['tags'] # else: # tags = [] # self.tags = ListFunctions.merge_lists_without_duplicates(self.tags, tags) # # @classmethod # def create_or_update(cls, **kwargs): # raise ValidationError('Samples of the base type Sample should not be instantiated directly.') # # Path: mass_flask_core/utils/time_functions.py # class TimeFunctions: # @staticmethod # def get_timestamp(): # # We remove the microsecond part of the timestamp here since mongoengine can not handle it correctly and test cases fail due to the lost precision # return datetime.now(utc).replace(microsecond=0) . Output only the next line.
'ordering': ['-analysis_scheduled'],
Using the snippet: <|code_start|> @webui_blueprint.route('/profile/', methods=['GET']) @privilege_required(RolePrivilege('user')) def profile(): api_key = UserAPIKey.get_or_create(current_authenticated_entity).generate_auth_token() <|code_end|> , determine the next line of code. You have imports: from flask import render_template from flask_modular_auth import current_authenticated_entity, privilege_required, RolePrivilege from mass_flask_core.models import UserAPIKey from mass_flask_webui.config import webui_blueprint and context (class names, function names, or code) available: # Path: mass_flask_core/models/api_key.py # class UserAPIKey(APIKey): # user = ReferenceField(User, required=True) # # @staticmethod # def get_or_create(user): # api_key = UserAPIKey.objects(user=user.id).first() # if not api_key: # api_key = UserAPIKey(user=user.id) # api_key.save() # return api_key # # @property # def referenced_entity(self): # return self.user # # Path: mass_flask_webui/config.py . Output only the next line.
return render_template('profile.html', api_key=api_key)
Here is a snippet: <|code_start|> @webui_blueprint.route('/profile/', methods=['GET']) @privilege_required(RolePrivilege('user')) def profile(): api_key = UserAPIKey.get_or_create(current_authenticated_entity).generate_auth_token() <|code_end|> . Write the next line using the current file imports: from flask import render_template from flask_modular_auth import current_authenticated_entity, privilege_required, RolePrivilege from mass_flask_core.models import UserAPIKey from mass_flask_webui.config import webui_blueprint and context from other files: # Path: mass_flask_core/models/api_key.py # class UserAPIKey(APIKey): # user = ReferenceField(User, required=True) # # @staticmethod # def get_or_create(user): # api_key = UserAPIKey.objects(user=user.id).first() # if not api_key: # api_key = UserAPIKey(user=user.id) # api_key.save() # return api_key # # @property # def referenced_entity(self): # return self.user # # Path: mass_flask_webui/config.py , which may include functions, classes, or code. Output only the next line.
return render_template('profile.html', api_key=api_key)
Given the code snippet: <|code_start|> BASE = os.path.join(FileBASE,sub) commit = '0' branch = 'manual' describe = '' commit_short = '' if BASE is not None: try: os.chdir(BASE) branch = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], stderr=subprocess.STDOUT).decode().strip('\n') commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], stderr=subprocess.STDOUT).decode().strip('\n') commit_short = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], stderr=subprocess.STDOUT).decode().strip('\n') describe = subprocess.check_output(['git', 'describe', '--all'], stderr=subprocess.STDOUT).decode().strip('\n') except Exception as e: pass if printout: print() print("_get_git_data: BASE={}".format(BASE)) print("- describe: {}".format(describe)) print("- commit_short : {}".format(commit_short)) print("- commit .: {}".format(commit)) print("- branch .: {}".format(branch)) print() return commit, commit_short, branch, describe # --------------------------------------------------------------------------------- def get_shng_main_version(): return Version.format( shNG_version ) def get_shng_plugins_version(): <|code_end|> , generate the next line using the imports in this file: import os import sys import subprocess import plugins.__init__ as plugin_vers from lib.utils import Version and context (functions, classes, or occasionally code) from other files: # Path: lib/utils.py # class Version(): # # @staticmethod # def check_list(versl): # # while len(versl) < 4: # if isinstance(versl[0], str): # versl.append('0') # else: # versl.append(0) # while len(versl) > 4: # del versl[-1] # return versl # # @classmethod # def to_list(cls, vers): # """ # Split version number to list and get rid of non-numeric parts # # :param vers: # # :return: version as list # :rtype: list # """ # if len(vers) == 0: # vers = '0' # if vers[0].lower() == 'v': # vers = vers[1:] # # # create list with [major,minor,revision,build] # vsplit = vers.split('.') # vsplit = cls.check_list(vsplit) # # # get rid of non numeric parts # vlist = [] # build = 0 # if vsplit == '': # return '' # for v in vsplit: # if v[-1].isalpha(): # build += ord(v[-1].lower()) - 96 # v = v[:-1] # vi = 0 # try: # vi = int(v) # except: # pass # vlist.append(vi) # vlist[3] += build # return vlist # # @classmethod # def to_string(cls, versl): # # if versl == [0, 0, 0, 0]: # return '' # import copy # versl2 = copy.deepcopy(versl) # cls.check_list(versl2) # if versl2 == '': # return '' # # if versl2[3] == 0: # del versl2[3] # versls = [str(int) for int in versl2] # vers = ".".join(versls) # # return 'v' + vers # # @classmethod # def format(cls, vers): # # return cls.to_string(cls.to_list(str(vers))) # # @classmethod # def compare(cls, v1, v2, operator): # """ # Compare two version numbers and return if the condition is met # # :param v1: # :param v2: # :param operator: # :type v1: str or list of int # :type v2: str or list of int # :type operator: str # # :return: true if condition is met # :rtype: bool # """ # if isinstance(v1, str): # v1 = cls.to_list(v1) # if isinstance(v2, str): # v2 = cls.to_list(v2) # # result = False # if v1 == v2 and operator in ['>=', '==', '<=']: # result = True # if v1 < v2 and operator in ['<', '<=']: # result = True # if v1 > v2 and operator in ['>', '>=']: # result = True # # logger.warning(f"_compare_versions: v1={v1}, v2={v2}, operator='{operator}', result={result}") # return result . Output only the next line.
plgversion = get_plugins_version().split('-')[0]
Here is a snippet: <|code_start|># SmartHomeNG 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. # # SmartHomeNG 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 SmartHomeNG. If not, see <http://www.gnu.org/licenses/>. ######################################################################### try: HOLIDAYS_imported = True except: HOLIDAYS_imported = False #from lib.translation import translate _shtime_instance = None # Pointer to the initialized instance of the shtime class (for use by static methods) class Shtime: _tzinfo = None <|code_end|> . Write the next line using the current file imports: import holidays import datetime import dateutil import pytz import dateutil.relativedelta import json import logging import os import lib.shyaml as shyaml import inspect from dateutil.tz import tzlocal from dateutil import parser from lib.constants import (YAML_FILE) from lib.translation import translate as lib_translate and context from other files: # Path: lib/constants.py # YAML_FILE = '.yaml' , which may include functions, classes, or code. Output only the next line.
_timezone = None
Predict the next line after this snippet: <|code_start|> try: except ImportError: # Django < 1.10 # Works perfectly for everyone using MIDDLEWARE_CLASSES MiddlewareMixin = object class MfaMiddleware(MiddlewareMixin): def process_request(self, request): if request.user.is_authenticated and ((is_mfa_enabled(request.user) and not verify_rmb_cookie(request)) or is_u2f_enabled(request.user)): if not request.session.get('verfied_otp') and not request.session.get('verfied_u2f'): <|code_end|> using the current file's imports: from django.urls import reverse from django.shortcuts import resolve_url from django.contrib.auth import REDIRECT_FIELD_NAME as redirect_field_name from .models import is_mfa_enabled, is_u2f_enabled from .views import verify_rmb_cookie from django.utils.deprecation import MiddlewareMixin from django.contrib.auth.views import redirect_to_login and any relevant context from other files: # Path: django_mfa/models.py # def is_mfa_enabled(user): # """ # Determine if a user has MFA enabled # """ # return hasattr(user, 'userotp') # # def is_u2f_enabled(user): # """ # Determine if a user has U2F enabled # """ # return user.u2f_keys.all().exists() # # Path: django_mfa/views.py # def verify_rmb_cookie(request): # try: # remember_my_browser = settings.MFA_REMEMBER_MY_BROWSER # max_cookie_age = settings.MFA_REMEMBER_DAYS * 24 * 3600 # except: # return False # if not remember_my_browser: # return False # # cookie_name = MFA_COOKIE_PREFIX + str(request.user.pk) # cookie_salt = _generate_cookie_salt(request.user) # if not cookie_salt: # return False # cookie_value = request.get_signed_cookie( # cookie_name, False, max_age=max_cookie_age, salt=cookie_salt) # # if the cookie value is True and the signature is good than the browser can be trusted # return cookie_value . Output only the next line.
current_path = request.path
Given the code snippet: <|code_start|> try: except ImportError: # Django < 1.10 # Works perfectly for everyone using MIDDLEWARE_CLASSES MiddlewareMixin = object <|code_end|> , generate the next line using the imports in this file: from django.urls import reverse from django.shortcuts import resolve_url from django.contrib.auth import REDIRECT_FIELD_NAME as redirect_field_name from .models import is_mfa_enabled, is_u2f_enabled from .views import verify_rmb_cookie from django.utils.deprecation import MiddlewareMixin from django.contrib.auth.views import redirect_to_login and context (functions, classes, or occasionally code) from other files: # Path: django_mfa/models.py # def is_mfa_enabled(user): # """ # Determine if a user has MFA enabled # """ # return hasattr(user, 'userotp') # # def is_u2f_enabled(user): # """ # Determine if a user has U2F enabled # """ # return user.u2f_keys.all().exists() # # Path: django_mfa/views.py # def verify_rmb_cookie(request): # try: # remember_my_browser = settings.MFA_REMEMBER_MY_BROWSER # max_cookie_age = settings.MFA_REMEMBER_DAYS * 24 * 3600 # except: # return False # if not remember_my_browser: # return False # # cookie_name = MFA_COOKIE_PREFIX + str(request.user.pk) # cookie_salt = _generate_cookie_salt(request.user) # if not cookie_salt: # return False # cookie_value = request.get_signed_cookie( # cookie_name, False, max_age=max_cookie_age, salt=cookie_salt) # # if the cookie value is True and the signature is good than the browser can be trusted # return cookie_value . Output only the next line.
class MfaMiddleware(MiddlewareMixin):
Given the following code snippet before the placeholder: <|code_start|> try: except ImportError: # Django < 1.10 # Works perfectly for everyone using MIDDLEWARE_CLASSES MiddlewareMixin = object class MfaMiddleware(MiddlewareMixin): def process_request(self, request): if request.user.is_authenticated and ((is_mfa_enabled(request.user) and not verify_rmb_cookie(request)) or is_u2f_enabled(request.user)): if not request.session.get('verfied_otp') and not request.session.get('verfied_u2f'): current_path = request.path paths = [reverse("mfa:verify_second_factor"), reverse( "mfa:verify_second_factor_u2f"), reverse("mfa:verify_second_factor_totp")] if current_path not in paths: path = request.get_full_path() resolved_login_url = resolve_url( reverse("mfa:verify_second_factor")) return redirect_to_login(path, resolved_login_url, redirect_field_name) <|code_end|> , predict the next line using imports from the current file: from django.urls import reverse from django.shortcuts import resolve_url from django.contrib.auth import REDIRECT_FIELD_NAME as redirect_field_name from .models import is_mfa_enabled, is_u2f_enabled from .views import verify_rmb_cookie from django.utils.deprecation import MiddlewareMixin from django.contrib.auth.views import redirect_to_login and context including class names, function names, and sometimes code from other files: # Path: django_mfa/models.py # def is_mfa_enabled(user): # """ # Determine if a user has MFA enabled # """ # return hasattr(user, 'userotp') # # def is_u2f_enabled(user): # """ # Determine if a user has U2F enabled # """ # return user.u2f_keys.all().exists() # # Path: django_mfa/views.py # def verify_rmb_cookie(request): # try: # remember_my_browser = settings.MFA_REMEMBER_MY_BROWSER # max_cookie_age = settings.MFA_REMEMBER_DAYS * 24 * 3600 # except: # return False # if not remember_my_browser: # return False # # cookie_name = MFA_COOKIE_PREFIX + str(request.user.pk) # cookie_salt = _generate_cookie_salt(request.user) # if not cookie_salt: # return False # cookie_value = request.get_signed_cookie( # cookie_name, False, max_age=max_cookie_age, salt=cookie_salt) # # if the cookie value is True and the signature is good than the browser can be trusted # return cookie_value . Output only the next line.
return None
Next line prediction: <|code_start|> def index(request): if request.user and request.user.is_authenticated: return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) if request.method == 'POST': form = LoginForm(request.POST, request.FILES) if form.is_valid(): user = form.user if is_u2f_enabled(user): request.session['u2f_pre_verify_user_pk'] = user.pk request.session['u2f_pre_verify_user_backend'] = user.backend login(request, form.user) return JsonResponse({"error": False}) else: return JsonResponse({"error": True, "errors": form.errors}) context = { "registration_form": RegistrationForm, "login_form": LoginForm } <|code_end|> . Use current file imports: (from django.shortcuts import render from django.contrib.auth import login, logout from django.http.response import HttpResponseRedirect, JsonResponse from .forms import RegistrationForm, LoginForm from django.contrib.auth.models import User from django_mfa.models import is_u2f_enabled from django.conf import settings) and context including class names, function names, or small code snippets from other files: # Path: sandbox/sample/forms.py # class RegistrationForm(forms.Form): # email = forms.EmailField() # password = forms.CharField(widget=forms.PasswordInput) # confirm_password = forms.CharField(widget=forms.PasswordInput) # # def __init__(self, *args, **kwargs): # super(RegistrationForm, self).__init__(*args, **kwargs) # for field in self.fields.values(): # field.widget.attrs = {'class': 'form-control'} # # def clean_confirm_password(self): # password = self.cleaned_data.get("password") # confirm_password = self.cleaned_data.get("confirm_password") # if password and confirm_password and password != confirm_password: # raise forms.ValidationError("Passwords not matched") # return confirm_password # # class LoginForm(forms.Form): # email = forms.EmailField() # password = forms.CharField(widget=forms.PasswordInput) # # def __init__(self, *args, **kwargs): # super(LoginForm, self).__init__(*args, **kwargs) # for field in self.fields.values(): # field.widget.attrs = {'class': 'form-control'} # # def clean(self): # email = self.cleaned_data.get('email') # password = self.cleaned_data.get('password') # self.user = authenticate(username=email, password=password) # if not self.user: # raise forms.ValidationError("Invalid Credentials") # return self.cleaned_data # # Path: django_mfa/models.py # def is_u2f_enabled(user): # """ # Determine if a user has U2F enabled # """ # return user.u2f_keys.all().exists() . Output only the next line.
return render(request, 'login.html', context)
Predict the next line after this snippet: <|code_start|> user = form.user if is_u2f_enabled(user): request.session['u2f_pre_verify_user_pk'] = user.pk request.session['u2f_pre_verify_user_backend'] = user.backend login(request, form.user) return JsonResponse({"error": False}) else: return JsonResponse({"error": True, "errors": form.errors}) context = { "registration_form": RegistrationForm, "login_form": LoginForm } return render(request, 'login.html', context) def register(request): form = RegistrationForm(request.POST, request.FILES) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = User.objects.create(email=email, username=email) user.set_password(password) user.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return JsonResponse({"error": False}) else: return JsonResponse({"error": True, "errors": form.errors}) <|code_end|> using the current file's imports: from django.shortcuts import render from django.contrib.auth import login, logout from django.http.response import HttpResponseRedirect, JsonResponse from .forms import RegistrationForm, LoginForm from django.contrib.auth.models import User from django_mfa.models import is_u2f_enabled from django.conf import settings and any relevant context from other files: # Path: sandbox/sample/forms.py # class RegistrationForm(forms.Form): # email = forms.EmailField() # password = forms.CharField(widget=forms.PasswordInput) # confirm_password = forms.CharField(widget=forms.PasswordInput) # # def __init__(self, *args, **kwargs): # super(RegistrationForm, self).__init__(*args, **kwargs) # for field in self.fields.values(): # field.widget.attrs = {'class': 'form-control'} # # def clean_confirm_password(self): # password = self.cleaned_data.get("password") # confirm_password = self.cleaned_data.get("confirm_password") # if password and confirm_password and password != confirm_password: # raise forms.ValidationError("Passwords not matched") # return confirm_password # # class LoginForm(forms.Form): # email = forms.EmailField() # password = forms.CharField(widget=forms.PasswordInput) # # def __init__(self, *args, **kwargs): # super(LoginForm, self).__init__(*args, **kwargs) # for field in self.fields.values(): # field.widget.attrs = {'class': 'form-control'} # # def clean(self): # email = self.cleaned_data.get('email') # password = self.cleaned_data.get('password') # self.user = authenticate(username=email, password=password) # if not self.user: # raise forms.ValidationError("Invalid Credentials") # return self.cleaned_data # # Path: django_mfa/models.py # def is_u2f_enabled(user): # """ # Determine if a user has U2F enabled # """ # return user.u2f_keys.all().exists() . Output only the next line.
def home(request):
Here is a snippet: <|code_start|> try: except ImportError: warnings.warn("Pandas library not installed, dataframes disabled") pd = None <|code_end|> . Write the next line using the current file imports: import sys import warnings import requests import re import json import csv import pandas as pd import doctest from lxml import etree from pkg_resources import resource_filename from pytaxize.refactor import Refactor from pytaxize.itis.itis import _df and context from other files: # Path: pytaxize/refactor.py # class Refactor: # def __init__(self, url, payload={}, request="get"): # self.url = url # self.payload = payload # self.request = request # # def return_requests(self, **kwargs): # if self.request == "get": # return requests.get(self.url, params=self.payload, **kwargs) # else: # return requests.post(self.url, params=self.payload, **kwargs) # # def xml(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # xmlparser = etree.XMLParser() # tt = etree.fromstring(out.content, xmlparser) # try: # # If entrez api 'X-RateLimit-Remaining' header is 1 or below, pause for a second to allow rate limit to reset # if (int(out.headers['X-RateLimit-Remaining'])<=1): # time.sleep(1) # except: # pass # return tt # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # xmlparser = etree.XMLParser() # tt = etree.fromstring(out.content, xmlparser) # return tt # # def json(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.json() # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.json() # # def raw(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.text # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.text # # Path: pytaxize/itis/itis.py # def _df(x, as_dataframe=False): # if as_dataframe and pd: # if isinstance(x, dict): # x = [x] # df = pd.DataFrame.from_records(x) # return df # else: # return x , which may include functions, classes, or code. Output only the next line.
class NoResultException(Exception):
Here is a snippet: <|code_start|> try: except ImportError: warnings.warn("Pandas library not installed, dataframes disabled") pd = None class NoResultException(Exception): <|code_end|> . Write the next line using the current file imports: import sys import warnings import requests import re import json import csv import pandas as pd import doctest from lxml import etree from pkg_resources import resource_filename from pytaxize.refactor import Refactor from pytaxize.itis.itis import _df and context from other files: # Path: pytaxize/refactor.py # class Refactor: # def __init__(self, url, payload={}, request="get"): # self.url = url # self.payload = payload # self.request = request # # def return_requests(self, **kwargs): # if self.request == "get": # return requests.get(self.url, params=self.payload, **kwargs) # else: # return requests.post(self.url, params=self.payload, **kwargs) # # def xml(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # xmlparser = etree.XMLParser() # tt = etree.fromstring(out.content, xmlparser) # try: # # If entrez api 'X-RateLimit-Remaining' header is 1 or below, pause for a second to allow rate limit to reset # if (int(out.headers['X-RateLimit-Remaining'])<=1): # time.sleep(1) # except: # pass # return tt # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # xmlparser = etree.XMLParser() # tt = etree.fromstring(out.content, xmlparser) # return tt # # def json(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.json() # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.json() # # def raw(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.text # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.text # # Path: pytaxize/itis/itis.py # def _df(x, as_dataframe=False): # if as_dataframe and pd: # if isinstance(x, dict): # x = [x] # df = pd.DataFrame.from_records(x) # return df # else: # return x , which may include functions, classes, or code. Output only the next line.
pass
Here is a snippet: <|code_start|> def gbif_query_for_single_name(name, rank): response = species.name_usage(name=name, rank=rank.upper())["results"] return response def process_gbif_response(list_of_response_dicts, rank): key = rank + "Key" extracted_ids = list( map( lambda x: _make_id(x.get(key, None), x.get(rank, None), rank, "gbif"), list_of_response_dicts, ) ) <|code_end|> . Write the next line using the current file imports: from pygbif import species from .format_helpers import _make_id and context from other files: # Path: pytaxize/ids/format_helpers.py # def _make_id(id_, name, rank, type_): # uri = None # if id_ is not None: # uri = _make_id_uri(rank, type_, id_) # # return {"id": id_, "name": name, "rank": rank, "uri": uri} , which may include functions, classes, or code. Output only the next line.
return extracted_ids
Predict the next line for this snippet: <|code_start|> def eol_search_query_for_single_name(name): # will replace later with either a pre-made package # or with an implementation of EoL in taxize response = ( Refactor( url="https://eol.org/api/search/1.0.json", request="get", payload={'q':name,'exact':True} ) .json() .get("results", {}) ) return response def eol_taxa_query(list_of_ids): <|code_end|> with the help of current file imports: from ..refactor import Refactor from .format_helpers import _make_id and context from other files: # Path: pytaxize/refactor.py # class Refactor: # def __init__(self, url, payload={}, request="get"): # self.url = url # self.payload = payload # self.request = request # # def return_requests(self, **kwargs): # if self.request == "get": # return requests.get(self.url, params=self.payload, **kwargs) # else: # return requests.post(self.url, params=self.payload, **kwargs) # # def xml(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # xmlparser = etree.XMLParser() # tt = etree.fromstring(out.content, xmlparser) # try: # # If entrez api 'X-RateLimit-Remaining' header is 1 or below, pause for a second to allow rate limit to reset # if (int(out.headers['X-RateLimit-Remaining'])<=1): # time.sleep(1) # except: # pass # return tt # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # xmlparser = etree.XMLParser() # tt = etree.fromstring(out.content, xmlparser) # return tt # # def json(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.json() # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.json() # # def raw(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.text # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.text # # Path: pytaxize/ids/format_helpers.py # def _make_id(id_, name, rank, type_): # uri = None # if id_ is not None: # uri = _make_id_uri(rank, type_, id_) # # return {"id": id_, "name": name, "rank": rank, "uri": uri} , which may contain function names, class names, or code. Output only the next line.
return list(map(eol_taxa_query_for_single_PageID, list_of_ids))
Predict the next line after this snippet: <|code_start|> response = list(map(lambda x: {**x, "page_id": pid}, response)) return response def process_eol_search_response(name_response_tuple): user_input_name, list_of_response_dicts = name_response_tuple user_input_name = user_input_name.lower() extracted_ids = list( filter( lambda page_dict: user_input_name in page_dict["title"].lower(), list_of_response_dicts, ) ) extracted_ids = list( map(lambda page_dict: page_dict.get("id", None), list_of_response_dicts,) ) extracted_ids = list(filter(lambda id_: id_ is not None, extracted_ids)) return extracted_ids def process_list_of_taxa_details(list_of_responses): useful_data = list( map( lambda x: { **_make_id( x.get("identifier", ""), x.get("scientificName", ""), x.get("taxonRank", None), "eol", ), <|code_end|> using the current file's imports: from ..refactor import Refactor from .format_helpers import _make_id and any relevant context from other files: # Path: pytaxize/refactor.py # class Refactor: # def __init__(self, url, payload={}, request="get"): # self.url = url # self.payload = payload # self.request = request # # def return_requests(self, **kwargs): # if self.request == "get": # return requests.get(self.url, params=self.payload, **kwargs) # else: # return requests.post(self.url, params=self.payload, **kwargs) # # def xml(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # xmlparser = etree.XMLParser() # tt = etree.fromstring(out.content, xmlparser) # try: # # If entrez api 'X-RateLimit-Remaining' header is 1 or below, pause for a second to allow rate limit to reset # if (int(out.headers['X-RateLimit-Remaining'])<=1): # time.sleep(1) # except: # pass # return tt # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # xmlparser = etree.XMLParser() # tt = etree.fromstring(out.content, xmlparser) # return tt # # def json(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.json() # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.json() # # def raw(self, **kwargs): # if self.request == "get": # out = requests.get(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.text # else: # out = requests.post(self.url, params=self.payload, **kwargs) # out.raise_for_status() # return out.text # # Path: pytaxize/ids/format_helpers.py # def _make_id(id_, name, rank, type_): # uri = None # if id_ is not None: # uri = _make_id_uri(rank, type_, id_) # # return {"id": id_, "name": name, "rank": rank, "uri": uri} . Output only the next line.
"page_id": x.get("page_id", ""),
Here is a snippet: <|code_start|> dataset = data.DATASETS()[FLAGS.dataset]() log_width = utils.ilog2(dataset.width) model = CTAFSMixup( os.path.join(FLAGS.train_dir, dataset.name, CTAFSMixup.cta_name()), dataset, lr=FLAGS.lr, wd=FLAGS.wd, arch=FLAGS.arch, batch=FLAGS.batch, nclass=dataset.nclass, ema=FLAGS.ema, beta=FLAGS.beta, dropout=FLAGS.dropout, scales=FLAGS.scales or (log_width - 2), filters=FLAGS.filters, repeat=FLAGS.repeat) model.train(FLAGS.train_kimg << 10, FLAGS.report_kimg << 10) if __name__ == '__main__': utils.setup_tf() flags.DEFINE_float('wd', 0.002, 'Weight decay.') flags.DEFINE_float('ema', 0.999, 'Exponential moving average of params.') flags.DEFINE_float('beta', 0.5, 'Mixup beta distribution.') flags.DEFINE_float('dropout', 0, 'Dropout on embedding layer.') flags.DEFINE_integer('scales', 0, 'Number of 2x2 downscalings in the classifier.') flags.DEFINE_integer('filters', 32, 'Filter size of convolutions.') flags.DEFINE_integer('repeat', 4, 'Number of residual layers per stage.') FLAGS.set_default('augment', 'd.d') <|code_end|> . Write the next line using the current file imports: import os from absl import app from absl import flags from cta.lib.train import CTAClassifyFullySupervised from fully_supervised.fs_mixup import FSMixup from fully_supervised.lib import data from libml import utils and context from other files: # Path: cta/lib/train.py # class CTAClassifyFullySupervised(ClassifyFullySupervised, CTAClassifySemi): # """Fully-supervised classification.""" # # def train_step(self, train_session, gen_labeled): # x = gen_labeled() # v = train_session.run([self.ops.classify_op, self.ops.train_op, self.ops.update_step], # feed_dict={self.ops.x: x['probe'], # self.ops.xt: x['image'], # self.ops.label: x['label']}) # self.tmp.step = v[-1] # lx = v[0] # for p in range(lx.shape[0]): # error = lx[p] # error[x['label'][p]] -= 1 # error = np.abs(error).sum() # self.augmenter.update_rates(x['policy'][p], 1 - 0.5 * error) # # Path: fully_supervised/lib/data.py # FLAGS = flags.FLAGS # DATASETS = create_datasets # class DataSetsFS(data.DataSets): # def creator(cls, name, train_files, test_files, valid, augment, parse_fn=data.record_parse, do_memoize=True, # nclass=10, height=32, width=32, colors=3): # def create(): # def augment_function(dataset: str): # def create_datasets(): # # Path: libml/utils.py # _GPUS = None # FLAGS = flags.FLAGS # _GPUS = tuple([x.name for x in local_device_protos if x.device_type == 'GPU']) # class EasyDict(dict): # def __init__(self, *args, **kwargs): # def get_config(): # def setup_main(): # def setup_tf(): # def smart_shape(x): # def ilog2(x): # def find_latest_checkpoint(dir, glob_term='model.ckpt-*.meta'): # def get_latest_global_step(dir): # def get_latest_global_step_in_subdir(dir): # def getter_ema(ema, getter, name, *args, **kwargs): # def model_vars(scope=None): # def gpu(x): # def get_available_gpus(): # def get_gpu(): # def average_gradients(tower_grads): # def para_list(fn, *args): # def para_mean(fn, *args): # def para_cat(fn, *args): # def interleave(x, batch): # def de_interleave(x, batch): # def combine_dicts(*args): , which may include functions, classes, or code. Output only the next line.
FLAGS.set_default('dataset', 'cifar10-1')
Given the code snippet: <|code_start|> def main(argv): utils.setup_main() del argv # Unused. dataset = data.DATASETS()[FLAGS.dataset]() log_width = utils.ilog2(dataset.width) model = CTAFSMixup( os.path.join(FLAGS.train_dir, dataset.name, CTAFSMixup.cta_name()), dataset, lr=FLAGS.lr, wd=FLAGS.wd, arch=FLAGS.arch, batch=FLAGS.batch, nclass=dataset.nclass, ema=FLAGS.ema, beta=FLAGS.beta, dropout=FLAGS.dropout, scales=FLAGS.scales or (log_width - 2), filters=FLAGS.filters, repeat=FLAGS.repeat) model.train(FLAGS.train_kimg << 10, FLAGS.report_kimg << 10) if __name__ == '__main__': utils.setup_tf() flags.DEFINE_float('wd', 0.002, 'Weight decay.') flags.DEFINE_float('ema', 0.999, 'Exponential moving average of params.') flags.DEFINE_float('beta', 0.5, 'Mixup beta distribution.') flags.DEFINE_float('dropout', 0, 'Dropout on embedding layer.') <|code_end|> , generate the next line using the imports in this file: import os from absl import app from absl import flags from cta.lib.train import CTAClassifyFullySupervised from fully_supervised.fs_mixup import FSMixup from fully_supervised.lib import data from libml import utils and context (functions, classes, or occasionally code) from other files: # Path: cta/lib/train.py # class CTAClassifyFullySupervised(ClassifyFullySupervised, CTAClassifySemi): # """Fully-supervised classification.""" # # def train_step(self, train_session, gen_labeled): # x = gen_labeled() # v = train_session.run([self.ops.classify_op, self.ops.train_op, self.ops.update_step], # feed_dict={self.ops.x: x['probe'], # self.ops.xt: x['image'], # self.ops.label: x['label']}) # self.tmp.step = v[-1] # lx = v[0] # for p in range(lx.shape[0]): # error = lx[p] # error[x['label'][p]] -= 1 # error = np.abs(error).sum() # self.augmenter.update_rates(x['policy'][p], 1 - 0.5 * error) # # Path: fully_supervised/lib/data.py # FLAGS = flags.FLAGS # DATASETS = create_datasets # class DataSetsFS(data.DataSets): # def creator(cls, name, train_files, test_files, valid, augment, parse_fn=data.record_parse, do_memoize=True, # nclass=10, height=32, width=32, colors=3): # def create(): # def augment_function(dataset: str): # def create_datasets(): # # Path: libml/utils.py # _GPUS = None # FLAGS = flags.FLAGS # _GPUS = tuple([x.name for x in local_device_protos if x.device_type == 'GPU']) # class EasyDict(dict): # def __init__(self, *args, **kwargs): # def get_config(): # def setup_main(): # def setup_tf(): # def smart_shape(x): # def ilog2(x): # def find_latest_checkpoint(dir, glob_term='model.ckpt-*.meta'): # def get_latest_global_step(dir): # def get_latest_global_step_in_subdir(dir): # def getter_ema(ema, getter, name, *args, **kwargs): # def model_vars(scope=None): # def gpu(x): # def get_available_gpus(): # def get_gpu(): # def average_gradients(tower_grads): # def para_list(fn, *args): # def para_mean(fn, *args): # def para_cat(fn, *args): # def interleave(x, batch): # def de_interleave(x, batch): # def combine_dicts(*args): . Output only the next line.
flags.DEFINE_integer('scales', 0, 'Number of 2x2 downscalings in the classifier.')
Based on the snippet: <|code_start|> def main(argv): utils.setup_main() del argv # Unused. dataset = data.DATASETS()[FLAGS.dataset]() log_width = utils.ilog2(dataset.width) model = CTAFSMixup( os.path.join(FLAGS.train_dir, dataset.name, CTAFSMixup.cta_name()), dataset, lr=FLAGS.lr, wd=FLAGS.wd, arch=FLAGS.arch, batch=FLAGS.batch, nclass=dataset.nclass, ema=FLAGS.ema, beta=FLAGS.beta, dropout=FLAGS.dropout, scales=FLAGS.scales or (log_width - 2), filters=FLAGS.filters, repeat=FLAGS.repeat) model.train(FLAGS.train_kimg << 10, FLAGS.report_kimg << 10) if __name__ == '__main__': utils.setup_tf() flags.DEFINE_float('wd', 0.002, 'Weight decay.') flags.DEFINE_float('ema', 0.999, 'Exponential moving average of params.') flags.DEFINE_float('beta', 0.5, 'Mixup beta distribution.') <|code_end|> , predict the immediate next line with the help of imports: import os from absl import app from absl import flags from cta.lib.train import CTAClassifyFullySupervised from fully_supervised.fs_mixup import FSMixup from fully_supervised.lib import data from libml import utils and context (classes, functions, sometimes code) from other files: # Path: cta/lib/train.py # class CTAClassifyFullySupervised(ClassifyFullySupervised, CTAClassifySemi): # """Fully-supervised classification.""" # # def train_step(self, train_session, gen_labeled): # x = gen_labeled() # v = train_session.run([self.ops.classify_op, self.ops.train_op, self.ops.update_step], # feed_dict={self.ops.x: x['probe'], # self.ops.xt: x['image'], # self.ops.label: x['label']}) # self.tmp.step = v[-1] # lx = v[0] # for p in range(lx.shape[0]): # error = lx[p] # error[x['label'][p]] -= 1 # error = np.abs(error).sum() # self.augmenter.update_rates(x['policy'][p], 1 - 0.5 * error) # # Path: fully_supervised/lib/data.py # FLAGS = flags.FLAGS # DATASETS = create_datasets # class DataSetsFS(data.DataSets): # def creator(cls, name, train_files, test_files, valid, augment, parse_fn=data.record_parse, do_memoize=True, # nclass=10, height=32, width=32, colors=3): # def create(): # def augment_function(dataset: str): # def create_datasets(): # # Path: libml/utils.py # _GPUS = None # FLAGS = flags.FLAGS # _GPUS = tuple([x.name for x in local_device_protos if x.device_type == 'GPU']) # class EasyDict(dict): # def __init__(self, *args, **kwargs): # def get_config(): # def setup_main(): # def setup_tf(): # def smart_shape(x): # def ilog2(x): # def find_latest_checkpoint(dir, glob_term='model.ckpt-*.meta'): # def get_latest_global_step(dir): # def get_latest_global_step_in_subdir(dir): # def getter_ema(ema, getter, name, *args, **kwargs): # def model_vars(scope=None): # def gpu(x): # def get_available_gpus(): # def get_gpu(): # def average_gradients(tower_grads): # def para_list(fn, *args): # def para_mean(fn, *args): # def para_cat(fn, *args): # def interleave(x, batch): # def de_interleave(x, batch): # def combine_dicts(*args): . Output only the next line.
flags.DEFINE_float('dropout', 0, 'Dropout on embedding layer.')
Given snippet: <|code_start|> utils.setup_main() del argv # Unused. dataset = data.PAIR_DATASETS()[FLAGS.dataset]() log_width = utils.ilog2(dataset.width) model = AB_FixMatch_Momentum( os.path.join(FLAGS.train_dir, dataset.name, AB_FixMatch_Momentum.cta_name()), dataset, lr=FLAGS.lr, wd=FLAGS.wd, arch=FLAGS.arch, batch=FLAGS.batch, nclass=dataset.nclass, wu=FLAGS.wu, confidence=FLAGS.confidence, uratio=FLAGS.uratio, scales=FLAGS.scales or (log_width - 2), filters=FLAGS.filters, repeat=FLAGS.repeat, use_nesterov=FLAGS.nesterov, momentum=FLAGS.momentum) model.train(FLAGS.train_kimg << 10, FLAGS.report_kimg << 10) if __name__ == '__main__': utils.setup_tf() flags.DEFINE_float('confidence', 0.95, 'Confidence threshold.') flags.DEFINE_float('wd', 0.0005, 'Weight decay.') flags.DEFINE_float('wu', 1, 'Pseudo label loss weight.') flags.DEFINE_integer('filters', 32, 'Filter size of convolutions.') flags.DEFINE_integer('repeat', 4, 'Number of residual layers per stage.') <|code_end|> , continue by predicting the next line. Consider current file imports: import functools import os import numpy as np import tensorflow as tf from absl import app from absl import flags from cta.cta_remixmatch import CTAReMixMatch from libml import data, utils and context: # Path: libml/data.py # DATA_DIR = None # _DATA_CACHE = None # SAMPLES_PER_CLASS = [1, 2, 3, 4, 5, 10, 25, 100, 400] # FLAGS = flags.FLAGS # DATA_DIR = FLAGS.data_dir or os.environ['ML_DATA'] # DATASETS = functools.partial(create_datasets, augment_module.augment_function) # PAIR_DATASETS = functools.partial(create_datasets, augment_module.pair_augment_function) # MANY_DATASETS = functools.partial(create_datasets, augment_module.many_augment_function) # QUAD_DATASETS = functools.partial(create_datasets, augment_module.quad_augment_function) # def _data_setup(): # def record_parse_mnist(serialized_example, image_shape=None): # def record_parse(serialized_example, image_shape=None): # def compute_mean_std(data: tf.data.Dataset): # def iterator(): # def __init__(self, data: tf.data.Dataset, augment_fn: AugmentPair, parse_fn=record_parse, image_shape=None): # def from_files(cls, filenames: list, augment_fn: AugmentPair, parse_fn=record_parse, image_shape=None): # def fetch_dataset(filename): # def empty_data(cls, image_shape, augment_fn: AugmentPair = None): # def _get_null_input(_): # def __getattr__(self, item): # def call_and_update(*args, **kwargs): # def parse(self): # def numpy_augment(self, *args, **kwargs): # def augment(self): # def memoize(self): # def tf_get(index, image_shape): # def get(index): # def __init__(self, name, train_labeled: DataSet, train_unlabeled: DataSet, test: DataSet, valid: DataSet, # height=32, width=32, colors=3, nclass=10, mean=0, std=1, p_labeled=None, p_unlabeled=None): # def creator(cls, name, seed, label, valid, augment, parse_fn=record_parse, do_memoize=False, # nclass=10, colors=3, height=32, width=32): # def create(): # def create_datasets(augment_fn): # class DataSet: # class DataSets: # # Path: libml/utils.py # _GPUS = None # FLAGS = flags.FLAGS # _GPUS = tuple([x.name for x in local_device_protos if x.device_type == 'GPU']) # class EasyDict(dict): # def __init__(self, *args, **kwargs): # def get_config(): # def setup_main(): # def setup_tf(): # def smart_shape(x): # def ilog2(x): # def find_latest_checkpoint(dir, glob_term='model.ckpt-*.meta'): # def get_latest_global_step(dir): # def get_latest_global_step_in_subdir(dir): # def getter_ema(ema, getter, name, *args, **kwargs): # def model_vars(scope=None): # def gpu(x): # def get_available_gpus(): # def get_gpu(): # def average_gradients(tower_grads): # def para_list(fn, *args): # def para_mean(fn, *args): # def para_cat(fn, *args): # def interleave(x, batch): # def de_interleave(x, batch): # def combine_dicts(*args): which might include code, classes, or functions. Output only the next line.
flags.DEFINE_integer('scales', 0, 'Number of 2x2 downscalings in the classifier.')
Given the following code snippet before the placeholder: <|code_start|> model = AB_FixMatch_Momentum( os.path.join(FLAGS.train_dir, dataset.name, AB_FixMatch_Momentum.cta_name()), dataset, lr=FLAGS.lr, wd=FLAGS.wd, arch=FLAGS.arch, batch=FLAGS.batch, nclass=dataset.nclass, wu=FLAGS.wu, confidence=FLAGS.confidence, uratio=FLAGS.uratio, scales=FLAGS.scales or (log_width - 2), filters=FLAGS.filters, repeat=FLAGS.repeat, use_nesterov=FLAGS.nesterov, momentum=FLAGS.momentum) model.train(FLAGS.train_kimg << 10, FLAGS.report_kimg << 10) if __name__ == '__main__': utils.setup_tf() flags.DEFINE_float('confidence', 0.95, 'Confidence threshold.') flags.DEFINE_float('wd', 0.0005, 'Weight decay.') flags.DEFINE_float('wu', 1, 'Pseudo label loss weight.') flags.DEFINE_integer('filters', 32, 'Filter size of convolutions.') flags.DEFINE_integer('repeat', 4, 'Number of residual layers per stage.') flags.DEFINE_integer('scales', 0, 'Number of 2x2 downscalings in the classifier.') flags.DEFINE_integer('uratio', 7, 'Unlabeled batch size ratio.') flags.DEFINE_boolean('nesterov', True, 'Use Nesterov in the optimizer or not') flags.DEFINE_float('momentum', 0.9, 'Momentum of SGD optimizer') <|code_end|> , predict the next line using imports from the current file: import functools import os import numpy as np import tensorflow as tf from absl import app from absl import flags from cta.cta_remixmatch import CTAReMixMatch from libml import data, utils and context including class names, function names, and sometimes code from other files: # Path: libml/data.py # DATA_DIR = None # _DATA_CACHE = None # SAMPLES_PER_CLASS = [1, 2, 3, 4, 5, 10, 25, 100, 400] # FLAGS = flags.FLAGS # DATA_DIR = FLAGS.data_dir or os.environ['ML_DATA'] # DATASETS = functools.partial(create_datasets, augment_module.augment_function) # PAIR_DATASETS = functools.partial(create_datasets, augment_module.pair_augment_function) # MANY_DATASETS = functools.partial(create_datasets, augment_module.many_augment_function) # QUAD_DATASETS = functools.partial(create_datasets, augment_module.quad_augment_function) # def _data_setup(): # def record_parse_mnist(serialized_example, image_shape=None): # def record_parse(serialized_example, image_shape=None): # def compute_mean_std(data: tf.data.Dataset): # def iterator(): # def __init__(self, data: tf.data.Dataset, augment_fn: AugmentPair, parse_fn=record_parse, image_shape=None): # def from_files(cls, filenames: list, augment_fn: AugmentPair, parse_fn=record_parse, image_shape=None): # def fetch_dataset(filename): # def empty_data(cls, image_shape, augment_fn: AugmentPair = None): # def _get_null_input(_): # def __getattr__(self, item): # def call_and_update(*args, **kwargs): # def parse(self): # def numpy_augment(self, *args, **kwargs): # def augment(self): # def memoize(self): # def tf_get(index, image_shape): # def get(index): # def __init__(self, name, train_labeled: DataSet, train_unlabeled: DataSet, test: DataSet, valid: DataSet, # height=32, width=32, colors=3, nclass=10, mean=0, std=1, p_labeled=None, p_unlabeled=None): # def creator(cls, name, seed, label, valid, augment, parse_fn=record_parse, do_memoize=False, # nclass=10, colors=3, height=32, width=32): # def create(): # def create_datasets(augment_fn): # class DataSet: # class DataSets: # # Path: libml/utils.py # _GPUS = None # FLAGS = flags.FLAGS # _GPUS = tuple([x.name for x in local_device_protos if x.device_type == 'GPU']) # class EasyDict(dict): # def __init__(self, *args, **kwargs): # def get_config(): # def setup_main(): # def setup_tf(): # def smart_shape(x): # def ilog2(x): # def find_latest_checkpoint(dir, glob_term='model.ckpt-*.meta'): # def get_latest_global_step(dir): # def get_latest_global_step_in_subdir(dir): # def getter_ema(ema, getter, name, *args, **kwargs): # def model_vars(scope=None): # def gpu(x): # def get_available_gpus(): # def get_gpu(): # def average_gradients(tower_grads): # def para_list(fn, *args): # def para_mean(fn, *args): # def para_cat(fn, *args): # def interleave(x, batch): # def de_interleave(x, batch): # def combine_dicts(*args): . Output only the next line.
FLAGS.set_default('augment', 'd.d.d')
Predict the next line for this snippet: <|code_start|> post_ops.append(ema_op) train_op = tf.train.MomentumOptimizer(lr, 0.9, use_nesterov=True).minimize( loss_xe + wu * loss_xeu + wd * loss_wd, colocate_gradients_with_ops=True) with tf.control_dependencies([train_op]): train_op = tf.group(*post_ops) return utils.EasyDict( xt=xt_in, x=x_in, y=y_in, label=l_in, train_op=train_op, classify_raw=tf.nn.softmax(classifier(x_in, training=False)), # No EMA, for debugging. classify_op=tf.nn.softmax(classifier(x_in, getter=ema_getter, training=False))) def main(argv): utils.setup_main() del argv # Unused. dataset = data.PAIR_DATASETS()[FLAGS.dataset]() log_width = utils.ilog2(dataset.width) model = FixMatch_RA( os.path.join(FLAGS.train_dir, dataset.name), dataset, lr=FLAGS.lr, wd=FLAGS.wd, arch=FLAGS.arch, batch=FLAGS.batch, nclass=dataset.nclass, wu=FLAGS.wu, confidence=FLAGS.confidence, uratio=FLAGS.uratio, scales=FLAGS.scales or (log_width - 2), <|code_end|> with the help of current file imports: import functools import os import numpy as np import tensorflow as tf from absl import app from absl import flags from tqdm import trange from libml import data, utils, models and context from other files: # Path: libml/data.py # DATA_DIR = None # _DATA_CACHE = None # SAMPLES_PER_CLASS = [1, 2, 3, 4, 5, 10, 25, 100, 400] # FLAGS = flags.FLAGS # DATA_DIR = FLAGS.data_dir or os.environ['ML_DATA'] # DATASETS = functools.partial(create_datasets, augment_module.augment_function) # PAIR_DATASETS = functools.partial(create_datasets, augment_module.pair_augment_function) # MANY_DATASETS = functools.partial(create_datasets, augment_module.many_augment_function) # QUAD_DATASETS = functools.partial(create_datasets, augment_module.quad_augment_function) # def _data_setup(): # def record_parse_mnist(serialized_example, image_shape=None): # def record_parse(serialized_example, image_shape=None): # def compute_mean_std(data: tf.data.Dataset): # def iterator(): # def __init__(self, data: tf.data.Dataset, augment_fn: AugmentPair, parse_fn=record_parse, image_shape=None): # def from_files(cls, filenames: list, augment_fn: AugmentPair, parse_fn=record_parse, image_shape=None): # def fetch_dataset(filename): # def empty_data(cls, image_shape, augment_fn: AugmentPair = None): # def _get_null_input(_): # def __getattr__(self, item): # def call_and_update(*args, **kwargs): # def parse(self): # def numpy_augment(self, *args, **kwargs): # def augment(self): # def memoize(self): # def tf_get(index, image_shape): # def get(index): # def __init__(self, name, train_labeled: DataSet, train_unlabeled: DataSet, test: DataSet, valid: DataSet, # height=32, width=32, colors=3, nclass=10, mean=0, std=1, p_labeled=None, p_unlabeled=None): # def creator(cls, name, seed, label, valid, augment, parse_fn=record_parse, do_memoize=False, # nclass=10, colors=3, height=32, width=32): # def create(): # def create_datasets(augment_fn): # class DataSet: # class DataSets: # # Path: libml/utils.py # _GPUS = None # FLAGS = flags.FLAGS # _GPUS = tuple([x.name for x in local_device_protos if x.device_type == 'GPU']) # class EasyDict(dict): # def __init__(self, *args, **kwargs): # def get_config(): # def setup_main(): # def setup_tf(): # def smart_shape(x): # def ilog2(x): # def find_latest_checkpoint(dir, glob_term='model.ckpt-*.meta'): # def get_latest_global_step(dir): # def get_latest_global_step_in_subdir(dir): # def getter_ema(ema, getter, name, *args, **kwargs): # def model_vars(scope=None): # def gpu(x): # def get_available_gpus(): # def get_gpu(): # def average_gradients(tower_grads): # def para_list(fn, *args): # def para_mean(fn, *args): # def para_cat(fn, *args): # def interleave(x, batch): # def de_interleave(x, batch): # def combine_dicts(*args): , which may contain function names, class names, or code. Output only the next line.
filters=FLAGS.filters,
Based on the snippet: <|code_start|>def main(argv): utils.setup_main() del argv # Unused. dataset = data.PAIR_DATASETS()[FLAGS.dataset]() log_width = utils.ilog2(dataset.width) model = FixMatch_RA( os.path.join(FLAGS.train_dir, dataset.name), dataset, lr=FLAGS.lr, wd=FLAGS.wd, arch=FLAGS.arch, batch=FLAGS.batch, nclass=dataset.nclass, wu=FLAGS.wu, confidence=FLAGS.confidence, uratio=FLAGS.uratio, scales=FLAGS.scales or (log_width - 2), filters=FLAGS.filters, repeat=FLAGS.repeat) model.train(FLAGS.train_kimg << 10, FLAGS.report_kimg << 10) if __name__ == '__main__': utils.setup_tf() flags.DEFINE_float('confidence', 0.95, 'Confidence threshold.') flags.DEFINE_float('wd', 0.0005, 'Weight decay.') flags.DEFINE_float('wu', 1, 'Pseudo label loss weight.') flags.DEFINE_integer('filters', 32, 'Filter size of convolutions.') flags.DEFINE_integer('repeat', 4, 'Number of residual layers per stage.') flags.DEFINE_integer('scales', 0, 'Number of 2x2 downscalings in the classifier.') <|code_end|> , predict the immediate next line with the help of imports: import functools import os import numpy as np import tensorflow as tf from absl import app from absl import flags from tqdm import trange from libml import data, utils, models and context (classes, functions, sometimes code) from other files: # Path: libml/data.py # DATA_DIR = None # _DATA_CACHE = None # SAMPLES_PER_CLASS = [1, 2, 3, 4, 5, 10, 25, 100, 400] # FLAGS = flags.FLAGS # DATA_DIR = FLAGS.data_dir or os.environ['ML_DATA'] # DATASETS = functools.partial(create_datasets, augment_module.augment_function) # PAIR_DATASETS = functools.partial(create_datasets, augment_module.pair_augment_function) # MANY_DATASETS = functools.partial(create_datasets, augment_module.many_augment_function) # QUAD_DATASETS = functools.partial(create_datasets, augment_module.quad_augment_function) # def _data_setup(): # def record_parse_mnist(serialized_example, image_shape=None): # def record_parse(serialized_example, image_shape=None): # def compute_mean_std(data: tf.data.Dataset): # def iterator(): # def __init__(self, data: tf.data.Dataset, augment_fn: AugmentPair, parse_fn=record_parse, image_shape=None): # def from_files(cls, filenames: list, augment_fn: AugmentPair, parse_fn=record_parse, image_shape=None): # def fetch_dataset(filename): # def empty_data(cls, image_shape, augment_fn: AugmentPair = None): # def _get_null_input(_): # def __getattr__(self, item): # def call_and_update(*args, **kwargs): # def parse(self): # def numpy_augment(self, *args, **kwargs): # def augment(self): # def memoize(self): # def tf_get(index, image_shape): # def get(index): # def __init__(self, name, train_labeled: DataSet, train_unlabeled: DataSet, test: DataSet, valid: DataSet, # height=32, width=32, colors=3, nclass=10, mean=0, std=1, p_labeled=None, p_unlabeled=None): # def creator(cls, name, seed, label, valid, augment, parse_fn=record_parse, do_memoize=False, # nclass=10, colors=3, height=32, width=32): # def create(): # def create_datasets(augment_fn): # class DataSet: # class DataSets: # # Path: libml/utils.py # _GPUS = None # FLAGS = flags.FLAGS # _GPUS = tuple([x.name for x in local_device_protos if x.device_type == 'GPU']) # class EasyDict(dict): # def __init__(self, *args, **kwargs): # def get_config(): # def setup_main(): # def setup_tf(): # def smart_shape(x): # def ilog2(x): # def find_latest_checkpoint(dir, glob_term='model.ckpt-*.meta'): # def get_latest_global_step(dir): # def get_latest_global_step_in_subdir(dir): # def getter_ema(ema, getter, name, *args, **kwargs): # def model_vars(scope=None): # def gpu(x): # def get_available_gpus(): # def get_gpu(): # def average_gradients(tower_grads): # def para_list(fn, *args): # def para_mean(fn, *args): # def para_cat(fn, *args): # def interleave(x, batch): # def de_interleave(x, batch): # def combine_dicts(*args): . Output only the next line.
flags.DEFINE_integer('uratio', 7, 'Unlabeled batch size ratio.')
Given the following code snippet before the placeholder: <|code_start|>sys.path.extend(['.', '..']) inf = float('inf') _logger = get_logger() class BDT(Basic): <|code_end|> , predict the next line using imports from the current file: import json import time import pdb import sys import Orange import orange import heapq import bsddb as bsddb3 import bsddb as bsddb3 from multiprocessing import Process, Queue, Pool, Pipe from Queue import Empty from collections import deque from itertools import chain from rtree.index import Index as RTree from rtree.index import Property as RProp from scorpionsql.errfunc import ErrTypes from ..learners.cn2sd.rule import fill_in_rules from ..learners.cn2sd.refiner import * from ..bottomup.bounding_box import * from ..bottomup.cluster import * from ..util import * from ..settings import * from basic import Basic from sampler import Sampler from merger import Merger from rangemerger import RangeMerger, RangeMerger2 from streamrangemerger import * from frontier import Frontier from bdtpartitioner import * and context including class names, function names, and sometimes code from other files: # Path: scorpion/learners/cn2sd/rule.py # def fill_in_rules(rules, table, cols=None, cont_dists=None): # # compute bounds for columns in self.cols # if cols is None: # cols = [attr.name for attr in table.domain] # # nparr = None # ref_bounds = {} # for col in cols: # attr = table.domain[col] # if attr.var_type == Orange.feature.Type.Discrete: # ref_bounds[col] = None # continue # # if cont_dists: # bound = cont_dists[attr.name].min, cont_dists[attr.name].max # else: # if nparr is None: # nparr = table.to_numpyMA('ac')[0] # pos = table.domain.index(attr) # arr = nparr[:,pos] # bound = (arr.min(), arr.max()) # # ref_bounds[col] = bound # # # for rule in rules: # rule.fill_in_rule(table, ref_bounds) . Output only the next line.
def __init__(self, **kwargs):
Next line prediction: <|code_start|># Parser for the assembly language # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # ## ## The following 'classes' are the intermediate form into which ## the parser reads the assembly code. ## Number = namedtuple('Number', 'val') Id = namedtuple('Id', 'id') String = namedtuple('String', 'val') MemRef = namedtuple('Memref', 'offset id') Instruction = namedtuple('Instruction', 'label name args lineno') Directive = namedtuple('Directive', 'label name args lineno') LabelDef = namedtuple('LabelDef', 'label lineno') class ParseError(Exception): pass <|code_end|> . Use current file imports: (import re import sys import ply.yacc from collections import namedtuple from .asmlexer import AsmLexer) and context including class names, function names, or small code snippets from other files: # Path: luz_asm_sim/lib/asmlib/asmlexer.py # class AsmLexer(object): # def __init__(self, error_func): # self.error_func = error_func # # def build(self, **kwargs): # """ Builds the lexer from the specification. Must be # called after the lexer object is created. # """ # self.lexer = ply.lex.lex(object=self, **kwargs) # # def input(self, text): # self.lexer.input(text) # # def token(self): # return self.lexer.token() # # def reset_lineno(self): # self.lexer.lineno = 1 # # #######################-- PRIVATE --####################### # # tokens = ( # 'ID', 'DIRECTIVE', # 'NEWLINE', # 'DEC_NUM', 'HEX_NUM', # 'STRING', # 'COLON', 'COMMA', # 'LPAREN', 'RPAREN', # ) # # ## # ## Regexes for use in tokens # ## # identifier = r'[a-zA-Z_\$][0-9a-zA-Z_]*' # directive = r'\.'+identifier # # escape_char = r'\\["\\nt]' # string_char = r'([^"\\\n]|'+escape_char+')' # string = '"'+string_char+'*"' # # ## # ## Token rules # ## # t_COLON = r':' # t_COMMA = r',' # t_LPAREN = r'\(' # t_RPAREN = r'\)' # # t_ignore = ' \t' # # def t_NEWLINE(self, t): # r'\n+' # t.lexer.lineno += t.value.count('\n') # return t # # def t_COMMENT(self, t): # r'\#.*' # pass # # @TOKEN(string) # def t_STRING(self, t): # t.value = self._translate_string(t.value) # return t # # @TOKEN(identifier) # def t_ID(self, t): # t.value = t.value.lower() # return t # # @TOKEN(directive) # def t_DIRECTIVE(self, t): # t.value = t.value.lower() # return t # # def t_HEX_NUM(self, t): # r'\-?0[xX][0-9a-fA-F]+' # t.value = int(t.value, 16) # return t # # def t_DEC_NUM(self, t): # r'\-?\d+' # t.value = int(t.value) # return t # # def t_error(self, t): # msg = 'Illegal character %s (at %s)' % ( # repr(t.value[0]), self._make_tok_location(t)) # self._error(msg) # # ## # ## Internal methods # ## # def _error(self, msg): # self.error_func(msg) # self.lexer.skip(1) # # def _make_tok_location(self, t): # return 'line %s' % t.lineno # # _trans_str_table = { # 'n': '\n', # 't': '\t', # '\\': '\\', # '"': '"' # } # # def _translate_string(self, s): # """ Given a string as accepted by the lexer, translates # it into a real string (truncates "s, inserts real # escape characters where needed). # """ # t = '' # escape = False # # for i, c in enumerate(s[1:-1]): # if escape: # t += self._trans_str_table[c] # escape = False # else: # if c == '\\': # escape = True # else: # t += c # escape = False # # return t . Output only the next line.
class AsmParser(object):
Next line prediction: <|code_start|># Simulates the CPU control registers # # Luz micro-controller simulator # Eli Bendersky (C) 2008-2010 # Maps memory addresses of registers to names # cregs_memory_map = { ADDR_EXCEPTION_VECTOR: 'exception_vector', ADDR_CONTROL_1: 'control_1', ADDR_EXCEPTION_CAUSE: 'exception_cause', ADDR_EXCEPTION_RETURN_ADDR: 'exception_return_addr', ADDR_INTERRUPT_ENABLE: 'interrupt_enable', ADDR_INTERRUPT_PENDING: 'interrupt_pending', <|code_end|> . Use current file imports: (from .peripheral import Peripheral from .errors import (PeripheralMemoryAccessError, PeripheralMemoryAlignError) from ...commonlib.utils import MASK_WORD from ...commonlib.luz_defs import ( ADDR_EXCEPTION_VECTOR, ADDR_CONTROL_1, ADDR_EXCEPTION_CAUSE, ADDR_EXCEPTION_RETURN_ADDR, ADDR_INTERRUPT_ENABLE, ADDR_INTERRUPT_PENDING)) and context including class names, function names, or small code snippets from other files: # Path: luz_asm_sim/lib/simlib/peripheral/peripheral.py # class Peripheral(object): # """ An abstract memory-mapped perhipheral interface. # Memory-mapped peripherals are accessed through memory # reads and writes. # # The address given to reads and writes is relative to the # peripheral's memory map. # Width is 1, 2, 4 for byte, halfword and word accesses. # """ # def read_mem(self, addr, width): # raise NotImplementedError() # # def write_mem(self, addr, width, data): # raise NotImplementedError() # # Path: luz_asm_sim/lib/commonlib/luz_defs.py # ADDR_EXCEPTION_VECTOR = 0x004 # # ADDR_CONTROL_1 = 0x100 # # ADDR_EXCEPTION_CAUSE = 0x108 # # ADDR_EXCEPTION_RETURN_ADDR = 0x10C # # ADDR_INTERRUPT_ENABLE = 0x120 # # ADDR_INTERRUPT_PENDING = 0x124 . Output only the next line.
}
Predict the next line for this snippet: <|code_start|># Simulates the CPU control registers # # Luz micro-controller simulator # Eli Bendersky (C) 2008-2010 # Maps memory addresses of registers to names # cregs_memory_map = { ADDR_EXCEPTION_VECTOR: 'exception_vector', ADDR_CONTROL_1: 'control_1', ADDR_EXCEPTION_CAUSE: 'exception_cause', ADDR_EXCEPTION_RETURN_ADDR: 'exception_return_addr', ADDR_INTERRUPT_ENABLE: 'interrupt_enable', ADDR_INTERRUPT_PENDING: 'interrupt_pending', <|code_end|> with the help of current file imports: from .peripheral import Peripheral from .errors import (PeripheralMemoryAccessError, PeripheralMemoryAlignError) from ...commonlib.utils import MASK_WORD from ...commonlib.luz_defs import ( ADDR_EXCEPTION_VECTOR, ADDR_CONTROL_1, ADDR_EXCEPTION_CAUSE, ADDR_EXCEPTION_RETURN_ADDR, ADDR_INTERRUPT_ENABLE, ADDR_INTERRUPT_PENDING) and context from other files: # Path: luz_asm_sim/lib/simlib/peripheral/peripheral.py # class Peripheral(object): # """ An abstract memory-mapped perhipheral interface. # Memory-mapped peripherals are accessed through memory # reads and writes. # # The address given to reads and writes is relative to the # peripheral's memory map. # Width is 1, 2, 4 for byte, halfword and word accesses. # """ # def read_mem(self, addr, width): # raise NotImplementedError() # # def write_mem(self, addr, width, data): # raise NotImplementedError() # # Path: luz_asm_sim/lib/commonlib/luz_defs.py # ADDR_EXCEPTION_VECTOR = 0x004 # # ADDR_CONTROL_1 = 0x100 # # ADDR_EXCEPTION_CAUSE = 0x108 # # ADDR_EXCEPTION_RETURN_ADDR = 0x10C # # ADDR_INTERRUPT_ENABLE = 0x120 # # ADDR_INTERRUPT_PENDING = 0x124 , which may contain function names, class names, or code. Output only the next line.
}
Based on the snippet: <|code_start|># Simulates the CPU control registers # # Luz micro-controller simulator # Eli Bendersky (C) 2008-2010 # Maps memory addresses of registers to names # cregs_memory_map = { ADDR_EXCEPTION_VECTOR: 'exception_vector', ADDR_CONTROL_1: 'control_1', ADDR_EXCEPTION_CAUSE: 'exception_cause', ADDR_EXCEPTION_RETURN_ADDR: 'exception_return_addr', ADDR_INTERRUPT_ENABLE: 'interrupt_enable', ADDR_INTERRUPT_PENDING: 'interrupt_pending', <|code_end|> , predict the immediate next line with the help of imports: from .peripheral import Peripheral from .errors import (PeripheralMemoryAccessError, PeripheralMemoryAlignError) from ...commonlib.utils import MASK_WORD from ...commonlib.luz_defs import ( ADDR_EXCEPTION_VECTOR, ADDR_CONTROL_1, ADDR_EXCEPTION_CAUSE, ADDR_EXCEPTION_RETURN_ADDR, ADDR_INTERRUPT_ENABLE, ADDR_INTERRUPT_PENDING) and context (classes, functions, sometimes code) from other files: # Path: luz_asm_sim/lib/simlib/peripheral/peripheral.py # class Peripheral(object): # """ An abstract memory-mapped perhipheral interface. # Memory-mapped peripherals are accessed through memory # reads and writes. # # The address given to reads and writes is relative to the # peripheral's memory map. # Width is 1, 2, 4 for byte, halfword and word accesses. # """ # def read_mem(self, addr, width): # raise NotImplementedError() # # def write_mem(self, addr, width, data): # raise NotImplementedError() # # Path: luz_asm_sim/lib/commonlib/luz_defs.py # ADDR_EXCEPTION_VECTOR = 0x004 # # ADDR_CONTROL_1 = 0x100 # # ADDR_EXCEPTION_CAUSE = 0x108 # # ADDR_EXCEPTION_RETURN_ADDR = 0x10C # # ADDR_INTERRUPT_ENABLE = 0x120 # # ADDR_INTERRUPT_PENDING = 0x124 . Output only the next line.
}
Next line prediction: <|code_start|># Simulates the CPU control registers # # Luz micro-controller simulator # Eli Bendersky (C) 2008-2010 # Maps memory addresses of registers to names # cregs_memory_map = { ADDR_EXCEPTION_VECTOR: 'exception_vector', ADDR_CONTROL_1: 'control_1', ADDR_EXCEPTION_CAUSE: 'exception_cause', ADDR_EXCEPTION_RETURN_ADDR: 'exception_return_addr', ADDR_INTERRUPT_ENABLE: 'interrupt_enable', ADDR_INTERRUPT_PENDING: 'interrupt_pending', <|code_end|> . Use current file imports: (from .peripheral import Peripheral from .errors import (PeripheralMemoryAccessError, PeripheralMemoryAlignError) from ...commonlib.utils import MASK_WORD from ...commonlib.luz_defs import ( ADDR_EXCEPTION_VECTOR, ADDR_CONTROL_1, ADDR_EXCEPTION_CAUSE, ADDR_EXCEPTION_RETURN_ADDR, ADDR_INTERRUPT_ENABLE, ADDR_INTERRUPT_PENDING)) and context including class names, function names, or small code snippets from other files: # Path: luz_asm_sim/lib/simlib/peripheral/peripheral.py # class Peripheral(object): # """ An abstract memory-mapped perhipheral interface. # Memory-mapped peripherals are accessed through memory # reads and writes. # # The address given to reads and writes is relative to the # peripheral's memory map. # Width is 1, 2, 4 for byte, halfword and word accesses. # """ # def read_mem(self, addr, width): # raise NotImplementedError() # # def write_mem(self, addr, width, data): # raise NotImplementedError() # # Path: luz_asm_sim/lib/commonlib/luz_defs.py # ADDR_EXCEPTION_VECTOR = 0x004 # # ADDR_CONTROL_1 = 0x100 # # ADDR_EXCEPTION_CAUSE = 0x108 # # ADDR_EXCEPTION_RETURN_ADDR = 0x10C # # ADDR_INTERRUPT_ENABLE = 0x120 # # ADDR_INTERRUPT_PENDING = 0x124 . Output only the next line.
}
Given the following code snippet before the placeholder: <|code_start|># Simulates the memory unit of the CPU. Provides memory mapping # for both the user-memory area and the CPU internal registers # and peripherals. # # Luz micro-controller simulator # Eli Bendersky (C) 2008-2010 USER_MEMORY_END = USER_MEMORY_START + USER_MEMORY_SIZE # Error classes class MemoryError(Exception): pass class MemoryAlignError(MemoryError): pass class MemoryAccessError(MemoryError): pass class MemoryUnit(object): def __init__(self, user_image): <|code_end|> , predict the next line using imports from the current file: from ..commonlib.luz_defs import ( USER_MEMORY_START, USER_MEMORY_SIZE) from ..commonlib.utils import ( MASK_WORD, MASK_BYTE, bytes2word, bytes2halfword, word2bytes, halfword2bytes) from .peripheral.coreregisters import CoreRegisters and context including class names, function names, and sometimes code from other files: # Path: luz_asm_sim/lib/commonlib/luz_defs.py # USER_MEMORY_START = 0x100000 # # USER_MEMORY_SIZE = 0x40000 # # Path: luz_asm_sim/lib/simlib/peripheral/coreregisters.py # class CoreRegisters(Peripheral): # """ Simulates the CPU core registers (accessible to the # program via the memory unit in the core address space). # """ # class CoreReg(object): # def __init__(self, value, user_writable): # self.value = value # self.user_writable = user_writable # # def __init__(self): # self.exception_vector = self.CoreReg(0, True) # self.control_1 = self.CoreReg(0, True) # self.exception_cause = self.CoreReg(0, False) # self.exception_return_addr = self.CoreReg(0, False) # self.interrupt_enable = self.CoreReg(0, True) # self.interrupt_pending = self.CoreReg(0, False) # # def __getitem__(self, name): # """ Allow accessing registers by name # """ # return self.__dict__[name] # # def read_mem(self, addr, width): # if width != 4 or addr % 4 != 0: # raise PeripheralMemoryAlignError() # # if addr in cregs_memory_map: # creg_name = cregs_memory_map[addr] # return self[creg_name].value # else: # raise PeripheralMemoryAccessError() # # def write_mem(self, addr, width, data): # if width != 4 or addr % 4 != 0: # raise PeripheralMemoryAlignError() # # if addr in cregs_memory_map: # creg_name = cregs_memory_map[addr] # if self[creg_name].user_writable: # self[creg_name].value = data & MASK_WORD # else: # raise PeripheralMemoryAccessError() . Output only the next line.
self.user_image = user_image
Next line prediction: <|code_start|># Simulates the memory unit of the CPU. Provides memory mapping # for both the user-memory area and the CPU internal registers # and peripherals. # # Luz micro-controller simulator # Eli Bendersky (C) 2008-2010 USER_MEMORY_END = USER_MEMORY_START + USER_MEMORY_SIZE # Error classes class MemoryError(Exception): pass class MemoryAlignError(MemoryError): pass class MemoryAccessError(MemoryError): pass <|code_end|> . Use current file imports: (from ..commonlib.luz_defs import ( USER_MEMORY_START, USER_MEMORY_SIZE) from ..commonlib.utils import ( MASK_WORD, MASK_BYTE, bytes2word, bytes2halfword, word2bytes, halfword2bytes) from .peripheral.coreregisters import CoreRegisters) and context including class names, function names, or small code snippets from other files: # Path: luz_asm_sim/lib/commonlib/luz_defs.py # USER_MEMORY_START = 0x100000 # # USER_MEMORY_SIZE = 0x40000 # # Path: luz_asm_sim/lib/simlib/peripheral/coreregisters.py # class CoreRegisters(Peripheral): # """ Simulates the CPU core registers (accessible to the # program via the memory unit in the core address space). # """ # class CoreReg(object): # def __init__(self, value, user_writable): # self.value = value # self.user_writable = user_writable # # def __init__(self): # self.exception_vector = self.CoreReg(0, True) # self.control_1 = self.CoreReg(0, True) # self.exception_cause = self.CoreReg(0, False) # self.exception_return_addr = self.CoreReg(0, False) # self.interrupt_enable = self.CoreReg(0, True) # self.interrupt_pending = self.CoreReg(0, False) # # def __getitem__(self, name): # """ Allow accessing registers by name # """ # return self.__dict__[name] # # def read_mem(self, addr, width): # if width != 4 or addr % 4 != 0: # raise PeripheralMemoryAlignError() # # if addr in cregs_memory_map: # creg_name = cregs_memory_map[addr] # return self[creg_name].value # else: # raise PeripheralMemoryAccessError() # # def write_mem(self, addr, width, data): # if width != 4 or addr % 4 != 0: # raise PeripheralMemoryAlignError() # # if addr in cregs_memory_map: # creg_name = cregs_memory_map[addr] # if self[creg_name].user_writable: # self[creg_name].value = data & MASK_WORD # else: # raise PeripheralMemoryAccessError() . Output only the next line.
class MemoryUnit(object):
Based on the snippet: <|code_start|># Assembler - main class # # Input: a single assembly source file # Output: an object file with the assembled source and other # linkage information (relocation table, list of unresolved # and exported labels). # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # class ArgumentError(Exception): pass class AssemblyError(Exception): pass class Assembler(object): <|code_end|> , predict the immediate next line with the help of imports: import pprint, os, sys from collections import defaultdict from ..commonlib.utils import word2bytes, num_fits_in_nbits, unpack_bytes from .asmparser import ( AsmParser, Instruction, Directive, Id, Number, String) from .asm_common_types import ( SegAddr, ExportEntry, ImportEntry, RelocEntry) from .asm_instructions import ( InstructionError, instruction_exists, instruction_length, assemble_instruction) from .objectfile import ObjectFile and context (classes, functions, sometimes code) from other files: # Path: luz_asm_sim/lib/asmlib/asmparser.py # class ParseError(Exception): pass # class AsmParser(object): # def __init__(self, yacctab='parsetab'): # def parse(self, text): # def _lex_error_func(self, msg): # def p_asm_file(self, p): # def p_asm_line_1(self, p): # def p_asm_line_2(self, p): # def p_empty_line(self, p): # def p_directive_1(self, p): # def p_directive_2(self, p): # def p_instruction_1(self, p): # def p_instruction_2(self, p): # def p_label_def(self, p): # def p_arguments_opt(self, p): # def p_arguments_1(self, p): # def p_arguments_2(self, p): # def p_argument_1(self, p): # def p_argument_2(self, p): # def p_argument_3(self, p): # def p_argument_4(self, p): # def p_argument_5(self, p): # def p_number(self, p): # def p_error(self, p): # # Path: luz_asm_sim/lib/asmlib/asm_common_types.py # # Path: luz_asm_sim/lib/asmlib/asm_instructions.py # class InstructionError(Exception): pass # # def instruction_exists(name): # """ Does such an instruction exist ? # """ # return name in _INSTR # # def instruction_length(name): # """ The length of an instruction, in bytes. # """ # return _INSTR[name]['len'] # # def assemble_instruction(name, args, addr, symtab, defines): # """ Assembles the instruction. # # name: # The instruction name. # # args: # The arguments passed to the instruction. # # addr: # A (segment, addr) pair, specifying the location into # which the instruction is assembled. # # symtab: # The label symbol table from the first pass of the # assembler. # # defines: # A table of constants defined by the .define directive # # Returns an array of AssembledInstruction objects (most # instructions assemble into a single AssembledInstruction, # but some pseudo-instructions produce more than one). # # Throws InstructionError for errors in the instruction. # """ # if not instruction_exists(name): # raise InstructionError('Unknown instruction %s' % name) # # instr = _INSTR[name] # # if not instr['nargs'] == len(args): # raise InstructionError('%s expected %d arguments' % ( # name, instr['nargs'])) # # asm_instr = instr['func'](args, addr, symtab, defines) # # if isinstance(asm_instr, list): # return asm_instr # else: # return [asm_instr] # # Path: luz_asm_sim/lib/asmlib/objectfile.py # class ObjectFile(object): # """ Use one of the factory methods to create ObjectFile # instances: from_assembler, from_file # # The name of the object can be accessed via the .name # attribute. # """ # def __init__(self): # self.seg_data = {} # self.export_table = [] # self.import_table = [] # self.reloc_table = [] # # self.name = None # # @classmethod # def from_assembler( cls, # seg_data, # export_table, # import_table, # reloc_table): # """ Create a new ObjectFile from assembler-generated data # structures. # """ # obj = cls() # assert isinstance(seg_data, dict) # for table in (export_table, import_table, reloc_table): # assert isinstance(table, list) # # obj.seg_data = seg_data # obj.export_table = export_table # obj.import_table = import_table # obj.reloc_table = reloc_table # return obj # # @classmethod # def from_file(cls, file): # """ 'file' is either a filename (a String), or a readable # IO object. # """ # pass . Output only the next line.
def __init__(self):
Using the snippet: <|code_start|># Assembler - main class # # Input: a single assembly source file # Output: an object file with the assembled source and other # linkage information (relocation table, list of unresolved # and exported labels). # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # class ArgumentError(Exception): pass class AssemblyError(Exception): pass class Assembler(object): def __init__(self): self.parser = AsmParser() <|code_end|> , determine the next line of code. You have imports: import pprint, os, sys from collections import defaultdict from ..commonlib.utils import word2bytes, num_fits_in_nbits, unpack_bytes from .asmparser import ( AsmParser, Instruction, Directive, Id, Number, String) from .asm_common_types import ( SegAddr, ExportEntry, ImportEntry, RelocEntry) from .asm_instructions import ( InstructionError, instruction_exists, instruction_length, assemble_instruction) from .objectfile import ObjectFile and context (class names, function names, or code) available: # Path: luz_asm_sim/lib/asmlib/asmparser.py # class ParseError(Exception): pass # class AsmParser(object): # def __init__(self, yacctab='parsetab'): # def parse(self, text): # def _lex_error_func(self, msg): # def p_asm_file(self, p): # def p_asm_line_1(self, p): # def p_asm_line_2(self, p): # def p_empty_line(self, p): # def p_directive_1(self, p): # def p_directive_2(self, p): # def p_instruction_1(self, p): # def p_instruction_2(self, p): # def p_label_def(self, p): # def p_arguments_opt(self, p): # def p_arguments_1(self, p): # def p_arguments_2(self, p): # def p_argument_1(self, p): # def p_argument_2(self, p): # def p_argument_3(self, p): # def p_argument_4(self, p): # def p_argument_5(self, p): # def p_number(self, p): # def p_error(self, p): # # Path: luz_asm_sim/lib/asmlib/asm_common_types.py # # Path: luz_asm_sim/lib/asmlib/asm_instructions.py # class InstructionError(Exception): pass # # def instruction_exists(name): # """ Does such an instruction exist ? # """ # return name in _INSTR # # def instruction_length(name): # """ The length of an instruction, in bytes. # """ # return _INSTR[name]['len'] # # def assemble_instruction(name, args, addr, symtab, defines): # """ Assembles the instruction. # # name: # The instruction name. # # args: # The arguments passed to the instruction. # # addr: # A (segment, addr) pair, specifying the location into # which the instruction is assembled. # # symtab: # The label symbol table from the first pass of the # assembler. # # defines: # A table of constants defined by the .define directive # # Returns an array of AssembledInstruction objects (most # instructions assemble into a single AssembledInstruction, # but some pseudo-instructions produce more than one). # # Throws InstructionError for errors in the instruction. # """ # if not instruction_exists(name): # raise InstructionError('Unknown instruction %s' % name) # # instr = _INSTR[name] # # if not instr['nargs'] == len(args): # raise InstructionError('%s expected %d arguments' % ( # name, instr['nargs'])) # # asm_instr = instr['func'](args, addr, symtab, defines) # # if isinstance(asm_instr, list): # return asm_instr # else: # return [asm_instr] # # Path: luz_asm_sim/lib/asmlib/objectfile.py # class ObjectFile(object): # """ Use one of the factory methods to create ObjectFile # instances: from_assembler, from_file # # The name of the object can be accessed via the .name # attribute. # """ # def __init__(self): # self.seg_data = {} # self.export_table = [] # self.import_table = [] # self.reloc_table = [] # # self.name = None # # @classmethod # def from_assembler( cls, # seg_data, # export_table, # import_table, # reloc_table): # """ Create a new ObjectFile from assembler-generated data # structures. # """ # obj = cls() # assert isinstance(seg_data, dict) # for table in (export_table, import_table, reloc_table): # assert isinstance(table, list) # # obj.seg_data = seg_data # obj.export_table = export_table # obj.import_table = import_table # obj.reloc_table = reloc_table # return obj # # @classmethod # def from_file(cls, file): # """ 'file' is either a filename (a String), or a readable # IO object. # """ # pass . Output only the next line.
def assemble(self, str=None, filename=None):
Here is a snippet: <|code_start|># Assembler - main class # # Input: a single assembly source file # Output: an object file with the assembled source and other # linkage information (relocation table, list of unresolved # and exported labels). # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # class ArgumentError(Exception): pass class AssemblyError(Exception): pass class Assembler(object): def __init__(self): self.parser = AsmParser() <|code_end|> . Write the next line using the current file imports: import pprint, os, sys from collections import defaultdict from ..commonlib.utils import word2bytes, num_fits_in_nbits, unpack_bytes from .asmparser import ( AsmParser, Instruction, Directive, Id, Number, String) from .asm_common_types import ( SegAddr, ExportEntry, ImportEntry, RelocEntry) from .asm_instructions import ( InstructionError, instruction_exists, instruction_length, assemble_instruction) from .objectfile import ObjectFile and context from other files: # Path: luz_asm_sim/lib/asmlib/asmparser.py # class ParseError(Exception): pass # class AsmParser(object): # def __init__(self, yacctab='parsetab'): # def parse(self, text): # def _lex_error_func(self, msg): # def p_asm_file(self, p): # def p_asm_line_1(self, p): # def p_asm_line_2(self, p): # def p_empty_line(self, p): # def p_directive_1(self, p): # def p_directive_2(self, p): # def p_instruction_1(self, p): # def p_instruction_2(self, p): # def p_label_def(self, p): # def p_arguments_opt(self, p): # def p_arguments_1(self, p): # def p_arguments_2(self, p): # def p_argument_1(self, p): # def p_argument_2(self, p): # def p_argument_3(self, p): # def p_argument_4(self, p): # def p_argument_5(self, p): # def p_number(self, p): # def p_error(self, p): # # Path: luz_asm_sim/lib/asmlib/asm_common_types.py # # Path: luz_asm_sim/lib/asmlib/asm_instructions.py # class InstructionError(Exception): pass # # def instruction_exists(name): # """ Does such an instruction exist ? # """ # return name in _INSTR # # def instruction_length(name): # """ The length of an instruction, in bytes. # """ # return _INSTR[name]['len'] # # def assemble_instruction(name, args, addr, symtab, defines): # """ Assembles the instruction. # # name: # The instruction name. # # args: # The arguments passed to the instruction. # # addr: # A (segment, addr) pair, specifying the location into # which the instruction is assembled. # # symtab: # The label symbol table from the first pass of the # assembler. # # defines: # A table of constants defined by the .define directive # # Returns an array of AssembledInstruction objects (most # instructions assemble into a single AssembledInstruction, # but some pseudo-instructions produce more than one). # # Throws InstructionError for errors in the instruction. # """ # if not instruction_exists(name): # raise InstructionError('Unknown instruction %s' % name) # # instr = _INSTR[name] # # if not instr['nargs'] == len(args): # raise InstructionError('%s expected %d arguments' % ( # name, instr['nargs'])) # # asm_instr = instr['func'](args, addr, symtab, defines) # # if isinstance(asm_instr, list): # return asm_instr # else: # return [asm_instr] # # Path: luz_asm_sim/lib/asmlib/objectfile.py # class ObjectFile(object): # """ Use one of the factory methods to create ObjectFile # instances: from_assembler, from_file # # The name of the object can be accessed via the .name # attribute. # """ # def __init__(self): # self.seg_data = {} # self.export_table = [] # self.import_table = [] # self.reloc_table = [] # # self.name = None # # @classmethod # def from_assembler( cls, # seg_data, # export_table, # import_table, # reloc_table): # """ Create a new ObjectFile from assembler-generated data # structures. # """ # obj = cls() # assert isinstance(seg_data, dict) # for table in (export_table, import_table, reloc_table): # assert isinstance(table, list) # # obj.seg_data = seg_data # obj.export_table = export_table # obj.import_table = import_table # obj.reloc_table = reloc_table # return obj # # @classmethod # def from_file(cls, file): # """ 'file' is either a filename (a String), or a readable # IO object. # """ # pass , which may include functions, classes, or code. Output only the next line.
def assemble(self, str=None, filename=None):
Based on the snippet: <|code_start|># Assembler - main class # # Input: a single assembly source file # Output: an object file with the assembled source and other # linkage information (relocation table, list of unresolved # and exported labels). # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # class ArgumentError(Exception): pass class AssemblyError(Exception): pass class Assembler(object): def __init__(self): self.parser = AsmParser() <|code_end|> , predict the immediate next line with the help of imports: import pprint, os, sys from collections import defaultdict from ..commonlib.utils import word2bytes, num_fits_in_nbits, unpack_bytes from .asmparser import ( AsmParser, Instruction, Directive, Id, Number, String) from .asm_common_types import ( SegAddr, ExportEntry, ImportEntry, RelocEntry) from .asm_instructions import ( InstructionError, instruction_exists, instruction_length, assemble_instruction) from .objectfile import ObjectFile and context (classes, functions, sometimes code) from other files: # Path: luz_asm_sim/lib/asmlib/asmparser.py # class ParseError(Exception): pass # class AsmParser(object): # def __init__(self, yacctab='parsetab'): # def parse(self, text): # def _lex_error_func(self, msg): # def p_asm_file(self, p): # def p_asm_line_1(self, p): # def p_asm_line_2(self, p): # def p_empty_line(self, p): # def p_directive_1(self, p): # def p_directive_2(self, p): # def p_instruction_1(self, p): # def p_instruction_2(self, p): # def p_label_def(self, p): # def p_arguments_opt(self, p): # def p_arguments_1(self, p): # def p_arguments_2(self, p): # def p_argument_1(self, p): # def p_argument_2(self, p): # def p_argument_3(self, p): # def p_argument_4(self, p): # def p_argument_5(self, p): # def p_number(self, p): # def p_error(self, p): # # Path: luz_asm_sim/lib/asmlib/asm_common_types.py # # Path: luz_asm_sim/lib/asmlib/asm_instructions.py # class InstructionError(Exception): pass # # def instruction_exists(name): # """ Does such an instruction exist ? # """ # return name in _INSTR # # def instruction_length(name): # """ The length of an instruction, in bytes. # """ # return _INSTR[name]['len'] # # def assemble_instruction(name, args, addr, symtab, defines): # """ Assembles the instruction. # # name: # The instruction name. # # args: # The arguments passed to the instruction. # # addr: # A (segment, addr) pair, specifying the location into # which the instruction is assembled. # # symtab: # The label symbol table from the first pass of the # assembler. # # defines: # A table of constants defined by the .define directive # # Returns an array of AssembledInstruction objects (most # instructions assemble into a single AssembledInstruction, # but some pseudo-instructions produce more than one). # # Throws InstructionError for errors in the instruction. # """ # if not instruction_exists(name): # raise InstructionError('Unknown instruction %s' % name) # # instr = _INSTR[name] # # if not instr['nargs'] == len(args): # raise InstructionError('%s expected %d arguments' % ( # name, instr['nargs'])) # # asm_instr = instr['func'](args, addr, symtab, defines) # # if isinstance(asm_instr, list): # return asm_instr # else: # return [asm_instr] # # Path: luz_asm_sim/lib/asmlib/objectfile.py # class ObjectFile(object): # """ Use one of the factory methods to create ObjectFile # instances: from_assembler, from_file # # The name of the object can be accessed via the .name # attribute. # """ # def __init__(self): # self.seg_data = {} # self.export_table = [] # self.import_table = [] # self.reloc_table = [] # # self.name = None # # @classmethod # def from_assembler( cls, # seg_data, # export_table, # import_table, # reloc_table): # """ Create a new ObjectFile from assembler-generated data # structures. # """ # obj = cls() # assert isinstance(seg_data, dict) # for table in (export_table, import_table, reloc_table): # assert isinstance(table, list) # # obj.seg_data = seg_data # obj.export_table = export_table # obj.import_table = import_table # obj.reloc_table = reloc_table # return obj # # @classmethod # def from_file(cls, file): # """ 'file' is either a filename (a String), or a readable # IO object. # """ # pass . Output only the next line.
def assemble(self, str=None, filename=None):
Given the following code snippet before the placeholder: <|code_start|># Assembler - main class # # Input: a single assembly source file # Output: an object file with the assembled source and other # linkage information (relocation table, list of unresolved # and exported labels). # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # class ArgumentError(Exception): pass class AssemblyError(Exception): pass class Assembler(object): <|code_end|> , predict the next line using imports from the current file: import pprint, os, sys from collections import defaultdict from ..commonlib.utils import word2bytes, num_fits_in_nbits, unpack_bytes from .asmparser import ( AsmParser, Instruction, Directive, Id, Number, String) from .asm_common_types import ( SegAddr, ExportEntry, ImportEntry, RelocEntry) from .asm_instructions import ( InstructionError, instruction_exists, instruction_length, assemble_instruction) from .objectfile import ObjectFile and context including class names, function names, and sometimes code from other files: # Path: luz_asm_sim/lib/asmlib/asmparser.py # class ParseError(Exception): pass # class AsmParser(object): # def __init__(self, yacctab='parsetab'): # def parse(self, text): # def _lex_error_func(self, msg): # def p_asm_file(self, p): # def p_asm_line_1(self, p): # def p_asm_line_2(self, p): # def p_empty_line(self, p): # def p_directive_1(self, p): # def p_directive_2(self, p): # def p_instruction_1(self, p): # def p_instruction_2(self, p): # def p_label_def(self, p): # def p_arguments_opt(self, p): # def p_arguments_1(self, p): # def p_arguments_2(self, p): # def p_argument_1(self, p): # def p_argument_2(self, p): # def p_argument_3(self, p): # def p_argument_4(self, p): # def p_argument_5(self, p): # def p_number(self, p): # def p_error(self, p): # # Path: luz_asm_sim/lib/asmlib/asm_common_types.py # # Path: luz_asm_sim/lib/asmlib/asm_instructions.py # class InstructionError(Exception): pass # # def instruction_exists(name): # """ Does such an instruction exist ? # """ # return name in _INSTR # # def instruction_length(name): # """ The length of an instruction, in bytes. # """ # return _INSTR[name]['len'] # # def assemble_instruction(name, args, addr, symtab, defines): # """ Assembles the instruction. # # name: # The instruction name. # # args: # The arguments passed to the instruction. # # addr: # A (segment, addr) pair, specifying the location into # which the instruction is assembled. # # symtab: # The label symbol table from the first pass of the # assembler. # # defines: # A table of constants defined by the .define directive # # Returns an array of AssembledInstruction objects (most # instructions assemble into a single AssembledInstruction, # but some pseudo-instructions produce more than one). # # Throws InstructionError for errors in the instruction. # """ # if not instruction_exists(name): # raise InstructionError('Unknown instruction %s' % name) # # instr = _INSTR[name] # # if not instr['nargs'] == len(args): # raise InstructionError('%s expected %d arguments' % ( # name, instr['nargs'])) # # asm_instr = instr['func'](args, addr, symtab, defines) # # if isinstance(asm_instr, list): # return asm_instr # else: # return [asm_instr] # # Path: luz_asm_sim/lib/asmlib/objectfile.py # class ObjectFile(object): # """ Use one of the factory methods to create ObjectFile # instances: from_assembler, from_file # # The name of the object can be accessed via the .name # attribute. # """ # def __init__(self): # self.seg_data = {} # self.export_table = [] # self.import_table = [] # self.reloc_table = [] # # self.name = None # # @classmethod # def from_assembler( cls, # seg_data, # export_table, # import_table, # reloc_table): # """ Create a new ObjectFile from assembler-generated data # structures. # """ # obj = cls() # assert isinstance(seg_data, dict) # for table in (export_table, import_table, reloc_table): # assert isinstance(table, list) # # obj.seg_data = seg_data # obj.export_table = export_table # obj.import_table = import_table # obj.reloc_table = reloc_table # return obj # # @classmethod # def from_file(cls, file): # """ 'file' is either a filename (a String), or a readable # IO object. # """ # pass . Output only the next line.
def __init__(self):
Predict the next line for this snippet: <|code_start|># Assembler - main class # # Input: a single assembly source file # Output: an object file with the assembled source and other # linkage information (relocation table, list of unresolved # and exported labels). # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # class ArgumentError(Exception): pass class AssemblyError(Exception): pass class Assembler(object): def __init__(self): self.parser = AsmParser() <|code_end|> with the help of current file imports: import pprint, os, sys from collections import defaultdict from ..commonlib.utils import word2bytes, num_fits_in_nbits, unpack_bytes from .asmparser import ( AsmParser, Instruction, Directive, Id, Number, String) from .asm_common_types import ( SegAddr, ExportEntry, ImportEntry, RelocEntry) from .asm_instructions import ( InstructionError, instruction_exists, instruction_length, assemble_instruction) from .objectfile import ObjectFile and context from other files: # Path: luz_asm_sim/lib/asmlib/asmparser.py # class ParseError(Exception): pass # class AsmParser(object): # def __init__(self, yacctab='parsetab'): # def parse(self, text): # def _lex_error_func(self, msg): # def p_asm_file(self, p): # def p_asm_line_1(self, p): # def p_asm_line_2(self, p): # def p_empty_line(self, p): # def p_directive_1(self, p): # def p_directive_2(self, p): # def p_instruction_1(self, p): # def p_instruction_2(self, p): # def p_label_def(self, p): # def p_arguments_opt(self, p): # def p_arguments_1(self, p): # def p_arguments_2(self, p): # def p_argument_1(self, p): # def p_argument_2(self, p): # def p_argument_3(self, p): # def p_argument_4(self, p): # def p_argument_5(self, p): # def p_number(self, p): # def p_error(self, p): # # Path: luz_asm_sim/lib/asmlib/asm_common_types.py # # Path: luz_asm_sim/lib/asmlib/asm_instructions.py # class InstructionError(Exception): pass # # def instruction_exists(name): # """ Does such an instruction exist ? # """ # return name in _INSTR # # def instruction_length(name): # """ The length of an instruction, in bytes. # """ # return _INSTR[name]['len'] # # def assemble_instruction(name, args, addr, symtab, defines): # """ Assembles the instruction. # # name: # The instruction name. # # args: # The arguments passed to the instruction. # # addr: # A (segment, addr) pair, specifying the location into # which the instruction is assembled. # # symtab: # The label symbol table from the first pass of the # assembler. # # defines: # A table of constants defined by the .define directive # # Returns an array of AssembledInstruction objects (most # instructions assemble into a single AssembledInstruction, # but some pseudo-instructions produce more than one). # # Throws InstructionError for errors in the instruction. # """ # if not instruction_exists(name): # raise InstructionError('Unknown instruction %s' % name) # # instr = _INSTR[name] # # if not instr['nargs'] == len(args): # raise InstructionError('%s expected %d arguments' % ( # name, instr['nargs'])) # # asm_instr = instr['func'](args, addr, symtab, defines) # # if isinstance(asm_instr, list): # return asm_instr # else: # return [asm_instr] # # Path: luz_asm_sim/lib/asmlib/objectfile.py # class ObjectFile(object): # """ Use one of the factory methods to create ObjectFile # instances: from_assembler, from_file # # The name of the object can be accessed via the .name # attribute. # """ # def __init__(self): # self.seg_data = {} # self.export_table = [] # self.import_table = [] # self.reloc_table = [] # # self.name = None # # @classmethod # def from_assembler( cls, # seg_data, # export_table, # import_table, # reloc_table): # """ Create a new ObjectFile from assembler-generated data # structures. # """ # obj = cls() # assert isinstance(seg_data, dict) # for table in (export_table, import_table, reloc_table): # assert isinstance(table, list) # # obj.seg_data = seg_data # obj.export_table = export_table # obj.import_table = import_table # obj.reloc_table = reloc_table # return obj # # @classmethod # def from_file(cls, file): # """ 'file' is either a filename (a String), or a readable # IO object. # """ # pass , which may contain function names, class names, or code. Output only the next line.
def assemble(self, str=None, filename=None):
Here is a snippet: <|code_start|># Assembler - main class # # Input: a single assembly source file # Output: an object file with the assembled source and other # linkage information (relocation table, list of unresolved # and exported labels). # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # class ArgumentError(Exception): pass class AssemblyError(Exception): pass class Assembler(object): <|code_end|> . Write the next line using the current file imports: import pprint, os, sys from collections import defaultdict from ..commonlib.utils import word2bytes, num_fits_in_nbits, unpack_bytes from .asmparser import ( AsmParser, Instruction, Directive, Id, Number, String) from .asm_common_types import ( SegAddr, ExportEntry, ImportEntry, RelocEntry) from .asm_instructions import ( InstructionError, instruction_exists, instruction_length, assemble_instruction) from .objectfile import ObjectFile and context from other files: # Path: luz_asm_sim/lib/asmlib/asmparser.py # class ParseError(Exception): pass # class AsmParser(object): # def __init__(self, yacctab='parsetab'): # def parse(self, text): # def _lex_error_func(self, msg): # def p_asm_file(self, p): # def p_asm_line_1(self, p): # def p_asm_line_2(self, p): # def p_empty_line(self, p): # def p_directive_1(self, p): # def p_directive_2(self, p): # def p_instruction_1(self, p): # def p_instruction_2(self, p): # def p_label_def(self, p): # def p_arguments_opt(self, p): # def p_arguments_1(self, p): # def p_arguments_2(self, p): # def p_argument_1(self, p): # def p_argument_2(self, p): # def p_argument_3(self, p): # def p_argument_4(self, p): # def p_argument_5(self, p): # def p_number(self, p): # def p_error(self, p): # # Path: luz_asm_sim/lib/asmlib/asm_common_types.py # # Path: luz_asm_sim/lib/asmlib/asm_instructions.py # class InstructionError(Exception): pass # # def instruction_exists(name): # """ Does such an instruction exist ? # """ # return name in _INSTR # # def instruction_length(name): # """ The length of an instruction, in bytes. # """ # return _INSTR[name]['len'] # # def assemble_instruction(name, args, addr, symtab, defines): # """ Assembles the instruction. # # name: # The instruction name. # # args: # The arguments passed to the instruction. # # addr: # A (segment, addr) pair, specifying the location into # which the instruction is assembled. # # symtab: # The label symbol table from the first pass of the # assembler. # # defines: # A table of constants defined by the .define directive # # Returns an array of AssembledInstruction objects (most # instructions assemble into a single AssembledInstruction, # but some pseudo-instructions produce more than one). # # Throws InstructionError for errors in the instruction. # """ # if not instruction_exists(name): # raise InstructionError('Unknown instruction %s' % name) # # instr = _INSTR[name] # # if not instr['nargs'] == len(args): # raise InstructionError('%s expected %d arguments' % ( # name, instr['nargs'])) # # asm_instr = instr['func'](args, addr, symtab, defines) # # if isinstance(asm_instr, list): # return asm_instr # else: # return [asm_instr] # # Path: luz_asm_sim/lib/asmlib/objectfile.py # class ObjectFile(object): # """ Use one of the factory methods to create ObjectFile # instances: from_assembler, from_file # # The name of the object can be accessed via the .name # attribute. # """ # def __init__(self): # self.seg_data = {} # self.export_table = [] # self.import_table = [] # self.reloc_table = [] # # self.name = None # # @classmethod # def from_assembler( cls, # seg_data, # export_table, # import_table, # reloc_table): # """ Create a new ObjectFile from assembler-generated data # structures. # """ # obj = cls() # assert isinstance(seg_data, dict) # for table in (export_table, import_table, reloc_table): # assert isinstance(table, list) # # obj.seg_data = seg_data # obj.export_table = export_table # obj.import_table = import_table # obj.reloc_table = reloc_table # return obj # # @classmethod # def from_file(cls, file): # """ 'file' is either a filename (a String), or a readable # IO object. # """ # pass , which may include functions, classes, or code. Output only the next line.
def __init__(self):
Given snippet: <|code_start|># Assembler - main class # # Input: a single assembly source file # Output: an object file with the assembled source and other # linkage information (relocation table, list of unresolved # and exported labels). # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # class ArgumentError(Exception): pass class AssemblyError(Exception): pass class Assembler(object): <|code_end|> , continue by predicting the next line. Consider current file imports: import pprint, os, sys from collections import defaultdict from ..commonlib.utils import word2bytes, num_fits_in_nbits, unpack_bytes from .asmparser import ( AsmParser, Instruction, Directive, Id, Number, String) from .asm_common_types import ( SegAddr, ExportEntry, ImportEntry, RelocEntry) from .asm_instructions import ( InstructionError, instruction_exists, instruction_length, assemble_instruction) from .objectfile import ObjectFile and context: # Path: luz_asm_sim/lib/asmlib/asmparser.py # class ParseError(Exception): pass # class AsmParser(object): # def __init__(self, yacctab='parsetab'): # def parse(self, text): # def _lex_error_func(self, msg): # def p_asm_file(self, p): # def p_asm_line_1(self, p): # def p_asm_line_2(self, p): # def p_empty_line(self, p): # def p_directive_1(self, p): # def p_directive_2(self, p): # def p_instruction_1(self, p): # def p_instruction_2(self, p): # def p_label_def(self, p): # def p_arguments_opt(self, p): # def p_arguments_1(self, p): # def p_arguments_2(self, p): # def p_argument_1(self, p): # def p_argument_2(self, p): # def p_argument_3(self, p): # def p_argument_4(self, p): # def p_argument_5(self, p): # def p_number(self, p): # def p_error(self, p): # # Path: luz_asm_sim/lib/asmlib/asm_common_types.py # # Path: luz_asm_sim/lib/asmlib/asm_instructions.py # class InstructionError(Exception): pass # # def instruction_exists(name): # """ Does such an instruction exist ? # """ # return name in _INSTR # # def instruction_length(name): # """ The length of an instruction, in bytes. # """ # return _INSTR[name]['len'] # # def assemble_instruction(name, args, addr, symtab, defines): # """ Assembles the instruction. # # name: # The instruction name. # # args: # The arguments passed to the instruction. # # addr: # A (segment, addr) pair, specifying the location into # which the instruction is assembled. # # symtab: # The label symbol table from the first pass of the # assembler. # # defines: # A table of constants defined by the .define directive # # Returns an array of AssembledInstruction objects (most # instructions assemble into a single AssembledInstruction, # but some pseudo-instructions produce more than one). # # Throws InstructionError for errors in the instruction. # """ # if not instruction_exists(name): # raise InstructionError('Unknown instruction %s' % name) # # instr = _INSTR[name] # # if not instr['nargs'] == len(args): # raise InstructionError('%s expected %d arguments' % ( # name, instr['nargs'])) # # asm_instr = instr['func'](args, addr, symtab, defines) # # if isinstance(asm_instr, list): # return asm_instr # else: # return [asm_instr] # # Path: luz_asm_sim/lib/asmlib/objectfile.py # class ObjectFile(object): # """ Use one of the factory methods to create ObjectFile # instances: from_assembler, from_file # # The name of the object can be accessed via the .name # attribute. # """ # def __init__(self): # self.seg_data = {} # self.export_table = [] # self.import_table = [] # self.reloc_table = [] # # self.name = None # # @classmethod # def from_assembler( cls, # seg_data, # export_table, # import_table, # reloc_table): # """ Create a new ObjectFile from assembler-generated data # structures. # """ # obj = cls() # assert isinstance(seg_data, dict) # for table in (export_table, import_table, reloc_table): # assert isinstance(table, list) # # obj.seg_data = seg_data # obj.export_table = export_table # obj.import_table = import_table # obj.reloc_table = reloc_table # return obj # # @classmethod # def from_file(cls, file): # """ 'file' is either a filename (a String), or a readable # IO object. # """ # pass which might include code, classes, or functions. Output only the next line.
def __init__(self):
Continue the code snippet: <|code_start|># Assembler - main class # # Input: a single assembly source file # Output: an object file with the assembled source and other # linkage information (relocation table, list of unresolved # and exported labels). # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # class ArgumentError(Exception): pass class AssemblyError(Exception): pass class Assembler(object): def __init__(self): self.parser = AsmParser() <|code_end|> . Use current file imports: import pprint, os, sys from collections import defaultdict from ..commonlib.utils import word2bytes, num_fits_in_nbits, unpack_bytes from .asmparser import ( AsmParser, Instruction, Directive, Id, Number, String) from .asm_common_types import ( SegAddr, ExportEntry, ImportEntry, RelocEntry) from .asm_instructions import ( InstructionError, instruction_exists, instruction_length, assemble_instruction) from .objectfile import ObjectFile and context (classes, functions, or code) from other files: # Path: luz_asm_sim/lib/asmlib/asmparser.py # class ParseError(Exception): pass # class AsmParser(object): # def __init__(self, yacctab='parsetab'): # def parse(self, text): # def _lex_error_func(self, msg): # def p_asm_file(self, p): # def p_asm_line_1(self, p): # def p_asm_line_2(self, p): # def p_empty_line(self, p): # def p_directive_1(self, p): # def p_directive_2(self, p): # def p_instruction_1(self, p): # def p_instruction_2(self, p): # def p_label_def(self, p): # def p_arguments_opt(self, p): # def p_arguments_1(self, p): # def p_arguments_2(self, p): # def p_argument_1(self, p): # def p_argument_2(self, p): # def p_argument_3(self, p): # def p_argument_4(self, p): # def p_argument_5(self, p): # def p_number(self, p): # def p_error(self, p): # # Path: luz_asm_sim/lib/asmlib/asm_common_types.py # # Path: luz_asm_sim/lib/asmlib/asm_instructions.py # class InstructionError(Exception): pass # # def instruction_exists(name): # """ Does such an instruction exist ? # """ # return name in _INSTR # # def instruction_length(name): # """ The length of an instruction, in bytes. # """ # return _INSTR[name]['len'] # # def assemble_instruction(name, args, addr, symtab, defines): # """ Assembles the instruction. # # name: # The instruction name. # # args: # The arguments passed to the instruction. # # addr: # A (segment, addr) pair, specifying the location into # which the instruction is assembled. # # symtab: # The label symbol table from the first pass of the # assembler. # # defines: # A table of constants defined by the .define directive # # Returns an array of AssembledInstruction objects (most # instructions assemble into a single AssembledInstruction, # but some pseudo-instructions produce more than one). # # Throws InstructionError for errors in the instruction. # """ # if not instruction_exists(name): # raise InstructionError('Unknown instruction %s' % name) # # instr = _INSTR[name] # # if not instr['nargs'] == len(args): # raise InstructionError('%s expected %d arguments' % ( # name, instr['nargs'])) # # asm_instr = instr['func'](args, addr, symtab, defines) # # if isinstance(asm_instr, list): # return asm_instr # else: # return [asm_instr] # # Path: luz_asm_sim/lib/asmlib/objectfile.py # class ObjectFile(object): # """ Use one of the factory methods to create ObjectFile # instances: from_assembler, from_file # # The name of the object can be accessed via the .name # attribute. # """ # def __init__(self): # self.seg_data = {} # self.export_table = [] # self.import_table = [] # self.reloc_table = [] # # self.name = None # # @classmethod # def from_assembler( cls, # seg_data, # export_table, # import_table, # reloc_table): # """ Create a new ObjectFile from assembler-generated data # structures. # """ # obj = cls() # assert isinstance(seg_data, dict) # for table in (export_table, import_table, reloc_table): # assert isinstance(table, list) # # obj.seg_data = seg_data # obj.export_table = export_table # obj.import_table = import_table # obj.reloc_table = reloc_table # return obj # # @classmethod # def from_file(cls, file): # """ 'file' is either a filename (a String), or a readable # IO object. # """ # pass . Output only the next line.
def assemble(self, str=None, filename=None):
Given snippet: <|code_start|># Assembler - main class # # Input: a single assembly source file # Output: an object file with the assembled source and other # linkage information (relocation table, list of unresolved # and exported labels). # # Luz micro-controller assembler # Eli Bendersky (C) 2008-2010 # class ArgumentError(Exception): pass class AssemblyError(Exception): pass class Assembler(object): <|code_end|> , continue by predicting the next line. Consider current file imports: import pprint, os, sys from collections import defaultdict from ..commonlib.utils import word2bytes, num_fits_in_nbits, unpack_bytes from .asmparser import ( AsmParser, Instruction, Directive, Id, Number, String) from .asm_common_types import ( SegAddr, ExportEntry, ImportEntry, RelocEntry) from .asm_instructions import ( InstructionError, instruction_exists, instruction_length, assemble_instruction) from .objectfile import ObjectFile and context: # Path: luz_asm_sim/lib/asmlib/asmparser.py # class ParseError(Exception): pass # class AsmParser(object): # def __init__(self, yacctab='parsetab'): # def parse(self, text): # def _lex_error_func(self, msg): # def p_asm_file(self, p): # def p_asm_line_1(self, p): # def p_asm_line_2(self, p): # def p_empty_line(self, p): # def p_directive_1(self, p): # def p_directive_2(self, p): # def p_instruction_1(self, p): # def p_instruction_2(self, p): # def p_label_def(self, p): # def p_arguments_opt(self, p): # def p_arguments_1(self, p): # def p_arguments_2(self, p): # def p_argument_1(self, p): # def p_argument_2(self, p): # def p_argument_3(self, p): # def p_argument_4(self, p): # def p_argument_5(self, p): # def p_number(self, p): # def p_error(self, p): # # Path: luz_asm_sim/lib/asmlib/asm_common_types.py # # Path: luz_asm_sim/lib/asmlib/asm_instructions.py # class InstructionError(Exception): pass # # def instruction_exists(name): # """ Does such an instruction exist ? # """ # return name in _INSTR # # def instruction_length(name): # """ The length of an instruction, in bytes. # """ # return _INSTR[name]['len'] # # def assemble_instruction(name, args, addr, symtab, defines): # """ Assembles the instruction. # # name: # The instruction name. # # args: # The arguments passed to the instruction. # # addr: # A (segment, addr) pair, specifying the location into # which the instruction is assembled. # # symtab: # The label symbol table from the first pass of the # assembler. # # defines: # A table of constants defined by the .define directive # # Returns an array of AssembledInstruction objects (most # instructions assemble into a single AssembledInstruction, # but some pseudo-instructions produce more than one). # # Throws InstructionError for errors in the instruction. # """ # if not instruction_exists(name): # raise InstructionError('Unknown instruction %s' % name) # # instr = _INSTR[name] # # if not instr['nargs'] == len(args): # raise InstructionError('%s expected %d arguments' % ( # name, instr['nargs'])) # # asm_instr = instr['func'](args, addr, symtab, defines) # # if isinstance(asm_instr, list): # return asm_instr # else: # return [asm_instr] # # Path: luz_asm_sim/lib/asmlib/objectfile.py # class ObjectFile(object): # """ Use one of the factory methods to create ObjectFile # instances: from_assembler, from_file # # The name of the object can be accessed via the .name # attribute. # """ # def __init__(self): # self.seg_data = {} # self.export_table = [] # self.import_table = [] # self.reloc_table = [] # # self.name = None # # @classmethod # def from_assembler( cls, # seg_data, # export_table, # import_table, # reloc_table): # """ Create a new ObjectFile from assembler-generated data # structures. # """ # obj = cls() # assert isinstance(seg_data, dict) # for table in (export_table, import_table, reloc_table): # assert isinstance(table, list) # # obj.seg_data = seg_data # obj.export_table = export_table # obj.import_table = import_table # obj.reloc_table = reloc_table # return obj # # @classmethod # def from_file(cls, file): # """ 'file' is either a filename (a String), or a readable # IO object. # """ # pass which might include code, classes, or functions. Output only the next line.
def __init__(self):
Predict the next line for this snippet: <|code_start|> room: str mail: str mail_forwarded: bool mail_confirmed: bool properties: List[str] traffic_history: List[TrafficHistoryEntry] interfaces: List[Interface] finance_balance: Decimal finance_history: List[FinanceHistoryEntry] last_finance_update: date # TODO introduce properties once they can be excluded birthdate: Optional[date] membership_end_date: Optional[date] membership_begin_date: Optional[date] wifi_password: Optional[str] @unserializer class UserStatus: member: bool traffic_exceeded: bool network_access: bool account_balanced: bool violation: bool @unserializer class Interface: <|code_end|> with the help of current file imports: from datetime import date from decimal import Decimal from typing import List, Optional from sipa.model.pycroft.unserialize import unserializer and context from other files: # Path: sipa/model/pycroft/unserialize.py # def unserializer(cls: type) -> type: # """A class decorator providing a magic __init__ method""" # annotations = {canonicalize_key(key): val # for key, val in getattr(cls, '__annotations__', {}).items()} # setattr(cls, '__annotations__', annotations) # # # noinspection Mypy # @property # def _json_keys(self): # return self.__annotations__.keys() # TODO we might exclude some things # # _maybe_setattr(cls, '_json_keys', _json_keys) # # def __init__(self, dict_like: dict = None): # if not dict_like: # dict_like = {} # # # TODO read `Optional` attributes # module = sys.modules[type(self).__module__] # constructor_map = {key: constructor_from_annotation(type_=val, # module=module) # for key, val in self.__annotations__.items()} # # missing_keys = set(constructor_map.keys()) - set(dict_like.keys()) # if missing_keys: # raise MissingKeysError( # f"Missing {len(missing_keys)} keys" # f" to construct {type(self).__name__}:" # f" {', '.join(missing_keys)}" # ) # # TODO perhaps warn on superfluous keys # # for attrname, constructor in constructor_map.items(): # val = dict_like[attrname] # if not constructor or val is None: # converted = val # else: # try: # converted = constructor(val) # except (TypeError, ValueError) as e: # typename = self.__annotations__[attrname] # raise ConversionError(f"Failed to convert {val!r}" # f" to type {typename!r}") from e # # self.__dict__[attrname] = converted # # _maybe_setattr(cls, '__init__', __init__) # # return cls , which may contain function names, class names, or code. Output only the next line.
id: int
Next line prediction: <|code_start|> DataRequired(lazy_gettext("Betreff muss angegeben werden!"))]) message = TextAreaField(label=lazy_gettext("Nachricht"), validators=[ DataRequired(lazy_gettext("Nachricht fehlt!")) ]) class OfficialContactForm(SpamProtectedForm): email = EmailField(label=lazy_gettext("E-Mail-Adresse")) name = StringField( label=lazy_gettext("Name / Organisation"), validators=[DataRequired(lazy_gettext("Bitte gib einen Namen an!"))], ) subject = StrippedStringField(label=lazy_gettext("Betreff"), validators=[ DataRequired(lazy_gettext("Betreff muss angegeben werden!"))]) message = TextAreaField(label=lazy_gettext("Nachricht"), validators=[ DataRequired(lazy_gettext("Nachricht fehlt!")) ]) class ChangePasswordForm(FlaskForm): old = PasswordField(label=lazy_gettext("Altes Passwort"), validators=[ DataRequired(lazy_gettext("Altes Passwort muss angegeben werden!"))]) new = PasswordField(label=lazy_gettext("Neues Passwort"), validators=[ DataRequired(lazy_gettext("Neues Passwort fehlt!")), PasswordComplexity(), ]) confirm = PasswordField(label=lazy_gettext("Bestätigung"), validators=[ DataRequired(lazy_gettext("Bestätigung des neuen Passworts fehlt!")), EqualTo('new', message=lazy_gettext("Neue Passwörter stimmen nicht überein!")) <|code_end|> . Use current file imports: (import re from datetime import date from operator import itemgetter from flask_babel import gettext, lazy_gettext from flask import flash from flask_login import current_user from flask_wtf import FlaskForm from werkzeug.local import LocalProxy from wtforms import (BooleanField, HiddenField, PasswordField, SelectField, StringField, TextAreaField, RadioField, IntegerField, DateField, SubmitField) from wtforms.validators import (AnyOf, DataRequired, Email, EqualTo, InputRequired, Regexp, ValidationError, NumberRange, Optional, Length) from sipa.backends.extension import backends, _dorm_summary) and context including class names, function names, or small code snippets from other files: # Path: sipa/backends/extension.py # def evaluates_uniquely(objects, func) -> bool: # def __init__(self): # def init_app(self, app: Flask): # def register(self, datasource: DataSource): # def _activate_datasource(self, name: str): # def _register_dormitory(self, dormitory: Dormitory): # def pre_init_hook(self) -> Callable[[Callable], Callable]: # Decorators are fun :-) # def decorator(f): # def init_backends(self): # def datasources(self) -> List[DataSource]: # def dormitories(self) -> List[Dormitory]: # def all_dormitories(self) -> List[Dormitory]: # def dormitories_short(self) -> List[_dorm_summary]: # def supported_dormitories_short(self) -> List[_dorm_summary]: # def get_dormitory(self, name: str) -> Optional[Dormitory]: # def get_first_dormitory(self) -> Optional[Dormitory]: # def get_datasource(self, name: str) -> Optional[DataSource]: # def dormitory_from_ip(self, ip: str) -> Optional[Dormitory]: # def preferred_dormitory_name(self) -> Optional[str]: # def user_from_ip(self, ip: str) -> Optional[UserLike]: # def current_dormitory(self) -> Optional[Dormitory]: # def current_datasource(self) -> Optional[DataSource]: # class Backends: . Output only the next line.
])
Predict the next line after this snippet: <|code_start|> "https://api.github.com/repos/{}/{}/zipball/{}".format( user, repo_name, tag ), ) self.assertEqual(repr(release), 'GitRelease(title="Test")') def testGetRelease(self): release_by_id = self.release release_by_tag = self.repo.get_release(tag) self.assertEqual(release_by_id, release_by_tag) def testGetLatestRelease(self): latest_release = self.repo.get_latest_release() self.assertEqual(latest_release.tag_name, tag) def testGetAssets(self): repo = self.repo release = self.release self.assertEqual(release.id, release_id) asset_list = [x for x in release.get_assets()] self.assertTrue(asset_list is not None) self.assertEqual(len(asset_list), 1) asset_id = asset_list[0].id asset = repo.get_release_asset(asset_id) self.assertTrue(asset is not None) self.assertEqual(asset.id, asset_id) def testDelete(self): <|code_end|> using the current file's imports: import datetime import os import zipfile from github import GithubException from . import Framework and any relevant context from other files: # Path: github/GithubException.py # class GithubException(Exception): # """ # Error handling in PyGithub is done with exceptions. This class is the base of all exceptions raised by PyGithub (but :class:`github.GithubException.BadAttributeException`). # # Some other types of exceptions might be raised by underlying libraries, for example for network-related issues. # """ # # def __init__(self, status, data, headers): # super().__init__() # self.__status = status # self.__data = data # self.__headers = headers # self.args = [status, data, headers] # # @property # def status(self): # """ # The status returned by the Github API # """ # return self.__status # # @property # def data(self): # """ # The (decoded) data returned by the Github API # """ # return self.__data # # @property # def headers(self): # """ # The headers returned by the Github API # """ # return self.__headers # # def __str__(self): # return "{status} {data}".format(status=self.status, data=json.dumps(self.data)) . Output only the next line.
self.setUpNewRelease()
Given snippet: <|code_start|> try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error deleting message in log channel. Should work anyway though.") try: bot.send_message(message.forward_from_chat.id, "This channel has been set as the log channel for {}.".format( chat.title or chat.first_name)) except Unauthorized as excp: if excp.message == "Forbidden: bot is not a member of the channel chat": bot.send_message(chat.id, "Successfully set log channel!") else: LOGGER.exception("ERROR in setting the log channel.") bot.send_message(chat.id, "Successfully set log channel!") else: message.reply_text("The steps to set a log channel are:\n" " - add bot to the desired channel\n" " - send /setlog to the channel\n" " - forward the /setlog to the group\n") @run_async @user_admin def unsetlog(bot: Bot, update: Update): <|code_end|> , continue by predicting the next line. Consider current file imports: from functools import wraps from typing import Optional from tg_bot.modules.helper_funcs.misc import is_module_loaded from telegram import Bot, Update, ParseMode, Message, Chat from telegram.error import BadRequest, Unauthorized from telegram.ext import CommandHandler, run_async from telegram.utils.helpers import escape_markdown from tg_bot import dispatcher, LOGGER from tg_bot.modules.helper_funcs.chat_status import user_admin from tg_bot.modules.sql import log_channel_sql as sql and context: # Path: tg_bot/modules/helper_funcs/misc.py # def is_module_loaded(name): # return (not LOAD or name in LOAD) and name not in NO_LOAD which might include code, classes, or functions. Output only the next line.
message = update.effective_message # type: Optional[Message]
Continue the code snippet: <|code_start|> @unique class Types(IntEnum): TEXT = 0 BUTTON_TEXT = 1 STICKER = 2 DOCUMENT = 3 PHOTO = 4 AUDIO = 5 VOICE = 6 VIDEO = 7 def get_note_type(msg: Message): data_type = None content = None text = "" raw_text = msg.text or msg.caption args = raw_text.split(None, 2) # use python's maxsplit to separate cmd and args note_name = args[1] buttons = [] # determine what the contents of the filter are - text, image, sticker, etc if len(args) >= 3: offset = len(args[2]) - len(raw_text) # set correct offset relative to command + notename text, buttons = button_markdown_parser(args[2], entities=msg.parse_entities() or msg.parse_caption_entities(), offset=offset) if buttons: data_type = Types.BUTTON_TEXT <|code_end|> . Use current file imports: from enum import IntEnum, unique from telegram import Message from tg_bot.modules.helper_funcs.string_handling import button_markdown_parser and context (classes, functions, or code) from other files: # Path: tg_bot/modules/helper_funcs/string_handling.py # def button_markdown_parser(txt: str, entities: Dict[MessageEntity, str] = None, offset: int = 0) -> (str, List): # markdown_note = markdown_parser(txt, entities, offset) # prev = 0 # note_data = "" # buttons = [] # for match in BTN_URL_REGEX.finditer(markdown_note): # # Check if btnurl is escaped # n_escapes = 0 # to_check = match.start(1) - 1 # while to_check > 0 and markdown_note[to_check] == "\\": # n_escapes += 1 # to_check -= 1 # # # if even, not escaped -> create button # if n_escapes % 2 == 0: # # create a thruple with button label, url, and newline status # buttons.append((match.group(2), match.group(3), bool(match.group(4)))) # note_data += markdown_note[prev:match.start(1)] # prev = match.end(1) # # if odd, escaped -> move along # else: # note_data += markdown_note[prev:to_check] # prev = match.start(1) - 1 # else: # note_data += markdown_note[prev:] # # return note_data, buttons . Output only the next line.
else:
Using the snippet: <|code_start|>__all__ = ["BaseResolver", "Resolver", "VersionedResolver"] # fmt: off # resolvers consist of # - a list of applicable version # - a tag # - a regexp # - a list of first characters to match implicit_resolvers = [ ([(1, 2)], u'tag:yaml.org,2002:bool', RegExp(u'''^(?:true|True|TRUE|false|False|FALSE)$''', re.X), list(u'tTfF')), ([(1, 1)], u'tag:yaml.org,2002:bool', RegExp(u'''^(?:y|Y|yes|Yes|YES|n|N|no|No|NO |true|True|TRUE|false|False|FALSE |on|On|ON|off|Off|OFF)$''', re.X), list(u'yYnNtTfFoO')), ([(1, 2)], u'tag:yaml.org,2002:float', RegExp(u'''^(?: [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |[-+]?\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?\\.(?:inf|Inf|INF) |\\.(?:nan|NaN|NAN))$''', re.X), list(u'-+0123456789.')), ([(1, 1)], <|code_end|> , determine the next line of code. You have imports: import re from typing import Any, Dict, List, Union, Text, Optional # NOQA from strictyaml.ruamel.compat import VersionType # NOQA from strictyaml.ruamel.compat import string_types, _DEFAULT_YAML_VERSION # NOQA from strictyaml.ruamel.error import * # NOQA from strictyaml.ruamel.nodes import MappingNode, ScalarNode, SequenceNode # NOQA from strictyaml.ruamel.util import RegExp # NOQA and context (class names, function names, or code) available: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/nodes.py # class MappingNode(CollectionNode): # __slots__ = ("merge",) # id = "mapping" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # flow_style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # CollectionNode.__init__( # self, tag, value, start_mark, end_mark, flow_style, comment, anchor # ) # self.merge = None # # class ScalarNode(Node): # """ # styles: # ? -> set() ? key, no value # " -> double quoted # ' -> single quoted # | -> literal style # > -> folding style # """ # # __slots__ = ("style",) # id = "scalar" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # Node.__init__( # self, tag, value, start_mark, end_mark, comment=comment, anchor=anchor # ) # self.style = style # # class SequenceNode(CollectionNode): # __slots__ = () # id = "sequence" # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
u'tag:yaml.org,2002:float',
Using the snippet: <|code_start|> RegExp(u'''^(?:[-+]?0b[0-1_]+ |[-+]?0o?[0-7_]+ |[-+]?[0-9_]+ |[-+]?0x[0-9a-fA-F_]+)$''', re.X), list(u'-+0123456789')), ([(1, 1)], u'tag:yaml.org,2002:int', RegExp(u'''^(?:[-+]?0b[0-1_]+ |[-+]?0?[0-7_]+ |[-+]?(?:0|[1-9][0-9_]*) |[-+]?0x[0-9a-fA-F_]+ |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X), # sexagesimal int list(u'-+0123456789')), ([(1, 2), (1, 1)], u'tag:yaml.org,2002:merge', RegExp(u'^(?:<<)$'), [u'<']), ([(1, 2), (1, 1)], u'tag:yaml.org,2002:null', RegExp(u'''^(?: ~ |null|Null|NULL | )$''', re.X), [u'~', u'n', u'N', u'']), ([(1, 2), (1, 1)], u'tag:yaml.org,2002:timestamp', RegExp(u'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]? (?:[Tt]|[ \\t]+)[0-9][0-9]? :[0-9][0-9] :[0-9][0-9] (?:\\.[0-9]*)? (?:[ \\t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X), <|code_end|> , determine the next line of code. You have imports: import re from typing import Any, Dict, List, Union, Text, Optional # NOQA from strictyaml.ruamel.compat import VersionType # NOQA from strictyaml.ruamel.compat import string_types, _DEFAULT_YAML_VERSION # NOQA from strictyaml.ruamel.error import * # NOQA from strictyaml.ruamel.nodes import MappingNode, ScalarNode, SequenceNode # NOQA from strictyaml.ruamel.util import RegExp # NOQA and context (class names, function names, or code) available: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/nodes.py # class MappingNode(CollectionNode): # __slots__ = ("merge",) # id = "mapping" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # flow_style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # CollectionNode.__init__( # self, tag, value, start_mark, end_mark, flow_style, comment, anchor # ) # self.merge = None # # class ScalarNode(Node): # """ # styles: # ? -> set() ? key, no value # " -> double quoted # ' -> single quoted # | -> literal style # > -> folding style # """ # # __slots__ = ("style",) # id = "scalar" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # Node.__init__( # self, tag, value, start_mark, end_mark, comment=comment, anchor=anchor # ) # self.style = style # # class SequenceNode(CollectionNode): # __slots__ = () # id = "sequence" # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
list(u'0123456789')),
Given the code snippet: <|code_start|> |[-+]?\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?\\.(?:inf|Inf|INF) |\\.(?:nan|NaN|NAN))$''', re.X), list(u'-+0123456789.')), ([(1, 1)], u'tag:yaml.org,2002:float', RegExp(u'''^(?: [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]* # sexagesimal float |[-+]?\\.(?:inf|Inf|INF) |\\.(?:nan|NaN|NAN))$''', re.X), list(u'-+0123456789.')), ([(1, 2)], u'tag:yaml.org,2002:int', RegExp(u'''^(?:[-+]?0b[0-1_]+ |[-+]?0o?[0-7_]+ |[-+]?[0-9_]+ |[-+]?0x[0-9a-fA-F_]+)$''', re.X), list(u'-+0123456789')), ([(1, 1)], u'tag:yaml.org,2002:int', RegExp(u'''^(?:[-+]?0b[0-1_]+ |[-+]?0?[0-7_]+ |[-+]?(?:0|[1-9][0-9_]*) |[-+]?0x[0-9a-fA-F_]+ |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X), # sexagesimal int list(u'-+0123456789')), ([(1, 2), (1, 1)], <|code_end|> , generate the next line using the imports in this file: import re from typing import Any, Dict, List, Union, Text, Optional # NOQA from strictyaml.ruamel.compat import VersionType # NOQA from strictyaml.ruamel.compat import string_types, _DEFAULT_YAML_VERSION # NOQA from strictyaml.ruamel.error import * # NOQA from strictyaml.ruamel.nodes import MappingNode, ScalarNode, SequenceNode # NOQA from strictyaml.ruamel.util import RegExp # NOQA and context (functions, classes, or occasionally code) from other files: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/nodes.py # class MappingNode(CollectionNode): # __slots__ = ("merge",) # id = "mapping" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # flow_style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # CollectionNode.__init__( # self, tag, value, start_mark, end_mark, flow_style, comment, anchor # ) # self.merge = None # # class ScalarNode(Node): # """ # styles: # ? -> set() ? key, no value # " -> double quoted # ' -> single quoted # | -> literal style # > -> folding style # """ # # __slots__ = ("style",) # id = "scalar" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # Node.__init__( # self, tag, value, start_mark, end_mark, comment=comment, anchor=anchor # ) # self.style = style # # class SequenceNode(CollectionNode): # __slots__ = () # id = "sequence" # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
u'tag:yaml.org,2002:merge',
Given the code snippet: <|code_start|> RegExp(u'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]? (?:[Tt]|[ \\t]+)[0-9][0-9]? :[0-9][0-9] :[0-9][0-9] (?:\\.[0-9]*)? (?:[ \\t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X), list(u'0123456789')), ([(1, 2), (1, 1)], u'tag:yaml.org,2002:value', RegExp(u'^(?:=)$'), [u'=']), # The following resolver is only for documentation purposes. It cannot work # because plain scalars cannot start with '!', '&', or '*'. ([(1, 2), (1, 1)], u'tag:yaml.org,2002:yaml', RegExp(u'^(?:!|&|\\*)$'), list(u'!&*')), ] # fmt: on class ResolverError(YAMLError): pass class BaseResolver(object): DEFAULT_SCALAR_TAG = u"tag:yaml.org,2002:str" DEFAULT_SEQUENCE_TAG = u"tag:yaml.org,2002:seq" DEFAULT_MAPPING_TAG = u"tag:yaml.org,2002:map" <|code_end|> , generate the next line using the imports in this file: import re from typing import Any, Dict, List, Union, Text, Optional # NOQA from strictyaml.ruamel.compat import VersionType # NOQA from strictyaml.ruamel.compat import string_types, _DEFAULT_YAML_VERSION # NOQA from strictyaml.ruamel.error import * # NOQA from strictyaml.ruamel.nodes import MappingNode, ScalarNode, SequenceNode # NOQA from strictyaml.ruamel.util import RegExp # NOQA and context (functions, classes, or occasionally code) from other files: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/nodes.py # class MappingNode(CollectionNode): # __slots__ = ("merge",) # id = "mapping" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # flow_style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # CollectionNode.__init__( # self, tag, value, start_mark, end_mark, flow_style, comment, anchor # ) # self.merge = None # # class ScalarNode(Node): # """ # styles: # ? -> set() ? key, no value # " -> double quoted # ' -> single quoted # | -> literal style # > -> folding style # """ # # __slots__ = ("style",) # id = "scalar" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # Node.__init__( # self, tag, value, start_mark, end_mark, comment=comment, anchor=anchor # ) # self.style = style # # class SequenceNode(CollectionNode): # __slots__ = () # id = "sequence" # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
yaml_implicit_resolvers = {} # type: Dict[Any, Any]
Given the following code snippet before the placeholder: <|code_start|> |[-+]?0x[0-9a-fA-F_]+ |[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+)$''', re.X), # sexagesimal int list(u'-+0123456789')), ([(1, 2), (1, 1)], u'tag:yaml.org,2002:merge', RegExp(u'^(?:<<)$'), [u'<']), ([(1, 2), (1, 1)], u'tag:yaml.org,2002:null', RegExp(u'''^(?: ~ |null|Null|NULL | )$''', re.X), [u'~', u'n', u'N', u'']), ([(1, 2), (1, 1)], u'tag:yaml.org,2002:timestamp', RegExp(u'''^(?:[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] |[0-9][0-9][0-9][0-9] -[0-9][0-9]? -[0-9][0-9]? (?:[Tt]|[ \\t]+)[0-9][0-9]? :[0-9][0-9] :[0-9][0-9] (?:\\.[0-9]*)? (?:[ \\t]*(?:Z|[-+][0-9][0-9]?(?::[0-9][0-9])?))?)$''', re.X), list(u'0123456789')), ([(1, 2), (1, 1)], u'tag:yaml.org,2002:value', RegExp(u'^(?:=)$'), [u'=']), # The following resolver is only for documentation purposes. It cannot work # because plain scalars cannot start with '!', '&', or '*'. ([(1, 2), (1, 1)], u'tag:yaml.org,2002:yaml', RegExp(u'^(?:!|&|\\*)$'), <|code_end|> , predict the next line using imports from the current file: import re from typing import Any, Dict, List, Union, Text, Optional # NOQA from strictyaml.ruamel.compat import VersionType # NOQA from strictyaml.ruamel.compat import string_types, _DEFAULT_YAML_VERSION # NOQA from strictyaml.ruamel.error import * # NOQA from strictyaml.ruamel.nodes import MappingNode, ScalarNode, SequenceNode # NOQA from strictyaml.ruamel.util import RegExp # NOQA and context including class names, function names, and sometimes code from other files: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/nodes.py # class MappingNode(CollectionNode): # __slots__ = ("merge",) # id = "mapping" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # flow_style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # CollectionNode.__init__( # self, tag, value, start_mark, end_mark, flow_style, comment, anchor # ) # self.merge = None # # class ScalarNode(Node): # """ # styles: # ? -> set() ? key, no value # " -> double quoted # ' -> single quoted # | -> literal style # > -> folding style # """ # # __slots__ = ("style",) # id = "scalar" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # Node.__init__( # self, tag, value, start_mark, end_mark, comment=comment, anchor=anchor # ) # self.style = style # # class SequenceNode(CollectionNode): # __slots__ = () # id = "sequence" # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
list(u'!&*')),
Continue the code snippet: <|code_start|> RegExp(u'''^(?:true|True|TRUE|false|False|FALSE)$''', re.X), list(u'tTfF')), ([(1, 1)], u'tag:yaml.org,2002:bool', RegExp(u'''^(?:y|Y|yes|Yes|YES|n|N|no|No|NO |true|True|TRUE|false|False|FALSE |on|On|ON|off|Off|OFF)$''', re.X), list(u'yYnNtTfFoO')), ([(1, 2)], u'tag:yaml.org,2002:float', RegExp(u'''^(?: [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |[-+]?\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?\\.(?:inf|Inf|INF) |\\.(?:nan|NaN|NAN))$''', re.X), list(u'-+0123456789.')), ([(1, 1)], u'tag:yaml.org,2002:float', RegExp(u'''^(?: [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)? |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+) |\\.[0-9_]+(?:[eE][-+][0-9]+)? |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]* # sexagesimal float |[-+]?\\.(?:inf|Inf|INF) |\\.(?:nan|NaN|NAN))$''', re.X), list(u'-+0123456789.')), ([(1, 2)], u'tag:yaml.org,2002:int', RegExp(u'''^(?:[-+]?0b[0-1_]+ <|code_end|> . Use current file imports: import re from typing import Any, Dict, List, Union, Text, Optional # NOQA from strictyaml.ruamel.compat import VersionType # NOQA from strictyaml.ruamel.compat import string_types, _DEFAULT_YAML_VERSION # NOQA from strictyaml.ruamel.error import * # NOQA from strictyaml.ruamel.nodes import MappingNode, ScalarNode, SequenceNode # NOQA from strictyaml.ruamel.util import RegExp # NOQA and context (classes, functions, or code) from other files: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/nodes.py # class MappingNode(CollectionNode): # __slots__ = ("merge",) # id = "mapping" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # flow_style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # CollectionNode.__init__( # self, tag, value, start_mark, end_mark, flow_style, comment, anchor # ) # self.merge = None # # class ScalarNode(Node): # """ # styles: # ? -> set() ? key, no value # " -> double quoted # ' -> single quoted # | -> literal style # > -> folding style # """ # # __slots__ = ("style",) # id = "scalar" # # def __init__( # self, # tag, # value, # start_mark=None, # end_mark=None, # style=None, # comment=None, # anchor=None, # ): # # type: (Any, Any, Any, Any, Any, Any, Any) -> None # Node.__init__( # self, tag, value, start_mark, end_mark, comment=comment, anchor=anchor # ) # self.style = style # # class SequenceNode(CollectionNode): # __slots__ = () # id = "sequence" # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
|[-+]?0o?[0-7_]+
Predict the next line after this snippet: <|code_start|> # type: (Any) -> Any x = type(self)(self + a) x._width = self._width # type: ignore x._underscore = ( # type: ignore self._underscore[:] if self._underscore is not None else None # type: ignore ) # NOQA return x def __ifloordiv__(self, a): # type: ignore # type: (Any) -> Any x = type(self)(self // a) x._width = self._width # type: ignore x._underscore = ( # type: ignore self._underscore[:] if self._underscore is not None else None # type: ignore ) # NOQA return x def __imul__(self, a): # type: ignore # type: (Any) -> Any x = type(self)(self * a) x._width = self._width # type: ignore x._underscore = ( # type: ignore self._underscore[:] if self._underscore is not None else None # type: ignore ) # NOQA return x def __ipow__(self, a): # type: ignore # type: (Any) -> Any x = type(self)(self ** a) x._width = self._width # type: ignore <|code_end|> using the current file's imports: from .compat import no_limit_int # NOQA from strictyaml.ruamel.anchor import Anchor from typing import Text, Any, Dict, List # NOQA and any relevant context from other files: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/anchor.py # class Anchor(object): # __slots__ = "value", "always_dump" # attrib = anchor_attrib # # def __init__(self): # # type: () -> None # self.value = None # self.always_dump = False # # def __repr__(self): # # type: () -> Any # ad = ", (always dump)" if self.always_dump else "" # return "Anchor({!r}{})".format(self.value, ad) . Output only the next line.
x._underscore = ( # type: ignore
Based on the snippet: <|code_start|> @property def anchor(self): # type: () -> Any if not hasattr(self, Anchor.attrib): setattr(self, Anchor.attrib, Anchor()) return getattr(self, Anchor.attrib) def yaml_anchor(self, any=False): # type: (bool) -> Any if not hasattr(self, Anchor.attrib): return None if any or self.anchor.always_dump: return self.anchor return None def yaml_set_anchor(self, value, always_dump=False): # type: (Any, bool) -> None self.anchor.value = value self.anchor.always_dump = always_dump class BinaryInt(ScalarInt): def __new__(cls, value, width=None, underscore=None, anchor=None): # type: (Any, Any, Any, Any) -> Any return ScalarInt.__new__( cls, value, width=width, underscore=underscore, anchor=anchor ) <|code_end|> , predict the immediate next line with the help of imports: from .compat import no_limit_int # NOQA from strictyaml.ruamel.anchor import Anchor from typing import Text, Any, Dict, List # NOQA and context (classes, functions, sometimes code) from other files: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/anchor.py # class Anchor(object): # __slots__ = "value", "always_dump" # attrib = anchor_attrib # # def __init__(self): # # type: () -> None # self.value = None # self.always_dump = False # # def __repr__(self): # # type: () -> Any # ad = ", (always dump)" if self.always_dump else "" # return "Anchor({!r}{})".format(self.value, ad) . Output only the next line.
class OctalInt(ScalarInt):
Predict the next line after this snippet: <|code_start|># SCALAR(value, plain, style) # # RoundTripScanner # COMMENT(value) # # Read comments in the Scanner code for more details. # if False: # MYPY __all__ = ["Scanner", "RoundTripScanner", "ScannerError"] _THE_END = "\n\0\r\x85\u2028\u2029" _THE_END_SPACE_TAB = " \n\0\t\r\x85\u2028\u2029" _SPACE_TAB = " \t" class ScannerError(MarkedYAMLError): pass class SimpleKey(object): # See below simple keys treatment. def __init__(self, token_number, required, index, line, column, mark): # type: (Any, Any, int, int, int, Any) -> None self.token_number = token_number self.required = required <|code_end|> using the current file's imports: from strictyaml.ruamel.error import MarkedYAMLError from strictyaml.ruamel.tokens import * # NOQA from strictyaml.ruamel.compat import ( utf8, unichr, PY3, check_anchorname_char, nprint, ) # NOQA from typing import Any, Dict, Optional, List, Union, Text # NOQA from strictyaml.ruamel.compat import VersionType # NOQA and any relevant context from other files: # Path: strictyaml/ruamel/error.py # class MarkedYAMLError(YAMLError): # def __init__( # self, # context=None, # context_mark=None, # problem=None, # problem_mark=None, # note=None, # warn=None, # ): # # type: (Any, Any, Any, Any, Any, Any) -> None # self.context = context # self.context_mark = context_mark # self.problem = problem # self.problem_mark = problem_mark # self.note = note # # warn is ignored # # def __str__(self): # # type: () -> Any # lines = [] # type: List[str] # if self.context is not None: # lines.append(self.context) # if self.context_mark is not None and ( # self.problem is None # or self.problem_mark is None # or self.context_mark.name != self.problem_mark.name # or self.context_mark.line != self.problem_mark.line # or self.context_mark.column != self.problem_mark.column # ): # lines.append(str(self.context_mark)) # if self.problem is not None: # lines.append(self.problem) # if self.problem_mark is not None: # lines.append(str(self.problem_mark)) # if self.note is not None and self.note: # note = textwrap.dedent(self.note) # lines.append(note) # return "\n".join(lines) # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): . Output only the next line.
self.index = index
Predict the next line after this snippet: <|code_start|># # RoundTripScanner # COMMENT(value) # # Read comments in the Scanner code for more details. # if False: # MYPY __all__ = ["Scanner", "RoundTripScanner", "ScannerError"] _THE_END = "\n\0\r\x85\u2028\u2029" _THE_END_SPACE_TAB = " \n\0\t\r\x85\u2028\u2029" _SPACE_TAB = " \t" class ScannerError(MarkedYAMLError): pass class SimpleKey(object): # See below simple keys treatment. def __init__(self, token_number, required, index, line, column, mark): # type: (Any, Any, int, int, int, Any) -> None self.token_number = token_number self.required = required self.index = index <|code_end|> using the current file's imports: from strictyaml.ruamel.error import MarkedYAMLError from strictyaml.ruamel.tokens import * # NOQA from strictyaml.ruamel.compat import ( utf8, unichr, PY3, check_anchorname_char, nprint, ) # NOQA from typing import Any, Dict, Optional, List, Union, Text # NOQA from strictyaml.ruamel.compat import VersionType # NOQA and any relevant context from other files: # Path: strictyaml/ruamel/error.py # class MarkedYAMLError(YAMLError): # def __init__( # self, # context=None, # context_mark=None, # problem=None, # problem_mark=None, # note=None, # warn=None, # ): # # type: (Any, Any, Any, Any, Any, Any) -> None # self.context = context # self.context_mark = context_mark # self.problem = problem # self.problem_mark = problem_mark # self.note = note # # warn is ignored # # def __str__(self): # # type: () -> Any # lines = [] # type: List[str] # if self.context is not None: # lines.append(self.context) # if self.context_mark is not None and ( # self.problem is None # or self.problem_mark is None # or self.context_mark.name != self.problem_mark.name # or self.context_mark.line != self.problem_mark.line # or self.context_mark.column != self.problem_mark.column # ): # lines.append(str(self.context_mark)) # if self.problem is not None: # lines.append(self.problem) # if self.problem_mark is not None: # lines.append(str(self.problem_mark)) # if self.note is not None and self.note: # note = textwrap.dedent(self.note) # lines.append(note) # return "\n".join(lines) # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): . Output only the next line.
self.line = line
Given the following code snippet before the placeholder: <|code_start|># if False: # MYPY __all__ = ["Scanner", "RoundTripScanner", "ScannerError"] _THE_END = "\n\0\r\x85\u2028\u2029" _THE_END_SPACE_TAB = " \n\0\t\r\x85\u2028\u2029" _SPACE_TAB = " \t" class ScannerError(MarkedYAMLError): pass class SimpleKey(object): # See below simple keys treatment. def __init__(self, token_number, required, index, line, column, mark): # type: (Any, Any, int, int, int, Any) -> None self.token_number = token_number self.required = required self.index = index self.line = line self.column = column self.mark = mark <|code_end|> , predict the next line using imports from the current file: from strictyaml.ruamel.error import MarkedYAMLError from strictyaml.ruamel.tokens import * # NOQA from strictyaml.ruamel.compat import ( utf8, unichr, PY3, check_anchorname_char, nprint, ) # NOQA from typing import Any, Dict, Optional, List, Union, Text # NOQA from strictyaml.ruamel.compat import VersionType # NOQA and context including class names, function names, and sometimes code from other files: # Path: strictyaml/ruamel/error.py # class MarkedYAMLError(YAMLError): # def __init__( # self, # context=None, # context_mark=None, # problem=None, # problem_mark=None, # note=None, # warn=None, # ): # # type: (Any, Any, Any, Any, Any, Any) -> None # self.context = context # self.context_mark = context_mark # self.problem = problem # self.problem_mark = problem_mark # self.note = note # # warn is ignored # # def __str__(self): # # type: () -> Any # lines = [] # type: List[str] # if self.context is not None: # lines.append(self.context) # if self.context_mark is not None and ( # self.problem is None # or self.problem_mark is None # or self.context_mark.name != self.problem_mark.name # or self.context_mark.line != self.problem_mark.line # or self.context_mark.column != self.problem_mark.column # ): # lines.append(str(self.context_mark)) # if self.problem is not None: # lines.append(self.problem) # if self.problem_mark is not None: # lines.append(str(self.problem_mark)) # if self.note is not None and self.note: # note = textwrap.dedent(self.note) # lines.append(note) # return "\n".join(lines) # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): . Output only the next line.
class Scanner(object):
Continue the code snippet: <|code_start|># SCALAR(value, plain, style) # # RoundTripScanner # COMMENT(value) # # Read comments in the Scanner code for more details. # if False: # MYPY __all__ = ["Scanner", "RoundTripScanner", "ScannerError"] _THE_END = "\n\0\r\x85\u2028\u2029" _THE_END_SPACE_TAB = " \n\0\t\r\x85\u2028\u2029" _SPACE_TAB = " \t" class ScannerError(MarkedYAMLError): pass class SimpleKey(object): # See below simple keys treatment. def __init__(self, token_number, required, index, line, column, mark): # type: (Any, Any, int, int, int, Any) -> None self.token_number = token_number self.required = required <|code_end|> . Use current file imports: from strictyaml.ruamel.error import MarkedYAMLError from strictyaml.ruamel.tokens import * # NOQA from strictyaml.ruamel.compat import ( utf8, unichr, PY3, check_anchorname_char, nprint, ) # NOQA from typing import Any, Dict, Optional, List, Union, Text # NOQA from strictyaml.ruamel.compat import VersionType # NOQA and context (classes, functions, or code) from other files: # Path: strictyaml/ruamel/error.py # class MarkedYAMLError(YAMLError): # def __init__( # self, # context=None, # context_mark=None, # problem=None, # problem_mark=None, # note=None, # warn=None, # ): # # type: (Any, Any, Any, Any, Any, Any) -> None # self.context = context # self.context_mark = context_mark # self.problem = problem # self.problem_mark = problem_mark # self.note = note # # warn is ignored # # def __str__(self): # # type: () -> Any # lines = [] # type: List[str] # if self.context is not None: # lines.append(self.context) # if self.context_mark is not None and ( # self.problem is None # or self.problem_mark is None # or self.context_mark.name != self.problem_mark.name # or self.context_mark.line != self.problem_mark.line # or self.context_mark.column != self.problem_mark.column # ): # lines.append(str(self.context_mark)) # if self.problem is not None: # lines.append(self.problem) # if self.problem_mark is not None: # lines.append(str(self.problem_mark)) # if self.note is not None and self.note: # note = textwrap.dedent(self.note) # lines.append(note) # return "\n".join(lines) # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): . Output only the next line.
self.index = index
Given the following code snippet before the placeholder: <|code_start|> self.name = getattr(self.stream, "name", "<file>") self.eof = False self.raw_buffer = None self.determine_encoding() def peek(self, index=0): # type: (int) -> Text try: return self.buffer[self.pointer + index] except IndexError: self.update(index + 1) return self.buffer[self.pointer + index] def prefix(self, length=1): # type: (int) -> Any if self.pointer + length >= len(self.buffer): self.update(length) return self.buffer[self.pointer : self.pointer + length] def forward_1_1(self, length=1): # type: (int) -> None if self.pointer + length + 1 >= len(self.buffer): self.update(length + 1) while length != 0: ch = self.buffer[self.pointer] self.pointer += 1 self.index += 1 if ch in u"\n\x85\u2028\u2029" or ( ch == u"\r" and self.buffer[self.pointer] != u"\n" ): <|code_end|> , predict the next line using imports from the current file: import codecs from strictyaml.ruamel.error import YAMLError, FileMark, StringMark, YAMLStreamError from strictyaml.ruamel.compat import text_type, binary_type, PY3, UNICODE_SIZE from strictyaml.ruamel.util import RegExp from typing import Any, Dict, Optional, List, Union, Text, Tuple, Optional # NOQA and context including class names, function names, and sometimes code from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class FileMark(StreamMark): # __slots__ = () # # class StringMark(StreamMark): # __slots__ = "name", "index", "line", "column", "buffer", "pointer" # # def __init__(self, name, index, line, column, buffer, pointer): # # type: (Any, int, int, int, Any, Any) -> None # StreamMark.__init__(self, name, index, line, column) # self.buffer = buffer # self.pointer = pointer # # def get_snippet(self, indent=4, max_length=75): # # type: (int, int) -> Any # if self.buffer is None: # always False # return None # head = "" # start = self.pointer # while start > 0 and self.buffer[start - 1] not in u"\0\r\n\x85\u2028\u2029": # start -= 1 # if self.pointer - start > max_length / 2 - 1: # head = " ... " # start += 5 # break # tail = "" # end = self.pointer # while ( # end < len(self.buffer) and self.buffer[end] not in u"\0\r\n\x85\u2028\u2029" # ): # end += 1 # if end - self.pointer > max_length / 2 - 1: # tail = " ... " # end -= 5 # break # snippet = utf8(self.buffer[start:end]) # caret = "^" # caret = "^ (line: {})".format(self.line + 1) # return ( # " " * indent # + head # + snippet # + tail # + "\n" # + " " * (indent + self.pointer - start + len(head)) # + caret # ) # # def __str__(self): # # type: () -> Any # snippet = self.get_snippet() # where = ' in "%s", line %d, column %d' % ( # self.name, # self.line + 1, # self.column + 1, # ) # if snippet is not None: # where += ":\n" + snippet # return where # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
self.line += 1
Given snippet: <|code_start|> self.determine_encoding() def peek(self, index=0): # type: (int) -> Text try: return self.buffer[self.pointer + index] except IndexError: self.update(index + 1) return self.buffer[self.pointer + index] def prefix(self, length=1): # type: (int) -> Any if self.pointer + length >= len(self.buffer): self.update(length) return self.buffer[self.pointer : self.pointer + length] def forward_1_1(self, length=1): # type: (int) -> None if self.pointer + length + 1 >= len(self.buffer): self.update(length + 1) while length != 0: ch = self.buffer[self.pointer] self.pointer += 1 self.index += 1 if ch in u"\n\x85\u2028\u2029" or ( ch == u"\r" and self.buffer[self.pointer] != u"\n" ): self.line += 1 self.column = 0 elif ch != u"\uFEFF": <|code_end|> , continue by predicting the next line. Consider current file imports: import codecs from strictyaml.ruamel.error import YAMLError, FileMark, StringMark, YAMLStreamError from strictyaml.ruamel.compat import text_type, binary_type, PY3, UNICODE_SIZE from strictyaml.ruamel.util import RegExp from typing import Any, Dict, Optional, List, Union, Text, Tuple, Optional # NOQA and context: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class FileMark(StreamMark): # __slots__ = () # # class StringMark(StreamMark): # __slots__ = "name", "index", "line", "column", "buffer", "pointer" # # def __init__(self, name, index, line, column, buffer, pointer): # # type: (Any, int, int, int, Any, Any) -> None # StreamMark.__init__(self, name, index, line, column) # self.buffer = buffer # self.pointer = pointer # # def get_snippet(self, indent=4, max_length=75): # # type: (int, int) -> Any # if self.buffer is None: # always False # return None # head = "" # start = self.pointer # while start > 0 and self.buffer[start - 1] not in u"\0\r\n\x85\u2028\u2029": # start -= 1 # if self.pointer - start > max_length / 2 - 1: # head = " ... " # start += 5 # break # tail = "" # end = self.pointer # while ( # end < len(self.buffer) and self.buffer[end] not in u"\0\r\n\x85\u2028\u2029" # ): # end += 1 # if end - self.pointer > max_length / 2 - 1: # tail = " ... " # end -= 5 # break # snippet = utf8(self.buffer[start:end]) # caret = "^" # caret = "^ (line: {})".format(self.line + 1) # return ( # " " * indent # + head # + snippet # + tail # + "\n" # + " " * (indent + self.pointer - start + len(head)) # + caret # ) # # def __str__(self): # # type: () -> Any # snippet = self.get_snippet() # where = ' in "%s", line %d, column %d' % ( # self.name, # self.line + 1, # self.column + 1, # ) # if snippet is not None: # where += ":\n" + snippet # return where # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): which might include code, classes, or functions. Output only the next line.
self.column += 1
Predict the next line for this snippet: <|code_start|># reader.forward(length=1) - move the current position to `length` # characters. # reader.index - the number of the current character. # reader.line, stream.column - the line and the column of the current # character. if False: # MYPY # from strictyaml.ruamel.compat import StreamTextType # NOQA __all__ = ["Reader", "ReaderError"] class ReaderError(YAMLError): def __init__(self, name, position, character, encoding, reason): # type: (Any, Any, Any, Any, Any) -> None self.name = name self.character = character self.position = position self.encoding = encoding self.reason = reason def __str__(self): # type: () -> str if isinstance(self.character, binary_type): return ( "'%s' codec can't decode byte #x%02x: %s\n" ' in "%s", position %d' % ( <|code_end|> with the help of current file imports: import codecs from strictyaml.ruamel.error import YAMLError, FileMark, StringMark, YAMLStreamError from strictyaml.ruamel.compat import text_type, binary_type, PY3, UNICODE_SIZE from strictyaml.ruamel.util import RegExp from typing import Any, Dict, Optional, List, Union, Text, Tuple, Optional # NOQA and context from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class FileMark(StreamMark): # __slots__ = () # # class StringMark(StreamMark): # __slots__ = "name", "index", "line", "column", "buffer", "pointer" # # def __init__(self, name, index, line, column, buffer, pointer): # # type: (Any, int, int, int, Any, Any) -> None # StreamMark.__init__(self, name, index, line, column) # self.buffer = buffer # self.pointer = pointer # # def get_snippet(self, indent=4, max_length=75): # # type: (int, int) -> Any # if self.buffer is None: # always False # return None # head = "" # start = self.pointer # while start > 0 and self.buffer[start - 1] not in u"\0\r\n\x85\u2028\u2029": # start -= 1 # if self.pointer - start > max_length / 2 - 1: # head = " ... " # start += 5 # break # tail = "" # end = self.pointer # while ( # end < len(self.buffer) and self.buffer[end] not in u"\0\r\n\x85\u2028\u2029" # ): # end += 1 # if end - self.pointer > max_length / 2 - 1: # tail = " ... " # end -= 5 # break # snippet = utf8(self.buffer[start:end]) # caret = "^" # caret = "^ (line: {})".format(self.line + 1) # return ( # " " * indent # + head # + snippet # + tail # + "\n" # + " " * (indent + self.pointer - start + len(head)) # + caret # ) # # def __str__(self): # # type: () -> Any # snippet = self.get_snippet() # where = ' in "%s", line %d, column %d' % ( # self.name, # self.line + 1, # self.column + 1, # ) # if snippet is not None: # where += ":\n" + snippet # return where # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): , which may contain function names, class names, or code. Output only the next line.
self.encoding,
Next line prediction: <|code_start|> self.name, self.index, self.line, self.column, self.buffer, self.pointer ) else: return FileMark(self.name, self.index, self.line, self.column) def determine_encoding(self): # type: () -> None while not self.eof and (self.raw_buffer is None or len(self.raw_buffer) < 2): self.update_raw() if isinstance(self.raw_buffer, binary_type): if self.raw_buffer.startswith(codecs.BOM_UTF16_LE): self.raw_decode = codecs.utf_16_le_decode # type: ignore self.encoding = "utf-16-le" elif self.raw_buffer.startswith(codecs.BOM_UTF16_BE): self.raw_decode = codecs.utf_16_be_decode # type: ignore self.encoding = "utf-16-be" else: self.raw_decode = codecs.utf_8_decode # type: ignore self.encoding = "utf-8" self.update(1) if UNICODE_SIZE == 2: NON_PRINTABLE = RegExp( u"[^\x09\x0A\x0D\x20-\x7E\x85" u"\xA0-\uD7FF" u"\uE000-\uFFFD" u"]" ) else: NON_PRINTABLE = RegExp( u"[^\x09\x0A\x0D\x20-\x7E\x85" u"\xA0-\uD7FF" u"\uE000-\uFFFD" <|code_end|> . Use current file imports: (import codecs from strictyaml.ruamel.error import YAMLError, FileMark, StringMark, YAMLStreamError from strictyaml.ruamel.compat import text_type, binary_type, PY3, UNICODE_SIZE from strictyaml.ruamel.util import RegExp from typing import Any, Dict, Optional, List, Union, Text, Tuple, Optional # NOQA) and context including class names, function names, or small code snippets from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class FileMark(StreamMark): # __slots__ = () # # class StringMark(StreamMark): # __slots__ = "name", "index", "line", "column", "buffer", "pointer" # # def __init__(self, name, index, line, column, buffer, pointer): # # type: (Any, int, int, int, Any, Any) -> None # StreamMark.__init__(self, name, index, line, column) # self.buffer = buffer # self.pointer = pointer # # def get_snippet(self, indent=4, max_length=75): # # type: (int, int) -> Any # if self.buffer is None: # always False # return None # head = "" # start = self.pointer # while start > 0 and self.buffer[start - 1] not in u"\0\r\n\x85\u2028\u2029": # start -= 1 # if self.pointer - start > max_length / 2 - 1: # head = " ... " # start += 5 # break # tail = "" # end = self.pointer # while ( # end < len(self.buffer) and self.buffer[end] not in u"\0\r\n\x85\u2028\u2029" # ): # end += 1 # if end - self.pointer > max_length / 2 - 1: # tail = " ... " # end -= 5 # break # snippet = utf8(self.buffer[start:end]) # caret = "^" # caret = "^ (line: {})".format(self.line + 1) # return ( # " " * indent # + head # + snippet # + tail # + "\n" # + " " * (indent + self.pointer - start + len(head)) # + caret # ) # # def __str__(self): # # type: () -> Any # snippet = self.get_snippet() # where = ' in "%s", line %d, column %d' % ( # self.name, # self.line + 1, # self.column + 1, # ) # if snippet is not None: # where += ":\n" + snippet # return where # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
u"\U00010000-\U0010FFFF"
Next line prediction: <|code_start|> # type: () -> None self.name = None # type: Any self.stream_pointer = 0 self.eof = True self.buffer = "" self.pointer = 0 self.raw_buffer = None # type: Any self.raw_decode = None self.encoding = None # type: Optional[Text] self.index = 0 self.line = 0 self.column = 0 @property def stream(self): # type: () -> Any try: return self._stream except AttributeError: raise YAMLStreamError("input stream needs to specified") @stream.setter def stream(self, val): # type: (Any) -> None if val is None: return self._stream = None if isinstance(val, text_type): self.name = "<unicode string>" self.check_printable(val) <|code_end|> . Use current file imports: (import codecs from strictyaml.ruamel.error import YAMLError, FileMark, StringMark, YAMLStreamError from strictyaml.ruamel.compat import text_type, binary_type, PY3, UNICODE_SIZE from strictyaml.ruamel.util import RegExp from typing import Any, Dict, Optional, List, Union, Text, Tuple, Optional # NOQA) and context including class names, function names, or small code snippets from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class FileMark(StreamMark): # __slots__ = () # # class StringMark(StreamMark): # __slots__ = "name", "index", "line", "column", "buffer", "pointer" # # def __init__(self, name, index, line, column, buffer, pointer): # # type: (Any, int, int, int, Any, Any) -> None # StreamMark.__init__(self, name, index, line, column) # self.buffer = buffer # self.pointer = pointer # # def get_snippet(self, indent=4, max_length=75): # # type: (int, int) -> Any # if self.buffer is None: # always False # return None # head = "" # start = self.pointer # while start > 0 and self.buffer[start - 1] not in u"\0\r\n\x85\u2028\u2029": # start -= 1 # if self.pointer - start > max_length / 2 - 1: # head = " ... " # start += 5 # break # tail = "" # end = self.pointer # while ( # end < len(self.buffer) and self.buffer[end] not in u"\0\r\n\x85\u2028\u2029" # ): # end += 1 # if end - self.pointer > max_length / 2 - 1: # tail = " ... " # end -= 5 # break # snippet = utf8(self.buffer[start:end]) # caret = "^" # caret = "^ (line: {})".format(self.line + 1) # return ( # " " * indent # + head # + snippet # + tail # + "\n" # + " " * (indent + self.pointer - start + len(head)) # + caret # ) # # def __str__(self): # # type: () -> Any # snippet = self.get_snippet() # where = ' in "%s", line %d, column %d' % ( # self.name, # self.line + 1, # self.column + 1, # ) # if snippet is not None: # where += ":\n" + snippet # return where # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
self.buffer = val + u"\0" # type: ignore
Here is a snippet: <|code_start|> class Reader(object): # Reader: # - determines the data encoding and converts it to a unicode string, # - checks if characters are in allowed range, # - adds '\0' to the end. # Reader accepts # - a `str` object (PY2) / a `bytes` object (PY3), # - a `unicode` object (PY2) / a `str` object (PY3), # - a file-like object with its `read` method returning `str`, # - a file-like object with its `read` method returning `unicode`. # Yeah, it's ugly and slow. def __init__(self, stream, loader=None): # type: (Any, Any) -> None self.loader = loader if self.loader is not None and getattr(self.loader, "_reader", None) is None: self.loader._reader = self self.reset_reader() self.stream = stream # type: Any # as .read is called def reset_reader(self): # type: () -> None self.name = None # type: Any self.stream_pointer = 0 self.eof = True self.buffer = "" <|code_end|> . Write the next line using the current file imports: import codecs from strictyaml.ruamel.error import YAMLError, FileMark, StringMark, YAMLStreamError from strictyaml.ruamel.compat import text_type, binary_type, PY3, UNICODE_SIZE from strictyaml.ruamel.util import RegExp from typing import Any, Dict, Optional, List, Union, Text, Tuple, Optional # NOQA and context from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class FileMark(StreamMark): # __slots__ = () # # class StringMark(StreamMark): # __slots__ = "name", "index", "line", "column", "buffer", "pointer" # # def __init__(self, name, index, line, column, buffer, pointer): # # type: (Any, int, int, int, Any, Any) -> None # StreamMark.__init__(self, name, index, line, column) # self.buffer = buffer # self.pointer = pointer # # def get_snippet(self, indent=4, max_length=75): # # type: (int, int) -> Any # if self.buffer is None: # always False # return None # head = "" # start = self.pointer # while start > 0 and self.buffer[start - 1] not in u"\0\r\n\x85\u2028\u2029": # start -= 1 # if self.pointer - start > max_length / 2 - 1: # head = " ... " # start += 5 # break # tail = "" # end = self.pointer # while ( # end < len(self.buffer) and self.buffer[end] not in u"\0\r\n\x85\u2028\u2029" # ): # end += 1 # if end - self.pointer > max_length / 2 - 1: # tail = " ... " # end -= 5 # break # snippet = utf8(self.buffer[start:end]) # caret = "^" # caret = "^ (line: {})".format(self.line + 1) # return ( # " " * indent # + head # + snippet # + tail # + "\n" # + " " * (indent + self.pointer - start + len(head)) # + caret # ) # # def __str__(self): # # type: () -> Any # snippet = self.get_snippet() # where = ' in "%s", line %d, column %d' % ( # self.name, # self.line + 1, # self.column + 1, # ) # if snippet is not None: # where += ":\n" + snippet # return where # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): , which may include functions, classes, or code. Output only the next line.
self.pointer = 0
Next line prediction: <|code_start|> if self.pointer + length + 1 >= len(self.buffer): self.update(length + 1) while length != 0: ch = self.buffer[self.pointer] self.pointer += 1 self.index += 1 if ch in u"\n\x85\u2028\u2029" or ( ch == u"\r" and self.buffer[self.pointer] != u"\n" ): self.line += 1 self.column = 0 elif ch != u"\uFEFF": self.column += 1 length -= 1 def forward(self, length=1): # type: (int) -> None if self.pointer + length + 1 >= len(self.buffer): self.update(length + 1) while length != 0: ch = self.buffer[self.pointer] self.pointer += 1 self.index += 1 if ch == u"\n" or (ch == u"\r" and self.buffer[self.pointer] != u"\n"): self.line += 1 self.column = 0 elif ch != u"\uFEFF": self.column += 1 length -= 1 <|code_end|> . Use current file imports: (import codecs from strictyaml.ruamel.error import YAMLError, FileMark, StringMark, YAMLStreamError from strictyaml.ruamel.compat import text_type, binary_type, PY3, UNICODE_SIZE from strictyaml.ruamel.util import RegExp from typing import Any, Dict, Optional, List, Union, Text, Tuple, Optional # NOQA) and context including class names, function names, or small code snippets from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class FileMark(StreamMark): # __slots__ = () # # class StringMark(StreamMark): # __slots__ = "name", "index", "line", "column", "buffer", "pointer" # # def __init__(self, name, index, line, column, buffer, pointer): # # type: (Any, int, int, int, Any, Any) -> None # StreamMark.__init__(self, name, index, line, column) # self.buffer = buffer # self.pointer = pointer # # def get_snippet(self, indent=4, max_length=75): # # type: (int, int) -> Any # if self.buffer is None: # always False # return None # head = "" # start = self.pointer # while start > 0 and self.buffer[start - 1] not in u"\0\r\n\x85\u2028\u2029": # start -= 1 # if self.pointer - start > max_length / 2 - 1: # head = " ... " # start += 5 # break # tail = "" # end = self.pointer # while ( # end < len(self.buffer) and self.buffer[end] not in u"\0\r\n\x85\u2028\u2029" # ): # end += 1 # if end - self.pointer > max_length / 2 - 1: # tail = " ... " # end -= 5 # break # snippet = utf8(self.buffer[start:end]) # caret = "^" # caret = "^ (line: {})".format(self.line + 1) # return ( # " " * indent # + head # + snippet # + tail # + "\n" # + " " * (indent + self.pointer - start + len(head)) # + caret # ) # # def __str__(self): # # type: () -> Any # snippet = self.get_snippet() # where = ' in "%s", line %d, column %d' % ( # self.name, # self.line + 1, # self.column + 1, # ) # if snippet is not None: # where += ":\n" + snippet # return where # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
def get_mark(self):
Given the code snippet: <|code_start|> self.pointer += 1 self.index += 1 if ch in u"\n\x85\u2028\u2029" or ( ch == u"\r" and self.buffer[self.pointer] != u"\n" ): self.line += 1 self.column = 0 elif ch != u"\uFEFF": self.column += 1 length -= 1 def forward(self, length=1): # type: (int) -> None if self.pointer + length + 1 >= len(self.buffer): self.update(length + 1) while length != 0: ch = self.buffer[self.pointer] self.pointer += 1 self.index += 1 if ch == u"\n" or (ch == u"\r" and self.buffer[self.pointer] != u"\n"): self.line += 1 self.column = 0 elif ch != u"\uFEFF": self.column += 1 length -= 1 def get_mark(self): # type: () -> Any if self.stream is None: return StringMark( <|code_end|> , generate the next line using the imports in this file: import codecs from strictyaml.ruamel.error import YAMLError, FileMark, StringMark, YAMLStreamError from strictyaml.ruamel.compat import text_type, binary_type, PY3, UNICODE_SIZE from strictyaml.ruamel.util import RegExp from typing import Any, Dict, Optional, List, Union, Text, Tuple, Optional # NOQA and context (functions, classes, or occasionally code) from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class FileMark(StreamMark): # __slots__ = () # # class StringMark(StreamMark): # __slots__ = "name", "index", "line", "column", "buffer", "pointer" # # def __init__(self, name, index, line, column, buffer, pointer): # # type: (Any, int, int, int, Any, Any) -> None # StreamMark.__init__(self, name, index, line, column) # self.buffer = buffer # self.pointer = pointer # # def get_snippet(self, indent=4, max_length=75): # # type: (int, int) -> Any # if self.buffer is None: # always False # return None # head = "" # start = self.pointer # while start > 0 and self.buffer[start - 1] not in u"\0\r\n\x85\u2028\u2029": # start -= 1 # if self.pointer - start > max_length / 2 - 1: # head = " ... " # start += 5 # break # tail = "" # end = self.pointer # while ( # end < len(self.buffer) and self.buffer[end] not in u"\0\r\n\x85\u2028\u2029" # ): # end += 1 # if end - self.pointer > max_length / 2 - 1: # tail = " ... " # end -= 5 # break # snippet = utf8(self.buffer[start:end]) # caret = "^" # caret = "^ (line: {})".format(self.line + 1) # return ( # " " * indent # + head # + snippet # + tail # + "\n" # + " " * (indent + self.pointer - start + len(head)) # + caret # ) # # def __str__(self): # # type: () -> Any # snippet = self.get_snippet() # where = ' in "%s", line %d, column %d' % ( # self.name, # self.line + 1, # self.column + 1, # ) # if snippet is not None: # where += ":\n" + snippet # return where # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
self.name, self.index, self.line, self.column, self.buffer, self.pointer
Using the snippet: <|code_start|> elif ch != u"\uFEFF": self.column += 1 length -= 1 def forward(self, length=1): # type: (int) -> None if self.pointer + length + 1 >= len(self.buffer): self.update(length + 1) while length != 0: ch = self.buffer[self.pointer] self.pointer += 1 self.index += 1 if ch == u"\n" or (ch == u"\r" and self.buffer[self.pointer] != u"\n"): self.line += 1 self.column = 0 elif ch != u"\uFEFF": self.column += 1 length -= 1 def get_mark(self): # type: () -> Any if self.stream is None: return StringMark( self.name, self.index, self.line, self.column, self.buffer, self.pointer ) else: return FileMark(self.name, self.index, self.line, self.column) def determine_encoding(self): # type: () -> None <|code_end|> , determine the next line of code. You have imports: import codecs from strictyaml.ruamel.error import YAMLError, FileMark, StringMark, YAMLStreamError from strictyaml.ruamel.compat import text_type, binary_type, PY3, UNICODE_SIZE from strictyaml.ruamel.util import RegExp from typing import Any, Dict, Optional, List, Union, Text, Tuple, Optional # NOQA and context (class names, function names, or code) available: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class FileMark(StreamMark): # __slots__ = () # # class StringMark(StreamMark): # __slots__ = "name", "index", "line", "column", "buffer", "pointer" # # def __init__(self, name, index, line, column, buffer, pointer): # # type: (Any, int, int, int, Any, Any) -> None # StreamMark.__init__(self, name, index, line, column) # self.buffer = buffer # self.pointer = pointer # # def get_snippet(self, indent=4, max_length=75): # # type: (int, int) -> Any # if self.buffer is None: # always False # return None # head = "" # start = self.pointer # while start > 0 and self.buffer[start - 1] not in u"\0\r\n\x85\u2028\u2029": # start -= 1 # if self.pointer - start > max_length / 2 - 1: # head = " ... " # start += 5 # break # tail = "" # end = self.pointer # while ( # end < len(self.buffer) and self.buffer[end] not in u"\0\r\n\x85\u2028\u2029" # ): # end += 1 # if end - self.pointer > max_length / 2 - 1: # tail = " ... " # end -= 5 # break # snippet = utf8(self.buffer[start:end]) # caret = "^" # caret = "^ (line: {})".format(self.line + 1) # return ( # " " * indent # + head # + snippet # + tail # + "\n" # + " " * (indent + self.pointer - start + len(head)) # + caret # ) # # def __str__(self): # # type: () -> Any # snippet = self.get_snippet() # where = ' in "%s", line %d, column %d' % ( # self.name, # self.line + 1, # self.column + 1, # ) # if snippet is not None: # where += ":\n" + snippet # return where # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/util.py # class LazyEval(object): # def __init__(self, func, *args, **kwargs): # def lazy_self(): # def __getattribute__(self, name): # def __setattr__(self, name, value): # def load_yaml_guess_indent(stream, **kw): # def leading_spaces(line): # def configobj_walker(cfg): # def _walk_section(s, level=0): . Output only the next line.
while not self.eof and (self.raw_buffer is None or len(self.raw_buffer) < 2):
Given snippet: <|code_start|> def expect_flow_sequence_item(self): # type: () -> None if isinstance(self.event, SequenceEndEvent): self.indent = self.indents.pop() popped = self.flow_context.pop() assert popped == "[" if self.canonical: self.write_indicator(u",", False) self.write_indent() self.write_indicator(u"]", False) if self.event.comment and self.event.comment[0]: # eol comment on flow sequence self.write_post_comment(self.event) else: self.no_newline = False self.state = self.states.pop() else: self.write_indicator(u",", False) if self.canonical or self.column > self.best_width: self.write_indent() self.states.append(self.expect_flow_sequence_item) self.expect_node(sequence=True) # Flow mapping handlers. def expect_flow_mapping(self, single=False): # type: (Optional[bool]) -> None ind = self.indents.seq_flow_align(self.best_sequence_indent, self.column) map_init = u"{" if ( <|code_end|> , continue by predicting the next line. Consider current file imports: import sys from strictyaml.ruamel.error import YAMLError, YAMLStreamError from strictyaml.ruamel.events import * # NOQA from strictyaml.ruamel.compat import utf8, text_type, PY2, nprint, dbg, DBG_EVENT, \ check_anchorname_char from typing import Any, Dict, List, Union, Text, Tuple, Optional # NOQA from strictyaml.ruamel.compat import StreamType # NOQA and context: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): which might include code, classes, or functions. Output only the next line.
single
Next line prediction: <|code_start|> self.allow_space_break = None # Emitter is a state machine with a stack of states to handle nested # structures. self.states = [] # type: List[Any] self.state = self.expect_stream_start # type: Any # Current event and the event queue. self.events = [] # type: List[Any] self.event = None # type: Any # The current indentation level and the stack of previous indents. self.indents = Indents() self.indent = None # type: Optional[int] # flow_context is an expanding/shrinking list consisting of '{' and '[' # for each unclosed flow context. If empty list that means block context self.flow_context = [] # type: List[Text] # Contexts. self.root_context = False self.sequence_context = False self.mapping_context = False self.simple_key_context = False # Characteristics of the last emitted character: # - current position. # - is it a whitespace? # - is it an indention character # (indentation space, '-', '?', or ':')? <|code_end|> . Use current file imports: (import sys from strictyaml.ruamel.error import YAMLError, YAMLStreamError from strictyaml.ruamel.events import * # NOQA from strictyaml.ruamel.compat import utf8, text_type, PY2, nprint, dbg, DBG_EVENT, \ check_anchorname_char from typing import Any, Dict, List, Union, Text, Tuple, Optional # NOQA from strictyaml.ruamel.compat import StreamType # NOQA) and context including class names, function names, or small code snippets from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): . Output only the next line.
self.line = 0
Using the snippet: <|code_start|> allow_block_plain=allow_block_plain, allow_single_quoted=allow_single_quoted, allow_double_quoted=allow_double_quoted, allow_block=allow_block, ) # Writers. def flush_stream(self): # type: () -> None if hasattr(self.stream, "flush"): self.stream.flush() def write_stream_start(self): # type: () -> None # Write BOM if needed. if self.encoding and self.encoding.startswith("utf-16"): self.stream.write(u"\uFEFF".encode(self.encoding)) def write_stream_end(self): # type: () -> None self.flush_stream() def write_indicator( self, indicator, need_whitespace, whitespace=False, indention=False ): # type: (Any, Any, bool, bool) -> None if self.whitespace or not need_whitespace: data = indicator else: <|code_end|> , determine the next line of code. You have imports: import sys from strictyaml.ruamel.error import YAMLError, YAMLStreamError from strictyaml.ruamel.events import * # NOQA from strictyaml.ruamel.compat import utf8, text_type, PY2, nprint, dbg, DBG_EVENT, \ check_anchorname_char from typing import Any, Dict, List, Union, Text, Tuple, Optional # NOQA from strictyaml.ruamel.compat import StreamType # NOQA and context (class names, function names, or code) available: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): . Output only the next line.
data = u" " + indicator
Given the code snippet: <|code_start|> start = end + 1 if ( 0 < end < len(text) - 1 and (ch == u" " or start >= end) and self.column + (end - start) > self.best_width and split ): data = text[start:end] + u"\\" if start < end: start = end self.column += len(data) if bool(self.encoding): data = data.encode(self.encoding) self.stream.write(data) self.write_indent() self.whitespace = False self.indention = False if text[start] == u" ": data = u"\\" self.column += len(data) if bool(self.encoding): data = data.encode(self.encoding) self.stream.write(data) end += 1 self.write_indicator(u'"', False) def determine_block_hints(self, text): # type: (Any) -> Any indent = 0 indicator = u"" <|code_end|> , generate the next line using the imports in this file: import sys from strictyaml.ruamel.error import YAMLError, YAMLStreamError from strictyaml.ruamel.events import * # NOQA from strictyaml.ruamel.compat import utf8, text_type, PY2, nprint, dbg, DBG_EVENT, \ check_anchorname_char from typing import Any, Dict, List, Union, Text, Tuple, Optional # NOQA from strictyaml.ruamel.compat import StreamType # NOQA and context (functions, classes, or occasionally code) from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): . Output only the next line.
hints = u""
Given the following code snippet before the placeholder: <|code_start|> flow_indicators = True block_indicators = True if ch in u"?:": # ToDo if self.serializer.use_version == (1, 1): flow_indicators = True elif len(scalar) == 1: # single character flow_indicators = True if followed_by_whitespace: block_indicators = True if ch == u"-" and followed_by_whitespace: flow_indicators = True block_indicators = True else: # Some indicators cannot appear within a scalar as well. if ch in u",[]{}": # http://yaml.org/spec/1.2/spec.html#id2788859 flow_indicators = True if ch == u"?" and self.serializer.use_version == (1, 1): flow_indicators = True if ch == u":": if followed_by_whitespace: flow_indicators = True block_indicators = True if ch == u"#" and preceeded_by_whitespace: flow_indicators = True block_indicators = True # Check for line breaks, special, and unicode characters. if ch in u"\n\x85\u2028\u2029": line_breaks = True if not (ch == u"\n" or u"\x20" <= ch <= u"\x7E"): <|code_end|> , predict the next line using imports from the current file: import sys from strictyaml.ruamel.error import YAMLError, YAMLStreamError from strictyaml.ruamel.events import * # NOQA from strictyaml.ruamel.compat import utf8, text_type, PY2, nprint, dbg, DBG_EVENT, \ check_anchorname_char from typing import Any, Dict, List, Union, Text, Tuple, Optional # NOQA from strictyaml.ruamel.compat import StreamType # NOQA and context including class names, function names, and sometimes code from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): . Output only the next line.
if (
Predict the next line after this snippet: <|code_start|> start = end if ch is not None: spaces = ch == u" " breaks = ch in u"\n\x85\u2028\u2029" end += 1 def write_comment(self, comment, pre=False): # type: (Any, bool) -> None value = comment.value # nprintf('{:02d} {:02d} {!r}'.format(self.column, comment.start_mark.column, value)) if not pre and value[-1] == "\n": value = value[:-1] try: # get original column position col = comment.start_mark.column if comment.value and comment.value.startswith("\n"): # never inject extra spaces if the comment starts with a newline # and not a real comment (e.g. if you have an empty line following a key-value col = self.column elif col < self.column + 1: ValueError except ValueError: col = self.column + 1 # nprint('post_comment', self.line, self.column, value) try: # at least one space if the current column >= the start column of the comment # but not at the start of a line nr_spaces = col - self.column if self.column and value.strip() and nr_spaces < 1 and value[0] != "\n": nr_spaces = 1 <|code_end|> using the current file's imports: import sys from strictyaml.ruamel.error import YAMLError, YAMLStreamError from strictyaml.ruamel.events import * # NOQA from strictyaml.ruamel.compat import utf8, text_type, PY2, nprint, dbg, DBG_EVENT, \ check_anchorname_char from typing import Any, Dict, List, Union, Text, Tuple, Optional # NOQA from strictyaml.ruamel.compat import StreamType # NOQA and any relevant context from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): . Output only the next line.
value = " " * nr_spaces + value
Given snippet: <|code_start|> self.write_indent() else: data = text[start:end] self.column += len(data) if bool(self.encoding): data = data.encode(self.encoding) self.stream.write(data) start = end else: if ch is None or ch in u" \n\x85\u2028\u2029\a": data = text[start:end] self.column += len(data) if bool(self.encoding): data = data.encode(self.encoding) self.stream.write(data) if ch == u"\a": if end < (len(text) - 1) and not text[end + 2].isspace(): self.write_line_break() self.write_indent() end += 2 # \a and the space that is inserted on the fold else: raise EmitterError( "unexcpected fold indicator \\a before space" ) if ch is None: self.write_line_break() start = end if ch is not None: breaks = ch in u"\n\x85\u2028\u2029" spaces = ch == u" " <|code_end|> , continue by predicting the next line. Consider current file imports: import sys from strictyaml.ruamel.error import YAMLError, YAMLStreamError from strictyaml.ruamel.events import * # NOQA from strictyaml.ruamel.compat import utf8, text_type, PY2, nprint, dbg, DBG_EVENT, \ check_anchorname_char from typing import Any, Dict, List, Union, Text, Tuple, Optional # NOQA from strictyaml.ruamel.compat import StreamType # NOQA and context: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): which might include code, classes, or functions. Output only the next line.
end += 1
Continue the code snippet: <|code_start|> def write_version_directive(self, version_text): # type: (Any) -> None data = u"%%YAML %s" % version_text if self.encoding: data = data.encode(self.encoding) self.stream.write(data) self.write_line_break() def write_tag_directive(self, handle_text, prefix_text): # type: (Any, Any) -> None data = u"%%TAG %s %s" % (handle_text, prefix_text) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) self.write_line_break() # Scalar streams. def write_single_quoted(self, text, split=True): # type: (Any, Any) -> None if self.root_context: if self.requested_indent is not None: self.write_line_break() if self.requested_indent != 0: self.write_indent() self.write_indicator(u"'", True) spaces = False breaks = False start = end = 0 while end <= len(text): <|code_end|> . Use current file imports: import sys from strictyaml.ruamel.error import YAMLError, YAMLStreamError from strictyaml.ruamel.events import * # NOQA from strictyaml.ruamel.compat import utf8, text_type, PY2, nprint, dbg, DBG_EVENT, \ check_anchorname_char from typing import Any, Dict, List, Union, Text, Tuple, Optional # NOQA from strictyaml.ruamel.compat import StreamType # NOQA and context (classes, functions, or code) from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): . Output only the next line.
ch = None
Given the code snippet: <|code_start|> self.state = self.expect_document_start else: raise EmitterError("expected DocumentEndEvent, but got %s" % (self.event,)) def expect_document_root(self): # type: () -> None self.states.append(self.expect_document_end) self.expect_node(root=True) # Node handlers. def expect_node(self, root=False, sequence=False, mapping=False, simple_key=False): # type: (bool, bool, bool, bool) -> None self.root_context = root self.sequence_context = sequence # not used in PyYAML self.mapping_context = mapping self.simple_key_context = simple_key if isinstance(self.event, AliasEvent): self.expect_alias() elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)): if ( self.process_anchor(u"&") and isinstance(self.event, ScalarEvent) and self.sequence_context ): self.sequence_context = False if ( root and isinstance(self.event, ScalarEvent) and not self.scalar_after_indicator <|code_end|> , generate the next line using the imports in this file: import sys from strictyaml.ruamel.error import YAMLError, YAMLStreamError from strictyaml.ruamel.events import * # NOQA from strictyaml.ruamel.compat import utf8, text_type, PY2, nprint, dbg, DBG_EVENT, \ check_anchorname_char from typing import Any, Dict, List, Union, Text, Tuple, Optional # NOQA from strictyaml.ruamel.compat import StreamType # NOQA and context (functions, classes, or occasionally code) from other files: # Path: strictyaml/ruamel/error.py # class YAMLError(Exception): # pass # # class YAMLStreamError(Exception): # pass # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): . Output only the next line.
):
Predict the next line after this snippet: <|code_start|> start += 5 break tail = "" end = self.pointer while ( end < len(self.buffer) and self.buffer[end] not in u"\0\r\n\x85\u2028\u2029" ): end += 1 if end - self.pointer > max_length / 2 - 1: tail = " ... " end -= 5 break snippet = utf8(self.buffer[start:end]) caret = "^" caret = "^ (line: {})".format(self.line + 1) return ( " " * indent + head + snippet + tail + "\n" + " " * (indent + self.pointer - start + len(head)) + caret ) def __str__(self): # type: () -> Any snippet = self.get_snippet() where = ' in "%s", line %d, column %d' % ( self.name, <|code_end|> using the current file's imports: import warnings import textwrap from strictyaml.ruamel.compat import utf8 from typing import Any, Dict, Optional, List, Text # NOQA and any relevant context from other files: # Path: strictyaml/ruamel/compat.py # def utf8(s): # # type: (str) -> str # return s . Output only the next line.
self.line + 1,
Based on the snippet: <|code_start|> def __new__(cls, value, anchor=None): # type: (Text, Any) -> Any return ScalarString.__new__(cls, value, anchor=anchor) class DoubleQuotedScalarString(ScalarString): __slots__ = () style = '"' def __new__(cls, value, anchor=None): # type: (Text, Any) -> Any return ScalarString.__new__(cls, value, anchor=anchor) class PlainScalarString(ScalarString): __slots__ = () style = "" def __new__(cls, value, anchor=None): # type: (Text, Any) -> Any return ScalarString.__new__(cls, value, anchor=anchor) def preserve_literal(s): # type: (Text) -> Text return LiteralScalarString(s.replace("\r\n", "\n").replace("\r", "\n")) <|code_end|> , predict the immediate next line with the help of imports: from strictyaml.ruamel.compat import text_type from strictyaml.ruamel.anchor import Anchor from typing import Text, Any, Dict, List # NOQA from strictyaml.ruamel.compat import string_types from strictyaml.ruamel.compat import MutableMapping, MutableSequence # type: ignore and context (classes, functions, sometimes code) from other files: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/anchor.py # class Anchor(object): # __slots__ = "value", "always_dump" # attrib = anchor_attrib # # def __init__(self): # # type: () -> None # self.value = None # self.always_dump = False # # def __repr__(self): # # type: () -> Any # ad = ", (always dump)" if self.always_dump else "" # return "Anchor({!r}{})".format(self.value, ad) . Output only the next line.
def walk_tree(base, map=None):
Given snippet: <|code_start|> return type(self)((text_type.replace(self, old, new, maxreplace))) @property def anchor(self): # type: () -> Any if not hasattr(self, Anchor.attrib): setattr(self, Anchor.attrib, Anchor()) return getattr(self, Anchor.attrib) def yaml_anchor(self, any=False): # type: (bool) -> Any if not hasattr(self, Anchor.attrib): return None if any or self.anchor.always_dump: return self.anchor return None def yaml_set_anchor(self, value, always_dump=False): # type: (Any, bool) -> None self.anchor.value = value self.anchor.always_dump = always_dump class LiteralScalarString(ScalarString): __slots__ = "comment" # the comment after the | on the first line style = "|" def __new__(cls, value, anchor=None): # type: (Text, Any) -> Any <|code_end|> , continue by predicting the next line. Consider current file imports: from strictyaml.ruamel.compat import text_type from strictyaml.ruamel.anchor import Anchor from typing import Text, Any, Dict, List # NOQA from strictyaml.ruamel.compat import string_types from strictyaml.ruamel.compat import MutableMapping, MutableSequence # type: ignore and context: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/anchor.py # class Anchor(object): # __slots__ = "value", "always_dump" # attrib = anchor_attrib # # def __init__(self): # # type: () -> None # self.value = None # self.always_dump = False # # def __repr__(self): # # type: () -> Any # ad = ", (always dump)" if self.always_dump else "" # return "Anchor({!r}{})".format(self.value, ad) which might include code, classes, or functions. Output only the next line.
return ScalarString.__new__(cls, value, anchor=anchor)
Using the snippet: <|code_start|> # type: () -> Any if not hasattr(self, Anchor.attrib): setattr(self, Anchor.attrib, Anchor()) return getattr(self, Anchor.attrib) def yaml_anchor(self, any=False): # type: (bool) -> Any if not hasattr(self, Anchor.attrib): return None if any or self.anchor.always_dump: return self.anchor return None def yaml_set_anchor(self, value, always_dump=False): # type: (Any, bool) -> None self.anchor.value = value self.anchor.always_dump = always_dump def dump(self, out=sys.stdout): # type: (Any) -> Any out.write( "ScalarFloat({}| w:{}, p:{}, s:{}, lz:{}, _:{}|{}, w:{}, s:{})\n".format( self, self._width, # type: ignore self._prec, # type: ignore self._m_sign, # type: ignore self._m_lead0, # type: ignore self._underscore, # type: ignore self._exp, # type: ignore self._e_width, # type: ignore <|code_end|> , determine the next line of code. You have imports: import sys from .compat import no_limit_int # NOQA from strictyaml.ruamel.anchor import Anchor from typing import Text, Any, Dict, List # NOQA and context (class names, function names, or code) available: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/anchor.py # class Anchor(object): # __slots__ = "value", "always_dump" # attrib = anchor_attrib # # def __init__(self): # # type: () -> None # self.value = None # self.always_dump = False # # def __repr__(self): # # type: () -> Any # ad = ", (always dump)" if self.always_dump else "" # return "Anchor({!r}{})".format(self.value, ad) . Output only the next line.
self._e_sign, # type: ignore
Predict the next line for this snippet: <|code_start|> self.end_mark = end_mark self.comment = comment self.anchor = anchor def __repr__(self): # type: () -> str value = self.value # if isinstance(value, list): # if len(value) == 0: # value = '<empty>' # elif len(value) == 1: # value = '<1 item>' # else: # value = '<%d items>' % len(value) # else: # if len(value) > 75: # value = repr(value[:70]+u' ... ') # else: # value = repr(value) value = repr(value) return "%s(tag=%r, value=%s)" % (self.__class__.__name__, self.tag, value) def dump(self, indent=0): # type: (int) -> None if isinstance(self.value, string_types): sys.stdout.write( "{}{}(tag={!r}, value={!r})\n".format( " " * indent, self.__class__.__name__, self.tag, self.value ) ) <|code_end|> with the help of current file imports: import sys from .compat import string_types from typing import Dict, Any, Text # NOQA and context from other files: # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): , which may contain function names, class names, or code. Output only the next line.
if self.comment:
Next line prediction: <|code_start|> # to distinguish key from None def NoComment(): # type: () -> None pass class Format(object): __slots__ = ("_flow_style",) attrib = format_attrib def __init__(self): # type: () -> None self._flow_style = None # type: Any def set_flow_style(self): # type: () -> None self._flow_style = True def set_block_style(self): # type: () -> None self._flow_style = False def flow_style(self, default=None): # type: (Optional[Any]) -> Any """if default (the flow_style) is None, the flow style tacked on to the object explicitly will be taken. If that is None as well the default flow style rules the format down the line, or the type of the constituent values (simple -> flow, map/list -> block)""" if self._flow_style is None: <|code_end|> . Use current file imports: (import sys import copy from strictyaml.ruamel.compat import ordereddict # type: ignore from strictyaml.ruamel.compat import PY2, string_types, MutableSliceableSequence from strictyaml.ruamel.scalarstring import ScalarString from strictyaml.ruamel.anchor import Anchor from collections import MutableSet, Sized, Set, Mapping from collections.abc import MutableSet, Sized, Set, Mapping from typing import Any, Dict, Optional, List, Union, Optional, Iterator # NOQA from .error import CommentMark from .tokens import CommentToken from strictyaml.ruamel.error import CommentMark from strictyaml.ruamel.tokens import CommentToken from .tokens import CommentToken from .error import CommentMark) and context including class names, function names, or small code snippets from other files: # Path: strictyaml/ruamel/compat.py # class ordereddict(OrderedDict): # type: ignore # if not hasattr(OrderedDict, "insert"): # # def insert(self, pos, key, value): # # type: (int, Any, Any) -> None # if pos >= len(self): # self[key] = value # return # od = ordereddict() # od.update(self) # for k in od: # del self[k] # for index, old_key in enumerate(od): # if pos == index: # self[key] = value # self[old_key] = od[old_key] # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/scalarstring.py # class ScalarString(text_type): # __slots__ = Anchor.attrib # # def __new__(cls, *args, **kw): # # type: (Any, Any) -> Any # anchor = kw.pop("anchor", None) # type: ignore # ret_val = text_type.__new__(cls, *args, **kw) # type: ignore # if anchor is not None: # ret_val.yaml_set_anchor(anchor, always_dump=True) # return ret_val # # def replace(self, old, new, maxreplace=-1): # # type: (Any, Any, int) -> Any # return type(self)((text_type.replace(self, old, new, maxreplace))) # # @property # def anchor(self): # # type: () -> Any # if not hasattr(self, Anchor.attrib): # setattr(self, Anchor.attrib, Anchor()) # return getattr(self, Anchor.attrib) # # def yaml_anchor(self, any=False): # # type: (bool) -> Any # if not hasattr(self, Anchor.attrib): # return None # if any or self.anchor.always_dump: # return self.anchor # return None # # def yaml_set_anchor(self, value, always_dump=False): # # type: (Any, bool) -> None # self.anchor.value = value # self.anchor.always_dump = always_dump # # Path: strictyaml/ruamel/anchor.py # class Anchor(object): # __slots__ = "value", "always_dump" # attrib = anchor_attrib # # def __init__(self): # # type: () -> None # self.value = None # self.always_dump = False # # def __repr__(self): # # type: () -> Any # ad = ", (always dump)" if self.always_dump else "" # return "Anchor({!r}{})".format(self.value, ad) . Output only the next line.
return default
Next line prediction: <|code_start|> def __init__(self): # type: () -> None self._flow_style = None # type: Any def set_flow_style(self): # type: () -> None self._flow_style = True def set_block_style(self): # type: () -> None self._flow_style = False def flow_style(self, default=None): # type: (Optional[Any]) -> Any """if default (the flow_style) is None, the flow style tacked on to the object explicitly will be taken. If that is None as well the default flow style rules the format down the line, or the type of the constituent values (simple -> flow, map/list -> block)""" if self._flow_style is None: return default return self._flow_style class LineCol(object): attrib = line_col_attrib def __init__(self): # type: () -> None self.line = None self.col = None <|code_end|> . Use current file imports: (import sys import copy from strictyaml.ruamel.compat import ordereddict # type: ignore from strictyaml.ruamel.compat import PY2, string_types, MutableSliceableSequence from strictyaml.ruamel.scalarstring import ScalarString from strictyaml.ruamel.anchor import Anchor from collections import MutableSet, Sized, Set, Mapping from collections.abc import MutableSet, Sized, Set, Mapping from typing import Any, Dict, Optional, List, Union, Optional, Iterator # NOQA from .error import CommentMark from .tokens import CommentToken from strictyaml.ruamel.error import CommentMark from strictyaml.ruamel.tokens import CommentToken from .tokens import CommentToken from .error import CommentMark) and context including class names, function names, or small code snippets from other files: # Path: strictyaml/ruamel/compat.py # class ordereddict(OrderedDict): # type: ignore # if not hasattr(OrderedDict, "insert"): # # def insert(self, pos, key, value): # # type: (int, Any, Any) -> None # if pos >= len(self): # self[key] = value # return # od = ordereddict() # od.update(self) # for k in od: # del self[k] # for index, old_key in enumerate(od): # if pos == index: # self[key] = value # self[old_key] = od[old_key] # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/scalarstring.py # class ScalarString(text_type): # __slots__ = Anchor.attrib # # def __new__(cls, *args, **kw): # # type: (Any, Any) -> Any # anchor = kw.pop("anchor", None) # type: ignore # ret_val = text_type.__new__(cls, *args, **kw) # type: ignore # if anchor is not None: # ret_val.yaml_set_anchor(anchor, always_dump=True) # return ret_val # # def replace(self, old, new, maxreplace=-1): # # type: (Any, Any, int) -> Any # return type(self)((text_type.replace(self, old, new, maxreplace))) # # @property # def anchor(self): # # type: () -> Any # if not hasattr(self, Anchor.attrib): # setattr(self, Anchor.attrib, Anchor()) # return getattr(self, Anchor.attrib) # # def yaml_anchor(self, any=False): # # type: (bool) -> Any # if not hasattr(self, Anchor.attrib): # return None # if any or self.anchor.always_dump: # return self.anchor # return None # # def yaml_set_anchor(self, value, always_dump=False): # # type: (Any, bool) -> None # self.anchor.value = value # self.anchor.always_dump = always_dump # # Path: strictyaml/ruamel/anchor.py # class Anchor(object): # __slots__ = "value", "always_dump" # attrib = anchor_attrib # # def __init__(self): # # type: () -> None # self.value = None # self.always_dump = False # # def __repr__(self): # # type: () -> Any # ad = ", (always dump)" if self.always_dump else "" # return "Anchor({!r}{})".format(self.value, ad) . Output only the next line.
self.data = None # type: Optional[Dict[Any, Any]]
Given the following code snippet before the placeholder: <|code_start|> if self._flow_style is None: return default return self._flow_style class LineCol(object): attrib = line_col_attrib def __init__(self): # type: () -> None self.line = None self.col = None self.data = None # type: Optional[Dict[Any, Any]] def add_kv_line_col(self, key, data): # type: (Any, Any) -> None if self.data is None: self.data = {} self.data[key] = data def key(self, k): # type: (Any) -> Any return self._kv(k, 0, 1) def value(self, k): # type: (Any) -> Any return self._kv(k, 2, 3) def _kv(self, k, x0, x1): # type: (Any, Any, Any) -> Any <|code_end|> , predict the next line using imports from the current file: import sys import copy from strictyaml.ruamel.compat import ordereddict # type: ignore from strictyaml.ruamel.compat import PY2, string_types, MutableSliceableSequence from strictyaml.ruamel.scalarstring import ScalarString from strictyaml.ruamel.anchor import Anchor from collections import MutableSet, Sized, Set, Mapping from collections.abc import MutableSet, Sized, Set, Mapping from typing import Any, Dict, Optional, List, Union, Optional, Iterator # NOQA from .error import CommentMark from .tokens import CommentToken from strictyaml.ruamel.error import CommentMark from strictyaml.ruamel.tokens import CommentToken from .tokens import CommentToken from .error import CommentMark and context including class names, function names, and sometimes code from other files: # Path: strictyaml/ruamel/compat.py # class ordereddict(OrderedDict): # type: ignore # if not hasattr(OrderedDict, "insert"): # # def insert(self, pos, key, value): # # type: (int, Any, Any) -> None # if pos >= len(self): # self[key] = value # return # od = ordereddict() # od.update(self) # for k in od: # del self[k] # for index, old_key in enumerate(od): # if pos == index: # self[key] = value # self[old_key] = od[old_key] # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/scalarstring.py # class ScalarString(text_type): # __slots__ = Anchor.attrib # # def __new__(cls, *args, **kw): # # type: (Any, Any) -> Any # anchor = kw.pop("anchor", None) # type: ignore # ret_val = text_type.__new__(cls, *args, **kw) # type: ignore # if anchor is not None: # ret_val.yaml_set_anchor(anchor, always_dump=True) # return ret_val # # def replace(self, old, new, maxreplace=-1): # # type: (Any, Any, int) -> Any # return type(self)((text_type.replace(self, old, new, maxreplace))) # # @property # def anchor(self): # # type: () -> Any # if not hasattr(self, Anchor.attrib): # setattr(self, Anchor.attrib, Anchor()) # return getattr(self, Anchor.attrib) # # def yaml_anchor(self, any=False): # # type: (bool) -> Any # if not hasattr(self, Anchor.attrib): # return None # if any or self.anchor.always_dump: # return self.anchor # return None # # def yaml_set_anchor(self, value, always_dump=False): # # type: (Any, bool) -> None # self.anchor.value = value # self.anchor.always_dump = always_dump # # Path: strictyaml/ruamel/anchor.py # class Anchor(object): # __slots__ = "value", "always_dump" # attrib = anchor_attrib # # def __init__(self): # # type: () -> None # self.value = None # self.always_dump = False # # def __repr__(self): # # type: () -> Any # ad = ", (always dump)" if self.always_dump else "" # return "Anchor({!r}{})".format(self.value, ad) . Output only the next line.
if self.data is None:
Here is a snippet: <|code_start|>class Format(object): __slots__ = ("_flow_style",) attrib = format_attrib def __init__(self): # type: () -> None self._flow_style = None # type: Any def set_flow_style(self): # type: () -> None self._flow_style = True def set_block_style(self): # type: () -> None self._flow_style = False def flow_style(self, default=None): # type: (Optional[Any]) -> Any """if default (the flow_style) is None, the flow style tacked on to the object explicitly will be taken. If that is None as well the default flow style rules the format down the line, or the type of the constituent values (simple -> flow, map/list -> block)""" if self._flow_style is None: return default return self._flow_style class LineCol(object): attrib = line_col_attrib <|code_end|> . Write the next line using the current file imports: import sys import copy from strictyaml.ruamel.compat import ordereddict # type: ignore from strictyaml.ruamel.compat import PY2, string_types, MutableSliceableSequence from strictyaml.ruamel.scalarstring import ScalarString from strictyaml.ruamel.anchor import Anchor from collections import MutableSet, Sized, Set, Mapping from collections.abc import MutableSet, Sized, Set, Mapping from typing import Any, Dict, Optional, List, Union, Optional, Iterator # NOQA from .error import CommentMark from .tokens import CommentToken from strictyaml.ruamel.error import CommentMark from strictyaml.ruamel.tokens import CommentToken from .tokens import CommentToken from .error import CommentMark and context from other files: # Path: strictyaml/ruamel/compat.py # class ordereddict(OrderedDict): # type: ignore # if not hasattr(OrderedDict, "insert"): # # def insert(self, pos, key, value): # # type: (int, Any, Any) -> None # if pos >= len(self): # self[key] = value # return # od = ordereddict() # od.update(self) # for k in od: # del self[k] # for index, old_key in enumerate(od): # if pos == index: # self[key] = value # self[old_key] = od[old_key] # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/scalarstring.py # class ScalarString(text_type): # __slots__ = Anchor.attrib # # def __new__(cls, *args, **kw): # # type: (Any, Any) -> Any # anchor = kw.pop("anchor", None) # type: ignore # ret_val = text_type.__new__(cls, *args, **kw) # type: ignore # if anchor is not None: # ret_val.yaml_set_anchor(anchor, always_dump=True) # return ret_val # # def replace(self, old, new, maxreplace=-1): # # type: (Any, Any, int) -> Any # return type(self)((text_type.replace(self, old, new, maxreplace))) # # @property # def anchor(self): # # type: () -> Any # if not hasattr(self, Anchor.attrib): # setattr(self, Anchor.attrib, Anchor()) # return getattr(self, Anchor.attrib) # # def yaml_anchor(self, any=False): # # type: (bool) -> Any # if not hasattr(self, Anchor.attrib): # return None # if any or self.anchor.always_dump: # return self.anchor # return None # # def yaml_set_anchor(self, value, always_dump=False): # # type: (Any, bool) -> None # self.anchor.value = value # self.anchor.always_dump = always_dump # # Path: strictyaml/ruamel/anchor.py # class Anchor(object): # __slots__ = "value", "always_dump" # attrib = anchor_attrib # # def __init__(self): # # type: () -> None # self.value = None # self.always_dump = False # # def __repr__(self): # # type: () -> Any # ad = ", (always dump)" if self.always_dump else "" # return "Anchor({!r}{})".format(self.value, ad) , which may include functions, classes, or code. Output only the next line.
def __init__(self):
Given the following code snippet before the placeholder: <|code_start|> def __init__(self): # type: () -> None self.line = None self.col = None self.data = None # type: Optional[Dict[Any, Any]] def add_kv_line_col(self, key, data): # type: (Any, Any) -> None if self.data is None: self.data = {} self.data[key] = data def key(self, k): # type: (Any) -> Any return self._kv(k, 0, 1) def value(self, k): # type: (Any) -> Any return self._kv(k, 2, 3) def _kv(self, k, x0, x1): # type: (Any, Any, Any) -> Any if self.data is None: return None data = self.data[k] return data[x0], data[x1] def item(self, idx): # type: (Any) -> Any if self.data is None: <|code_end|> , predict the next line using imports from the current file: import sys import copy from strictyaml.ruamel.compat import ordereddict # type: ignore from strictyaml.ruamel.compat import PY2, string_types, MutableSliceableSequence from strictyaml.ruamel.scalarstring import ScalarString from strictyaml.ruamel.anchor import Anchor from collections import MutableSet, Sized, Set, Mapping from collections.abc import MutableSet, Sized, Set, Mapping from typing import Any, Dict, Optional, List, Union, Optional, Iterator # NOQA from .error import CommentMark from .tokens import CommentToken from strictyaml.ruamel.error import CommentMark from strictyaml.ruamel.tokens import CommentToken from .tokens import CommentToken from .error import CommentMark and context including class names, function names, and sometimes code from other files: # Path: strictyaml/ruamel/compat.py # class ordereddict(OrderedDict): # type: ignore # if not hasattr(OrderedDict, "insert"): # # def insert(self, pos, key, value): # # type: (int, Any, Any) -> None # if pos >= len(self): # self[key] = value # return # od = ordereddict() # od.update(self) # for k in od: # del self[k] # for index, old_key in enumerate(od): # if pos == index: # self[key] = value # self[old_key] = od[old_key] # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/scalarstring.py # class ScalarString(text_type): # __slots__ = Anchor.attrib # # def __new__(cls, *args, **kw): # # type: (Any, Any) -> Any # anchor = kw.pop("anchor", None) # type: ignore # ret_val = text_type.__new__(cls, *args, **kw) # type: ignore # if anchor is not None: # ret_val.yaml_set_anchor(anchor, always_dump=True) # return ret_val # # def replace(self, old, new, maxreplace=-1): # # type: (Any, Any, int) -> Any # return type(self)((text_type.replace(self, old, new, maxreplace))) # # @property # def anchor(self): # # type: () -> Any # if not hasattr(self, Anchor.attrib): # setattr(self, Anchor.attrib, Anchor()) # return getattr(self, Anchor.attrib) # # def yaml_anchor(self, any=False): # # type: (bool) -> Any # if not hasattr(self, Anchor.attrib): # return None # if any or self.anchor.always_dump: # return self.anchor # return None # # def yaml_set_anchor(self, value, always_dump=False): # # type: (Any, bool) -> None # self.anchor.value = value # self.anchor.always_dump = always_dump # # Path: strictyaml/ruamel/anchor.py # class Anchor(object): # __slots__ = "value", "always_dump" # attrib = anchor_attrib # # def __init__(self): # # type: () -> None # self.value = None # self.always_dump = False # # def __repr__(self): # # type: () -> Any # ad = ", (always dump)" if self.always_dump else "" # return "Anchor({!r}{})".format(self.value, ad) . Output only the next line.
return None
Based on the snippet: <|code_start|> """if default (the flow_style) is None, the flow style tacked on to the object explicitly will be taken. If that is None as well the default flow style rules the format down the line, or the type of the constituent values (simple -> flow, map/list -> block)""" if self._flow_style is None: return default return self._flow_style class LineCol(object): attrib = line_col_attrib def __init__(self): # type: () -> None self.line = None self.col = None self.data = None # type: Optional[Dict[Any, Any]] def add_kv_line_col(self, key, data): # type: (Any, Any) -> None if self.data is None: self.data = {} self.data[key] = data def key(self, k): # type: (Any) -> Any return self._kv(k, 0, 1) def value(self, k): # type: (Any) -> Any <|code_end|> , predict the immediate next line with the help of imports: import sys import copy from strictyaml.ruamel.compat import ordereddict # type: ignore from strictyaml.ruamel.compat import PY2, string_types, MutableSliceableSequence from strictyaml.ruamel.scalarstring import ScalarString from strictyaml.ruamel.anchor import Anchor from collections import MutableSet, Sized, Set, Mapping from collections.abc import MutableSet, Sized, Set, Mapping from typing import Any, Dict, Optional, List, Union, Optional, Iterator # NOQA from .error import CommentMark from .tokens import CommentToken from strictyaml.ruamel.error import CommentMark from strictyaml.ruamel.tokens import CommentToken from .tokens import CommentToken from .error import CommentMark and context (classes, functions, sometimes code) from other files: # Path: strictyaml/ruamel/compat.py # class ordereddict(OrderedDict): # type: ignore # if not hasattr(OrderedDict, "insert"): # # def insert(self, pos, key, value): # # type: (int, Any, Any) -> None # if pos >= len(self): # self[key] = value # return # od = ordereddict() # od.update(self) # for k in od: # del self[k] # for index, old_key in enumerate(od): # if pos == index: # self[key] = value # self[old_key] = od[old_key] # # Path: strictyaml/ruamel/compat.py # _DEFAULT_YAML_VERSION = (1, 2) # PY2 = sys.version_info[0] == 2 # PY3 = sys.version_info[0] == 3 # MAXSIZE = sys.maxsize # UNICODE_SIZE = 4 if sys.maxunicode > 65535 else 2 # DBG_TOKEN = 1 # DBG_EVENT = 2 # DBG_NODE = 4 # class ordereddict(OrderedDict): # type: ignore # class ObjectCounter(object): # class Nprint(object): # class MutableSliceableSequence(MutableSequence): # type: ignore # def insert(self, pos, key, value): # def utf8(s): # def to_str(s): # def to_unicode(s): # def utf8(s): # def to_str(s): # def to_unicode(s): # def with_metaclass(meta, *bases): # def __init__(self): # def __call__(self, k): # def dump(self): # def dbg(val=None): # def __init__(self, file_name=None): # def __call__(self, *args, **kw): # def set_max_print(self, i): # def check_namespace_char(ch): # def check_anchorname_char(ch): # def version_tnf(t1, t2=None): # def __getitem__(self, index): # def __setitem__(self, index, value): # def __delitem__(self, index): # def __getsingleitem__(self, index): # def __setsingleitem__(self, index, value): # def __delsingleitem__(self, index): # # Path: strictyaml/ruamel/scalarstring.py # class ScalarString(text_type): # __slots__ = Anchor.attrib # # def __new__(cls, *args, **kw): # # type: (Any, Any) -> Any # anchor = kw.pop("anchor", None) # type: ignore # ret_val = text_type.__new__(cls, *args, **kw) # type: ignore # if anchor is not None: # ret_val.yaml_set_anchor(anchor, always_dump=True) # return ret_val # # def replace(self, old, new, maxreplace=-1): # # type: (Any, Any, int) -> Any # return type(self)((text_type.replace(self, old, new, maxreplace))) # # @property # def anchor(self): # # type: () -> Any # if not hasattr(self, Anchor.attrib): # setattr(self, Anchor.attrib, Anchor()) # return getattr(self, Anchor.attrib) # # def yaml_anchor(self, any=False): # # type: (bool) -> Any # if not hasattr(self, Anchor.attrib): # return None # if any or self.anchor.always_dump: # return self.anchor # return None # # def yaml_set_anchor(self, value, always_dump=False): # # type: (Any, bool) -> None # self.anchor.value = value # self.anchor.always_dump = always_dump # # Path: strictyaml/ruamel/anchor.py # class Anchor(object): # __slots__ = "value", "always_dump" # attrib = anchor_attrib # # def __init__(self): # # type: () -> None # self.value = None # self.always_dump = False # # def __repr__(self): # # type: () -> Any # ad = ", (always dump)" if self.always_dump else "" # return "Anchor({!r}{})".format(self.value, ad) . Output only the next line.
return self._kv(k, 2, 3)
Predict the next line after this snippet: <|code_start|> class OrganizationTestCase(TestCase): def test_str(self): organization = Organization(name='My organization') <|code_end|> using the current file's imports: from django.test import TestCase from depot.models import Depot, Item, Organization and any relevant context from other files: # Path: depot/models.py # class Depot(models.Model): # """ # A depot has a name and many depot managers. # # :author: Leo Tappe # :author: Benedikt Seidl # """ # # name = models.CharField(max_length=32) # description = models.CharField(max_length=256, blank=True) # organization = models.ForeignKey(Organization, on_delete=models.CASCADE) # manager_users = models.ManyToManyField(User, blank=True) # manager_groups = models.ManyToManyField(Group, blank=True) # active = models.BooleanField(default=True) # # def managed_by(self, user): # """ # Depots are managed by superusers, the organization's managers, # any manager user and any user in a manager group. # """ # # return (user.is_superuser # or self.organization.managed_by(user) # or self.manager_users.filter(id=user.id).exists() # or self.manager_groups.filter(id__in=user.groups.all()).exists()) # # def show_internal_items(self, user): # """ # Internal items can be seen by superusers and organization members. # """ # # return user.is_superuser or self.organization.is_member(user) # # def visible_items(self, user): # """ # Return the list of items the user is allowed to see in this depot. # """ # # if self.show_internal_items(user): # return self.active_items.all() # else: # return self.public_items.all() # # @property # def managers(self): # """ # The list of users explicitly listed as managers of this depot. # Does not include any organization managers or superusers which are # not added to the depot. # """ # # return User.objects.filter( # models.Q(id__in=self.manager_users.all()) # | models.Q(groups__in=self.manager_groups.all()) # ).distinct() # # @property # def public_items(self): # """ # List all items with the visibility set to public. # """ # # return self.item_set.filter(visibility=Item.VISIBILITY_PUBLIC) # # @property # def active_items(self): # return self.item_set.filter( # models.Q(visibility=Item.VISIBILITY_PUBLIC) # | models.Q(visibility=Item.VISIBILITY_INTERNAL) # ) # # @staticmethod # def filter_by_user(user): # """ # Filter for depots managed by the given user # """ # # return (models.Q(organization__managers__id=user.id) # | models.Q(manager_users__id=user.id) # | models.Q(manager_groups__id__in=user.groups.all())) # # def __str__(self): # return self.name # # class Item(models.Model): # """ # An item describes one or more instances of an object in a depot. # # It always belongs to a single depot and has a unique name within the depot. # The location field can be used to roughly describe where # the item can be found in the depot. # Items can either be public or internal which affects the visibility # of the item to users outside of the organization connected to the depot. # The quantity describes how many version of the item exist in the depot. # # :author: Leo Tappe # """ # # VISIBILITY_PUBLIC = '1' # VISIBILITY_INTERNAL = '2' # VISIBILITY_DELETED = '3' # VISIBILITY_LEVELS = ( # (VISIBILITY_PUBLIC, _('public')), # (VISIBILITY_INTERNAL, _('internal')), # (VISIBILITY_DELETED, _('deleted')), # ) # # name = models.CharField(max_length=32) # description = models.CharField(max_length=1024, blank=True) # quantity = models.PositiveSmallIntegerField() # visibility = models.CharField(max_length=1, choices=VISIBILITY_LEVELS) # location = models.CharField(max_length=256, blank=True) # depot = models.ForeignKey(Depot, on_delete=models.CASCADE) # # @staticmethod # def filter_by_user(user): # """ # Filter for items managed by the given user # """ # # return (models.Q(depot__organization__managers__id=user.id) # | models.Q(depot__manager_users__id=user.id) # | models.Q(depot__manager_groups__id__in=user.groups.all())) # # class Meta: # unique_together = ( # ('name', 'depot'), # ) # # def __str__(self): # return self.name # # class Organization(models.Model): # """ # Representation of an organization, # such as FSMPI, FSMB or ASTA. # # An organization is defined by a list of user groups, # in our case LDAP groups. It is managed by a list of # users and has a list of depots. # # :author: Leo Tappe # :author: Benedikt Seidl # """ # # name = models.CharField(max_length=32) # groups = models.ManyToManyField(Group, blank=True) # managers = models.ManyToManyField(User, blank=True) # # def managed_by(self, user): # """ # Organizations are managed by superusers and organization managers. # """ # # return user.is_superuser or self.managers.filter(id=user.id).exists() # # def is_member(self, user): # """ # Checks if the user is in one of the groups defined in this organization. # """ # # return self.groups.filter(id__in=user.groups.all()).exists() # # @property # def active_depots(self): # """ # Returns all depots in this organization which have the active flag set. # """ # # return self.depot_set.filter(active=True) # # @staticmethod # def filter_by_user(user): # """ # Filter for organizations managed by the given user # """ # # return models.Q(managers__id=user.id) # # def __str__(self): # return self.name . Output only the next line.
self.assertEqual(organization.__str__(), 'My organization')
Predict the next line for this snippet: <|code_start|> class LoginTestCase(ClientTestCase): def test_login_form(self): response = self.as_guest.get('/login/') self.assertSuccess(response, 'login/login.html') def test_login_with_correct_password(self): response = self.as_guest.post('/login/', { 'username': 'user', 'password': 'password', }) self.assertRedirects(response, '/') def test_login_case_insensitive(self): <|code_end|> with the help of current file imports: from verleihtool.test import ClientTestCase and context from other files: # Path: verleihtool/test.py # class ClientTestCase(TestCase): # """ # Base test case with convenience methods to login and assert responses # # :author: Benedikt Seidl # """ # # def setUp(self): # # Create normal user # self.user = User.objects.create_user( # username='user', # email='user@example.com', # password='password', # first_name='Ursula', # last_name='User' # ) # # # Create superuser # self.superuser = User.objects.create_superuser( # username='admin', # email='admin@example.com', # password='pass', # first_name='Armin', # last_name='Admin' # ) # # # Create a group # self.group = Group.objects.create() # self.user.groups.add(self.group) # # @property # def as_guest(self): # return Client() # # @property # def as_user(self): # c = Client() # c.login(username='user', password='password') # return c # # @property # def as_superuser(self): # c = Client() # c.login(username='admin', password='pass') # return c # # def assertSuccess(self, response, template): # self.assertEqual(response.status_code, 200) # self.assertTemplateUsed(response, template) , which may contain function names, class names, or code. Output only the next line.
response = self.as_guest.post('/login/', {