Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|> super(FreeEmailProviderTestCase, self).setUp() self.url = url_for('accounts.free_email_providers_list') self.items = [FreeEmailProvider(domain='%s+freedomain.com' % i) for i in range(10)] self.db.session.add_all(self.items) self.db.session.commit() def test_login_required_for_list(self): response = self.client.get(self.url) self.assertRedirectToLogin(response, self.url) def test_login_required_for_add(self): response = self.client.post(self.url) self.assertRedirectToLogin(response, self.url) def test_listing_works(self): self.login() response = self.client.get(self.url) self.assert200(response) self.assertTemplateUsed('fep/list.jade') content = response.data.decode('utf-8') for item in self.items: self.assertTrue(item.domain in content) def test_add_duplicate(self): self.login() <|code_end|> . Use current file imports: from flask import url_for from tests.base import TestCase from app.accounts.models import FreeEmailProvider and context (classes, functions, or code) from other files: # Path: tests/base.py # class TestCase(_TestCase): # db = db # # def create_app(self): # app.config.from_object('tests.settings_test') # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' # return app # # def setUp(self): # db.create_all() # self.user = create_admin() # # def tearDown(self): # db.session.remove() # db.drop_all() # # def login(self, email=None, password=None): # data = dict( # email=email or self.app.config['ADMIN_USER']['email'], # password=password or self.app.config['ADMIN_USER']['password'], # remember=True, # ) # return self.client.post('/user/sign-in', data=data, # follow_redirects=True) # # def logout(self): # return self.client.get('/user/sign-out', follow_redirects=True) # # def assertRedirectToLogin(self, response, next_url): # expected = '/user/sign-in?next=http%3A//localhost{0}'.format(next_url) # self.assertRedirects(response, expected) # # Path: app/accounts/models.py # class FreeEmailProvider(db.Model, models.BaseModelMixin): # __tablename__ = 'free_email_providers' # # domain = db.Column(db.Unicode(255), nullable=False, index=True) # # def __unicode__(self): # return self.domain # # @classmethod # def exists(cls, domain): # return bool(cls.query.filter(cls.domain == domain).first()) . Output only the next line.
response = self.client.post(self.url,
Predict the next line for this snippet: <|code_start|> if self.model_class.query.filter(*args).first(): raise ValidationError( '%s must be an unique' % str(field.label).title()) class ProjectForm(BaseForm): title = default_string_field( 'title', validators=[UniqueValue(model_class=Project, per_user=True)]) intercom_app_id = default_string_field( 'intercom app_id', validators=[UniqueValue(model_class=Project)]) intercom_api_key = default_string_field('intercom api_key') aws_access_id = default_string_field('AWS access_id') aws_secret_access_key = default_string_field('AWS secret_access_key') submit = SubmitField('Save') repeat_import = SubmitField('Re-Import') def create_subscription_for(self, project): project.intercom_webhooks_internal_secret = str(uuid.uuid4()) client = project.get_intercom_client() sub = client.subscribe( hook_url=url_for( 'accounts.handle_intercom_hooks', internal_secret=project.intercom_webhooks_internal_secret, _external=True), topics=['user.created'] <|code_end|> with the help of current file imports: import uuid from flask import url_for from flask.ext.login import current_user from wtforms import SubmitField from wtforms.validators import DataRequired, ValidationError from app.accounts.models import Project, FreeEmailProvider from common.forms import BaseForm, TrackChangesStringField and context from other files: # Path: app/accounts/models.py # class Project(db.Model, models.BaseModelMixin, models.CreateAndModifyMixin): # __tablename__ = 'projects' # # title = db.Column(db.Unicode(255), nullable=False) # # intercom_app_id = db.Column(db.Unicode(255), nullable=False, unique=True) # intercom_api_key = db.Column(db.Unicode(255), nullable=False) # intercom_webhooks_internal_secret = db.Column(db.Unicode(255)) # intercom_subscription_id = db.Column(db.Unicode(255)) # # aws_access_id = db.Column(db.Unicode(255), nullable=False) # aws_secret_access_key = db.Column(db.Unicode(255), nullable=False) # # user_id = db.Column(db.Integer(), db.ForeignKey('users.id'), # nullable=False) # user = db.relationship('User', back_populates='projects') # # intercom_users = db.relationship('IntercomUser', # back_populates='project') # # def __unicode__(self): # return self.title # # @classmethod # def get_for_current_user_or_404(cls, pk): # return cls.get_or_404(cls.user_id == current_user.id, cls.id == pk) # # def get_intercom_client(project): # from app.intercom.service import IntercomClient # return IntercomClient(project.intercom_app_id, # project.intercom_api_key) # # def start_awis_session(project): # """ Initiate contextmanager for working with AWIS. # """ # return AWISContextManager(project.aws_access_id, # project.aws_secret_access_key) # # def delete(self): # client = self.get_intercom_client() # client.unsubscribe(self.intercom_subscription_id) # return super(Project, self).delete() # # class FreeEmailProvider(db.Model, models.BaseModelMixin): # __tablename__ = 'free_email_providers' # # domain = db.Column(db.Unicode(255), nullable=False, index=True) # # def __unicode__(self): # return self.domain # # @classmethod # def exists(cls, domain): # return bool(cls.query.filter(cls.domain == domain).first()) # # Path: common/forms.py # class BaseForm(Form): # """ Our base class for forms. # """ # def __init__(self, *args, **kwargs): # super(BaseForm, self).__init__(*args, **kwargs) # self.obj = kwargs.get('obj') # # class TrackChangesStringField(TrackChangesMixin, StringField): # pass , which may contain function names, class names, or code. Output only the next line.
)
Here is a snippet: <|code_start|> def default_string_field(label, **extra): validators = extra.pop('validators', []) validators.append(DataRequired()) return TrackChangesStringField(label, validators=validators, **extra) class UniqueValue: def __init__(self, model_class, per_user=False): self.model_class = model_class self.per_user = per_user def __call__(self, form, field): args = [getattr(self.model_class, field.name) == field.data] if self.per_user: args.append(self.model_class.user_id == current_user.id) if form.obj: args.append(self.model_class.id != form.obj.id) if self.model_class.query.filter(*args).first(): raise ValidationError( '%s must be an unique' % str(field.label).title()) class ProjectForm(BaseForm): title = default_string_field( <|code_end|> . Write the next line using the current file imports: import uuid from flask import url_for from flask.ext.login import current_user from wtforms import SubmitField from wtforms.validators import DataRequired, ValidationError from app.accounts.models import Project, FreeEmailProvider from common.forms import BaseForm, TrackChangesStringField and context from other files: # Path: app/accounts/models.py # class Project(db.Model, models.BaseModelMixin, models.CreateAndModifyMixin): # __tablename__ = 'projects' # # title = db.Column(db.Unicode(255), nullable=False) # # intercom_app_id = db.Column(db.Unicode(255), nullable=False, unique=True) # intercom_api_key = db.Column(db.Unicode(255), nullable=False) # intercom_webhooks_internal_secret = db.Column(db.Unicode(255)) # intercom_subscription_id = db.Column(db.Unicode(255)) # # aws_access_id = db.Column(db.Unicode(255), nullable=False) # aws_secret_access_key = db.Column(db.Unicode(255), nullable=False) # # user_id = db.Column(db.Integer(), db.ForeignKey('users.id'), # nullable=False) # user = db.relationship('User', back_populates='projects') # # intercom_users = db.relationship('IntercomUser', # back_populates='project') # # def __unicode__(self): # return self.title # # @classmethod # def get_for_current_user_or_404(cls, pk): # return cls.get_or_404(cls.user_id == current_user.id, cls.id == pk) # # def get_intercom_client(project): # from app.intercom.service import IntercomClient # return IntercomClient(project.intercom_app_id, # project.intercom_api_key) # # def start_awis_session(project): # """ Initiate contextmanager for working with AWIS. # """ # return AWISContextManager(project.aws_access_id, # project.aws_secret_access_key) # # def delete(self): # client = self.get_intercom_client() # client.unsubscribe(self.intercom_subscription_id) # return super(Project, self).delete() # # class FreeEmailProvider(db.Model, models.BaseModelMixin): # __tablename__ = 'free_email_providers' # # domain = db.Column(db.Unicode(255), nullable=False, index=True) # # def __unicode__(self): # return self.domain # # @classmethod # def exists(cls, domain): # return bool(cls.query.filter(cls.domain == domain).first()) # # Path: common/forms.py # class BaseForm(Form): # """ Our base class for forms. # """ # def __init__(self, *args, **kwargs): # super(BaseForm, self).__init__(*args, **kwargs) # self.obj = kwargs.get('obj') # # class TrackChangesStringField(TrackChangesMixin, StringField): # pass , which may include functions, classes, or code. Output only the next line.
'title',
Using the snippet: <|code_start|> class UniqueValue: def __init__(self, model_class, per_user=False): self.model_class = model_class self.per_user = per_user def __call__(self, form, field): args = [getattr(self.model_class, field.name) == field.data] if self.per_user: args.append(self.model_class.user_id == current_user.id) if form.obj: args.append(self.model_class.id != form.obj.id) if self.model_class.query.filter(*args).first(): raise ValidationError( '%s must be an unique' % str(field.label).title()) class ProjectForm(BaseForm): title = default_string_field( 'title', validators=[UniqueValue(model_class=Project, per_user=True)]) intercom_app_id = default_string_field( 'intercom app_id', validators=[UniqueValue(model_class=Project)]) intercom_api_key = default_string_field('intercom api_key') <|code_end|> , determine the next line of code. You have imports: import uuid from flask import url_for from flask.ext.login import current_user from wtforms import SubmitField from wtforms.validators import DataRequired, ValidationError from app.accounts.models import Project, FreeEmailProvider from common.forms import BaseForm, TrackChangesStringField and context (class names, function names, or code) available: # Path: app/accounts/models.py # class Project(db.Model, models.BaseModelMixin, models.CreateAndModifyMixin): # __tablename__ = 'projects' # # title = db.Column(db.Unicode(255), nullable=False) # # intercom_app_id = db.Column(db.Unicode(255), nullable=False, unique=True) # intercom_api_key = db.Column(db.Unicode(255), nullable=False) # intercom_webhooks_internal_secret = db.Column(db.Unicode(255)) # intercom_subscription_id = db.Column(db.Unicode(255)) # # aws_access_id = db.Column(db.Unicode(255), nullable=False) # aws_secret_access_key = db.Column(db.Unicode(255), nullable=False) # # user_id = db.Column(db.Integer(), db.ForeignKey('users.id'), # nullable=False) # user = db.relationship('User', back_populates='projects') # # intercom_users = db.relationship('IntercomUser', # back_populates='project') # # def __unicode__(self): # return self.title # # @classmethod # def get_for_current_user_or_404(cls, pk): # return cls.get_or_404(cls.user_id == current_user.id, cls.id == pk) # # def get_intercom_client(project): # from app.intercom.service import IntercomClient # return IntercomClient(project.intercom_app_id, # project.intercom_api_key) # # def start_awis_session(project): # """ Initiate contextmanager for working with AWIS. # """ # return AWISContextManager(project.aws_access_id, # project.aws_secret_access_key) # # def delete(self): # client = self.get_intercom_client() # client.unsubscribe(self.intercom_subscription_id) # return super(Project, self).delete() # # class FreeEmailProvider(db.Model, models.BaseModelMixin): # __tablename__ = 'free_email_providers' # # domain = db.Column(db.Unicode(255), nullable=False, index=True) # # def __unicode__(self): # return self.domain # # @classmethod # def exists(cls, domain): # return bool(cls.query.filter(cls.domain == domain).first()) # # Path: common/forms.py # class BaseForm(Form): # """ Our base class for forms. # """ # def __init__(self, *args, **kwargs): # super(BaseForm, self).__init__(*args, **kwargs) # self.obj = kwargs.get('obj') # # class TrackChangesStringField(TrackChangesMixin, StringField): # pass . Output only the next line.
aws_access_id = default_string_field('AWS access_id')
Continue the code snippet: <|code_start|> def default_string_field(label, **extra): validators = extra.pop('validators', []) validators.append(DataRequired()) return TrackChangesStringField(label, validators=validators, **extra) class UniqueValue: def __init__(self, model_class, per_user=False): self.model_class = model_class self.per_user = per_user def __call__(self, form, field): args = [getattr(self.model_class, field.name) == field.data] if self.per_user: args.append(self.model_class.user_id == current_user.id) if form.obj: args.append(self.model_class.id != form.obj.id) <|code_end|> . Use current file imports: import uuid from flask import url_for from flask.ext.login import current_user from wtforms import SubmitField from wtforms.validators import DataRequired, ValidationError from app.accounts.models import Project, FreeEmailProvider from common.forms import BaseForm, TrackChangesStringField and context (classes, functions, or code) from other files: # Path: app/accounts/models.py # class Project(db.Model, models.BaseModelMixin, models.CreateAndModifyMixin): # __tablename__ = 'projects' # # title = db.Column(db.Unicode(255), nullable=False) # # intercom_app_id = db.Column(db.Unicode(255), nullable=False, unique=True) # intercom_api_key = db.Column(db.Unicode(255), nullable=False) # intercom_webhooks_internal_secret = db.Column(db.Unicode(255)) # intercom_subscription_id = db.Column(db.Unicode(255)) # # aws_access_id = db.Column(db.Unicode(255), nullable=False) # aws_secret_access_key = db.Column(db.Unicode(255), nullable=False) # # user_id = db.Column(db.Integer(), db.ForeignKey('users.id'), # nullable=False) # user = db.relationship('User', back_populates='projects') # # intercom_users = db.relationship('IntercomUser', # back_populates='project') # # def __unicode__(self): # return self.title # # @classmethod # def get_for_current_user_or_404(cls, pk): # return cls.get_or_404(cls.user_id == current_user.id, cls.id == pk) # # def get_intercom_client(project): # from app.intercom.service import IntercomClient # return IntercomClient(project.intercom_app_id, # project.intercom_api_key) # # def start_awis_session(project): # """ Initiate contextmanager for working with AWIS. # """ # return AWISContextManager(project.aws_access_id, # project.aws_secret_access_key) # # def delete(self): # client = self.get_intercom_client() # client.unsubscribe(self.intercom_subscription_id) # return super(Project, self).delete() # # class FreeEmailProvider(db.Model, models.BaseModelMixin): # __tablename__ = 'free_email_providers' # # domain = db.Column(db.Unicode(255), nullable=False, index=True) # # def __unicode__(self): # return self.domain # # @classmethod # def exists(cls, domain): # return bool(cls.query.filter(cls.domain == domain).first()) # # Path: common/forms.py # class BaseForm(Form): # """ Our base class for forms. # """ # def __init__(self, *args, **kwargs): # super(BaseForm, self).__init__(*args, **kwargs) # self.obj = kwargs.get('obj') # # class TrackChangesStringField(TrackChangesMixin, StringField): # pass . Output only the next line.
if self.model_class.query.filter(*args).first():
Given the following code snippet before the placeholder: <|code_start|># coding:utf-8 # NOW MERGED INTO maclient_update.py reload(sys) sys.setdefaultencoding('utf-8') sys.path.append(os.path.abspath('..')) os.chdir(os.path.abspath('..')) sys.path[0] = os.path.abspath('.') loc = 'cn' mac = maclient.maClient(configfile = r'D:\Dev\Python\Workspace\maClient\_mine\config_cn.ini') mac.login() a, b = mac._dopost('masterdata/card/update', postdata = '%s&revision=0' % mac.poster.cookie, noencrypt = True) open(r'z:\card.%s.xml' % loc, 'w').write(b) a, b = mac._dopost('masterdata/item/update', postdata = '%s&revision=0' % mac.poster.cookie, noencrypt = True) open(r'z:\item.%s.xml' % loc, 'w').write(b) xml = open(r'z:\card.%s.xml' % loc, 'r').read().replace('&', '--').replace('--#', '&#') print XML2Dict().fromstring(xml).response.header.revision.card_rev body = XML2Dict().fromstring(xml).response.body cards = body.master_data.master_card_data.card strs = [] for c in cards: strs.append('%s,%s,%s,%s,%s,%s,%s,%s' % ( c.master_card_id, c.name, c.rarity, c.cost, str(c.char_description).strip('\n').strip(' ').replace('\n', '\\n'), c.skill_kana, c.skill_name, <|code_end|> , predict the next line using imports from the current file: import os import random import httplib2 import sys import maclient import maclient_logging from xml2dict import XML2Dict and context including class names, function names, and sometimes code from other files: # Path: xml2dict.py # class XML2Dict(object): # @classmethod # def _parse_node(self, node): # node_tree = object_dict() # # Save attrs and text, hope there will not be a child with same name # if node.text: # node_tree.value = node.text # for (k, v) in node.attrib.items(): # k, v = self._namespace_split(k, object_dict({'value':v})) # node_tree[k] = v # # Save childrens # for child in iter(node): # tag, tree = self._namespace_split(child.tag, self._parse_node(child)) # if tag not in node_tree: # the first time, so store it in dict # node_tree[tag] = tree # continue # old = node_tree[tag] # if not isinstance(old, list): # node_tree.pop(tag) # node_tree[tag] = [old] # multi times, so change old dict to a list # node_tree[tag].append(tree) # add the new one # # return node_tree # # @classmethod # def _namespace_split(self, tag, value): # """ # Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' # ns = http://cs.sfsu.edu/csc867/myscheduler # name = patients # """ # result = re.compile("\{(.*)\}(.*)").search(tag) # if result: # # print(tag) # value.namespace, tag = result.groups() # return (tag, value) # # @classmethod # def parse(self, file): # """parse a xml file to a dict""" # f = open(file, 'r') # return self.fromstring(f.read()) # # @classmethod # def fromstring(self, s): # """parse a string""" # t = ET.fromstring(s) # root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t)) # return object_dict({root_tag: root_tree}) . Output only the next line.
str(c.skill_description).replace('\n', '\\n')))
Using the snippet: <|code_start|> return #request enemy guild resp, ct = self._dopost('battle/guild/lobby', postdata = 'event_id=%s&event_part_id=0&guild_id=%s' % (PVP_LAKE_ID, self.guild_id)) if resp['error']: return #self.logger.info() e_guild = ct.body.guild_battle_info.enemy_guild_info m_guild = ct.body.guild_battle_info.my_guild_info self.logger.info(('土豪券 剩余%03s\n' % ct.body.ticket_num) + '[%s] Lv.%02s ID:%s\n' '本场战斗点数:%03s 累积点数:%03s\n' '本场对战记录: %s胜%s败 排名:%s\n' '============= VS =============\n' '[%s] Lv.%02s ID:%s\n' '本场战斗点数:%03s 累积点数:%03s\n' '本场对战记录: %s胜%s败 排名:%s' % ( m_guild.guild_name.center(8), m_guild.guild_level, m_guild.guild_id, m_guild.daily_battle_point, m_guild.season_battle_point, m_guild.win_count, m_guild.lose_count, m_guild.ranking, e_guild.guild_name.center(8), e_guild.guild_level, e_guild.guild_id, 0 if e_guild.daily_battle_point == {} else e_guild.daily_battle_point, e_guild.season_battle_point, e_guild.win_count, e_guild.lose_count, e_guild.ranking ) ) #request member list resp, ct = self._dopost('battle/guild/enemy_member_list', <|code_end|> , determine the next line of code. You have imports: import time import random from cross_platform import * from xml2dict import XML2Dict, object_dict and context (class names, function names, or code) available: # Path: xml2dict.py # class XML2Dict(object): # @classmethod # def _parse_node(self, node): # node_tree = object_dict() # # Save attrs and text, hope there will not be a child with same name # if node.text: # node_tree.value = node.text # for (k, v) in node.attrib.items(): # k, v = self._namespace_split(k, object_dict({'value':v})) # node_tree[k] = v # # Save childrens # for child in iter(node): # tag, tree = self._namespace_split(child.tag, self._parse_node(child)) # if tag not in node_tree: # the first time, so store it in dict # node_tree[tag] = tree # continue # old = node_tree[tag] # if not isinstance(old, list): # node_tree.pop(tag) # node_tree[tag] = [old] # multi times, so change old dict to a list # node_tree[tag].append(tree) # add the new one # # return node_tree # # @classmethod # def _namespace_split(self, tag, value): # """ # Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' # ns = http://cs.sfsu.edu/csc867/myscheduler # name = patients # """ # result = re.compile("\{(.*)\}(.*)").search(tag) # if result: # # print(tag) # value.namespace, tag = result.groups() # return (tag, value) # # @classmethod # def parse(self, file): # """parse a xml file to a dict""" # f = open(file, 'r') # return self.fromstring(f.read()) # # @classmethod # def fromstring(self, s): # """parse a string""" # t = ET.fromstring(s) # root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t)) # return object_dict({root_tag: root_tree}) # # class object_dict(dict): # """object view of dict, you can # >>> a = object_dict() # >>> a.fish = 'fish' # >>> a['fish'] # 'fish' # >>> a['water'] = 'water' # >>> a.water # 'water' # >>> a.test = {'value': 1} # >>> a.test2 = object_dict({'name': 'test2', 'value': 2}) # >>> a.test, a.test2.name, a.test2.value # (1, 'test2', 2) # """ # def __init__(self, initd = None): # if initd is None: # initd = {} # dict.__init__(self, initd) # # def __getattr__(self, item): # d = self.__getitem__(item) # # if value is the only key in object, you can omit it # if isinstance(d, dict) and 'value' in d and len(d) == 1: # return d['value'] # else: # return d # # # def __iter__(self): # # yield self # # return # # def __setattr__(self, item, value): # self.__setitem__(item, value) . Output only the next line.
postdata = 'enemy_guild_id=%s&event_id=%s&event_part_id=0&guild_id=%s' % (e_guild.guild_id, PVP_LAKE_ID, self.guild_id))
Continue the code snippet: <|code_start|># coding:utf-8 # start meta __plugin_name__ = '国服公会PVP' __author = 'fffonion' __version__ = 0.11 hooks = {} extra_cmd = {'gpvp':'guild_pvp', 'guild_pvp':'guild_pvp'} #simple version of _dopost def _dopost(self, urikey, postdata = '', usecookie = True, setcookie = True, extraheader = {'Cookie2': '$Version=1'}, xmlresp = True, noencrypt = False, savetraffic = False, no2ndkey=False ): resp, _dec = self.poster.post(urikey, postdata, usecookie, setcookie, extraheader, noencrypt, savetraffic, no2ndkey) self.lastposttime = time.time() if int(resp['status']) >= 400: return resp, _dec resp.update({'error':False, 'errno':0, 'errmsg':''}) if not xmlresp: dec = _dec else: try: dec = XML2Dict.fromstring(_dec).response except: dec = XML2Dict.fromstring(re.compile('&(?!#)').sub('&amp;',_dec)).response try: err = dec.header.error except: <|code_end|> . Use current file imports: import time import random from cross_platform import * from xml2dict import XML2Dict, object_dict and context (classes, functions, or code) from other files: # Path: xml2dict.py # class XML2Dict(object): # @classmethod # def _parse_node(self, node): # node_tree = object_dict() # # Save attrs and text, hope there will not be a child with same name # if node.text: # node_tree.value = node.text # for (k, v) in node.attrib.items(): # k, v = self._namespace_split(k, object_dict({'value':v})) # node_tree[k] = v # # Save childrens # for child in iter(node): # tag, tree = self._namespace_split(child.tag, self._parse_node(child)) # if tag not in node_tree: # the first time, so store it in dict # node_tree[tag] = tree # continue # old = node_tree[tag] # if not isinstance(old, list): # node_tree.pop(tag) # node_tree[tag] = [old] # multi times, so change old dict to a list # node_tree[tag].append(tree) # add the new one # # return node_tree # # @classmethod # def _namespace_split(self, tag, value): # """ # Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' # ns = http://cs.sfsu.edu/csc867/myscheduler # name = patients # """ # result = re.compile("\{(.*)\}(.*)").search(tag) # if result: # # print(tag) # value.namespace, tag = result.groups() # return (tag, value) # # @classmethod # def parse(self, file): # """parse a xml file to a dict""" # f = open(file, 'r') # return self.fromstring(f.read()) # # @classmethod # def fromstring(self, s): # """parse a string""" # t = ET.fromstring(s) # root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t)) # return object_dict({root_tag: root_tree}) # # class object_dict(dict): # """object view of dict, you can # >>> a = object_dict() # >>> a.fish = 'fish' # >>> a['fish'] # 'fish' # >>> a['water'] = 'water' # >>> a.water # 'water' # >>> a.test = {'value': 1} # >>> a.test2 = object_dict({'name': 'test2', 'value': 2}) # >>> a.test, a.test2.name, a.test2.value # (1, 'test2', 2) # """ # def __init__(self, initd = None): # if initd is None: # initd = {} # dict.__init__(self, initd) # # def __getattr__(self, item): # d = self.__getitem__(item) # # if value is the only key in object, you can omit it # if isinstance(d, dict) and 'value' in d and len(d) == 1: # return d['value'] # else: # return d # # # def __iter__(self): # # yield self # # return # # def __setattr__(self, item, value): # self.__setitem__(item, value) . Output only the next line.
pass
Given snippet: <|code_start|> return obj def iter_printer(l, sep = '\n'): cnt = 1 str = '' for e in l: str += '%d.%-10s%s' % (cnt, e.strip('\n'), (cnt % 3 and '' or sep)) cnt += 1 return str.decode('utf-8') def read_decks(plugin_vals): def do(*args): if plugin_vals['loc'] == 'jp': get=lambda x, y:XML2Dict.fromstring(x).response.body.roundtable_edit.deck[y - 1].deck_cards else: get=lambda x, y:XML2Dict.fromstring(x).response.body.roundtable_edit.deck_cards poster=plugin_vals['poster'] pcard=plugin_vals['player'].card cf=plugin_vals['cf'] def write_config(sec, key, val): if not cf.has_section(sec): cf.add_section(sec) cf.set(sec, key, val) f = open(plugin_vals['configfile'], "w") cf.write(f) f.flush() list_option=cf.options _jp_cache = None for i in (plugin_vals['loc'] == 'jp' and range(1,5,1) or range(1,4,1)): if i == 4: <|code_end|> , continue by predicting the next line. Consider current file imports: from _prototype import plugin_prototype from subprocess import Popen, PIPE from cross_platform import * from xml2dict import XML2Dict import sys import os import re and context: # Path: xml2dict.py # class XML2Dict(object): # @classmethod # def _parse_node(self, node): # node_tree = object_dict() # # Save attrs and text, hope there will not be a child with same name # if node.text: # node_tree.value = node.text # for (k, v) in node.attrib.items(): # k, v = self._namespace_split(k, object_dict({'value':v})) # node_tree[k] = v # # Save childrens # for child in iter(node): # tag, tree = self._namespace_split(child.tag, self._parse_node(child)) # if tag not in node_tree: # the first time, so store it in dict # node_tree[tag] = tree # continue # old = node_tree[tag] # if not isinstance(old, list): # node_tree.pop(tag) # node_tree[tag] = [old] # multi times, so change old dict to a list # node_tree[tag].append(tree) # add the new one # # return node_tree # # @classmethod # def _namespace_split(self, tag, value): # """ # Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' # ns = http://cs.sfsu.edu/csc867/myscheduler # name = patients # """ # result = re.compile("\{(.*)\}(.*)").search(tag) # if result: # # print(tag) # value.namespace, tag = result.groups() # return (tag, value) # # @classmethod # def parse(self, file): # """parse a xml file to a dict""" # f = open(file, 'r') # return self.fromstring(f.read()) # # @classmethod # def fromstring(self, s): # """parse a string""" # t = ET.fromstring(s) # root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t)) # return object_dict({root_tag: root_tree}) which might include code, classes, or functions. Output only the next line.
print(du8('推荐卡组:'))
Using the snippet: <|code_start|> print('total', len(clst), 'exists', len(os.listdir(download_dir)) / 4) while pct <= 100: for i in clst: if int(i) in xrange(161, 171): continue if loc != 'tw': if i in tlst: print(i, '-tw') delta += 4 continue j = random.choice([0, 1, 2, 3]) times = 0 print(i, '->', j, end = '') while (os.path.exists('%s/%s-%s_%d.png' % (download_dir, cname[i][0].decode('utf-8'), i, j)) or '%d_%d' % (i, j) in skip)\ and times < 3: j = (j + 3) % 4 times += 1 print(j, end = '') if times == 3: print() continue pct = 100.00 * (len(os.listdir(download_dir)) + delta) / 4 / len(clst) print(' ', (len(os.listdir(download_dir)) + delta) / 4, len(clst), '%.2f%%' % pct) a = download_card(i, j) if len(a) % 16: delta += 1 skip.append('%d_%d' % (i, j)) print('error') else: dt = ci.decode_res(a) <|code_end|> , determine the next line of code. You have imports: import os import os.path as opath import time import random import httplib2 import sys import glob import maclient_player import maclient_network import maclient_update import maclient_smart from xml2dict import XML2Dict and context (class names, function names, or code) available: # Path: xml2dict.py # class XML2Dict(object): # @classmethod # def _parse_node(self, node): # node_tree = object_dict() # # Save attrs and text, hope there will not be a child with same name # if node.text: # node_tree.value = node.text # for (k, v) in node.attrib.items(): # k, v = self._namespace_split(k, object_dict({'value':v})) # node_tree[k] = v # # Save childrens # for child in iter(node): # tag, tree = self._namespace_split(child.tag, self._parse_node(child)) # if tag not in node_tree: # the first time, so store it in dict # node_tree[tag] = tree # continue # old = node_tree[tag] # if not isinstance(old, list): # node_tree.pop(tag) # node_tree[tag] = [old] # multi times, so change old dict to a list # node_tree[tag].append(tree) # add the new one # # return node_tree # # @classmethod # def _namespace_split(self, tag, value): # """ # Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' # ns = http://cs.sfsu.edu/csc867/myscheduler # name = patients # """ # result = re.compile("\{(.*)\}(.*)").search(tag) # if result: # # print(tag) # value.namespace, tag = result.groups() # return (tag, value) # # @classmethod # def parse(self, file): # """parse a xml file to a dict""" # f = open(file, 'r') # return self.fromstring(f.read()) # # @classmethod # def fromstring(self, s): # """parse a string""" # t = ET.fromstring(s) # root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t)) # return object_dict({root_tag: root_tree}) . Output only the next line.
open('%s/%s-%s_%d.png' % (download_dir, cname[i][0].decode('utf-8'), i, j), 'wb').write(dt)
Given the code snippet: <|code_start|># coding:utf-8 # start meta __plugin_name__ = 'MAW自动配卡转换插件' __author = 'fffonion' __version__ = 0.11 hooks = {} extra_cmd = {'mi':'maw_importter', 'cmi':'clear_maw_importted'} def _set_cfg_val(cf, sec, key, val): if not cf.has_section(sec): cf.add_section(sec) cf.set(sec, key, val) def _write_cfg(cf, fname): f = open(fname, "w") <|code_end|> , generate the next line using the imports in this file: import os, os.path as opath import sys from cross_platform import * from xml2dict import XML2Dict and context (functions, classes, or occasionally code) from other files: # Path: xml2dict.py # class XML2Dict(object): # @classmethod # def _parse_node(self, node): # node_tree = object_dict() # # Save attrs and text, hope there will not be a child with same name # if node.text: # node_tree.value = node.text # for (k, v) in node.attrib.items(): # k, v = self._namespace_split(k, object_dict({'value':v})) # node_tree[k] = v # # Save childrens # for child in iter(node): # tag, tree = self._namespace_split(child.tag, self._parse_node(child)) # if tag not in node_tree: # the first time, so store it in dict # node_tree[tag] = tree # continue # old = node_tree[tag] # if not isinstance(old, list): # node_tree.pop(tag) # node_tree[tag] = [old] # multi times, so change old dict to a list # node_tree[tag].append(tree) # add the new one # # return node_tree # # @classmethod # def _namespace_split(self, tag, value): # """ # Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' # ns = http://cs.sfsu.edu/csc867/myscheduler # name = patients # """ # result = re.compile("\{(.*)\}(.*)").search(tag) # if result: # # print(tag) # value.namespace, tag = result.groups() # return (tag, value) # # @classmethod # def parse(self, file): # """parse a xml file to a dict""" # f = open(file, 'r') # return self.fromstring(f.read()) # # @classmethod # def fromstring(self, s): # """parse a string""" # t = ET.fromstring(s) # root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t)) # return object_dict({root_tag: root_tree}) . Output only the next line.
cf.write(f)
Using the snippet: <|code_start|> else: return body def _check_update(silent = False): check_file = opath.join(_get_temp(), '.MAClient.noupdate') if opath.exists(check_file): if time.time() - os.path.getmtime(check_file) < 10800:#3小时内只检查一次 return os.remove(check_file) if not silent: print('Retrieving meta info ...') body = _http_get('update/meta.xml', silent) if not body: print('Error fetching meta') return meta = XML2Dict.fromstring(body).maclient xml = '<?xml version="1.0" encoding="UTF-8"?><maclient><time>%d</time>' % int(time.time()) s_update = '<update_item><name>%s</name><version>%s</version><dir>%s</dir></update_item>' s_new = '<new_item><name>%s</name><version>%s</version><dir>%s</dir></new_item>' new = False for k in meta.plugin + meta.script: script = opath.join(getPATH0, k.dir or '', k.name) # reserved for exe bundle if k.name == 'maclient.py': mainitm = k elif k.name == 'maclient_smart.py': smtitm = k if EXEBUNDLE: if k.name == 'maclient_cli.py': continue <|code_end|> , determine the next line of code. You have imports: from _prototype import plugin_prototype from cross_platform import * from xml2dict import XML2Dict from io import StringIO from cStringIO import StringIO import re import sys import time import os, os.path as opath import urllib import gzip import threading import urllib.request as urllib2 import urllib2 import maclient import maclient_smart and context (class names, function names, or code) available: # Path: xml2dict.py # class XML2Dict(object): # @classmethod # def _parse_node(self, node): # node_tree = object_dict() # # Save attrs and text, hope there will not be a child with same name # if node.text: # node_tree.value = node.text # for (k, v) in node.attrib.items(): # k, v = self._namespace_split(k, object_dict({'value':v})) # node_tree[k] = v # # Save childrens # for child in iter(node): # tag, tree = self._namespace_split(child.tag, self._parse_node(child)) # if tag not in node_tree: # the first time, so store it in dict # node_tree[tag] = tree # continue # old = node_tree[tag] # if not isinstance(old, list): # node_tree.pop(tag) # node_tree[tag] = [old] # multi times, so change old dict to a list # node_tree[tag].append(tree) # add the new one # # return node_tree # # @classmethod # def _namespace_split(self, tag, value): # """ # Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' # ns = http://cs.sfsu.edu/csc867/myscheduler # name = patients # """ # result = re.compile("\{(.*)\}(.*)").search(tag) # if result: # # print(tag) # value.namespace, tag = result.groups() # return (tag, value) # # @classmethod # def parse(self, file): # """parse a xml file to a dict""" # f = open(file, 'r') # return self.fromstring(f.read()) # # @classmethod # def fromstring(self, s): # """parse a string""" # t = ET.fromstring(s) # root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t)) # return object_dict({root_tag: root_tree}) . Output only the next line.
elif k.name == 'maclient.py':
Given the following code snippet before the placeholder: <|code_start|> dec = _dec else: try: dec = XML2Dict.fromstring(_dec).response except: try: dec = XML2Dict.fromstring(re.compile('&(?!#)').sub('&amp;',_dec)).response except: self.logger.error('大概是换了版本号/新加密方法等等,总之是跪了orz…请提交debug_xxx.xml\n%s' 'http://yooooo.us/2013/maclient' % ('你也可以试试重新登录(输入rl)\n' if self.loc == 'jp' else '')) with open('debug_%s.xml' % urikey.replace('/', '#').replace('?', '~'),'w') as f: f.write(_dec) self._exit(3) try: err = dec.header.error except: pass else: if err.code != '0': resp['errmsg'] = err.message # 1050木有BC 1010卖了卡或妖精已被消灭 8000基友点或卡满了 1020维护 1030有新版本 if not err.code in ['1050', '1010', '1030'] and not (err.code == '1000' and self.loc == 'jp'): # ,'8000']: self.logger.error('code:%s msg:%s' % (err.code, err.message)) resp.update({'error':True, 'errno':int(err.code)}) if err.code == '9000': self._write_config('account_%s' % self.loc, 'session', '') self.logger.info('A一个新的小饼干……') #重连策略 _gap = self._read_config('system', 'reconnect_gap') or '0' <|code_end|> , predict the next line using imports from the current file: import math import os import os.path as opath import re import sys import time import locale import base64 import datetime import random import threading import traceback import configparser as ConfigParser import ConfigParser import maclient_player import maclient_network import maclient_logging import maclient_plugin import System.Console import maclient_update from xml2dict import XML2Dict from xml2dict import object_dict from cross_platform import * and context including class names, function names, and sometimes code from other files: # Path: xml2dict.py # class XML2Dict(object): # @classmethod # def _parse_node(self, node): # node_tree = object_dict() # # Save attrs and text, hope there will not be a child with same name # if node.text: # node_tree.value = node.text # for (k, v) in node.attrib.items(): # k, v = self._namespace_split(k, object_dict({'value':v})) # node_tree[k] = v # # Save childrens # for child in iter(node): # tag, tree = self._namespace_split(child.tag, self._parse_node(child)) # if tag not in node_tree: # the first time, so store it in dict # node_tree[tag] = tree # continue # old = node_tree[tag] # if not isinstance(old, list): # node_tree.pop(tag) # node_tree[tag] = [old] # multi times, so change old dict to a list # node_tree[tag].append(tree) # add the new one # # return node_tree # # @classmethod # def _namespace_split(self, tag, value): # """ # Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' # ns = http://cs.sfsu.edu/csc867/myscheduler # name = patients # """ # result = re.compile("\{(.*)\}(.*)").search(tag) # if result: # # print(tag) # value.namespace, tag = result.groups() # return (tag, value) # # @classmethod # def parse(self, file): # """parse a xml file to a dict""" # f = open(file, 'r') # return self.fromstring(f.read()) # # @classmethod # def fromstring(self, s): # """parse a string""" # t = ET.fromstring(s) # root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t)) # return object_dict({root_tag: root_tree}) # # Path: xml2dict.py # class object_dict(dict): # """object view of dict, you can # >>> a = object_dict() # >>> a.fish = 'fish' # >>> a['fish'] # 'fish' # >>> a['water'] = 'water' # >>> a.water # 'water' # >>> a.test = {'value': 1} # >>> a.test2 = object_dict({'name': 'test2', 'value': 2}) # >>> a.test, a.test2.name, a.test2.value # (1, 'test2', 2) # """ # def __init__(self, initd = None): # if initd is None: # initd = {} # dict.__init__(self, initd) # # def __getattr__(self, item): # d = self.__getitem__(item) # # if value is the only key in object, you can omit it # if isinstance(d, dict) and 'value' in d and len(d) == 1: # return d['value'] # else: # return d # # # def __iter__(self): # # yield self # # return # # def __setattr__(self, item, value): # self.__setitem__(item, value) . Output only the next line.
if re.match('\d+\:\d+', _gap):
Given the following code snippet before the placeholder: <|code_start|> else: arg_minbc = int(task[i + 1]) self.factor_battle(minbc = arg_minbc, sel_lake = arg_lake) elif task[0] == 'fairy_battle' or task[0] == 'fyb': self.fairy_battle_loop(task[1]) elif task[0] == 'fairy_select' or task[0] == 'fs': for i in xrange(1, len(task)): if task[i].startswith('deck:'): self.fairy_select(cond = ' '.join(task[1:i]), carddeck = ' '.join(task[i:-1])[5:]) break if i == len(task) - 1: self.fairy_select(cond = ' '.join(task[1:])) elif task[0] == 'green_tea' or task[0] == 'gt': self.green_tea(tea = HALF_TEA if '/' in ' '.join(task[1:]) else FULL_TEA) elif task[0] == 'red_tea' or task[0] == 'rt': self.red_tea(tea = HALF_TEA if '/' in ' '.join(task[1:]) else FULL_TEA) elif task[0] == 'sell_card' or task[0] == 'slc': self.sell_card(' '.join(task[1:])) elif task[0] == 'buildup_card' or task[0] == 'buc': self.buildup_card(*((' '.join(task[1:]) + ';').split(';')[:2]))#blc [food_cond],[base_cond] elif task[0] == 'set_server' or task[0] == 'ss': if task[1] not in ['cn','cn1','cn2','cn3','tw','kr','jp','sg','my']: self.logger.error('服务器"%s"无效'%(task[1])) else: self._write_config('system', 'server', task[1]) self.loc = task[1] self.poster.load_svr(self.loc) self.load_config() elif task[0] == 'relogin' or task[0] == 'rl': self._write_config('account_%s' % self.loc, 'session', '') <|code_end|> , predict the next line using imports from the current file: import math import os import os.path as opath import re import sys import time import locale import base64 import datetime import random import threading import traceback import configparser as ConfigParser import ConfigParser import maclient_player import maclient_network import maclient_logging import maclient_plugin import System.Console import maclient_update from xml2dict import XML2Dict from xml2dict import object_dict from cross_platform import * and context including class names, function names, and sometimes code from other files: # Path: xml2dict.py # class XML2Dict(object): # @classmethod # def _parse_node(self, node): # node_tree = object_dict() # # Save attrs and text, hope there will not be a child with same name # if node.text: # node_tree.value = node.text # for (k, v) in node.attrib.items(): # k, v = self._namespace_split(k, object_dict({'value':v})) # node_tree[k] = v # # Save childrens # for child in iter(node): # tag, tree = self._namespace_split(child.tag, self._parse_node(child)) # if tag not in node_tree: # the first time, so store it in dict # node_tree[tag] = tree # continue # old = node_tree[tag] # if not isinstance(old, list): # node_tree.pop(tag) # node_tree[tag] = [old] # multi times, so change old dict to a list # node_tree[tag].append(tree) # add the new one # # return node_tree # # @classmethod # def _namespace_split(self, tag, value): # """ # Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' # ns = http://cs.sfsu.edu/csc867/myscheduler # name = patients # """ # result = re.compile("\{(.*)\}(.*)").search(tag) # if result: # # print(tag) # value.namespace, tag = result.groups() # return (tag, value) # # @classmethod # def parse(self, file): # """parse a xml file to a dict""" # f = open(file, 'r') # return self.fromstring(f.read()) # # @classmethod # def fromstring(self, s): # """parse a string""" # t = ET.fromstring(s) # root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t)) # return object_dict({root_tag: root_tree}) # # Path: xml2dict.py # class object_dict(dict): # """object view of dict, you can # >>> a = object_dict() # >>> a.fish = 'fish' # >>> a['fish'] # 'fish' # >>> a['water'] = 'water' # >>> a.water # 'water' # >>> a.test = {'value': 1} # >>> a.test2 = object_dict({'name': 'test2', 'value': 2}) # >>> a.test, a.test2.name, a.test2.value # (1, 'test2', 2) # """ # def __init__(self, initd = None): # if initd is None: # initd = {} # dict.__init__(self, initd) # # def __getattr__(self, item): # d = self.__getitem__(item) # # if value is the only key in object, you can omit it # if isinstance(d, dict) and 'value' in d and len(d) == 1: # return d['value'] # else: # return d # # # def __iter__(self): # # yield self # # return # # def __setattr__(self, item, value): # self.__setitem__(item, value) . Output only the next line.
self.login()
Continue the code snippet: <|code_start|>__version__ = 0.35 hooks = {} extra_cmd = {"reg":"reg_gen"} def reg_gen(plugin_vals): def do(*args): loc = plugin_vals['loc'] po = plugin_vals['poster'] logger = plugin_vals['logger'] if 'player' not in plugin_vals: logger.error('玩家信息还没有初始化') return if args[0].strip().lstrip('-').isdigit(): reg_cnt = int(args[0].strip()) # >0 => auto_mode else: reg_cnt = -1 if reg_cnt == -0xe9:#ubw mode invid = hex(random.randrange(100000, 2333333))[2:] else: invid = hex(int(plugin_vals['player'].id))[2:] cnt = 0 _prt = lambda x: print(du8(x)) if reg_cnt != -0xe9 else None #logger.warning('如果连续注册遇到code 500\n请明天再试\n或者使用VPN或代理连接(MAClient会在启动时自动读取IE代理)') _prt('招待码 = %s' % invid) while True: po.cookie = '' po.post('check_inspection') if loc not in ['jp', 'my']: po.post('notification/post_devicetoken', postdata = 'S=nosessionid&login_id=&password=&app=and&token=') # s=raw_input('session: ').lstrip('S=').strip() # print po.cookie <|code_end|> . Use current file imports: from _prototype import plugin_prototype from cross_platform import * from xml2dict import XML2Dict import random import time import sys import os import sys import string import httplib2 import maclient_network and context (classes, functions, or code) from other files: # Path: xml2dict.py # class XML2Dict(object): # @classmethod # def _parse_node(self, node): # node_tree = object_dict() # # Save attrs and text, hope there will not be a child with same name # if node.text: # node_tree.value = node.text # for (k, v) in node.attrib.items(): # k, v = self._namespace_split(k, object_dict({'value':v})) # node_tree[k] = v # # Save childrens # for child in iter(node): # tag, tree = self._namespace_split(child.tag, self._parse_node(child)) # if tag not in node_tree: # the first time, so store it in dict # node_tree[tag] = tree # continue # old = node_tree[tag] # if not isinstance(old, list): # node_tree.pop(tag) # node_tree[tag] = [old] # multi times, so change old dict to a list # node_tree[tag].append(tree) # add the new one # # return node_tree # # @classmethod # def _namespace_split(self, tag, value): # """ # Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' # ns = http://cs.sfsu.edu/csc867/myscheduler # name = patients # """ # result = re.compile("\{(.*)\}(.*)").search(tag) # if result: # # print(tag) # value.namespace, tag = result.groups() # return (tag, value) # # @classmethod # def parse(self, file): # """parse a xml file to a dict""" # f = open(file, 'r') # return self.fromstring(f.read()) # # @classmethod # def fromstring(self, s): # """parse a string""" # t = ET.fromstring(s) # root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t)) # return object_dict({root_tag: root_tree}) . Output only the next line.
while True:
Continue the code snippet: <|code_start|> if cborev: rev[4] = str(cborev) rev_str = rev_str.replace(r, ','.join(rev)) open(opath.join(getPATH0, 'db/revision.txt'), 'w').write(rev_str) def check_revision(loc, rev_tuple): rev = get_revision(loc) + [0, 0]#legacy db support if rev: return rev_tuple[0] > float(rev[0]), rev_tuple[1] > float(rev[1]), rev_tuple[2] > float(rev[2]), rev_tuple[3] > float(rev[3]) else: return False, False, False, False def update_master(loc, need_update, poster): replace_AND = re.compile('&(?!#)')#no CDATA, sad #card, item, boss, combo new_rev = [None, None, None, None] for s in poster.ht.connections:#cleanup socket pool poster.ht.connections[s].close() poster.ht.connections = {} poster.set_timeout(240) if loc == 'jp': postdata = '' else: postdata = '%s&revision=0' % poster.cookie if need_update[0]: a, b = poster.post('masterdata/card/update', postdata = postdata) resp = XML2Dict().fromstring(replace_AND.sub('&amp;', b)).response # 不替换会解析出错摔 cards = resp.body.master_data.master_card_data.card strs = [('%s,%s,%s,%s,%s,%s,%s,%s' % ( c.master_card_id, <|code_end|> . Use current file imports: import os import re import os.path as opath import sys import base64 import time from xml2dict import XML2Dict from cross_platform import * from httplib2 import Http and context (classes, functions, or code) from other files: # Path: xml2dict.py # class XML2Dict(object): # @classmethod # def _parse_node(self, node): # node_tree = object_dict() # # Save attrs and text, hope there will not be a child with same name # if node.text: # node_tree.value = node.text # for (k, v) in node.attrib.items(): # k, v = self._namespace_split(k, object_dict({'value':v})) # node_tree[k] = v # # Save childrens # for child in iter(node): # tag, tree = self._namespace_split(child.tag, self._parse_node(child)) # if tag not in node_tree: # the first time, so store it in dict # node_tree[tag] = tree # continue # old = node_tree[tag] # if not isinstance(old, list): # node_tree.pop(tag) # node_tree[tag] = [old] # multi times, so change old dict to a list # node_tree[tag].append(tree) # add the new one # # return node_tree # # @classmethod # def _namespace_split(self, tag, value): # """ # Split the tag '{http://cs.sfsu.edu/csc867/myscheduler}patients' # ns = http://cs.sfsu.edu/csc867/myscheduler # name = patients # """ # result = re.compile("\{(.*)\}(.*)").search(tag) # if result: # # print(tag) # value.namespace, tag = result.groups() # return (tag, value) # # @classmethod # def parse(self, file): # """parse a xml file to a dict""" # f = open(file, 'r') # return self.fromstring(f.read()) # # @classmethod # def fromstring(self, s): # """parse a string""" # t = ET.fromstring(s) # root_tag, root_tree = self._namespace_split(t.tag, self._parse_node(t)) # return object_dict({root_tag: root_tree}) . Output only the next line.
c.name,
Based on the snippet: <|code_start|> # Standard library # Application modules # External modules class Jinja2ViewProviderFactory(object): """ """ implements(IPlugin, IViewProviderFactory) tag = "jinja2_view_provider" opt_help = dedent('''\ A view provider based on jinja2 templates. ''') opt_usage = '''A colon-separated key=value list.''' <|code_end|> , predict the immediate next line with the help of imports: import cgi import itertools import json import sys import urlparse import txcas.settings from textwrap import dedent from txcas.constants import VIEW_LOGIN, VIEW_LOGIN_SUCCESS, VIEW_LOGOUT, \ VIEW_INVALID_SERVICE, VIEW_ERROR_5XX, VIEW_NOT_FOUND from txcas.exceptions import ViewNotImplementedError from txcas.interface import IViewProvider, IViewProviderFactory, \ IServiceManagerAcceptor from jinja2 import Environment, FileSystemLoader from jinja2.exceptions import TemplateNotFound from twisted.internet import reactor, defer from twisted.plugin import IPlugin from twisted.python import log from twisted.python.filepath import FilePath from zope.interface import implements and context (classes, functions, sometimes code) from other files: # Path: txcas/constants.py # VIEW_LOGIN = 0 # # VIEW_LOGIN_SUCCESS = 1 # # VIEW_LOGOUT = 2 # # VIEW_INVALID_SERVICE = 3 # # VIEW_ERROR_5XX = 4 # # VIEW_NOT_FOUND = 5 # # Path: txcas/exceptions.py # class ViewNotImplementedError(CASError): # pass # # Path: txcas/interface.py # class IViewProvider(Interface): # # def provideView(view_type): # """ # Provide a function that will render the named view. # Return None if the view is not provided. # """ # # class IViewProviderFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateViewProvider(argstring=""): # """ # Create an object that provides one or more views. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') . Output only the next line.
def generateViewProvider(self, argstring=""):
Given the following code snippet before the placeholder: <|code_start|> # Standard library # Application modules # External modules class Jinja2ViewProviderFactory(object): """ """ implements(IPlugin, IViewProviderFactory) tag = "jinja2_view_provider" opt_help = dedent('''\ A view provider based on jinja2 templates. ''') opt_usage = '''A colon-separated key=value list.''' <|code_end|> , predict the next line using imports from the current file: import cgi import itertools import json import sys import urlparse import txcas.settings from textwrap import dedent from txcas.constants import VIEW_LOGIN, VIEW_LOGIN_SUCCESS, VIEW_LOGOUT, \ VIEW_INVALID_SERVICE, VIEW_ERROR_5XX, VIEW_NOT_FOUND from txcas.exceptions import ViewNotImplementedError from txcas.interface import IViewProvider, IViewProviderFactory, \ IServiceManagerAcceptor from jinja2 import Environment, FileSystemLoader from jinja2.exceptions import TemplateNotFound from twisted.internet import reactor, defer from twisted.plugin import IPlugin from twisted.python import log from twisted.python.filepath import FilePath from zope.interface import implements and context including class names, function names, and sometimes code from other files: # Path: txcas/constants.py # VIEW_LOGIN = 0 # # VIEW_LOGIN_SUCCESS = 1 # # VIEW_LOGOUT = 2 # # VIEW_INVALID_SERVICE = 3 # # VIEW_ERROR_5XX = 4 # # VIEW_NOT_FOUND = 5 # # Path: txcas/exceptions.py # class ViewNotImplementedError(CASError): # pass # # Path: txcas/interface.py # class IViewProvider(Interface): # # def provideView(view_type): # """ # Provide a function that will render the named view. # Return None if the view is not provided. # """ # # class IViewProviderFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateViewProvider(argstring=""): # """ # Create an object that provides one or more views. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') . Output only the next line.
def generateViewProvider(self, argstring=""):
Next line prediction: <|code_start|> # Standard library # Application modules # External modules class Jinja2ViewProviderFactory(object): """ """ implements(IPlugin, IViewProviderFactory) tag = "jinja2_view_provider" opt_help = dedent('''\ A view provider based on jinja2 templates. ''') opt_usage = '''A colon-separated key=value list.''' <|code_end|> . Use current file imports: (import cgi import itertools import json import sys import urlparse import txcas.settings from textwrap import dedent from txcas.constants import VIEW_LOGIN, VIEW_LOGIN_SUCCESS, VIEW_LOGOUT, \ VIEW_INVALID_SERVICE, VIEW_ERROR_5XX, VIEW_NOT_FOUND from txcas.exceptions import ViewNotImplementedError from txcas.interface import IViewProvider, IViewProviderFactory, \ IServiceManagerAcceptor from jinja2 import Environment, FileSystemLoader from jinja2.exceptions import TemplateNotFound from twisted.internet import reactor, defer from twisted.plugin import IPlugin from twisted.python import log from twisted.python.filepath import FilePath from zope.interface import implements) and context including class names, function names, or small code snippets from other files: # Path: txcas/constants.py # VIEW_LOGIN = 0 # # VIEW_LOGIN_SUCCESS = 1 # # VIEW_LOGOUT = 2 # # VIEW_INVALID_SERVICE = 3 # # VIEW_ERROR_5XX = 4 # # VIEW_NOT_FOUND = 5 # # Path: txcas/exceptions.py # class ViewNotImplementedError(CASError): # pass # # Path: txcas/interface.py # class IViewProvider(Interface): # # def provideView(view_type): # """ # Provide a function that will render the named view. # Return None if the view is not provided. # """ # # class IViewProviderFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateViewProvider(argstring=""): # """ # Create an object that provides one or more views. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') . Output only the next line.
def generateViewProvider(self, argstring=""):
Next line prediction: <|code_start|> # Standard library # Application modules # External modules class Jinja2ViewProviderFactory(object): """ """ implements(IPlugin, IViewProviderFactory) tag = "jinja2_view_provider" opt_help = dedent('''\ A view provider based on jinja2 templates. ''') opt_usage = '''A colon-separated key=value list.''' <|code_end|> . Use current file imports: (import cgi import itertools import json import sys import urlparse import txcas.settings from textwrap import dedent from txcas.constants import VIEW_LOGIN, VIEW_LOGIN_SUCCESS, VIEW_LOGOUT, \ VIEW_INVALID_SERVICE, VIEW_ERROR_5XX, VIEW_NOT_FOUND from txcas.exceptions import ViewNotImplementedError from txcas.interface import IViewProvider, IViewProviderFactory, \ IServiceManagerAcceptor from jinja2 import Environment, FileSystemLoader from jinja2.exceptions import TemplateNotFound from twisted.internet import reactor, defer from twisted.plugin import IPlugin from twisted.python import log from twisted.python.filepath import FilePath from zope.interface import implements) and context including class names, function names, or small code snippets from other files: # Path: txcas/constants.py # VIEW_LOGIN = 0 # # VIEW_LOGIN_SUCCESS = 1 # # VIEW_LOGOUT = 2 # # VIEW_INVALID_SERVICE = 3 # # VIEW_ERROR_5XX = 4 # # VIEW_NOT_FOUND = 5 # # Path: txcas/exceptions.py # class ViewNotImplementedError(CASError): # pass # # Path: txcas/interface.py # class IViewProvider(Interface): # # def provideView(view_type): # """ # Provide a function that will render the named view. # Return None if the view is not provided. # """ # # class IViewProviderFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateViewProvider(argstring=""): # """ # Create an object that provides one or more views. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') . Output only the next line.
def generateViewProvider(self, argstring=""):
Here is a snippet: <|code_start|> # Standard library # Application modules # External modules class Jinja2ViewProviderFactory(object): """ """ implements(IPlugin, IViewProviderFactory) tag = "jinja2_view_provider" opt_help = dedent('''\ A view provider based on jinja2 templates. ''') opt_usage = '''A colon-separated key=value list.''' <|code_end|> . Write the next line using the current file imports: import cgi import itertools import json import sys import urlparse import txcas.settings from textwrap import dedent from txcas.constants import VIEW_LOGIN, VIEW_LOGIN_SUCCESS, VIEW_LOGOUT, \ VIEW_INVALID_SERVICE, VIEW_ERROR_5XX, VIEW_NOT_FOUND from txcas.exceptions import ViewNotImplementedError from txcas.interface import IViewProvider, IViewProviderFactory, \ IServiceManagerAcceptor from jinja2 import Environment, FileSystemLoader from jinja2.exceptions import TemplateNotFound from twisted.internet import reactor, defer from twisted.plugin import IPlugin from twisted.python import log from twisted.python.filepath import FilePath from zope.interface import implements and context from other files: # Path: txcas/constants.py # VIEW_LOGIN = 0 # # VIEW_LOGIN_SUCCESS = 1 # # VIEW_LOGOUT = 2 # # VIEW_INVALID_SERVICE = 3 # # VIEW_ERROR_5XX = 4 # # VIEW_NOT_FOUND = 5 # # Path: txcas/exceptions.py # class ViewNotImplementedError(CASError): # pass # # Path: txcas/interface.py # class IViewProvider(Interface): # # def provideView(view_type): # """ # Provide a function that will render the named view. # Return None if the view is not provided. # """ # # class IViewProviderFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateViewProvider(argstring=""): # """ # Create an object that provides one or more views. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') , which may include functions, classes, or code. Output only the next line.
def generateViewProvider(self, argstring=""):
Given the code snippet: <|code_start|> # Standard library # Application modules # External modules class Jinja2ViewProviderFactory(object): """ """ implements(IPlugin, IViewProviderFactory) tag = "jinja2_view_provider" opt_help = dedent('''\ A view provider based on jinja2 templates. ''') opt_usage = '''A colon-separated key=value list.''' <|code_end|> , generate the next line using the imports in this file: import cgi import itertools import json import sys import urlparse import txcas.settings from textwrap import dedent from txcas.constants import VIEW_LOGIN, VIEW_LOGIN_SUCCESS, VIEW_LOGOUT, \ VIEW_INVALID_SERVICE, VIEW_ERROR_5XX, VIEW_NOT_FOUND from txcas.exceptions import ViewNotImplementedError from txcas.interface import IViewProvider, IViewProviderFactory, \ IServiceManagerAcceptor from jinja2 import Environment, FileSystemLoader from jinja2.exceptions import TemplateNotFound from twisted.internet import reactor, defer from twisted.plugin import IPlugin from twisted.python import log from twisted.python.filepath import FilePath from zope.interface import implements and context (functions, classes, or occasionally code) from other files: # Path: txcas/constants.py # VIEW_LOGIN = 0 # # VIEW_LOGIN_SUCCESS = 1 # # VIEW_LOGOUT = 2 # # VIEW_INVALID_SERVICE = 3 # # VIEW_ERROR_5XX = 4 # # VIEW_NOT_FOUND = 5 # # Path: txcas/exceptions.py # class ViewNotImplementedError(CASError): # pass # # Path: txcas/interface.py # class IViewProvider(Interface): # # def provideView(view_type): # """ # Provide a function that will render the named view. # Return None if the view is not provided. # """ # # class IViewProviderFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateViewProvider(argstring=""): # """ # Create an object that provides one or more views. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') . Output only the next line.
def generateViewProvider(self, argstring=""):
Given the code snippet: <|code_start|> # Standard library # Application module # External module class DemoRealmFactory(object): """ """ implements(IPlugin, IRealmFactory) tag = "demo_realm" opt_help = dedent('''\ A demonstration realm that creates an avatar from an ID with phony `email` and `domain` attributes. ''') opt_usage = '''This type of realm has no options.''' <|code_end|> , generate the next line using the imports in this file: from textwrap import dedent from txcas.casuser import User from txcas.interface import ICASUser, IRealmFactory from twisted.cred.portal import IRealm from twisted.internet import defer from twisted.plugin import IPlugin from zope.interface import implements and context (functions, classes, or occasionally code) from other files: # Path: txcas/casuser.py # class User(object): # # implements(ICASUser) # # username = None # attribs = None # # def __init__(self, username, attribs): # self.username = username # self.attribs = attribs # # def logout(self): # pass # # Path: txcas/interface.py # class ICASUser(Interface): # # username = Attribute('String username') # attribs = Attribute('List of (attribute, value) tuples.') # # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ . Output only the next line.
def generateRealm(self, argstring=""):
Predict the next line after this snippet: <|code_start|> # Standard library # Application module # External module class DemoRealmFactory(object): """ """ implements(IPlugin, IRealmFactory) tag = "demo_realm" opt_help = dedent('''\ A demonstration realm that creates an avatar from an ID with phony `email` and `domain` attributes. ''') opt_usage = '''This type of realm has no options.''' <|code_end|> using the current file's imports: from textwrap import dedent from txcas.casuser import User from txcas.interface import ICASUser, IRealmFactory from twisted.cred.portal import IRealm from twisted.internet import defer from twisted.plugin import IPlugin from zope.interface import implements and any relevant context from other files: # Path: txcas/casuser.py # class User(object): # # implements(ICASUser) # # username = None # attribs = None # # def __init__(self, username, attribs): # self.username = username # self.attribs = attribs # # def logout(self): # pass # # Path: txcas/interface.py # class ICASUser(Interface): # # username = Attribute('String username') # attribs = Attribute('List of (attribute, value) tuples.') # # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ . Output only the next line.
def generateRealm(self, argstring=""):
Given the following code snippet before the placeholder: <|code_start|> print("") print "== IRealmFactory test ==" for n, thing in enumerate(getPlugins(IRealmFactory)): print("%02d %s" % (n, thing)) print(thing.tag) print("") print "== ICredentialsChecker test ==" for n, thing in enumerate(getPlugins(ICheckerFactory)): print("%02d %s" % (n, thing)) print(thing.authType) print("") print "== IServiceManagerFactory test ==" for n, thing in enumerate(getPlugins(IServiceManagerFactory)): print("%02d %s" % (n, thing)) print(thing.tag) print("") print "== IViewProviderFactory test ==" for n, thing in enumerate(getPlugins(IViewProviderFactory)): print("%02d %s" % (n, thing)) print(thing.tag) print("") print("== IStreamServerEndpointStringParser ==") for n, thing in enumerate(getPlugins(IStreamServerEndpointStringParser)): print("%02d %s" % (n, thing)) print(thing.prefix) <|code_end|> , predict the next line using imports from the current file: from txcas.interface import ( IRealmFactory, IServiceManagerFactory, ITicketStoreFactory, IViewProviderFactory) from twisted.internet.interfaces import IStreamServerEndpointStringParser from twisted.plugin import getPlugins from twisted.cred.strcred import ICheckerFactory and context including class names, function names, and sometimes code from other files: # Path: txcas/interface.py # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ # # class IServiceManagerFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateServiceManager(argstring=""): # """ # Create an object that implements txcas.IServiceManager # """ # # class ITicketStoreFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateTicketStore(argstring=""): # """ # Create an object that implements ITicketStore. # """ # # class IViewProviderFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateViewProvider(argstring=""): # """ # Create an object that provides one or more views. # """ . Output only the next line.
print("")
Given snippet: <|code_start|> print("%02d %s" % (n, thing)) print(thing.tag) print("") print "== IRealmFactory test ==" for n, thing in enumerate(getPlugins(IRealmFactory)): print("%02d %s" % (n, thing)) print(thing.tag) print("") print "== ICredentialsChecker test ==" for n, thing in enumerate(getPlugins(ICheckerFactory)): print("%02d %s" % (n, thing)) print(thing.authType) print("") print "== IServiceManagerFactory test ==" for n, thing in enumerate(getPlugins(IServiceManagerFactory)): print("%02d %s" % (n, thing)) print(thing.tag) print("") print "== IViewProviderFactory test ==" for n, thing in enumerate(getPlugins(IViewProviderFactory)): print("%02d %s" % (n, thing)) print(thing.tag) print("") print("== IStreamServerEndpointStringParser ==") for n, thing in enumerate(getPlugins(IStreamServerEndpointStringParser)): <|code_end|> , continue by predicting the next line. Consider current file imports: from txcas.interface import ( IRealmFactory, IServiceManagerFactory, ITicketStoreFactory, IViewProviderFactory) from twisted.internet.interfaces import IStreamServerEndpointStringParser from twisted.plugin import getPlugins from twisted.cred.strcred import ICheckerFactory and context: # Path: txcas/interface.py # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ # # class IServiceManagerFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateServiceManager(argstring=""): # """ # Create an object that implements txcas.IServiceManager # """ # # class ITicketStoreFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateTicketStore(argstring=""): # """ # Create an object that implements ITicketStore. # """ # # class IViewProviderFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateViewProvider(argstring=""): # """ # Create an object that provides one or more views. # """ which might include code, classes, or functions. Output only the next line.
print("%02d %s" % (n, thing))
Given snippet: <|code_start|>#! /usr/bin/env python print "== ITicketStore test ==" for n, thing in enumerate(getPlugins(ITicketStoreFactory)): print("%02d %s" % (n, thing)) print(thing.tag) print("") print "== IRealmFactory test ==" for n, thing in enumerate(getPlugins(IRealmFactory)): print("%02d %s" % (n, thing)) print(thing.tag) print("") print "== ICredentialsChecker test ==" for n, thing in enumerate(getPlugins(ICheckerFactory)): print("%02d %s" % (n, thing)) <|code_end|> , continue by predicting the next line. Consider current file imports: from txcas.interface import ( IRealmFactory, IServiceManagerFactory, ITicketStoreFactory, IViewProviderFactory) from twisted.internet.interfaces import IStreamServerEndpointStringParser from twisted.plugin import getPlugins from twisted.cred.strcred import ICheckerFactory and context: # Path: txcas/interface.py # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ # # class IServiceManagerFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateServiceManager(argstring=""): # """ # Create an object that implements txcas.IServiceManager # """ # # class ITicketStoreFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateTicketStore(argstring=""): # """ # Create an object that implements ITicketStore. # """ # # class IViewProviderFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateViewProvider(argstring=""): # """ # Create an object that provides one or more views. # """ which might include code, classes, or functions. Output only the next line.
print(thing.authType)
Next line prediction: <|code_start|> # Standard library # Application module # External module class BasicRealmFactory(object): """ A basic realm factory. """ implements(IPlugin, IRealmFactory) tag = "basic_realm" opt_help = dedent('''\ A basic realm that creates an avatar from an ID with no attributes. ''') opt_usage = '''This type of realm has no options.''' <|code_end|> . Use current file imports: (from textwrap import dedent from txcas.casuser import User from txcas.interface import ICASUser, IRealmFactory from twisted.cred.portal import IRealm from twisted.internet import defer from twisted.plugin import IPlugin from zope.interface import implements) and context including class names, function names, or small code snippets from other files: # Path: txcas/casuser.py # class User(object): # # implements(ICASUser) # # username = None # attribs = None # # def __init__(self, username, attribs): # self.username = username # self.attribs = attribs # # def logout(self): # pass # # Path: txcas/interface.py # class ICASUser(Interface): # # username = Attribute('String username') # attribs = Attribute('List of (attribute, value) tuples.') # # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ . Output only the next line.
def generateRealm(self, argstring=""):
Predict the next line for this snippet: <|code_start|> # Standard library # Application modules # External modules def compose(*functions): return functools.reduce(lambda f, g: lambda x: f(g(x)), functions) def strip_domain(s): <|code_end|> with the help of current file imports: import functools import string import sys import txcas.settings import txcas.utils from textwrap import dedent from txcas.interface import ICASAuthWhen from twisted.cred.checkers import ICredentialsChecker from twisted.cred import credentials from twisted.cred.error import UnauthorizedLogin from twisted.cred.strcred import ICheckerFactory from twisted.internet import defer from twisted.internet.interfaces import ISSLTransport from twisted import plugin from zope.interface import implements and context from other files: # Path: txcas/interface.py # class ICASAuthWhen(Interface): # # auth_when = Attribute("One of 'cred_acceptor', 'cred_requestor'.") , which may contain function names, class names, or code. Output only the next line.
pos = s.find('@')
Here is a snippet: <|code_start|> # Application modules # External modules class User(object): implements(ICASUser) username = None attribs = None def __init__(self, username, attribs): self.username = username self.attribs = attribs def logout(self): <|code_end|> . Write the next line using the current file imports: from txcas.interface import ICASUser from zope.interface import implements and context from other files: # Path: txcas/interface.py # class ICASUser(Interface): # # username = Attribute('String username') # attribs = Attribute('List of (attribute, value) tuples.') , which may include functions, classes, or code. Output only the next line.
pass
Based on the snippet: <|code_start|> @defer.inlineCallbacks def _get_avatar(self, avatarId, mind): endpointstr = self._endpointstr basedn = self._basedn binddn = self._binddn bindpw = self._bindpw query = self._query_template % {'username': escape_filter_chars(avatarId)} if self._service_based_attribs: if mind: service = mind['service'] else: service = "" if service == "" or service is None or self.service_manager is None: attributes = self._attribs else: service_entry = yield defer.maybeDeferred(self.service_manager.getMatchingService, service) if service_entry and 'attributes' in service_entry: attributes = service_entry['attributes'] else: attributes = self._attribs else: attributes = self._attribs e = clientFromString(reactor, self._endpointstr) client = yield connectProtocol(e, LDAPClient()) startTls = self._startTls startTlsHostName = self._startTlsHostName startTlsAuthority = self._startTlsAuthority if startTls: startTlsArgs = [] if startTlsHostName is not None: <|code_end|> , predict the immediate next line with the help of imports: from textwrap import dedent from txcas.casuser import User from txcas.interface import ICASUser, IRealmFactory, IServiceManagerAcceptor from txcas.settings import get_bool, export_settings_to_dict, load_settings from ldaptor.protocols.ldap.ldapclient import LDAPClient from ldaptor.protocols.ldap import ldapsyntax from ldaptor.protocols.ldap.ldaperrors import LDAPInvalidCredentials from twisted.cred.portal import IRealm from twisted.internet import defer, reactor from twisted.internet.endpoints import clientFromString, connectProtocol from twisted.internet.ssl import Certificate, optionsForClientTLS, platformTrust from twisted.plugin import IPlugin from zope.interface import implements import sys import txcas.utils import pem and context (classes, functions, sometimes code) from other files: # Path: txcas/casuser.py # class User(object): # # implements(ICASUser) # # username = None # attribs = None # # def __init__(self, username, attribs): # self.username = username # self.attribs = attribs # # def logout(self): # pass # # Path: txcas/interface.py # class ICASUser(Interface): # # username = Attribute('String username') # attribs = Attribute('List of (attribute, value) tuples.') # # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') # # Path: txcas/settings.py # def get_bool(value, default=False): # if value is None: # return False # value = str(value).strip().lower() # if value in ('y', '1', 't', 'yes', 'true'): # return True # elif value in ('n', '0', 'f', 'no', 'false'): # return False # else: # return default # # def export_settings_to_dict(scp): # settings = {} # for section in scp.sections(): # for option in scp.options(section): # settings.setdefault(section, {})[option] = scp.get(section, option) # return settings # # def load_settings(config_basename, defaults=None, syspath=None, appdir=None): # """ # Load settings. # """ # if defaults is None: # defaults = {} # scp = load_defaults(defaults) # if appdir is None: # appdir = os.path.dirname(os.path.dirname(__file__)) # paths = [] # if syspath is not None: # paths.append(os.path.join(syspath, "%s.cfg" % config_basename)) # paths.append(os.path.expanduser("~/%src" % config_basename)) # paths.append(os.path.join(appdir, "%s.cfg" % config_basename)) # scp.read(paths) # return scp . Output only the next line.
if startTlsAuthority is not None:
Continue the code snippet: <|code_start|> if not ICASUser in interfaces: raise NotImplementedError("This realm only implements ICASUser.") return (ICASUser, avatar, avatar.logout) d = self._get_avatar(avatarId, mind) return d.addCallback(cb) @defer.inlineCallbacks def _get_avatar(self, avatarId, mind): endpointstr = self._endpointstr basedn = self._basedn binddn = self._binddn bindpw = self._bindpw query = self._query_template % {'username': escape_filter_chars(avatarId)} if self._service_based_attribs: if mind: service = mind['service'] else: service = "" if service == "" or service is None or self.service_manager is None: attributes = self._attribs else: service_entry = yield defer.maybeDeferred(self.service_manager.getMatchingService, service) if service_entry and 'attributes' in service_entry: attributes = service_entry['attributes'] else: attributes = self._attribs else: attributes = self._attribs e = clientFromString(reactor, self._endpointstr) <|code_end|> . Use current file imports: from textwrap import dedent from txcas.casuser import User from txcas.interface import ICASUser, IRealmFactory, IServiceManagerAcceptor from txcas.settings import get_bool, export_settings_to_dict, load_settings from ldaptor.protocols.ldap.ldapclient import LDAPClient from ldaptor.protocols.ldap import ldapsyntax from ldaptor.protocols.ldap.ldaperrors import LDAPInvalidCredentials from twisted.cred.portal import IRealm from twisted.internet import defer, reactor from twisted.internet.endpoints import clientFromString, connectProtocol from twisted.internet.ssl import Certificate, optionsForClientTLS, platformTrust from twisted.plugin import IPlugin from zope.interface import implements import sys import txcas.utils import pem and context (classes, functions, or code) from other files: # Path: txcas/casuser.py # class User(object): # # implements(ICASUser) # # username = None # attribs = None # # def __init__(self, username, attribs): # self.username = username # self.attribs = attribs # # def logout(self): # pass # # Path: txcas/interface.py # class ICASUser(Interface): # # username = Attribute('String username') # attribs = Attribute('List of (attribute, value) tuples.') # # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') # # Path: txcas/settings.py # def get_bool(value, default=False): # if value is None: # return False # value = str(value).strip().lower() # if value in ('y', '1', 't', 'yes', 'true'): # return True # elif value in ('n', '0', 'f', 'no', 'false'): # return False # else: # return default # # def export_settings_to_dict(scp): # settings = {} # for section in scp.sections(): # for option in scp.options(section): # settings.setdefault(section, {})[option] = scp.get(section, option) # return settings # # def load_settings(config_basename, defaults=None, syspath=None, appdir=None): # """ # Load settings. # """ # if defaults is None: # defaults = {} # scp = load_defaults(defaults) # if appdir is None: # appdir = os.path.dirname(os.path.dirname(__file__)) # paths = [] # if syspath is not None: # paths.append(os.path.join(syspath, "%s.cfg" % config_basename)) # paths.append(os.path.expanduser("~/%src" % config_basename)) # paths.append(os.path.join(appdir, "%s.cfg" % config_basename)) # scp.read(paths) # return scp . Output only the next line.
client = yield connectProtocol(e, LDAPClient())
Based on the snippet: <|code_start|> aliases=None, service_based_attribs=False, start_tls=False, start_tls_hostname=None, start_tls_cacert=None): if attribs is None: attribs = [] # Turn attribs into mapping of attrib_name => alias. if aliases is not None: assert len(aliases) == len(attribs), "[ERROR][LDAP REALM] Number of aliases must match number of attribs." attribs = dict(x for x in zip(attribs, aliases)) else: attribs = dict((k,k) for k in attribs) self._attribs = attribs self._endpointstr = endpointstr self._basedn = basedn self._binddn = binddn self._bindpw = bindpw self._query_template = query_template self._service_based_attribs = service_based_attribs self._startTls = get_bool(start_tls) self._startTlsAuthority = self.getTlsAuthority_(start_tls_cacert) self._startTlsHostName = start_tls_hostname def getTlsAuthority_(self, startTlsCaCert): if startTlsCaCert is None: return None authorities = [str(cert) for cert in pem.parse_file(startTlsCaCert)] if len(authorities) != 1: raise Exception( <|code_end|> , predict the immediate next line with the help of imports: from textwrap import dedent from txcas.casuser import User from txcas.interface import ICASUser, IRealmFactory, IServiceManagerAcceptor from txcas.settings import get_bool, export_settings_to_dict, load_settings from ldaptor.protocols.ldap.ldapclient import LDAPClient from ldaptor.protocols.ldap import ldapsyntax from ldaptor.protocols.ldap.ldaperrors import LDAPInvalidCredentials from twisted.cred.portal import IRealm from twisted.internet import defer, reactor from twisted.internet.endpoints import clientFromString, connectProtocol from twisted.internet.ssl import Certificate, optionsForClientTLS, platformTrust from twisted.plugin import IPlugin from zope.interface import implements import sys import txcas.utils import pem and context (classes, functions, sometimes code) from other files: # Path: txcas/casuser.py # class User(object): # # implements(ICASUser) # # username = None # attribs = None # # def __init__(self, username, attribs): # self.username = username # self.attribs = attribs # # def logout(self): # pass # # Path: txcas/interface.py # class ICASUser(Interface): # # username = Attribute('String username') # attribs = Attribute('List of (attribute, value) tuples.') # # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') # # Path: txcas/settings.py # def get_bool(value, default=False): # if value is None: # return False # value = str(value).strip().lower() # if value in ('y', '1', 't', 'yes', 'true'): # return True # elif value in ('n', '0', 'f', 'no', 'false'): # return False # else: # return default # # def export_settings_to_dict(scp): # settings = {} # for section in scp.sections(): # for option in scp.options(section): # settings.setdefault(section, {})[option] = scp.get(section, option) # return settings # # def load_settings(config_basename, defaults=None, syspath=None, appdir=None): # """ # Load settings. # """ # if defaults is None: # defaults = {} # scp = load_defaults(defaults) # if appdir is None: # appdir = os.path.dirname(os.path.dirname(__file__)) # paths = [] # if syspath is not None: # paths.append(os.path.join(syspath, "%s.cfg" % config_basename)) # paths.append(os.path.expanduser("~/%src" % config_basename)) # paths.append(os.path.join(appdir, "%s.cfg" % config_basename)) # scp.read(paths) # return scp . Output only the next line.
("The provided CA cert file, '{0}', "
Next line prediction: <|code_start|> raise Exception( ("The provided CA cert file, '{0}', " "contained {1} certificates. It must contain exactly one.").format( startTlsCaCert, len(authorities))) return Certificate.loadPEM(authorities[0]) def requestAvatar(self, avatarId, mind, *interfaces): def cb(avatar): if not ICASUser in interfaces: raise NotImplementedError("This realm only implements ICASUser.") return (ICASUser, avatar, avatar.logout) d = self._get_avatar(avatarId, mind) return d.addCallback(cb) @defer.inlineCallbacks def _get_avatar(self, avatarId, mind): endpointstr = self._endpointstr basedn = self._basedn binddn = self._binddn bindpw = self._bindpw query = self._query_template % {'username': escape_filter_chars(avatarId)} if self._service_based_attribs: if mind: service = mind['service'] else: service = "" if service == "" or service is None or self.service_manager is None: attributes = self._attribs <|code_end|> . Use current file imports: (from textwrap import dedent from txcas.casuser import User from txcas.interface import ICASUser, IRealmFactory, IServiceManagerAcceptor from txcas.settings import get_bool, export_settings_to_dict, load_settings from ldaptor.protocols.ldap.ldapclient import LDAPClient from ldaptor.protocols.ldap import ldapsyntax from ldaptor.protocols.ldap.ldaperrors import LDAPInvalidCredentials from twisted.cred.portal import IRealm from twisted.internet import defer, reactor from twisted.internet.endpoints import clientFromString, connectProtocol from twisted.internet.ssl import Certificate, optionsForClientTLS, platformTrust from twisted.plugin import IPlugin from zope.interface import implements import sys import txcas.utils import pem) and context including class names, function names, or small code snippets from other files: # Path: txcas/casuser.py # class User(object): # # implements(ICASUser) # # username = None # attribs = None # # def __init__(self, username, attribs): # self.username = username # self.attribs = attribs # # def logout(self): # pass # # Path: txcas/interface.py # class ICASUser(Interface): # # username = Attribute('String username') # attribs = Attribute('List of (attribute, value) tuples.') # # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') # # Path: txcas/settings.py # def get_bool(value, default=False): # if value is None: # return False # value = str(value).strip().lower() # if value in ('y', '1', 't', 'yes', 'true'): # return True # elif value in ('n', '0', 'f', 'no', 'false'): # return False # else: # return default # # def export_settings_to_dict(scp): # settings = {} # for section in scp.sections(): # for option in scp.options(section): # settings.setdefault(section, {})[option] = scp.get(section, option) # return settings # # def load_settings(config_basename, defaults=None, syspath=None, appdir=None): # """ # Load settings. # """ # if defaults is None: # defaults = {} # scp = load_defaults(defaults) # if appdir is None: # appdir = os.path.dirname(os.path.dirname(__file__)) # paths = [] # if syspath is not None: # paths.append(os.path.join(syspath, "%s.cfg" % config_basename)) # paths.append(os.path.expanduser("~/%src" % config_basename)) # paths.append(os.path.join(appdir, "%s.cfg" % config_basename)) # scp.read(paths) # return scp . Output only the next line.
else:
Predict the next line after this snippet: <|code_start|> class LDAPRealm(object): implements(IRealm, IServiceManagerAcceptor) service_manager = None def __init__(self, endpointstr, basedn, binddn, bindpw, query_template='(uid=%(username)s)', attribs=None, aliases=None, service_based_attribs=False, start_tls=False, start_tls_hostname=None, start_tls_cacert=None): if attribs is None: attribs = [] # Turn attribs into mapping of attrib_name => alias. if aliases is not None: assert len(aliases) == len(attribs), "[ERROR][LDAP REALM] Number of aliases must match number of attribs." attribs = dict(x for x in zip(attribs, aliases)) else: attribs = dict((k,k) for k in attribs) self._attribs = attribs self._endpointstr = endpointstr self._basedn = basedn self._binddn = binddn self._bindpw = bindpw self._query_template = query_template self._service_based_attribs = service_based_attribs self._startTls = get_bool(start_tls) self._startTlsAuthority = self.getTlsAuthority_(start_tls_cacert) <|code_end|> using the current file's imports: from textwrap import dedent from txcas.casuser import User from txcas.interface import ICASUser, IRealmFactory, IServiceManagerAcceptor from txcas.settings import get_bool, export_settings_to_dict, load_settings from ldaptor.protocols.ldap.ldapclient import LDAPClient from ldaptor.protocols.ldap import ldapsyntax from ldaptor.protocols.ldap.ldaperrors import LDAPInvalidCredentials from twisted.cred.portal import IRealm from twisted.internet import defer, reactor from twisted.internet.endpoints import clientFromString, connectProtocol from twisted.internet.ssl import Certificate, optionsForClientTLS, platformTrust from twisted.plugin import IPlugin from zope.interface import implements import sys import txcas.utils import pem and any relevant context from other files: # Path: txcas/casuser.py # class User(object): # # implements(ICASUser) # # username = None # attribs = None # # def __init__(self, username, attribs): # self.username = username # self.attribs = attribs # # def logout(self): # pass # # Path: txcas/interface.py # class ICASUser(Interface): # # username = Attribute('String username') # attribs = Attribute('List of (attribute, value) tuples.') # # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') # # Path: txcas/settings.py # def get_bool(value, default=False): # if value is None: # return False # value = str(value).strip().lower() # if value in ('y', '1', 't', 'yes', 'true'): # return True # elif value in ('n', '0', 'f', 'no', 'false'): # return False # else: # return default # # def export_settings_to_dict(scp): # settings = {} # for section in scp.sections(): # for option in scp.options(section): # settings.setdefault(section, {})[option] = scp.get(section, option) # return settings # # def load_settings(config_basename, defaults=None, syspath=None, appdir=None): # """ # Load settings. # """ # if defaults is None: # defaults = {} # scp = load_defaults(defaults) # if appdir is None: # appdir = os.path.dirname(os.path.dirname(__file__)) # paths = [] # if syspath is not None: # paths.append(os.path.join(syspath, "%s.cfg" % config_basename)) # paths.append(os.path.expanduser("~/%src" % config_basename)) # paths.append(os.path.join(appdir, "%s.cfg" % config_basename)) # scp.read(paths) # return scp . Output only the next line.
self._startTlsHostName = start_tls_hostname
Given the following code snippet before the placeholder: <|code_start|> def __init__(self, endpointstr, basedn, binddn, bindpw, query_template='(uid=%(username)s)', attribs=None, aliases=None, service_based_attribs=False, start_tls=False, start_tls_hostname=None, start_tls_cacert=None): if attribs is None: attribs = [] # Turn attribs into mapping of attrib_name => alias. if aliases is not None: assert len(aliases) == len(attribs), "[ERROR][LDAP REALM] Number of aliases must match number of attribs." attribs = dict(x for x in zip(attribs, aliases)) else: attribs = dict((k,k) for k in attribs) self._attribs = attribs self._endpointstr = endpointstr self._basedn = basedn self._binddn = binddn self._bindpw = bindpw self._query_template = query_template self._service_based_attribs = service_based_attribs self._startTls = get_bool(start_tls) self._startTlsAuthority = self.getTlsAuthority_(start_tls_cacert) self._startTlsHostName = start_tls_hostname def getTlsAuthority_(self, startTlsCaCert): if startTlsCaCert is None: return None <|code_end|> , predict the next line using imports from the current file: from textwrap import dedent from txcas.casuser import User from txcas.interface import ICASUser, IRealmFactory, IServiceManagerAcceptor from txcas.settings import get_bool, export_settings_to_dict, load_settings from ldaptor.protocols.ldap.ldapclient import LDAPClient from ldaptor.protocols.ldap import ldapsyntax from ldaptor.protocols.ldap.ldaperrors import LDAPInvalidCredentials from twisted.cred.portal import IRealm from twisted.internet import defer, reactor from twisted.internet.endpoints import clientFromString, connectProtocol from twisted.internet.ssl import Certificate, optionsForClientTLS, platformTrust from twisted.plugin import IPlugin from zope.interface import implements import sys import txcas.utils import pem and context including class names, function names, and sometimes code from other files: # Path: txcas/casuser.py # class User(object): # # implements(ICASUser) # # username = None # attribs = None # # def __init__(self, username, attribs): # self.username = username # self.attribs = attribs # # def logout(self): # pass # # Path: txcas/interface.py # class ICASUser(Interface): # # username = Attribute('String username') # attribs = Attribute('List of (attribute, value) tuples.') # # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') # # Path: txcas/settings.py # def get_bool(value, default=False): # if value is None: # return False # value = str(value).strip().lower() # if value in ('y', '1', 't', 'yes', 'true'): # return True # elif value in ('n', '0', 'f', 'no', 'false'): # return False # else: # return default # # def export_settings_to_dict(scp): # settings = {} # for section in scp.sections(): # for option in scp.options(section): # settings.setdefault(section, {})[option] = scp.get(section, option) # return settings # # def load_settings(config_basename, defaults=None, syspath=None, appdir=None): # """ # Load settings. # """ # if defaults is None: # defaults = {} # scp = load_defaults(defaults) # if appdir is None: # appdir = os.path.dirname(os.path.dirname(__file__)) # paths = [] # if syspath is not None: # paths.append(os.path.join(syspath, "%s.cfg" % config_basename)) # paths.append(os.path.expanduser("~/%src" % config_basename)) # paths.append(os.path.join(appdir, "%s.cfg" % config_basename)) # scp.read(paths) # return scp . Output only the next line.
authorities = [str(cert) for cert in pem.parse_file(startTlsCaCert)]
Given the code snippet: <|code_start|> if argstring.strip() != "": argdict = dict((x.split('=') for x in argstring.split(':'))) ldap_settings.update(argdict) missing = txcas.utils.get_missing_args( LDAPRealm.__init__, ldap_settings, ['self']) if len(missing) > 0: sys.stderr.write( "[ERROR][LDAPRealm] " "Missing the following settings: %s" % ', '.join(missing)) sys.stderr.write('\n') sys.exit(1) if 'attribs' in ldap_settings: attribs = ldap_settings['attribs'] attribs = attribs.split(',') ldap_settings['attribs'] = attribs if 'aliases' in ldap_settings: aliases = ldap_settings['aliases'] aliases = aliases.split(',') ldap_settings['aliases'] = aliases if 'service_based_attribs' in ldap_settings: ldap_settings['service_based_attribs'] = get_bool(ldap_settings['service_based_attribs']) if 'start_tls' in ldap_settings: ldap_settings['start_tls'] = get_bool(ldap_settings['start_tls']) txcas.utils.filter_args(LDAPRealm.__init__, ldap_settings, ['self']) buf = ["[CONFIG][LDAPRealm] Settings:"] for k in sorted(ldap_settings.keys()): if k != "bindpw": v = ldap_settings[k] else: v = "*******" <|code_end|> , generate the next line using the imports in this file: from textwrap import dedent from txcas.casuser import User from txcas.interface import ICASUser, IRealmFactory, IServiceManagerAcceptor from txcas.settings import get_bool, export_settings_to_dict, load_settings from ldaptor.protocols.ldap.ldapclient import LDAPClient from ldaptor.protocols.ldap import ldapsyntax from ldaptor.protocols.ldap.ldaperrors import LDAPInvalidCredentials from twisted.cred.portal import IRealm from twisted.internet import defer, reactor from twisted.internet.endpoints import clientFromString, connectProtocol from twisted.internet.ssl import Certificate, optionsForClientTLS, platformTrust from twisted.plugin import IPlugin from zope.interface import implements import sys import txcas.utils import pem and context (functions, classes, or occasionally code) from other files: # Path: txcas/casuser.py # class User(object): # # implements(ICASUser) # # username = None # attribs = None # # def __init__(self, username, attribs): # self.username = username # self.attribs = attribs # # def logout(self): # pass # # Path: txcas/interface.py # class ICASUser(Interface): # # username = Attribute('String username') # attribs = Attribute('List of (attribute, value) tuples.') # # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') # # Path: txcas/settings.py # def get_bool(value, default=False): # if value is None: # return False # value = str(value).strip().lower() # if value in ('y', '1', 't', 'yes', 'true'): # return True # elif value in ('n', '0', 'f', 'no', 'false'): # return False # else: # return default # # def export_settings_to_dict(scp): # settings = {} # for section in scp.sections(): # for option in scp.options(section): # settings.setdefault(section, {})[option] = scp.get(section, option) # return settings # # def load_settings(config_basename, defaults=None, syspath=None, appdir=None): # """ # Load settings. # """ # if defaults is None: # defaults = {} # scp = load_defaults(defaults) # if appdir is None: # appdir = os.path.dirname(os.path.dirname(__file__)) # paths = [] # if syspath is not None: # paths.append(os.path.join(syspath, "%s.cfg" % config_basename)) # paths.append(os.path.expanduser("~/%src" % config_basename)) # paths.append(os.path.join(appdir, "%s.cfg" % config_basename)) # scp.read(paths) # return scp . Output only the next line.
buf.append(" - %s: %s" % (k, v))
Given the code snippet: <|code_start|>#! /usr/bin/env python from __future__ import print_function def custom_login(ticket, service, failed, request): service_lookup = { 'http://127.0.0.1:9801/landing': 'Cool App #1', 'http://127.0.0.1:9802/landing': 'Awesome App #2', 'http://127.0.0.1:9803/landing': 'Super Secure App #3', 'http://127.0.0.1:9804/landing': 'Just Another App #4', } top = dedent('''\ <!DOCTYPE html> <html> <|code_end|> , generate the next line using the imports in this file: import argparse import cgi import sys import txcas.settings import sys from textwrap import dedent from urllib import urlencode from txcas.constants import ( VIEW_LOGIN, VIEW_LOGIN_SUCCESS, VIEW_LOGOUT, VIEW_INVALID_SERVICE, VIEW_ERROR_5XX, VIEW_NOT_FOUND) from txcas.interface import ( IRealmFactory, IServiceManagerFactory, ITicketStoreFactory) from txcas.server import escape_html from klein import Klein from twisted.python import log from twisted.web import microdom from twisted.web.client import getPage from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse from twisted.cred.strcred import ICheckerFactory from txcas.server import ServerApp from twisted.web.resource import Resource from twisted.web.server import Site from twisted.internet import reactor from twisted.python import log and context (functions, classes, or occasionally code) from other files: # Path: txcas/constants.py # VIEW_LOGIN = 0 # # VIEW_LOGIN_SUCCESS = 1 # # VIEW_LOGOUT = 2 # # VIEW_INVALID_SERVICE = 3 # # VIEW_ERROR_5XX = 4 # # VIEW_NOT_FOUND = 5 # # Path: txcas/interface.py # class IRealmFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateRealm(argstring=""): # """ # Create an object that implements IRealm. # """ # # class IServiceManagerFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateServiceManager(argstring=""): # """ # Create an object that implements txcas.IServiceManager # """ # # class ITicketStoreFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateTicketStore(argstring=""): # """ # Create an object that implements ITicketStore. # """ # # Path: txcas/server.py # def escape_html(text): # """Produce entities within text.""" # return "".join(html_escape_table.get(c,c) for c in text) . Output only the next line.
<body>
Predict the next line after this snippet: <|code_start|> if allowed_path == path: return True if not allow_child_paths: return False allowed_parts = allowed_path.split('/')[1:] parts = path.split('/')[1:] for allowed, presented in itertools.izip(allowed_parts, parts): if allowed == '': return True if allowed != presented: return False return True class JSONServiceManagerFactory(object): """ """ implements(IPlugin, IServiceManagerFactory) tag = "json_service_manager" opt_help = dedent('''\ A service manager configured in an external JSON file. ''') opt_usage = '''A colon-separated key=value list.''' <|code_end|> using the current file's imports: import cgi import itertools import json import sys import urlparse import txcas.settings from textwrap import dedent from txcas.interface import IServiceManager, IServiceManagerFactory from twisted.internet import reactor from twisted.plugin import IPlugin from twisted.python import log from twisted.python.filepath import FilePath from zope.interface import implements and any relevant context from other files: # Path: txcas/interface.py # class IServiceManager(Interface): # # def getMatchingService(service): # """ # Return the entry for the first matching service or None. # """ # # def isValidService(service): # """ # Returns True if the service is valid; False otherwise. # """ # # def isSSOService(service): # """ # Returns True if the service participates in SSO. # Returns False if the service will only accept primary credentials. # """ # # class IServiceManagerFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateServiceManager(argstring=""): # """ # Create an object that implements txcas.IServiceManager # """ . Output only the next line.
def generateServiceManager(self, argstring=""):
Given snippet: <|code_start|> # Standard library from __future__ import print_function # Application modules # External modules class InMemoryTicketStoreFactory(object): implements(IPlugin, ITicketStoreFactory) tag = "memory_ticket_store" opt_help = dedent('''\ A ticket store that manages all CAS tickets in local memory. It is easy to configure and quick to retreive and modify tickets. It is constained to a single process, however, so no high availability. Also, any tickets in the store when the CAS process is stopped are lost. Valid options include: - lt_lifespan - st_lifespan - pt_lifespan - tgt_lifespan - pgt_lifespan <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import random import string import sys import uuid import txcas.settings import treq from textwrap import dedent from xml.sax.saxutils import escape as xml_escape from txcas.exceptions import ( CASError, InvalidTicket, InvalidService, NotSSOService, InvalidTicketSpec) from txcas.http import ( createNonVerifyingHTTPClient, createVerifyingHTTPClient) from txcas.interface import ( ITicketStore, ITicketStoreFactory, IServiceManagerAcceptor) from txcas.urls import are_urls_equal from twisted.internet import defer from twisted.plugin import IPlugin from twisted.python import log from twisted.web.http_headers import Headers from zope.interface import implements from twisted.internet import reactor and context: # Path: txcas/exceptions.py # class CASError(Exception): # pass # # class InvalidTicket(CASError): # pass # # class InvalidService(CASError): # pass # # class NotSSOService(CASError): # pass # # class InvalidTicketSpec(InvalidTicket): # pass # # Path: txcas/http.py # def createNonVerifyingHTTPClient(reactor, agent_kwds=None, **kwds): # agent_kwds = normalizeDict_(agent_kwds) # agent_kwds['contextFactory'] = NonVerifyingContextFactory() # return HTTPClient(Agent(reactor, **agent_kwds), **kwds) # # def createVerifyingHTTPClient( # reactor, # agent_kwds=None, # policy_factory=BrowserLikePolicyForHTTPS, # **kwds): # agent_kwds = normalizeDict_(agent_kwds) # agent_kwds['contextFactory'] = policy_factory() # return HTTPClient(Agent(reactor, **agent_kwds), **kwds) # # Path: txcas/interface.py # class ITicketStore(Interface): # # lt_lifespan = Attribute('LT lifespan in seconds.') # st_lifespan = Attribute('ST lifespan in seconds.') # pt_lifespan = Attribute('PT lifespan in seconds.') # tgt_lifespan = Attribute('TGC lifespan in seconds.') # pgt_lifespan = Attribute('PGT lifespan in seconds.') # ticket_size = Attribute('Size of ticket ID in characters.') # # isSSOService = Attribute( # 'Function that accepts a service and returns True if' \ # 'the service may participate in SSO.') # # def mkLoginTicket(service): # """ # Make a login ticket. # # @type service: C{string} # @param service: The service URL. # # @rtpe: C{string} # @return: ticket ID # """ # # def useLoginTicket(ticket, service): # """ # Consume a login ticket. # Returns a dict with key `service`. # """ # # def mkServiceTicket(service, tgt, primaryCredentials): # """ # """ # # def useServiceTicket(ticket, service, requirePrimaryCredentials=False): # """ # """ # # def mkProxyTicket(service, pgt): # """ # """ # # def useServiceOrProxyTicket(ticket, service, requirePrimaryCredentials=False): # """ # """ # # def mkProxyGrantingTicket(service, ticket, tgt, pgturl, proxy_chain=None): # """ # """ # # def mkTicketGrantingCookie(avatar_id): # """ # """ # # def useTicketGrantingCookie(tgt, service): # """ # """ # # def expireTGT(tgt): # """ # """ # # def register_ticket_expiration_callback(callback): # """ # Register a function to be called when a ticket is expired. # The function should take 3 arguments, (ticket, data, explicit). # `ticket` is the ticket ID, `data` is a dict of the ticket data, # and `explicit` is a boolean that indicates whether the ticket # was explicitly expired (e.g. /logout, ST/PT validation) or # implicitly expired (e.g. timeout or parent ticket expired). # """ # # class ITicketStoreFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateTicketStore(argstring=""): # """ # Create an object that implements ITicketStore. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') # # Path: txcas/urls.py # def are_urls_equal(url0, url1): # p0 = urlparse(url0) # p1 = urlparse(url1) # scheme0 = p0.scheme.lower() # scheme1 = p1.scheme.lower() # if scheme0 != scheme1: # return False # netloc0 = normalize_netloc(scheme0, p0.netloc) # netloc1 = normalize_netloc(scheme1, p1.netloc) # if netloc0 != netloc1: # return False # if p0.path != p1.path: # return False # if p0.params != p1.params: # return False # if p0.fragment != p1.fragment: # return False # qs0 = set(parse_qsl(p0.query)) # qs1 = set(parse_qsl(p1.query)) # if qs0 != qs1: # return False # return True which might include code, classes, or functions. Output only the next line.
- ticket_size
Using the snippet: <|code_start|># Standard library from __future__ import print_function # Application modules # External modules class InMemoryTicketStoreFactory(object): implements(IPlugin, ITicketStoreFactory) tag = "memory_ticket_store" opt_help = dedent('''\ A ticket store that manages all CAS tickets in local memory. It is easy to configure and quick to retreive and modify tickets. It is constained to a single process, however, so no high availability. Also, any tickets in the store when the CAS process is stopped are lost. Valid options include: - lt_lifespan - st_lifespan - pt_lifespan - tgt_lifespan - pgt_lifespan - ticket_size - verify_cert ''') opt_usage = '''A colon-separated key=value list.''' def generateTicketStore(self, argstring=""): scp = txcas.settings.load_settings('cas', syspath='/etc/cas') settings = txcas.settings.export_settings_to_dict(scp) <|code_end|> , determine the next line of code. You have imports: import datetime import random import string import sys import uuid import txcas.settings import treq from textwrap import dedent from xml.sax.saxutils import escape as xml_escape from txcas.exceptions import ( CASError, InvalidTicket, InvalidService, NotSSOService, InvalidTicketSpec) from txcas.http import ( createNonVerifyingHTTPClient, createVerifyingHTTPClient) from txcas.interface import ( ITicketStore, ITicketStoreFactory, IServiceManagerAcceptor) from txcas.urls import are_urls_equal from twisted.internet import defer from twisted.plugin import IPlugin from twisted.python import log from twisted.web.http_headers import Headers from zope.interface import implements from twisted.internet import reactor and context (class names, function names, or code) available: # Path: txcas/exceptions.py # class CASError(Exception): # pass # # class InvalidTicket(CASError): # pass # # class InvalidService(CASError): # pass # # class NotSSOService(CASError): # pass # # class InvalidTicketSpec(InvalidTicket): # pass # # Path: txcas/http.py # def createNonVerifyingHTTPClient(reactor, agent_kwds=None, **kwds): # agent_kwds = normalizeDict_(agent_kwds) # agent_kwds['contextFactory'] = NonVerifyingContextFactory() # return HTTPClient(Agent(reactor, **agent_kwds), **kwds) # # def createVerifyingHTTPClient( # reactor, # agent_kwds=None, # policy_factory=BrowserLikePolicyForHTTPS, # **kwds): # agent_kwds = normalizeDict_(agent_kwds) # agent_kwds['contextFactory'] = policy_factory() # return HTTPClient(Agent(reactor, **agent_kwds), **kwds) # # Path: txcas/interface.py # class ITicketStore(Interface): # # lt_lifespan = Attribute('LT lifespan in seconds.') # st_lifespan = Attribute('ST lifespan in seconds.') # pt_lifespan = Attribute('PT lifespan in seconds.') # tgt_lifespan = Attribute('TGC lifespan in seconds.') # pgt_lifespan = Attribute('PGT lifespan in seconds.') # ticket_size = Attribute('Size of ticket ID in characters.') # # isSSOService = Attribute( # 'Function that accepts a service and returns True if' \ # 'the service may participate in SSO.') # # def mkLoginTicket(service): # """ # Make a login ticket. # # @type service: C{string} # @param service: The service URL. # # @rtpe: C{string} # @return: ticket ID # """ # # def useLoginTicket(ticket, service): # """ # Consume a login ticket. # Returns a dict with key `service`. # """ # # def mkServiceTicket(service, tgt, primaryCredentials): # """ # """ # # def useServiceTicket(ticket, service, requirePrimaryCredentials=False): # """ # """ # # def mkProxyTicket(service, pgt): # """ # """ # # def useServiceOrProxyTicket(ticket, service, requirePrimaryCredentials=False): # """ # """ # # def mkProxyGrantingTicket(service, ticket, tgt, pgturl, proxy_chain=None): # """ # """ # # def mkTicketGrantingCookie(avatar_id): # """ # """ # # def useTicketGrantingCookie(tgt, service): # """ # """ # # def expireTGT(tgt): # """ # """ # # def register_ticket_expiration_callback(callback): # """ # Register a function to be called when a ticket is expired. # The function should take 3 arguments, (ticket, data, explicit). # `ticket` is the ticket ID, `data` is a dict of the ticket data, # and `explicit` is a boolean that indicates whether the ticket # was explicitly expired (e.g. /logout, ST/PT validation) or # implicitly expired (e.g. timeout or parent ticket expired). # """ # # class ITicketStoreFactory(Interface): # # tag = Attribute('String used to identify the plugin factory.') # opt_help = Attribute('String description of the plugin.') # opt_usage = Attribute('String describes how to provide arguments for factory.') # # def generateTicketStore(argstring=""): # """ # Create an object that implements ITicketStore. # """ # # class IServiceManagerAcceptor(Interface): # # service_manager = Attribute('None or a reference to the current service manager plugin.') # # Path: txcas/urls.py # def are_urls_equal(url0, url1): # p0 = urlparse(url0) # p1 = urlparse(url1) # scheme0 = p0.scheme.lower() # scheme1 = p1.scheme.lower() # if scheme0 != scheme1: # return False # netloc0 = normalize_netloc(scheme0, p0.netloc) # netloc1 = normalize_netloc(scheme1, p1.netloc) # if netloc0 != netloc1: # return False # if p0.path != p1.path: # return False # if p0.params != p1.params: # return False # if p0.fragment != p1.fragment: # return False # qs0 = set(parse_qsl(p0.query)) # qs1 = set(parse_qsl(p1.query)) # if qs0 != qs1: # return False # return True . Output only the next line.
ts_settings = settings.get('CAS', {})
Continue the code snippet: <|code_start|> if result is None: result = fn(*args, **kwargs) cache.set(cache_key, result, expiration) return result return wrapper return cache_page_mesto_dc @gzip_page @never_cache # zabranime prohlizeci cachovat si kml @cache_page_mesto(24 * 60 * 60) # cachujeme view v memcached s platnosti 24h def kml_view(request, nazev_vrstvy): # najdeme vrstvu podle slugu. pokud neexistuje, vyhodime 404 v = get_object_or_404(OverlayLayer, slug=nazev_vrstvy, status__show=True) # vsechny body co jsou v teto vrstve a jsou zapnute points = Poi.visible.filter(marker__layer=v) return render_to_kml( "webmap/gis/kml/layer.kml", { 'places': points, 'site': get_current_site(request).domain, }, ) @gzip_page def popup_view(request, poi_id): poi = get_object_or_404(Poi, id=poi_id) return render( <|code_end|> . Use current file imports: import json import pathlib from django.conf import settings from django.contrib.gis.shortcuts import render_to_kml from django.contrib.sites.shortcuts import get_current_site from django.core.cache import cache from django.http import JsonResponse from django.shortcuts import get_object_or_404, render from django.views.decorators.cache import cache_page, never_cache from django.views.decorators.csrf import csrf_protect from django.views.decorators.gzip import gzip_page from django.views.generic import TemplateView from django.core.cache import cache from django.utils import timezone from django_comments.models import Comment from django_q.models import Success from django_q.tasks import async_task, result from webmap.models import Legend, MapPreset, Marker, OverlayLayer from .models import Mesto, Poi from. utils import check_download_cykliste_sobe_layer_job and context (classes, functions, or code) from other files: # Path: apps/cyklomapa/models.py # class Mesto(models.Model): # "Mesto - vyber na zaklade subdomeny" # aktivni = models.BooleanField(default=True, verbose_name=u"Aktivní", help_text=u"Město je přístupné pro veřejnost") # vyhledavani = models.BooleanField(verbose_name=u"Vyhledávač", default=True, help_text=u"Vyhledávání je aktivované") # zoom = models.PositiveIntegerField(default=13, help_text=u"Zoomlevel, ve kterém se zobrazí mapa po načtení") # maxzoom = models.PositiveIntegerField(default=18, help_text=u"Maximální zoomlevel mapy") # uvodni_zprava = models.TextField(null=True, blank=True, verbose_name=u"Úvodní zpráva", help_text=u"Zpráva, která se zobrazí v levém panelu") # # geom = models.PointField(verbose_name=u"Poloha středu", srid=4326) # sektor = models.OneToOneField(Sector, null=True, on_delete=models.CASCADE) # # class Meta: # permissions = [ # ("can_edit_all_fields", "Can edit all field"), # ] # verbose_name_plural = "města" # # def __str__(self): # return self.sektor.name # # class Poi(Poi): # class Meta: # proxy = True # # def get_absolute_url(self): # return "#misto=%s_%i/" % (self.marker.layer.slug, self.id) . Output only the next line.
request,
Given snippet: <|code_start|># views.py @gzip_page @cache_page(24 * 60 * 60) # cachujeme view v memcached s platnosti 24h @csrf_protect def mapa_view(request, poi_id=None): vrstvy = OverlayLayer.objects.filter(status__show=True) # volitelne poi_id zadane mape jako bod, na ktery se ma zazoomovat center_poi = None if poi_id: try: center_poi = Poi.visible.get(id=poi_id) except Poi.DoesNotExist: pass context = { 'vrstvy': vrstvy, 'center_poi': center_poi, 'mesto': request.mesto, 'presets': MapPreset.objects.filter(status__show=True), 'mesta': Mesto.objects.filter(aktivni=True).order_by('sektor__name').all(), <|code_end|> , continue by predicting the next line. Consider current file imports: import json import pathlib from django.conf import settings from django.contrib.gis.shortcuts import render_to_kml from django.contrib.sites.shortcuts import get_current_site from django.core.cache import cache from django.http import JsonResponse from django.shortcuts import get_object_or_404, render from django.views.decorators.cache import cache_page, never_cache from django.views.decorators.csrf import csrf_protect from django.views.decorators.gzip import gzip_page from django.views.generic import TemplateView from django.core.cache import cache from django.utils import timezone from django_comments.models import Comment from django_q.models import Success from django_q.tasks import async_task, result from webmap.models import Legend, MapPreset, Marker, OverlayLayer from .models import Mesto, Poi from. utils import check_download_cykliste_sobe_layer_job and context: # Path: apps/cyklomapa/models.py # class Mesto(models.Model): # "Mesto - vyber na zaklade subdomeny" # aktivni = models.BooleanField(default=True, verbose_name=u"Aktivní", help_text=u"Město je přístupné pro veřejnost") # vyhledavani = models.BooleanField(verbose_name=u"Vyhledávač", default=True, help_text=u"Vyhledávání je aktivované") # zoom = models.PositiveIntegerField(default=13, help_text=u"Zoomlevel, ve kterém se zobrazí mapa po načtení") # maxzoom = models.PositiveIntegerField(default=18, help_text=u"Maximální zoomlevel mapy") # uvodni_zprava = models.TextField(null=True, blank=True, verbose_name=u"Úvodní zpráva", help_text=u"Zpráva, která se zobrazí v levém panelu") # # geom = models.PointField(verbose_name=u"Poloha středu", srid=4326) # sektor = models.OneToOneField(Sector, null=True, on_delete=models.CASCADE) # # class Meta: # permissions = [ # ("can_edit_all_fields", "Can edit all field"), # ] # verbose_name_plural = "města" # # def __str__(self): # return self.sektor.name # # class Poi(Poi): # class Meta: # proxy = True # # def get_absolute_url(self): # return "#misto=%s_%i/" % (self.marker.layer.slug, self.id) which might include code, classes, or functions. Output only the next line.
'cyclestreetsapikey': settings.CYCLESTREETS_API_KEY,
Predict the next line for this snippet: <|code_start|> # Register your models here. class ScopesDefinitionAdminInline(admin.TabularInline): model = Scopes.scopes.through class GroupAdminInline(admin.TabularInline): model = Scopes.group.through @admin.register(Scopes) class ScopesAdmin(admin.ModelAdmin): list_display = ('get_scopes', 'description') exclude = ('group', 'scopes') inlines = (GroupAdminInline, ScopesDefinitionAdminInline,) <|code_end|> with the help of current file imports: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Scopes, ScopesDefinition and context from other files: # Path: apps/api/models.py # class Scopes(models.Model): # group = models.ManyToManyField(Group) # scopes = models.ManyToManyField(ScopesDefinition) # description = models.CharField(max_length=500) # # def __str__(self): # return ' '.join( # list( # self.scopes.all().values_list('scope', flat=True), # ), # ) # # class ScopesDefinition(models.Model): # scope = models.CharField(max_length=300) # description = models.CharField(max_length=500) # # def __str__(self): # return self.scope , which may contain function names, class names, or code. Output only the next line.
def get_scopes(self, obj):
Based on the snippet: <|code_start|> # Register your models here. class ScopesDefinitionAdminInline(admin.TabularInline): model = Scopes.scopes.through class GroupAdminInline(admin.TabularInline): model = Scopes.group.through @admin.register(Scopes) class ScopesAdmin(admin.ModelAdmin): list_display = ('get_scopes', 'description') exclude = ('group', 'scopes') inlines = (GroupAdminInline, ScopesDefinitionAdminInline,) def get_scopes(self, obj): <|code_end|> , predict the immediate next line with the help of imports: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Scopes, ScopesDefinition and context (classes, functions, sometimes code) from other files: # Path: apps/api/models.py # class Scopes(models.Model): # group = models.ManyToManyField(Group) # scopes = models.ManyToManyField(ScopesDefinition) # description = models.CharField(max_length=500) # # def __str__(self): # return ' '.join( # list( # self.scopes.all().values_list('scope', flat=True), # ), # ) # # class ScopesDefinition(models.Model): # scope = models.CharField(max_length=300) # description = models.CharField(max_length=500) # # def __str__(self): # return self.scope . Output only the next line.
return ' '.join(
Given the code snippet: <|code_start|> def process_request(self, request): request.domain = request.META['HTTP_HOST'] request.subdomain = '' request.mesto = None parts = request.domain.split('.') if len(parts) in (2, 3, 4): request.subdomain = parts[0] request.domain = '.'.join(parts[1:]) else: # fallback na Prahu request.subdomain = 'mapa' # umoznime nastavit subdomenu pomoci settings request.subdomain = getattr(settings, 'FORCE_SUBDOMAIN', request.subdomain) if (os.getenv('DJANGO_SETTINGS_MODULE') in settings.DEV_SETTINGS): request.subdomain = 'testing-sector' # najdeme mesto podle slugu. pokud neexistuje, vyhodime 404 try: request.mesto = Mesto.objects.get(sektor__slug=request.subdomain) except Mesto.DoesNotExist: request.mesto = None if django.VERSION >= (1, 10): class SubdomainsMiddleware( <|code_end|> , generate the next line using the imports in this file: import os import django from django.conf import settings from ..models import Mesto from django.utils import deprecation and context (functions, classes, or occasionally code) from other files: # Path: apps/cyklomapa/models.py # class Mesto(models.Model): # "Mesto - vyber na zaklade subdomeny" # aktivni = models.BooleanField(default=True, verbose_name=u"Aktivní", help_text=u"Město je přístupné pro veřejnost") # vyhledavani = models.BooleanField(verbose_name=u"Vyhledávač", default=True, help_text=u"Vyhledávání je aktivované") # zoom = models.PositiveIntegerField(default=13, help_text=u"Zoomlevel, ve kterém se zobrazí mapa po načtení") # maxzoom = models.PositiveIntegerField(default=18, help_text=u"Maximální zoomlevel mapy") # uvodni_zprava = models.TextField(null=True, blank=True, verbose_name=u"Úvodní zpráva", help_text=u"Zpráva, která se zobrazí v levém panelu") # # geom = models.PointField(verbose_name=u"Poloha středu", srid=4326) # sektor = models.OneToOneField(Sector, null=True, on_delete=models.CASCADE) # # class Meta: # permissions = [ # ("can_edit_all_fields", "Can edit all field"), # ] # verbose_name_plural = "města" # # def __str__(self): # return self.sektor.name . Output only the next line.
deprecation.MiddlewareMixin,
Based on the snippet: <|code_start|> sitemaps = { 'pages': NamesSitemap(['mapa_view']), 'pois': PoiSitemap(), } urlpatterns = [ url(r'^$', mapa_view, name="mapa_view"), url(r'^misto/(?P<poi_id>\d+)/$', mapa_view, name="mapa_view"), url(r'^kml/([-\w]+)/$', kml_view, name="kml_view"), url(r'^cs-layer/$', get_cykliste_sobe_layer, name="get_cykliste_sobe_layer"), url(r'^popup/(\d+)/$', popup_view, name="popup_view"), url(r'^uzavirky/$', uzavirky_view, name="uzavirky_view"), url(r'^uzavirky/feed/$', UzavirkyFeed(), name="uzavirky_feed"), url(r'^novinky/feed/$', NovinkyFeed(), name="novinky_feed"), url(r'^metro/$', metro_view, name="metro_view"), url(r'^znacky/$', znacky_view, name="znacky_view"), url(r'^panel-mapa/$', PanelMapaView.as_view(), name="panel_mapa_view"), url(r'^panel-informace/$', PanelInformaceView.as_view(), name="panel_informace_view"), url(r'^panel-hledani/$', PanelHledaniView.as_view(), name="panel_hledani_view"), url(r'^popup-list/$', PopupListView.as_view(), name="popup-list"), url(r'^comments/', include('fluent_comments.urls')), url(r'^comments/feeds/latest/$', LatestCommentFeed(), name="latest_comments_feed"), url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /popup-list\nDisallow: /popup/*\nUser-agent: LinkChecker\nAllow:", content_type="text/plain")), url(r'^sitemap\.xml$', cache_page(24 * 60 * 60)(sitemap), {'sitemaps': sitemaps}, name='sitemap'), # Redirect from most frequent error links url(r'^jak-na-to$', RedirectView.as_view(url='http://prahounakole.cz/jak-do-mesta/deset-zasad-jak-zacit/', permanent=True)), <|code_end|> , predict the immediate next line with the help of imports: from cyklomapa.feeds import NovinkyFeed, UzavirkyFeed from cyklomapa.views import ( PanelHledaniView, PanelInformaceView, PanelMapaView, PopupListView, kml_view, mapa_view, metro_view, popup_view, uzavirky_view, znacky_view, get_cykliste_sobe_layer ) from django.conf import settings from django.conf.urls import include, url from django.contrib.sitemaps.views import sitemap from django.http import HttpResponse from django.views.decorators.cache import cache_page from django.views.generic.base import RedirectView from django_comments.feeds import LatestCommentFeed from httpproxy.views import HttpProxy from .sitemap import NamesSitemap, PoiSitemap and context (classes, functions, sometimes code) from other files: # Path: apps/cyklomapa/sitemap.py # class NamesSitemap(sitemaps.Sitemap): # def __init__(self, names): # self.names = names # # def items(self): # return self.names # # def changefreq(self, obj): # return 'daily' # # def lastmod(self, obj): # return datetime.datetime.now() # # def location(self, obj): # return reverse(obj) # # class PoiSitemap(sitemaps.Sitemap): # def items(self): # return Poi.visible.all() # # def changefreq(self, obj): # return 'weekly' # # def lastmod(self, obj): # return obj.last_modification # # def location(self, obj): # return "%s#misto=%s_%s" % (reverse("mapa_view", kwargs={"poi_id": obj.pk}), obj.marker.layer.slug, obj.pk) . Output only the next line.
]
Predict the next line for this snippet: <|code_start|> sitemaps = { 'pages': NamesSitemap(['mapa_view']), 'pois': PoiSitemap(), <|code_end|> with the help of current file imports: from cyklomapa.feeds import NovinkyFeed, UzavirkyFeed from cyklomapa.views import ( PanelHledaniView, PanelInformaceView, PanelMapaView, PopupListView, kml_view, mapa_view, metro_view, popup_view, uzavirky_view, znacky_view, get_cykliste_sobe_layer ) from django.conf import settings from django.conf.urls import include, url from django.contrib.sitemaps.views import sitemap from django.http import HttpResponse from django.views.decorators.cache import cache_page from django.views.generic.base import RedirectView from django_comments.feeds import LatestCommentFeed from httpproxy.views import HttpProxy from .sitemap import NamesSitemap, PoiSitemap and context from other files: # Path: apps/cyklomapa/sitemap.py # class NamesSitemap(sitemaps.Sitemap): # def __init__(self, names): # self.names = names # # def items(self): # return self.names # # def changefreq(self, obj): # return 'daily' # # def lastmod(self, obj): # return datetime.datetime.now() # # def location(self, obj): # return reverse(obj) # # class PoiSitemap(sitemaps.Sitemap): # def items(self): # return Poi.visible.all() # # def changefreq(self, obj): # return 'weekly' # # def lastmod(self, obj): # return obj.last_modification # # def location(self, obj): # return "%s#misto=%s_%s" % (reverse("mapa_view", kwargs={"poi_id": obj.pk}), obj.marker.layer.slug, obj.pk) , which may contain function names, class names, or code. Output only the next line.
}
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- class UzavirkyFeed(Feed): title = "Městem na kole - aktuální uzavírky" link = "/" description = u"Aktuální uzavírky cyklostezek a cyklotras" def get_object(self, request): return request.mesto def items(self, obj): return Poi.objects.filter(geom__contained=obj.sektor.geom, status__show=True, marker__slug='vyluka_akt') <|code_end|> , generate the next line using the imports in this file: from django.contrib.syndication.views import Feed from .models import Poi and context (functions, classes, or occasionally code) from other files: # Path: apps/cyklomapa/models.py # class Poi(Poi): # class Meta: # proxy = True # # def get_absolute_url(self): # return "#misto=%s_%i/" % (self.marker.layer.slug, self.id) . Output only the next line.
def item_pubdate(self, item):
Next line prediction: <|code_start|> "windchill_C": "3.55555555556", "appTemp_C": "1.26842313302", "outTemp_C": "3.55555555556", "windGustDir": "275.0", "extraAlarm1": "0.0", "extraAlarm2": "0.0", "extraAlarm3": "0.0", "extraAlarm4": "0.0", "extraAlarm5": "0.0", "extraAlarm6": "0.0", "extraAlarm7": "0.0", "extraAlarm8": "0.0", "humidex_C": "3.55555555556", "rain24_cm": "0.88000000022", "rxCheckPercent": "87.9791666667", "hourRain_cm": "0.0", "inTemp_C": "26.8333333333", "watertemp": "8.33333333333", "trendIcon": "59.7350993377", "soilLeafAlarm2": "0.0", "soilLeafAlarm3": "0.0", "usUnits": "16.0", "soilLeafAlarm1": "0.0", "leafWet4": "0.0", "txBatteryStatus": "0.0", "yearET": "4.88", "monthRain_cm": "2.94000000074", "UV": "0.0", "rainRate_cm_per_hour": "0.0", "dayET": "0.0", <|code_end|> . Use current file imports: (import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep) and context including class names, function names, or small code snippets from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
"dateTime": "1492467300.0",
Given the code snippet: <|code_start|> "extraAlarm1": "0.0", "extraAlarm2": "0.0", "extraAlarm3": "0.0", "extraAlarm4": "0.0", "extraAlarm5": "0.0", "extraAlarm6": "0.0", "extraAlarm7": "0.0", "extraAlarm8": "0.0", "humidex_C": "3.55555555556", "rain24_cm": "0.88000000022", "rxCheckPercent": "87.9791666667", "hourRain_cm": "0.0", "inTemp_C": "26.8333333333", "watertemp": "8.33333333333", "trendIcon": "59.7350993377", "soilLeafAlarm2": "0.0", "soilLeafAlarm3": "0.0", "usUnits": "16.0", "soilLeafAlarm1": "0.0", "leafWet4": "0.0", "txBatteryStatus": "0.0", "yearET": "4.88", "monthRain_cm": "2.94000000074", "UV": "0.0", "rainRate_cm_per_hour": "0.0", "dayET": "0.0", "dateTime": "1492467300.0", "windDir": "283.55437192", "stormRain_cm": "1.72000000043", "ET_cm": "0.0", <|code_end|> , generate the next line using the imports in this file: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep and context (functions, classes, or occasionally code) from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
"sunset": "1492538940.0",
Given snippet: <|code_start|> # Data payload captured from a Vantage Pro 2 weather station. data = { "windSpeed10_kph": "5.78725803977", "monthET": "1.32", "highUV": "0.0", "cloudbase_meter": "773.082217509", "leafTemp1_C": "8.33333333333", "rainAlarm": "0.0", "pressure_mbar": "948.046280104", "rain_cm": "0.0", "highRadiation": "0.0", "interval_minute": "5.0", "barometer_mbar": "1018.35464712", "yearRain_cm": "17.2000000043", "consBatteryVoltage_volt": "4.72", "dewpoint_C": "2.07088485785", "insideAlarm": "0.0", "inHumidity": "29.0", "soilLeafAlarm4": "0.0", "sunrise": "1492489200.0", "windGust_kph": "9.65608800006", "heatindex_C": "3.55555555556", "dayRain_cm": "0.0", "lowOutTemp": "38.3", "outsideAlarm1": "0.0", "forecastIcon": "8.0", "outsideAlarm2": "0.0", "windSpeed_kph": "3.95409343049", "forecastRule": "40.0", <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep and context: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) which might include code, classes, or functions. Output only the next line.
"windrun_km": "1.07449640224",
Based on the snippet: <|code_start|> "extraAlarm8": "0.0", "humidex_C": "3.55555555556", "rain24_cm": "0.88000000022", "rxCheckPercent": "87.9791666667", "hourRain_cm": "0.0", "inTemp_C": "26.8333333333", "watertemp": "8.33333333333", "trendIcon": "59.7350993377", "soilLeafAlarm2": "0.0", "soilLeafAlarm3": "0.0", "usUnits": "16.0", "soilLeafAlarm1": "0.0", "leafWet4": "0.0", "txBatteryStatus": "0.0", "yearET": "4.88", "monthRain_cm": "2.94000000074", "UV": "0.0", "rainRate_cm_per_hour": "0.0", "dayET": "0.0", "dateTime": "1492467300.0", "windDir": "283.55437192", "stormRain_cm": "1.72000000043", "ET_cm": "0.0", "sunset": "1492538940.0", "highOutTemp": "38.4", "radiation_Wpm2": "0.0" } @pytest_twisted.inlineCallbacks <|code_end|> , predict the immediate next line with the help of imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep and context (classes, functions, sometimes code) from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
@pytest.mark.mqtt
Using the snippet: <|code_start|> "dewpoint_C": "2.07088485785", "insideAlarm": "0.0", "inHumidity": "29.0", "soilLeafAlarm4": "0.0", "sunrise": "1492489200.0", "windGust_kph": "9.65608800006", "heatindex_C": "3.55555555556", "dayRain_cm": "0.0", "lowOutTemp": "38.3", "outsideAlarm1": "0.0", "forecastIcon": "8.0", "outsideAlarm2": "0.0", "windSpeed_kph": "3.95409343049", "forecastRule": "40.0", "windrun_km": "1.07449640224", "outHumidity": "90.0", "stormStart": "1492207200.0", "inDewpoint": "45.1231125123", "altimeter_mbar": "1016.62778614", "windchill_C": "3.55555555556", "appTemp_C": "1.26842313302", "outTemp_C": "3.55555555556", "windGustDir": "275.0", "extraAlarm1": "0.0", "extraAlarm2": "0.0", "extraAlarm3": "0.0", "extraAlarm4": "0.0", "extraAlarm5": "0.0", "extraAlarm6": "0.0", "extraAlarm7": "0.0", <|code_end|> , determine the next line of code. You have imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep and context (class names, function names, or code) available: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
"extraAlarm8": "0.0",
Using the snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) @pytest_twisted.inlineCallbacks @pytest.mark.mqtt <|code_end|> , determine the next line of code. You have imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep, mqtt_sensor and context (class names, function names, or code) available: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) # # def mqtt_sensor(topic, payload): # # logger.info('MQTT: Submitting reading') # # # When running on CI (GHA), run ``mosquitto_pub`` from Docker image. # # https://stackoverflow.com/questions/24319662 # if os.environ.get("CI"): # if sys.platform == "linux": # mosquitto_pub = "docker run --rm --network=host eclipse-mosquitto:1.6 mosquitto_pub -h localhost" # elif sys.platform == "darwin": # mosquitto_pub = "docker run --rm eclipse-mosquitto:1.6 mosquitto_pub -h host.docker.internal" # else: # raise NotImplementedError("Invoking 'mosquitto_pub' through Docker on '{}' not supported yet".format(sys.platform)) # else: # mosquitto_pub = "mosquitto_pub -h localhost" # command = "{mosquitto_pub} -t '{topic}' -m '{payload}'".format(mosquitto_pub=mosquitto_pub, topic=topic, payload=payload) # # logger.info('Running command {}'.format(command)) # exitcode = os.system(command) # if exitcode != 0: # raise ChildProcessError("Invoking command failed: {command}. Exit code: {exitcode}".format(command=command, exitcode=exitcode)) . Output only the next line.
def test_mqtt_to_influxdb_json_single(machinery, create_influxdb, reset_influxdb):
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) @pytest_twisted.inlineCallbacks @pytest.mark.mqtt @pytest.mark.homie <|code_end|> , generate the next line using the imports in this file: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep and context (functions, classes, or occasionally code) from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
def test_mqtt_homie(machinery, create_influxdb, reset_influxdb):
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) @pytest_twisted.inlineCallbacks @pytest.mark.mqtt <|code_end|> . Use current file imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_sensors, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep and context (classes, functions, or code) from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
@pytest.mark.homie
Here is a snippet: <|code_start|>PirMotionDetector = BinaryInputPort PrivacyButton = BinaryInputPort SignalLight = BinaryOutputPort OperatorPresenceIndicator = BinaryTopicSignal class FeatureBase(object): # port allocation PORT_LED = 'P8_13' PORT_PRIVACY_BUTTON = 'P8_15' PORT_PIR_SENSOR = 'P8_19' def __init__(self, node_id, bus, event_filters=None): self.node_id = node_id self.bus = bus self.event_filters = event_filters self.state = None @staticmethod def state_for_display(state): return state and 'enabled' or 'disabled' def run_filters(self, state): if self.event_filters: for event_filter in self.event_filters: state = event_filter(state) return state def publish(self, name, data): <|code_end|> . Write the next line using the current file imports: from kotori.vendor.ilaundry.node.bricks import BinaryInputPort, BinaryOutputPort, TimedBinarySemaphore, Blinker, BinaryTopicSignal and context from other files: # Path: kotori/vendor/ilaundry/node/bricks.py # class BinaryInputPort(object): # # def __init__(self, portname, signal=None): # self.portname = portname # self.signal = signal # # # detect edge on port # self.gpio = GpioInput(self.portname, self.sensor_on) # # def sensor_on(self, port): # print("DEBUG: Port {0} EVENT".format(self.portname)) # # # signal sensor-on # if self.signal: # self.signal.set(True) # # # currently defunct # """ # def sensor_off(self, port): # print "SENSOR OFF:", port # # # signal sensor-off # if self.callback: # self.callback(False) # """ # # class BinaryOutputPort(object): # # # TODO: handle different ports, not only GPIO # # #HIGH = 1 # #LOW = 2 # #BLINK = 3 # # def __init__(self, portname): # self.portname = portname # #self.flavor = flavor or self.HIGH # self.gpio = GpioOutput(self.portname) # # #self.modifier = modifier # # def set(self, *args, **kwargs): # print("DEBUG: Port {0} ON".format(self.portname)) # self.gpio.on() # # # signal gpio port # #if self.flavor == self.HIGH: # #elif self.flavor == self.BLINK: # # def unset(self): # print("DEBUG: Port {0} OFF".format(self.portname)) # # #self.transition_stop() # # # signal gpio port # self.gpio.off() # # class TimedBinarySemaphore(object): # # def __init__(self, holdtime=None, callback=None): # self.holdtime = holdtime # self.callback = callback # self.timer = None # # def set(self, *args, **kwargs): # #print "SEMAPHORE SET: ", self.port # # # signal actor-on # if self.callback: # self.callback(True, *args, **kwargs) # # # start/reset timer for motion-off signal # if self.holdtime: # #print "SEMAPHORE SET: ", self.port, "holding for {0} seconds".format(self.holdtime) # if self.timer and not self.timer.called: # self.timer.cancel() # self.timer = reactor.callLater(self.holdtime, self.unset) # # def unset(self, *args, **kwargs): # #print "SEMAPHORE UNSET:", self.port # # # signal sensor-off # if self.callback: # self.callback(False, *args, **kwargs) # # class Blinker(object): # # def __init__(self, port, interval=0.5): # self.port = port # self.interval = interval # self.state = None # self.transition = None # # def set(self, *args, **kwargs): # self.blink() # # def unset(self): # self.transition_stop() # self.port.unset() # # def blink(self): # self.transition_stop() # self.transition = LoopingCall(self.blink_task) # self.transition.start(self.interval) # # def transition_stop(self): # if self.transition and self.transition.running: # self.transition.stop() # # def blink_task(self): # if self.state: # self.state = False # self.port.set() # else: # self.state = True # self.port.unset() # # class BinaryTopicSignal(object): # """Receives a signal from bus network and signals receiver (actor/port) accordingly""" # # def __init__(self, bus, topic, signal): # self.bus = bus # self.topic = topic # self.signal = signal # self.bus.subscribe(self.topic, self.process_event) # # def process_event(self, topic, state): # if state: # self.signal.set() # else: # self.signal.unset() , which may include functions, classes, or code. Output only the next line.
payload = {'node_id': self.node_id}
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2014 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de> PirMotionDetector = BinaryInputPort PrivacyButton = BinaryInputPort SignalLight = BinaryOutputPort OperatorPresenceIndicator = BinaryTopicSignal class FeatureBase(object): # port allocation PORT_LED = 'P8_13' PORT_PRIVACY_BUTTON = 'P8_15' <|code_end|> , predict the immediate next line with the help of imports: from kotori.vendor.ilaundry.node.bricks import BinaryInputPort, BinaryOutputPort, TimedBinarySemaphore, Blinker, BinaryTopicSignal and context (classes, functions, sometimes code) from other files: # Path: kotori/vendor/ilaundry/node/bricks.py # class BinaryInputPort(object): # # def __init__(self, portname, signal=None): # self.portname = portname # self.signal = signal # # # detect edge on port # self.gpio = GpioInput(self.portname, self.sensor_on) # # def sensor_on(self, port): # print("DEBUG: Port {0} EVENT".format(self.portname)) # # # signal sensor-on # if self.signal: # self.signal.set(True) # # # currently defunct # """ # def sensor_off(self, port): # print "SENSOR OFF:", port # # # signal sensor-off # if self.callback: # self.callback(False) # """ # # class BinaryOutputPort(object): # # # TODO: handle different ports, not only GPIO # # #HIGH = 1 # #LOW = 2 # #BLINK = 3 # # def __init__(self, portname): # self.portname = portname # #self.flavor = flavor or self.HIGH # self.gpio = GpioOutput(self.portname) # # #self.modifier = modifier # # def set(self, *args, **kwargs): # print("DEBUG: Port {0} ON".format(self.portname)) # self.gpio.on() # # # signal gpio port # #if self.flavor == self.HIGH: # #elif self.flavor == self.BLINK: # # def unset(self): # print("DEBUG: Port {0} OFF".format(self.portname)) # # #self.transition_stop() # # # signal gpio port # self.gpio.off() # # class TimedBinarySemaphore(object): # # def __init__(self, holdtime=None, callback=None): # self.holdtime = holdtime # self.callback = callback # self.timer = None # # def set(self, *args, **kwargs): # #print "SEMAPHORE SET: ", self.port # # # signal actor-on # if self.callback: # self.callback(True, *args, **kwargs) # # # start/reset timer for motion-off signal # if self.holdtime: # #print "SEMAPHORE SET: ", self.port, "holding for {0} seconds".format(self.holdtime) # if self.timer and not self.timer.called: # self.timer.cancel() # self.timer = reactor.callLater(self.holdtime, self.unset) # # def unset(self, *args, **kwargs): # #print "SEMAPHORE UNSET:", self.port # # # signal sensor-off # if self.callback: # self.callback(False, *args, **kwargs) # # class Blinker(object): # # def __init__(self, port, interval=0.5): # self.port = port # self.interval = interval # self.state = None # self.transition = None # # def set(self, *args, **kwargs): # self.blink() # # def unset(self): # self.transition_stop() # self.port.unset() # # def blink(self): # self.transition_stop() # self.transition = LoopingCall(self.blink_task) # self.transition.start(self.interval) # # def transition_stop(self): # if self.transition and self.transition.running: # self.transition.stop() # # def blink_task(self): # if self.state: # self.state = False # self.port.set() # else: # self.state = True # self.port.unset() # # class BinaryTopicSignal(object): # """Receives a signal from bus network and signals receiver (actor/port) accordingly""" # # def __init__(self, bus, topic, signal): # self.bus = bus # self.topic = topic # self.signal = signal # self.bus.subscribe(self.topic, self.process_event) # # def process_event(self, topic, state): # if state: # self.signal.set() # else: # self.signal.unset() . Output only the next line.
PORT_PIR_SENSOR = 'P8_19'
Using the snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2014 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de> PirMotionDetector = BinaryInputPort PrivacyButton = BinaryInputPort SignalLight = BinaryOutputPort OperatorPresenceIndicator = BinaryTopicSignal class FeatureBase(object): # port allocation PORT_LED = 'P8_13' PORT_PRIVACY_BUTTON = 'P8_15' <|code_end|> , determine the next line of code. You have imports: from kotori.vendor.ilaundry.node.bricks import BinaryInputPort, BinaryOutputPort, TimedBinarySemaphore, Blinker, BinaryTopicSignal and context (class names, function names, or code) available: # Path: kotori/vendor/ilaundry/node/bricks.py # class BinaryInputPort(object): # # def __init__(self, portname, signal=None): # self.portname = portname # self.signal = signal # # # detect edge on port # self.gpio = GpioInput(self.portname, self.sensor_on) # # def sensor_on(self, port): # print("DEBUG: Port {0} EVENT".format(self.portname)) # # # signal sensor-on # if self.signal: # self.signal.set(True) # # # currently defunct # """ # def sensor_off(self, port): # print "SENSOR OFF:", port # # # signal sensor-off # if self.callback: # self.callback(False) # """ # # class BinaryOutputPort(object): # # # TODO: handle different ports, not only GPIO # # #HIGH = 1 # #LOW = 2 # #BLINK = 3 # # def __init__(self, portname): # self.portname = portname # #self.flavor = flavor or self.HIGH # self.gpio = GpioOutput(self.portname) # # #self.modifier = modifier # # def set(self, *args, **kwargs): # print("DEBUG: Port {0} ON".format(self.portname)) # self.gpio.on() # # # signal gpio port # #if self.flavor == self.HIGH: # #elif self.flavor == self.BLINK: # # def unset(self): # print("DEBUG: Port {0} OFF".format(self.portname)) # # #self.transition_stop() # # # signal gpio port # self.gpio.off() # # class TimedBinarySemaphore(object): # # def __init__(self, holdtime=None, callback=None): # self.holdtime = holdtime # self.callback = callback # self.timer = None # # def set(self, *args, **kwargs): # #print "SEMAPHORE SET: ", self.port # # # signal actor-on # if self.callback: # self.callback(True, *args, **kwargs) # # # start/reset timer for motion-off signal # if self.holdtime: # #print "SEMAPHORE SET: ", self.port, "holding for {0} seconds".format(self.holdtime) # if self.timer and not self.timer.called: # self.timer.cancel() # self.timer = reactor.callLater(self.holdtime, self.unset) # # def unset(self, *args, **kwargs): # #print "SEMAPHORE UNSET:", self.port # # # signal sensor-off # if self.callback: # self.callback(False, *args, **kwargs) # # class Blinker(object): # # def __init__(self, port, interval=0.5): # self.port = port # self.interval = interval # self.state = None # self.transition = None # # def set(self, *args, **kwargs): # self.blink() # # def unset(self): # self.transition_stop() # self.port.unset() # # def blink(self): # self.transition_stop() # self.transition = LoopingCall(self.blink_task) # self.transition.start(self.interval) # # def transition_stop(self): # if self.transition and self.transition.running: # self.transition.stop() # # def blink_task(self): # if self.state: # self.state = False # self.port.set() # else: # self.state = True # self.port.unset() # # class BinaryTopicSignal(object): # """Receives a signal from bus network and signals receiver (actor/port) accordingly""" # # def __init__(self, bus, topic, signal): # self.bus = bus # self.topic = topic # self.signal = signal # self.bus.subscribe(self.topic, self.process_event) # # def process_event(self, topic, state): # if state: # self.signal.set() # else: # self.signal.unset() . Output only the next line.
PORT_PIR_SENSOR = 'P8_19'
Using the snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2014 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de> PirMotionDetector = BinaryInputPort PrivacyButton = BinaryInputPort SignalLight = BinaryOutputPort OperatorPresenceIndicator = BinaryTopicSignal class FeatureBase(object): # port allocation PORT_LED = 'P8_13' PORT_PRIVACY_BUTTON = 'P8_15' PORT_PIR_SENSOR = 'P8_19' def __init__(self, node_id, bus, event_filters=None): <|code_end|> , determine the next line of code. You have imports: from kotori.vendor.ilaundry.node.bricks import BinaryInputPort, BinaryOutputPort, TimedBinarySemaphore, Blinker, BinaryTopicSignal and context (class names, function names, or code) available: # Path: kotori/vendor/ilaundry/node/bricks.py # class BinaryInputPort(object): # # def __init__(self, portname, signal=None): # self.portname = portname # self.signal = signal # # # detect edge on port # self.gpio = GpioInput(self.portname, self.sensor_on) # # def sensor_on(self, port): # print("DEBUG: Port {0} EVENT".format(self.portname)) # # # signal sensor-on # if self.signal: # self.signal.set(True) # # # currently defunct # """ # def sensor_off(self, port): # print "SENSOR OFF:", port # # # signal sensor-off # if self.callback: # self.callback(False) # """ # # class BinaryOutputPort(object): # # # TODO: handle different ports, not only GPIO # # #HIGH = 1 # #LOW = 2 # #BLINK = 3 # # def __init__(self, portname): # self.portname = portname # #self.flavor = flavor or self.HIGH # self.gpio = GpioOutput(self.portname) # # #self.modifier = modifier # # def set(self, *args, **kwargs): # print("DEBUG: Port {0} ON".format(self.portname)) # self.gpio.on() # # # signal gpio port # #if self.flavor == self.HIGH: # #elif self.flavor == self.BLINK: # # def unset(self): # print("DEBUG: Port {0} OFF".format(self.portname)) # # #self.transition_stop() # # # signal gpio port # self.gpio.off() # # class TimedBinarySemaphore(object): # # def __init__(self, holdtime=None, callback=None): # self.holdtime = holdtime # self.callback = callback # self.timer = None # # def set(self, *args, **kwargs): # #print "SEMAPHORE SET: ", self.port # # # signal actor-on # if self.callback: # self.callback(True, *args, **kwargs) # # # start/reset timer for motion-off signal # if self.holdtime: # #print "SEMAPHORE SET: ", self.port, "holding for {0} seconds".format(self.holdtime) # if self.timer and not self.timer.called: # self.timer.cancel() # self.timer = reactor.callLater(self.holdtime, self.unset) # # def unset(self, *args, **kwargs): # #print "SEMAPHORE UNSET:", self.port # # # signal sensor-off # if self.callback: # self.callback(False, *args, **kwargs) # # class Blinker(object): # # def __init__(self, port, interval=0.5): # self.port = port # self.interval = interval # self.state = None # self.transition = None # # def set(self, *args, **kwargs): # self.blink() # # def unset(self): # self.transition_stop() # self.port.unset() # # def blink(self): # self.transition_stop() # self.transition = LoopingCall(self.blink_task) # self.transition.start(self.interval) # # def transition_stop(self): # if self.transition and self.transition.running: # self.transition.stop() # # def blink_task(self): # if self.state: # self.state = False # self.port.set() # else: # self.state = True # self.port.unset() # # class BinaryTopicSignal(object): # """Receives a signal from bus network and signals receiver (actor/port) accordingly""" # # def __init__(self, bus, topic, signal): # self.bus = bus # self.topic = topic # self.signal = signal # self.bus.subscribe(self.topic, self.process_event) # # def process_event(self, topic, state): # if state: # self.signal.set() # else: # self.signal.unset() . Output only the next line.
self.node_id = node_id
Given snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2014 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de> PirMotionDetector = BinaryInputPort PrivacyButton = BinaryInputPort SignalLight = BinaryOutputPort OperatorPresenceIndicator = BinaryTopicSignal class FeatureBase(object): # port allocation PORT_LED = 'P8_13' PORT_PRIVACY_BUTTON = 'P8_15' PORT_PIR_SENSOR = 'P8_19' def __init__(self, node_id, bus, event_filters=None): self.node_id = node_id self.bus = bus self.event_filters = event_filters self.state = None @staticmethod def state_for_display(state): return state and 'enabled' or 'disabled' def run_filters(self, state): if self.event_filters: <|code_end|> , continue by predicting the next line. Consider current file imports: from kotori.vendor.ilaundry.node.bricks import BinaryInputPort, BinaryOutputPort, TimedBinarySemaphore, Blinker, BinaryTopicSignal and context: # Path: kotori/vendor/ilaundry/node/bricks.py # class BinaryInputPort(object): # # def __init__(self, portname, signal=None): # self.portname = portname # self.signal = signal # # # detect edge on port # self.gpio = GpioInput(self.portname, self.sensor_on) # # def sensor_on(self, port): # print("DEBUG: Port {0} EVENT".format(self.portname)) # # # signal sensor-on # if self.signal: # self.signal.set(True) # # # currently defunct # """ # def sensor_off(self, port): # print "SENSOR OFF:", port # # # signal sensor-off # if self.callback: # self.callback(False) # """ # # class BinaryOutputPort(object): # # # TODO: handle different ports, not only GPIO # # #HIGH = 1 # #LOW = 2 # #BLINK = 3 # # def __init__(self, portname): # self.portname = portname # #self.flavor = flavor or self.HIGH # self.gpio = GpioOutput(self.portname) # # #self.modifier = modifier # # def set(self, *args, **kwargs): # print("DEBUG: Port {0} ON".format(self.portname)) # self.gpio.on() # # # signal gpio port # #if self.flavor == self.HIGH: # #elif self.flavor == self.BLINK: # # def unset(self): # print("DEBUG: Port {0} OFF".format(self.portname)) # # #self.transition_stop() # # # signal gpio port # self.gpio.off() # # class TimedBinarySemaphore(object): # # def __init__(self, holdtime=None, callback=None): # self.holdtime = holdtime # self.callback = callback # self.timer = None # # def set(self, *args, **kwargs): # #print "SEMAPHORE SET: ", self.port # # # signal actor-on # if self.callback: # self.callback(True, *args, **kwargs) # # # start/reset timer for motion-off signal # if self.holdtime: # #print "SEMAPHORE SET: ", self.port, "holding for {0} seconds".format(self.holdtime) # if self.timer and not self.timer.called: # self.timer.cancel() # self.timer = reactor.callLater(self.holdtime, self.unset) # # def unset(self, *args, **kwargs): # #print "SEMAPHORE UNSET:", self.port # # # signal sensor-off # if self.callback: # self.callback(False, *args, **kwargs) # # class Blinker(object): # # def __init__(self, port, interval=0.5): # self.port = port # self.interval = interval # self.state = None # self.transition = None # # def set(self, *args, **kwargs): # self.blink() # # def unset(self): # self.transition_stop() # self.port.unset() # # def blink(self): # self.transition_stop() # self.transition = LoopingCall(self.blink_task) # self.transition.start(self.interval) # # def transition_stop(self): # if self.transition and self.transition.running: # self.transition.stop() # # def blink_task(self): # if self.state: # self.state = False # self.port.set() # else: # self.state = True # self.port.unset() # # class BinaryTopicSignal(object): # """Receives a signal from bus network and signals receiver (actor/port) accordingly""" # # def __init__(self, bus, topic, signal): # self.bus = bus # self.topic = topic # self.signal = signal # self.bus.subscribe(self.topic, self.process_event) # # def process_event(self, topic, state): # if state: # self.signal.set() # else: # self.signal.unset() which might include code, classes, or functions. Output only the next line.
for event_filter in self.event_filters:
Next line prediction: <|code_start|> self.config = ConfigStoreJson() #print '----------------------', self.config.store #print '----------------------', self.config.get('nodes') #self.nodes = self.config.get('nodes', {}) #print '======================', self.nodes def persist(self): print("============= persist", self.nodes) #self.config['nodes'].update(self.nodes) #del self.config['nodes'] self.config['nodes'] = {'haha': {'hehe': 'dscsdcsdcsdcc'}} #self.config['nodes'] = self.nodes.copy() self.config['nodes2'] = deepcopy(self.nodes) self.config['ttt'] = 'huhu' # self.config['nodes']['abc'] = 'def2' #self.nodes.setdefault('ghi', {})['kli'] = 'DEFUNCT' #self.config['ghi']['jkl'] = 'defunct' def register(self, node_id, hostname=None): print("NodeRegistry.register:", node_id) self.nodes[node_id] = {'hostname': hostname} self.persist() client.publish('http://kotori.elmyra.de/dashboard#update', None) def unregister(self, node_id): print("NodeRegistry.unregister:", node_id) try: del self.nodes[node_id] self.persist() <|code_end|> . Use current file imports: (import sys import datetime from copy import deepcopy from urllib.parse import urlparse, parse_qs from autobahn.twisted.wamp import ApplicationRunner, ApplicationSession from autobahn.twisted.websocket import WampWebSocketClientProtocol, WampWebSocketClientFactory from autobahn.twisted.websocket import WampWebSocketServerProtocol, WampWebSocketServerFactory from twisted.python import log from twisted.internet import reactor from kotori.util.common import ConfigStoreJson) and context including class names, function names, or small code snippets from other files: # Path: kotori/util/common.py # class ConfigStoreJson(dict): # # store = None # # def __init__(self): # if not ConfigStoreJson.store: # #print "ConfigStoreJson.__init__" # self.app_data_dir = user_data_dir('kotori', 'daqzilla') # logger.debug("ConfigStoreJson app_data_dir: {}".format(self.app_data_dir)) # if not os.path.exists(self.app_data_dir): # os.makedirs(self.app_data_dir) # self.config_file = os.path.join(self.app_data_dir, 'config.json') # ConfigStoreJson.store = json_store.open(self.config_file) # # def has_key(self, key): # return key in ConfigStoreJson.store # # def __getitem__(self, key): # #print 'ConfigStoreJson.__getitem__' # return ConfigStoreJson.store[key] # # def __setitem__(self, key, value): # #print 'ConfigStoreJson.__setitem__', key, value # ConfigStoreJson.store[key] = value # ConfigStoreJson.store.sync() . Output only the next line.
except KeyError:
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) @pytest_twisted.inlineCallbacks @pytest.mark.grafana <|code_end|> using the current file's imports: import logging import pytest import pytest_twisted from test.settings.mqttkit import settings, grafana, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep and any relevant context from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
def test_mqtt_to_grafana_single(machinery, create_influxdb, reset_influxdb, reset_grafana):
Next line prediction: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) @pytest_twisted.inlineCallbacks @pytest.mark.grafana <|code_end|> . Use current file imports: (import logging import pytest import pytest_twisted from test.settings.mqttkit import settings, grafana, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep) and context including class names, function names, or small code snippets from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
def test_mqtt_to_grafana_single(machinery, create_influxdb, reset_influxdb, reset_grafana):
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2014-2015 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de> # # derived from https://github.com/tavendo/AutobahnPython/blob/master/examples/twisted/wamp/pubsub/simple/example2/client.py node_manager = None NODE_ID = str(NodeId()) NODE_HOSTNAME = get_hostname() <|code_end|> . Write the next line using the current file imports: import sys from autobahn.twisted.wamp import ApplicationRunner, ApplicationSession from twisted.internet.defer import inlineCallbacks from twisted.python import log from twisted.internet import reactor from autobahn.twisted.websocket import connectWS, WampWebSocketClientProtocol, WampWebSocketClientFactory from kotori.util.common import NodeId, get_hostname from kotori.vendor.ilaundry.node.util import tts_say from kotori.vendor.ilaundry.node.feature import FeatureSet and context from other files: # Path: kotori/util/common.py # class NodeId(Singleton): # # config = None # NODE_ID = 'NODE_UNKNOWN' # # def __init__(self): # if not self.config: # self.config = ConfigStoreJson() # if 'uuid' not in self.config: # self.config['uuid'] = str(uuid4()) # self.NODE_ID = self.config['uuid'] # logger.debug("NODE ID: {}".format(self.NODE_ID)) # # def __str__(self): # return str(self.NODE_ID) # # def get_hostname(): # return socket.gethostname() # # Path: kotori/vendor/ilaundry/node/util.py # def tts_say(message, language='de'): # # # FIXME: add queue here # print("say:", message) # # # Google Translate TTS # # FIXME: urlescape "message" # tts_url = u'http://translate.google.com/translate_tts?tl={language}&q={message}'.format(language=language, message=urllib.parse.quote(message.encode('utf8'))) # more_args = u'' # if sys.platform.startswith('linux'): # # TODO: dynamic configuration of output device # more_args += u'-ao alsa:device=hw=1.0' # # user_agent = u"-http-header-fields 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36'" # command = u"mplayer -really-quiet -noconsolecontrols {user_agent} {more_args} '{tts_url}'".format(**locals()) # #command = command.encode('utf8') # print(command) # # FIXME: don't do this synchronously # # FIXME: show errors (stdout/stderr) if command fails # os.system(command) , which may include functions, classes, or code. Output only the next line.
class NodeProtocol(WampWebSocketClientProtocol):
Predict the next line for this snippet: <|code_start|> ] docker_image_version = "0.11.0" def run(self): """ Invoke the image building for all enabled recipes. """ for recipe in self.recipes: # Skip recipes not enabled. if not recipe.enabled: continue # Build all distributions. for distribution in recipe.distributions: # Build all architectures per distribution. for architecture in recipe.architectures: print_header( f'Building baseline image for {recipe.vendor} "{distribution}" on {architecture}' ) image = recipe.image.format(**locals()) commands = [ f""" docker build \ --pull \ --tag ephemeral/{distribution}-{architecture}-baseline:{self.docker_image_version} \ --tag ephemeral/{distribution}-{architecture}-baseline:latest \ <|code_end|> with the help of current file imports: from typing import List from tasks.packaging.model import DockerBaselineImageRecipe from tasks.util import print_header, run_commands, task and context from other files: # Path: tasks/packaging/model.py # class DockerBaselineImageRecipe: # """ # Data structure for holding information about a recipe for building baseline # Docker images. Those images will be used for building the actual operating # system distribution packages. # """ # # # Whether this recipe is enabled. # enabled: bool # # # The operating system vendor, e.g. Debian, Ubuntu. # vendor: str # # # List of operating system distributions, e.g. stretch, buster. # distributions: List[str] # # # List of architectures, e.g. amd64, arm64v8, arm32v7. # architectures: List[str] # # # Docker image to use. # image: str # # Path: tasks/util.py # def print_header(label, char="-"): # length = max(len(label), 42) # print(char * length) # print(label.center(length)) # print(char * length) # # def run_commands(commands): # if isinstance(commands, str): # commands = [commands] # for command in commands: # command = command.strip() # print(command) # exitcode = os.system(command) # if exitcode != 0: # raise SystemExit("Command failed") # # def task(f: F) -> F: # f.__annotations__ = {} # return invoke.task(f) , which may contain function names, class names, or code. Output only the next line.
--build-arg BASE_IMAGE={image} - \
Continue the code snippet: <|code_start|> architecture=architecture, flavor=flavor, version=version, ) self.deb(spec) @staticmethod def build_container_name(spec): return f"ephemeral/kotori-build-{spec.distribution}-{spec.architecture}:{spec.version}" def deb(self, spec: PackageSpecification): # Compute package name and path to `.deb` file. package_name = spec.deb_name() package_file = Path("dist") / package_name # Sanity checks. if package_file.exists(): print(f"Package {package_file} already exists, skipping.") return print_header( f"Building package {spec.name} for {spec.distribution} on {spec.architecture}" ) print(json.dumps(dataclasses.asdict(spec), indent=4)) # Build Linux distribution package within Docker container. os.environ["DOCKER_BUILDKIT"] = "0" command = f""" docker build \ <|code_end|> . Use current file imports: import dataclasses import json import os from pathlib import Path from invoke import Context from tasks.packaging.model import PackageRecipe, PackageSpecification from tasks.util import print_header, run_commands, task and context (classes, functions, or code) from other files: # Path: tasks/packaging/model.py # class PackageRecipe: # """ # Data structure for holding information about a recipe for building # distribution packages. # """ # # # Whether this recipe is enabled. # enabled: bool # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # List of operating system distributions, e.g. stretch, buster. # distributions: List[str] # # # List of package flavors, e.g. minimal, standard, full. # flavors: List[str] # # class PackageSpecification: # """ # Data structure for holding information about individual distribution # packages. # """ # # # Package flavor, e.g. minimal, standard, full. # flavor: str # # # Package version. # version: str # # # Distribution name, e.g. stretch, buster. # distribution: str # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # Computed package name, taking `flavor` into account. # name: str = None # # # List of Python `extra` labels, taking `flavor` into account. # features: str = None # # # Map architecture labels to Debian distribution package architecture name. # debian_architecture_map: ClassVar = { # "arm64v8": "arm64", # "arm32v7": "armhf", # } # # def __post_init__(self): # self.resolve() # self.validate() # # def validate(self): # """ # Sanity checks. All designated specification fields must be set and not # be empty. # """ # for field in dataclasses.fields(self): # value = getattr(self, field.name) # if value is None: # raise ValueError( # f'Package specification field "{field.name}" is required.' # ) # # def resolve(self): # """ # Resolve the designated package flavor to a list of Python package # `extra` labels. # """ # if self.flavor == "minimal": # self.name = "kotori-minimal" # self.features = "daq" # elif self.flavor == "standard": # self.name = "kotori-standard" # self.features = "daq,daq_geospatial,export" # elif self.flavor == "full": # self.name = "kotori" # self.features = "daq,daq_geospatial,export,plotting,firmware,scientific" # else: # raise ValueError("Unknown package flavor") # # @property # def debian_architecture(self): # """ # Resolve the architecture label to a Debian package architecture suffix. # """ # return self.debian_architecture_map.get(self.architecture, self.architecture) # # def deb_name(self): # """ # Compute the full name of the Debian `.deb` package. # """ # return f"{self.name}_{self.version}-1~{self.distribution}_{self.debian_architecture}.deb" # # Path: tasks/util.py # def print_header(label, char="-"): # length = max(len(label), 42) # print(char * length) # print(label.center(length)) # print(char * length) # # def run_commands(commands): # if isinstance(commands, str): # commands = [commands] # for command in commands: # command = command.strip() # print(command) # exitcode = os.system(command) # if exitcode != 0: # raise SystemExit("Command failed") # # def task(f: F) -> F: # f.__annotations__ = {} # return invoke.task(f) . Output only the next line.
--tag {self.build_container_name(spec)} \
Using the snippet: <|code_start|> flavor=flavor, version=version, ) self.deb(spec) @staticmethod def build_container_name(spec): return f"ephemeral/kotori-build-{spec.distribution}-{spec.architecture}:{spec.version}" def deb(self, spec: PackageSpecification): # Compute package name and path to `.deb` file. package_name = spec.deb_name() package_file = Path("dist") / package_name # Sanity checks. if package_file.exists(): print(f"Package {package_file} already exists, skipping.") return print_header( f"Building package {spec.name} for {spec.distribution} on {spec.architecture}" ) print(json.dumps(dataclasses.asdict(spec), indent=4)) # Build Linux distribution package within Docker container. os.environ["DOCKER_BUILDKIT"] = "0" command = f""" docker build \ --tag {self.build_container_name(spec)} \ <|code_end|> , determine the next line of code. You have imports: import dataclasses import json import os from pathlib import Path from invoke import Context from tasks.packaging.model import PackageRecipe, PackageSpecification from tasks.util import print_header, run_commands, task and context (class names, function names, or code) available: # Path: tasks/packaging/model.py # class PackageRecipe: # """ # Data structure for holding information about a recipe for building # distribution packages. # """ # # # Whether this recipe is enabled. # enabled: bool # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # List of operating system distributions, e.g. stretch, buster. # distributions: List[str] # # # List of package flavors, e.g. minimal, standard, full. # flavors: List[str] # # class PackageSpecification: # """ # Data structure for holding information about individual distribution # packages. # """ # # # Package flavor, e.g. minimal, standard, full. # flavor: str # # # Package version. # version: str # # # Distribution name, e.g. stretch, buster. # distribution: str # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # Computed package name, taking `flavor` into account. # name: str = None # # # List of Python `extra` labels, taking `flavor` into account. # features: str = None # # # Map architecture labels to Debian distribution package architecture name. # debian_architecture_map: ClassVar = { # "arm64v8": "arm64", # "arm32v7": "armhf", # } # # def __post_init__(self): # self.resolve() # self.validate() # # def validate(self): # """ # Sanity checks. All designated specification fields must be set and not # be empty. # """ # for field in dataclasses.fields(self): # value = getattr(self, field.name) # if value is None: # raise ValueError( # f'Package specification field "{field.name}" is required.' # ) # # def resolve(self): # """ # Resolve the designated package flavor to a list of Python package # `extra` labels. # """ # if self.flavor == "minimal": # self.name = "kotori-minimal" # self.features = "daq" # elif self.flavor == "standard": # self.name = "kotori-standard" # self.features = "daq,daq_geospatial,export" # elif self.flavor == "full": # self.name = "kotori" # self.features = "daq,daq_geospatial,export,plotting,firmware,scientific" # else: # raise ValueError("Unknown package flavor") # # @property # def debian_architecture(self): # """ # Resolve the architecture label to a Debian package architecture suffix. # """ # return self.debian_architecture_map.get(self.architecture, self.architecture) # # def deb_name(self): # """ # Compute the full name of the Debian `.deb` package. # """ # return f"{self.name}_{self.version}-1~{self.distribution}_{self.debian_architecture}.deb" # # Path: tasks/util.py # def print_header(label, char="-"): # length = max(len(label), 42) # print(char * length) # print(label.center(length)) # print(char * length) # # def run_commands(commands): # if isinstance(commands, str): # commands = [commands] # for command in commands: # command = command.strip() # print(command) # exitcode = os.system(command) # if exitcode != 0: # raise SystemExit("Command failed") # # def task(f: F) -> F: # f.__annotations__ = {} # return invoke.task(f) . Output only the next line.
--build-arg BASE_IMAGE=ephemeral/{spec.distribution}-{spec.architecture}-baseline:latest \
Based on the snippet: <|code_start|> @staticmethod def build_container_name(spec): return f"ephemeral/kotori-build-{spec.distribution}-{spec.architecture}:{spec.version}" def deb(self, spec: PackageSpecification): # Compute package name and path to `.deb` file. package_name = spec.deb_name() package_file = Path("dist") / package_name # Sanity checks. if package_file.exists(): print(f"Package {package_file} already exists, skipping.") return print_header( f"Building package {spec.name} for {spec.distribution} on {spec.architecture}" ) print(json.dumps(dataclasses.asdict(spec), indent=4)) # Build Linux distribution package within Docker container. os.environ["DOCKER_BUILDKIT"] = "0" command = f""" docker build \ --tag {self.build_container_name(spec)} \ --build-arg BASE_IMAGE=ephemeral/{spec.distribution}-{spec.architecture}-baseline:latest \ --build-arg NAME={spec.name} \ --build-arg FEATURES={spec.features} \ --build-arg VERSION={spec.version} \ --build-arg DISTRIBUTION={spec.distribution} \ <|code_end|> , predict the immediate next line with the help of imports: import dataclasses import json import os from pathlib import Path from invoke import Context from tasks.packaging.model import PackageRecipe, PackageSpecification from tasks.util import print_header, run_commands, task and context (classes, functions, sometimes code) from other files: # Path: tasks/packaging/model.py # class PackageRecipe: # """ # Data structure for holding information about a recipe for building # distribution packages. # """ # # # Whether this recipe is enabled. # enabled: bool # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # List of operating system distributions, e.g. stretch, buster. # distributions: List[str] # # # List of package flavors, e.g. minimal, standard, full. # flavors: List[str] # # class PackageSpecification: # """ # Data structure for holding information about individual distribution # packages. # """ # # # Package flavor, e.g. minimal, standard, full. # flavor: str # # # Package version. # version: str # # # Distribution name, e.g. stretch, buster. # distribution: str # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # Computed package name, taking `flavor` into account. # name: str = None # # # List of Python `extra` labels, taking `flavor` into account. # features: str = None # # # Map architecture labels to Debian distribution package architecture name. # debian_architecture_map: ClassVar = { # "arm64v8": "arm64", # "arm32v7": "armhf", # } # # def __post_init__(self): # self.resolve() # self.validate() # # def validate(self): # """ # Sanity checks. All designated specification fields must be set and not # be empty. # """ # for field in dataclasses.fields(self): # value = getattr(self, field.name) # if value is None: # raise ValueError( # f'Package specification field "{field.name}" is required.' # ) # # def resolve(self): # """ # Resolve the designated package flavor to a list of Python package # `extra` labels. # """ # if self.flavor == "minimal": # self.name = "kotori-minimal" # self.features = "daq" # elif self.flavor == "standard": # self.name = "kotori-standard" # self.features = "daq,daq_geospatial,export" # elif self.flavor == "full": # self.name = "kotori" # self.features = "daq,daq_geospatial,export,plotting,firmware,scientific" # else: # raise ValueError("Unknown package flavor") # # @property # def debian_architecture(self): # """ # Resolve the architecture label to a Debian package architecture suffix. # """ # return self.debian_architecture_map.get(self.architecture, self.architecture) # # def deb_name(self): # """ # Compute the full name of the Debian `.deb` package. # """ # return f"{self.name}_{self.version}-1~{self.distribution}_{self.debian_architecture}.deb" # # Path: tasks/util.py # def print_header(label, char="-"): # length = max(len(label), 42) # print(char * length) # print(label.center(length)) # print(char * length) # # def run_commands(commands): # if isinstance(commands, str): # commands = [commands] # for command in commands: # command = command.strip() # print(command) # exitcode = os.system(command) # if exitcode != 0: # raise SystemExit("Command failed") # # def task(f: F) -> F: # f.__annotations__ = {} # return invoke.task(f) . Output only the next line.
--build-arg ARCHITECTURE={spec.architecture} \
Given the following code snippet before the placeholder: <|code_start|> self.deb(spec) @staticmethod def build_container_name(spec): return f"ephemeral/kotori-build-{spec.distribution}-{spec.architecture}:{spec.version}" def deb(self, spec: PackageSpecification): # Compute package name and path to `.deb` file. package_name = spec.deb_name() package_file = Path("dist") / package_name # Sanity checks. if package_file.exists(): print(f"Package {package_file} already exists, skipping.") return print_header( f"Building package {spec.name} for {spec.distribution} on {spec.architecture}" ) print(json.dumps(dataclasses.asdict(spec), indent=4)) # Build Linux distribution package within Docker container. os.environ["DOCKER_BUILDKIT"] = "0" command = f""" docker build \ --tag {self.build_container_name(spec)} \ --build-arg BASE_IMAGE=ephemeral/{spec.distribution}-{spec.architecture}-baseline:latest \ --build-arg NAME={spec.name} \ --build-arg FEATURES={spec.features} \ <|code_end|> , predict the next line using imports from the current file: import dataclasses import json import os from pathlib import Path from invoke import Context from tasks.packaging.model import PackageRecipe, PackageSpecification from tasks.util import print_header, run_commands, task and context including class names, function names, and sometimes code from other files: # Path: tasks/packaging/model.py # class PackageRecipe: # """ # Data structure for holding information about a recipe for building # distribution packages. # """ # # # Whether this recipe is enabled. # enabled: bool # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # List of operating system distributions, e.g. stretch, buster. # distributions: List[str] # # # List of package flavors, e.g. minimal, standard, full. # flavors: List[str] # # class PackageSpecification: # """ # Data structure for holding information about individual distribution # packages. # """ # # # Package flavor, e.g. minimal, standard, full. # flavor: str # # # Package version. # version: str # # # Distribution name, e.g. stretch, buster. # distribution: str # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # Computed package name, taking `flavor` into account. # name: str = None # # # List of Python `extra` labels, taking `flavor` into account. # features: str = None # # # Map architecture labels to Debian distribution package architecture name. # debian_architecture_map: ClassVar = { # "arm64v8": "arm64", # "arm32v7": "armhf", # } # # def __post_init__(self): # self.resolve() # self.validate() # # def validate(self): # """ # Sanity checks. All designated specification fields must be set and not # be empty. # """ # for field in dataclasses.fields(self): # value = getattr(self, field.name) # if value is None: # raise ValueError( # f'Package specification field "{field.name}" is required.' # ) # # def resolve(self): # """ # Resolve the designated package flavor to a list of Python package # `extra` labels. # """ # if self.flavor == "minimal": # self.name = "kotori-minimal" # self.features = "daq" # elif self.flavor == "standard": # self.name = "kotori-standard" # self.features = "daq,daq_geospatial,export" # elif self.flavor == "full": # self.name = "kotori" # self.features = "daq,daq_geospatial,export,plotting,firmware,scientific" # else: # raise ValueError("Unknown package flavor") # # @property # def debian_architecture(self): # """ # Resolve the architecture label to a Debian package architecture suffix. # """ # return self.debian_architecture_map.get(self.architecture, self.architecture) # # def deb_name(self): # """ # Compute the full name of the Debian `.deb` package. # """ # return f"{self.name}_{self.version}-1~{self.distribution}_{self.debian_architecture}.deb" # # Path: tasks/util.py # def print_header(label, char="-"): # length = max(len(label), 42) # print(char * length) # print(label.center(length)) # print(char * length) # # def run_commands(commands): # if isinstance(commands, str): # commands = [commands] # for command in commands: # command = command.strip() # print(command) # exitcode = os.system(command) # if exitcode != 0: # raise SystemExit("Command failed") # # def task(f: F) -> F: # f.__annotations__ = {} # return invoke.task(f) . Output only the next line.
--build-arg VERSION={spec.version} \
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) event_data = { 'title': 'Some event', 'text': '<a href="https://somewhere.example.org/events?reference=482a38ce-791e-11e6-b152-7cd1c55000be">see also</a>', <|code_end|> , generate the next line using the imports in this file: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_events, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep, http_json_sensor, http_form_sensor and context (functions, classes, or occasionally code) from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) # # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def http_form_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using x-www-form-urlencoded'.format(uri)) # return requests.post(uri, data=data) . Output only the next line.
'tags': 'event,alert,important',
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) event_data = { 'title': 'Some event', 'text': '<a href="https://somewhere.example.org/events?reference=482a38ce-791e-11e6-b152-7cd1c55000be">see also</a>', 'tags': 'event,alert,important', <|code_end|> with the help of current file imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_events, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep, http_json_sensor, http_form_sensor and context from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) # # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def http_form_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using x-www-form-urlencoded'.format(uri)) # return requests.post(uri, data=data) , which may contain function names, class names, or code. Output only the next line.
'reference': '482a38ce-791e-11e6-b152-7cd1c55000be',
Given snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) event_data = { 'title': 'Some event', 'text': '<a href="https://somewhere.example.org/events?reference=482a38ce-791e-11e6-b152-7cd1c55000be">see also</a>', 'tags': 'event,alert,important', 'reference': '482a38ce-791e-11e6-b152-7cd1c55000be', } @pytest_twisted.inlineCallbacks @pytest.mark.mqtt <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_events, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep, http_json_sensor, http_form_sensor and context: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) # # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def http_form_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using x-www-form-urlencoded'.format(uri)) # return requests.post(uri, data=data) which might include code, classes, or functions. Output only the next line.
@pytest.mark.events
Next line prediction: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) event_data = { 'title': 'Some event', 'text': '<a href="https://somewhere.example.org/events?reference=482a38ce-791e-11e6-b152-7cd1c55000be">see also</a>', 'tags': 'event,alert,important', 'reference': '482a38ce-791e-11e6-b152-7cd1c55000be', } @pytest_twisted.inlineCallbacks <|code_end|> . Use current file imports: (import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_events, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep, http_json_sensor, http_form_sensor) and context including class names, function names, or small code snippets from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) # # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def http_form_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using x-www-form-urlencoded'.format(uri)) # return requests.post(uri, data=data) . Output only the next line.
@pytest.mark.mqtt
Given snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) event_data = { 'title': 'Some event', 'text': '<a href="https://somewhere.example.org/events?reference=482a38ce-791e-11e6-b152-7cd1c55000be">see also</a>', <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.mqttkit import settings, influx_events, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep, http_json_sensor, http_form_sensor and context: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) # # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def http_form_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using x-www-form-urlencoded'.format(uri)) # return requests.post(uri, data=data) which might include code, classes, or functions. Output only the next line.
'tags': 'event,alert,important',
Here is a snippet: <|code_start|> logger.info('Setting up library "{}" with headers "{}", cache file is "{}"'.format( self.library_file, ', '.join(self.header_files), self.cache_file)) # holding the library essentials self.parser = None self.clib = None self.annotations = None self.setup() self.parse() self.parse_annotations() self.load() def setup(self): # counter "ValueError: number of bits invalid for bit field" monkeypatch_pyclibrary_ctypes_struct() # register header- and library paths # https://pyclibrary.readthedocs.org/en/latest/get_started/configuration.html#specifying-headers-and-libraries-locations # TODO: this probably acts on a global basis; think about it if self.include_path: add_header_locations([self.include_path]) if self.library_path: add_library_locations([self.library_path]) # define extra types suitable for embedded use types = { 'uint8_t': c_uint8, 'uint16_t': c_uint16, <|code_end|> . Write the next line using the current file imports: import os import re from collections import OrderedDict from cornice.util import to_list from pprint import pprint from binascii import hexlify from tabulate import tabulate from appdirs import user_cache_dir from ctypes import c_uint8, c_uint16, c_uint32, c_int8, c_int16, c_int32 from pyclibrary.c_parser import CParser from pyclibrary import CLibrary, auto_init from pyclibrary.utils import add_header_locations, add_library_locations from sympy.core.sympify import sympify from twisted.logger import Logger from kotori.daq.intercom.pyclibrary_ext.c_parser import CParserEnhanced from kotori.daq.intercom.pyclibrary_ext.backend_ctypes import monkeypatch_pyclibrary_ctypes_struct from kotori.util.common import slm and context from other files: # Path: kotori/daq/intercom/pyclibrary_ext/backend_ctypes.py # def monkeypatch_pyclibrary_ctypes_struct(): # pyclibrary.backends.ctypes.CTypesCLibrary._get_struct = _get_struct # # Path: kotori/util/common.py # def slm(message): # """sanitize log message""" # return str(message).replace('{', '{{').replace('}', '}}') , which may include functions, classes, or code. Output only the next line.
'uint32_t': c_uint32,
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2015-2016 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de> logger = Logger() class LibraryAdapter(object): def __init__(self, header_files, library_file, include_path=None, library_path=None, cache_path=None): self.header_files = to_list(header_files) self.library_file = library_file self.include_path = include_path or os.curdir self.library_path = library_path or os.curdir self.cache_path = cache_path or './var' self.include_path = os.path.abspath(self.include_path) self.library_path = os.path.abspath(self.library_path) <|code_end|> . Write the next line using the current file imports: import os import re from collections import OrderedDict from cornice.util import to_list from pprint import pprint from binascii import hexlify from tabulate import tabulate from appdirs import user_cache_dir from ctypes import c_uint8, c_uint16, c_uint32, c_int8, c_int16, c_int32 from pyclibrary.c_parser import CParser from pyclibrary import CLibrary, auto_init from pyclibrary.utils import add_header_locations, add_library_locations from sympy.core.sympify import sympify from twisted.logger import Logger from kotori.daq.intercom.pyclibrary_ext.c_parser import CParserEnhanced from kotori.daq.intercom.pyclibrary_ext.backend_ctypes import monkeypatch_pyclibrary_ctypes_struct from kotori.util.common import slm and context from other files: # Path: kotori/daq/intercom/pyclibrary_ext/backend_ctypes.py # def monkeypatch_pyclibrary_ctypes_struct(): # pyclibrary.backends.ctypes.CTypesCLibrary._get_struct = _get_struct # # Path: kotori/util/common.py # def slm(message): # """sanitize log message""" # return str(message).replace('{', '{{').replace('}', '}}') , which may include functions, classes, or code. Output only the next line.
cache_key = \
Predict the next line after this snippet: <|code_start|> @dataclasses.dataclass class DockerImage: name: str architecture: str version: str base_image: str dockerfile: str errors: str @property def tag(self): architecture = self.architecture if architecture == "arm32v7": architecture = "armv7" return f"daqzilla/{self.name}-{architecture}:{self.version}" <|code_end|> using the current file's imports: import dataclasses import os import requests import sh from datetime import datetime from pathlib import Path from typing import List from invoke import Context from tasks.packaging.model import DockerImageRecipe, PackageSpecification from tasks.util import print_header, run_commands, task and any relevant context from other files: # Path: tasks/packaging/model.py # class DockerImageRecipe: # enabled: bool # architecture: str # flavors: List[str] # base_distribution: str # base_image: str # platform: str # # class PackageSpecification: # """ # Data structure for holding information about individual distribution # packages. # """ # # # Package flavor, e.g. minimal, standard, full. # flavor: str # # # Package version. # version: str # # # Distribution name, e.g. stretch, buster. # distribution: str # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # Computed package name, taking `flavor` into account. # name: str = None # # # List of Python `extra` labels, taking `flavor` into account. # features: str = None # # # Map architecture labels to Debian distribution package architecture name. # debian_architecture_map: ClassVar = { # "arm64v8": "arm64", # "arm32v7": "armhf", # } # # def __post_init__(self): # self.resolve() # self.validate() # # def validate(self): # """ # Sanity checks. All designated specification fields must be set and not # be empty. # """ # for field in dataclasses.fields(self): # value = getattr(self, field.name) # if value is None: # raise ValueError( # f'Package specification field "{field.name}" is required.' # ) # # def resolve(self): # """ # Resolve the designated package flavor to a list of Python package # `extra` labels. # """ # if self.flavor == "minimal": # self.name = "kotori-minimal" # self.features = "daq" # elif self.flavor == "standard": # self.name = "kotori-standard" # self.features = "daq,daq_geospatial,export" # elif self.flavor == "full": # self.name = "kotori" # self.features = "daq,daq_geospatial,export,plotting,firmware,scientific" # else: # raise ValueError("Unknown package flavor") # # @property # def debian_architecture(self): # """ # Resolve the architecture label to a Debian package architecture suffix. # """ # return self.debian_architecture_map.get(self.architecture, self.architecture) # # def deb_name(self): # """ # Compute the full name of the Debian `.deb` package. # """ # return f"{self.name}_{self.version}-1~{self.distribution}_{self.debian_architecture}.deb" # # Path: tasks/util.py # def print_header(label, char="-"): # length = max(len(label), 42) # print(char * length) # print(label.center(length)) # print(char * length) # # def run_commands(commands): # if isinstance(commands, str): # commands = [commands] # for command in commands: # command = command.strip() # print(command) # exitcode = os.system(command) # if exitcode != 0: # raise SystemExit("Command failed") # # def task(f: F) -> F: # f.__annotations__ = {} # return invoke.task(f) . Output only the next line.
def build(self, package_file: Path):
Based on the snippet: <|code_start|> @dataclasses.dataclass class DockerImage: name: str architecture: str version: str base_image: str dockerfile: str errors: str @property def tag(self): architecture = self.architecture if architecture == "arm32v7": architecture = "armv7" <|code_end|> , predict the immediate next line with the help of imports: import dataclasses import os import requests import sh from datetime import datetime from pathlib import Path from typing import List from invoke import Context from tasks.packaging.model import DockerImageRecipe, PackageSpecification from tasks.util import print_header, run_commands, task and context (classes, functions, sometimes code) from other files: # Path: tasks/packaging/model.py # class DockerImageRecipe: # enabled: bool # architecture: str # flavors: List[str] # base_distribution: str # base_image: str # platform: str # # class PackageSpecification: # """ # Data structure for holding information about individual distribution # packages. # """ # # # Package flavor, e.g. minimal, standard, full. # flavor: str # # # Package version. # version: str # # # Distribution name, e.g. stretch, buster. # distribution: str # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # Computed package name, taking `flavor` into account. # name: str = None # # # List of Python `extra` labels, taking `flavor` into account. # features: str = None # # # Map architecture labels to Debian distribution package architecture name. # debian_architecture_map: ClassVar = { # "arm64v8": "arm64", # "arm32v7": "armhf", # } # # def __post_init__(self): # self.resolve() # self.validate() # # def validate(self): # """ # Sanity checks. All designated specification fields must be set and not # be empty. # """ # for field in dataclasses.fields(self): # value = getattr(self, field.name) # if value is None: # raise ValueError( # f'Package specification field "{field.name}" is required.' # ) # # def resolve(self): # """ # Resolve the designated package flavor to a list of Python package # `extra` labels. # """ # if self.flavor == "minimal": # self.name = "kotori-minimal" # self.features = "daq" # elif self.flavor == "standard": # self.name = "kotori-standard" # self.features = "daq,daq_geospatial,export" # elif self.flavor == "full": # self.name = "kotori" # self.features = "daq,daq_geospatial,export,plotting,firmware,scientific" # else: # raise ValueError("Unknown package flavor") # # @property # def debian_architecture(self): # """ # Resolve the architecture label to a Debian package architecture suffix. # """ # return self.debian_architecture_map.get(self.architecture, self.architecture) # # def deb_name(self): # """ # Compute the full name of the Debian `.deb` package. # """ # return f"{self.name}_{self.version}-1~{self.distribution}_{self.debian_architecture}.deb" # # Path: tasks/util.py # def print_header(label, char="-"): # length = max(len(label), 42) # print(char * length) # print(label.center(length)) # print(char * length) # # def run_commands(commands): # if isinstance(commands, str): # commands = [commands] # for command in commands: # command = command.strip() # print(command) # exitcode = os.system(command) # if exitcode != 0: # raise SystemExit("Command failed") # # def task(f: F) -> F: # f.__annotations__ = {} # return invoke.task(f) . Output only the next line.
return f"daqzilla/{self.name}-{architecture}:{self.version}"
Given the following code snippet before the placeholder: <|code_start|> @dataclasses.dataclass class DockerImage: name: str architecture: str version: str base_image: str dockerfile: str errors: str @property def tag(self): architecture = self.architecture if architecture == "arm32v7": architecture = "armv7" return f"daqzilla/{self.name}-{architecture}:{self.version}" def build(self, package_file: Path): # Sanity checks. if not package_file.exists(): message = f"Package {package_file} missing." <|code_end|> , predict the next line using imports from the current file: import dataclasses import os import requests import sh from datetime import datetime from pathlib import Path from typing import List from invoke import Context from tasks.packaging.model import DockerImageRecipe, PackageSpecification from tasks.util import print_header, run_commands, task and context including class names, function names, and sometimes code from other files: # Path: tasks/packaging/model.py # class DockerImageRecipe: # enabled: bool # architecture: str # flavors: List[str] # base_distribution: str # base_image: str # platform: str # # class PackageSpecification: # """ # Data structure for holding information about individual distribution # packages. # """ # # # Package flavor, e.g. minimal, standard, full. # flavor: str # # # Package version. # version: str # # # Distribution name, e.g. stretch, buster. # distribution: str # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # Computed package name, taking `flavor` into account. # name: str = None # # # List of Python `extra` labels, taking `flavor` into account. # features: str = None # # # Map architecture labels to Debian distribution package architecture name. # debian_architecture_map: ClassVar = { # "arm64v8": "arm64", # "arm32v7": "armhf", # } # # def __post_init__(self): # self.resolve() # self.validate() # # def validate(self): # """ # Sanity checks. All designated specification fields must be set and not # be empty. # """ # for field in dataclasses.fields(self): # value = getattr(self, field.name) # if value is None: # raise ValueError( # f'Package specification field "{field.name}" is required.' # ) # # def resolve(self): # """ # Resolve the designated package flavor to a list of Python package # `extra` labels. # """ # if self.flavor == "minimal": # self.name = "kotori-minimal" # self.features = "daq" # elif self.flavor == "standard": # self.name = "kotori-standard" # self.features = "daq,daq_geospatial,export" # elif self.flavor == "full": # self.name = "kotori" # self.features = "daq,daq_geospatial,export,plotting,firmware,scientific" # else: # raise ValueError("Unknown package flavor") # # @property # def debian_architecture(self): # """ # Resolve the architecture label to a Debian package architecture suffix. # """ # return self.debian_architecture_map.get(self.architecture, self.architecture) # # def deb_name(self): # """ # Compute the full name of the Debian `.deb` package. # """ # return f"{self.name}_{self.version}-1~{self.distribution}_{self.debian_architecture}.deb" # # Path: tasks/util.py # def print_header(label, char="-"): # length = max(len(label), 42) # print(char * length) # print(label.center(length)) # print(char * length) # # def run_commands(commands): # if isinstance(commands, str): # commands = [commands] # for command in commands: # command = command.strip() # print(command) # exitcode = os.system(command) # if exitcode != 0: # raise SystemExit("Command failed") # # def task(f: F) -> F: # f.__annotations__ = {} # return invoke.task(f) . Output only the next line.
if self.errors == "raise":
Next line prediction: <|code_start|> @dataclasses.dataclass class DockerImage: name: str architecture: str version: str <|code_end|> . Use current file imports: (import dataclasses import os import requests import sh from datetime import datetime from pathlib import Path from typing import List from invoke import Context from tasks.packaging.model import DockerImageRecipe, PackageSpecification from tasks.util import print_header, run_commands, task) and context including class names, function names, or small code snippets from other files: # Path: tasks/packaging/model.py # class DockerImageRecipe: # enabled: bool # architecture: str # flavors: List[str] # base_distribution: str # base_image: str # platform: str # # class PackageSpecification: # """ # Data structure for holding information about individual distribution # packages. # """ # # # Package flavor, e.g. minimal, standard, full. # flavor: str # # # Package version. # version: str # # # Distribution name, e.g. stretch, buster. # distribution: str # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # Computed package name, taking `flavor` into account. # name: str = None # # # List of Python `extra` labels, taking `flavor` into account. # features: str = None # # # Map architecture labels to Debian distribution package architecture name. # debian_architecture_map: ClassVar = { # "arm64v8": "arm64", # "arm32v7": "armhf", # } # # def __post_init__(self): # self.resolve() # self.validate() # # def validate(self): # """ # Sanity checks. All designated specification fields must be set and not # be empty. # """ # for field in dataclasses.fields(self): # value = getattr(self, field.name) # if value is None: # raise ValueError( # f'Package specification field "{field.name}" is required.' # ) # # def resolve(self): # """ # Resolve the designated package flavor to a list of Python package # `extra` labels. # """ # if self.flavor == "minimal": # self.name = "kotori-minimal" # self.features = "daq" # elif self.flavor == "standard": # self.name = "kotori-standard" # self.features = "daq,daq_geospatial,export" # elif self.flavor == "full": # self.name = "kotori" # self.features = "daq,daq_geospatial,export,plotting,firmware,scientific" # else: # raise ValueError("Unknown package flavor") # # @property # def debian_architecture(self): # """ # Resolve the architecture label to a Debian package architecture suffix. # """ # return self.debian_architecture_map.get(self.architecture, self.architecture) # # def deb_name(self): # """ # Compute the full name of the Debian `.deb` package. # """ # return f"{self.name}_{self.version}-1~{self.distribution}_{self.debian_architecture}.deb" # # Path: tasks/util.py # def print_header(label, char="-"): # length = max(len(label), 42) # print(char * length) # print(label.center(length)) # print(char * length) # # def run_commands(commands): # if isinstance(commands, str): # commands = [commands] # for command in commands: # command = command.strip() # print(command) # exitcode = os.system(command) # if exitcode != 0: # raise SystemExit("Command failed") # # def task(f: F) -> F: # f.__annotations__ = {} # return invoke.task(f) . Output only the next line.
base_image: str
Predict the next line after this snippet: <|code_start|> @dataclasses.dataclass class DockerImage: name: str architecture: str version: str base_image: str dockerfile: str errors: str @property def tag(self): architecture = self.architecture if architecture == "arm32v7": architecture = "armv7" <|code_end|> using the current file's imports: import dataclasses import os import requests import sh from datetime import datetime from pathlib import Path from typing import List from invoke import Context from tasks.packaging.model import DockerImageRecipe, PackageSpecification from tasks.util import print_header, run_commands, task and any relevant context from other files: # Path: tasks/packaging/model.py # class DockerImageRecipe: # enabled: bool # architecture: str # flavors: List[str] # base_distribution: str # base_image: str # platform: str # # class PackageSpecification: # """ # Data structure for holding information about individual distribution # packages. # """ # # # Package flavor, e.g. minimal, standard, full. # flavor: str # # # Package version. # version: str # # # Distribution name, e.g. stretch, buster. # distribution: str # # # Architecture, e.g. amd64, arm64v8, arm32v7. # architecture: str # # # Computed package name, taking `flavor` into account. # name: str = None # # # List of Python `extra` labels, taking `flavor` into account. # features: str = None # # # Map architecture labels to Debian distribution package architecture name. # debian_architecture_map: ClassVar = { # "arm64v8": "arm64", # "arm32v7": "armhf", # } # # def __post_init__(self): # self.resolve() # self.validate() # # def validate(self): # """ # Sanity checks. All designated specification fields must be set and not # be empty. # """ # for field in dataclasses.fields(self): # value = getattr(self, field.name) # if value is None: # raise ValueError( # f'Package specification field "{field.name}" is required.' # ) # # def resolve(self): # """ # Resolve the designated package flavor to a list of Python package # `extra` labels. # """ # if self.flavor == "minimal": # self.name = "kotori-minimal" # self.features = "daq" # elif self.flavor == "standard": # self.name = "kotori-standard" # self.features = "daq,daq_geospatial,export" # elif self.flavor == "full": # self.name = "kotori" # self.features = "daq,daq_geospatial,export,plotting,firmware,scientific" # else: # raise ValueError("Unknown package flavor") # # @property # def debian_architecture(self): # """ # Resolve the architecture label to a Debian package architecture suffix. # """ # return self.debian_architecture_map.get(self.architecture, self.architecture) # # def deb_name(self): # """ # Compute the full name of the Debian `.deb` package. # """ # return f"{self.name}_{self.version}-1~{self.distribution}_{self.debian_architecture}.deb" # # Path: tasks/util.py # def print_header(label, char="-"): # length = max(len(label), 42) # print(char * length) # print(label.center(length)) # print(char * length) # # def run_commands(commands): # if isinstance(commands, str): # commands = [commands] # for command in commands: # command = command.strip() # print(command) # exitcode = os.system(command) # if exitcode != 0: # raise SystemExit("Command failed") # # def task(f: F) -> F: # f.__annotations__ = {} # return invoke.task(f) . Output only the next line.
return f"daqzilla/{self.name}-{architecture}:{self.version}"
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) tasmota_sensor_topic = 'mqttkit-1/itest/foo/bar/tele/SENSOR' tasmota_state_topic = 'mqttkit-1/itest/foo/bar/tele/STATE' @pytest_twisted.inlineCallbacks @pytest.mark.tasmota <|code_end|> , generate the next line using the imports in this file: import json import logging import pytest import pytest_twisted from test.settings.mqttkit import influx_sensors, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep and context (functions, classes, or occasionally code) from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
def test_tasmota_sonoff_sc(machinery, create_influxdb, reset_influxdb):
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) tasmota_sensor_topic = 'mqttkit-1/itest/foo/bar/tele/SENSOR' tasmota_state_topic = 'mqttkit-1/itest/foo/bar/tele/STATE' @pytest_twisted.inlineCallbacks <|code_end|> , predict the next line using imports from the current file: import json import logging import pytest import pytest_twisted from test.settings.mqttkit import influx_sensors, PROCESS_DELAY_MQTT from test.util import mqtt_json_sensor, sleep and context including class names, function names, and sometimes code from other files: # Path: test/settings/mqttkit.py # PROCESS_DELAY_MQTT = 0.3 # PROCESS_DELAY_HTTP = 0.3 # class TestSettings: # # Path: test/util.py # def mqtt_json_sensor(topic, data): # payload = json.dumps(data) # return mqtt_sensor(topic, payload) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
@pytest.mark.tasmota
Given snippet: <|code_start|> for channel_label in channel_labels: channel_settings = config[channel_label] channel_info = get_channel_info(channel_label, channel_settings) channel_infos.append(channel_info) print(tabulate(channel_infos, headers='keys')) def get_channel_info(channel_label, channel_settings): channel = OrderedDict() channel['name'] = sanitize_channel_label(channel_label) #channel['label'] = channel_label channel['udp port'] = channel_settings['udp_port'] channel['wamp topic'] = channel_settings['wamp_topic'] channel['header files'] = channel_settings['header_files'] channel['path'] = os.path.abspath(channel_settings['include_path']) return channel def lst_message(channel, adapter, options): target = options.get('--target') struct_name = options.get('<name>') payload_ascii = options.get('<payload>') if options.get('info'): print() if struct_name: try: struct_adapter = adapter.struct_registry.get(struct_name) struct_adapter.print_schema() <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys import socket import logging from binascii import unhexlify from urllib.parse import urlparse from tabulate import tabulate from collections import OrderedDict from kotori.util.configuration import read_list and context: # Path: kotori/util/configuration.py # def read_list(string, separator=u',', empty_elements=True): # data = list(map(str.strip, string.split(separator))) # if empty_elements == False: # data = [x for x in data if bool(x)] # return data which might include code, classes, or functions. Output only the next line.
except KeyError:
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2016-2021 Andreas Motl <andreas.motl@elmyra.de> log = Logger() try: except ImportError: <|code_end|> . Use current file imports: import tempfile import pandas from twisted.logger import Logger, LogLevel from twisted.web.template import renderElement from kotori.io.export.html import DatatablesPage from kotori.io.protocol.util import get_data_uri from kotori.io.export.util import dataframe_index_and_sort, make_timezone_unaware and context (classes, functions, or code) from other files: # Path: kotori/io/export/html.py # class DatatablesPage(GenericPage): # """ # DataTables plugin, see https://datatables.net/ # """ # # loader = XMLString(""" # <html xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1" t:render="fill_slots"> # <head> # <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/u/dt/jq-2.2.3,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.12,b-1.2.1,b-colvis-1.2.1,b-html5-1.2.1,b-print-1.2.1,cr-1.3.2,fc-3.2.2,fh-3.1.2,kt-2.1.2,r-2.1.0,rr-1.1.2,sc-1.4.2,se-1.2.0/datatables.min.css" /> # <script src="//cdn.datatables.net/u/dt/jq-2.2.3,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.12,b-1.2.1,b-colvis-1.2.1,b-html5-1.2.1,b-print-1.2.1,cr-1.3.2,fc-3.2.2,fh-3.1.2,kt-2.1.2,r-2.1.0,rr-1.1.2,sc-1.4.2,se-1.2.0/datatables.min.js"></script> # <style type="text/css" media="screen"> # body { # font-family: Arial, sans-serif; # font-size2: larger; # } # h1 { # font-size: large; # } # .footer { # padding-top: 1em; # font-size: x-small; # } # .footer.left { # float: left; # } # .footer.right { # float: right; # } # .clearfix { # clear: both; # } # </style> # </head> # <body> # <h1 t:render="header"/> # <div id="dataframe" class="display" style="width: 100%"/> # <table id="example" class="display" cellspacing="0" width="100%"> # </table> # <script type="text/javascript"> # $(document).ready(function(){ # var data_uri = '<t:slot name="data_uri" />'.replace('<![CDATA[', '').replace(']]>', ''); # $('#dataframe').load(data_uri, function() { # var table = $('.dataframe'); # table.attr('border', '0'); # table.DataTable({ # buttons: [ # //'copy', 'csv', 'excel', 'pdf', 'print' # 'copy', 'csv', 'excel', 'print' # ] # }); # table.attr('class', 'display dataTable'); # }); # console.log('READY.'); # # }); # </script> # <div class="footer left" t:render="footer_left"/> # <div class="footer right" t:render="footer_right"/> # <div class="clearfix"/> # </body> # </html> # """) # # def __init__(self, data_uri=None, bucket=None): # self.data_uri = data_uri # self.bucket = bucket # # Path: kotori/io/protocol/util.py # def get_data_uri(bucket, sibling=None, more_params=None): # """ # Compute uri to data source as sibling to the current path. # Add "from" and "to" query parameters from bucket. # """ # # more_params = more_params or {} # # forward_parameters = [u'from', u'to', u'exclude', u'include', u'pad', u'backfill', u'interpolate'] # # request = bucket.request # # # Honor X-Forwarded-Proto request header if behind SSL-terminating HTTP proxy # twisted_honor_reverse_proxy(request) # # url = URL() # for param in forward_parameters: # if param in bucket.tdata: # url = url.add(str(param), str(bucket.tdata[param])) # # for param, value in more_params.items(): # # # Special rule: Don't add any of "pad" or "backfill", if "interpolate" is true # do_interpolate = 'interpolate' in bucket.tdata and asbool(bucket.tdata.interpolate) # if do_interpolate and param in ['pad', 'backfill']: # continue # # url = url.add(str(param), str(value)) # # data_uri = str(request.URLPath().sibling(sibling.encode()).click(url._to_bytes())) # return data_uri # # Path: kotori/io/export/util.py # def dataframe_index_and_sort(df, column): # """ # Index and sort DataFrame on specified column. # """ # df = df.set_index([column]) # df = df.sort_index() # return df # # def make_timezone_unaware(df): # # Please ensure that datetimes are timezone unaware before writing to Excel. # # https://github.com/pandas-dev/pandas/pull/27129 # # https://github.com/pandas-dev/pandas/issues/28921 # # https://stackoverflow.com/questions/61802080/excelwriter-valueerror-excel-does-not-support-datetime-with-timezone-when-savin # # https://github.com/pandas-dev/pandas/issues/7056 # df['time'] = pandas.to_datetime( # df['time'], utc=True) \ # .dt.tz_convert('UTC') \ # .dt.tz_localize(None) . Output only the next line.
log.failure('Tabular export not available, please install "pandas".', level=LogLevel.warn)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2016-2021 Andreas Motl <andreas.motl@elmyra.de> log = Logger() try: except ImportError: log.failure('Tabular export not available, please install "pandas".', level=LogLevel.warn) <|code_end|> , generate the next line using the imports in this file: import tempfile import pandas from twisted.logger import Logger, LogLevel from twisted.web.template import renderElement from kotori.io.export.html import DatatablesPage from kotori.io.protocol.util import get_data_uri from kotori.io.export.util import dataframe_index_and_sort, make_timezone_unaware and context (functions, classes, or occasionally code) from other files: # Path: kotori/io/export/html.py # class DatatablesPage(GenericPage): # """ # DataTables plugin, see https://datatables.net/ # """ # # loader = XMLString(""" # <html xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1" t:render="fill_slots"> # <head> # <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/u/dt/jq-2.2.3,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.12,b-1.2.1,b-colvis-1.2.1,b-html5-1.2.1,b-print-1.2.1,cr-1.3.2,fc-3.2.2,fh-3.1.2,kt-2.1.2,r-2.1.0,rr-1.1.2,sc-1.4.2,se-1.2.0/datatables.min.css" /> # <script src="//cdn.datatables.net/u/dt/jq-2.2.3,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.12,b-1.2.1,b-colvis-1.2.1,b-html5-1.2.1,b-print-1.2.1,cr-1.3.2,fc-3.2.2,fh-3.1.2,kt-2.1.2,r-2.1.0,rr-1.1.2,sc-1.4.2,se-1.2.0/datatables.min.js"></script> # <style type="text/css" media="screen"> # body { # font-family: Arial, sans-serif; # font-size2: larger; # } # h1 { # font-size: large; # } # .footer { # padding-top: 1em; # font-size: x-small; # } # .footer.left { # float: left; # } # .footer.right { # float: right; # } # .clearfix { # clear: both; # } # </style> # </head> # <body> # <h1 t:render="header"/> # <div id="dataframe" class="display" style="width: 100%"/> # <table id="example" class="display" cellspacing="0" width="100%"> # </table> # <script type="text/javascript"> # $(document).ready(function(){ # var data_uri = '<t:slot name="data_uri" />'.replace('<![CDATA[', '').replace(']]>', ''); # $('#dataframe').load(data_uri, function() { # var table = $('.dataframe'); # table.attr('border', '0'); # table.DataTable({ # buttons: [ # //'copy', 'csv', 'excel', 'pdf', 'print' # 'copy', 'csv', 'excel', 'print' # ] # }); # table.attr('class', 'display dataTable'); # }); # console.log('READY.'); # # }); # </script> # <div class="footer left" t:render="footer_left"/> # <div class="footer right" t:render="footer_right"/> # <div class="clearfix"/> # </body> # </html> # """) # # def __init__(self, data_uri=None, bucket=None): # self.data_uri = data_uri # self.bucket = bucket # # Path: kotori/io/protocol/util.py # def get_data_uri(bucket, sibling=None, more_params=None): # """ # Compute uri to data source as sibling to the current path. # Add "from" and "to" query parameters from bucket. # """ # # more_params = more_params or {} # # forward_parameters = [u'from', u'to', u'exclude', u'include', u'pad', u'backfill', u'interpolate'] # # request = bucket.request # # # Honor X-Forwarded-Proto request header if behind SSL-terminating HTTP proxy # twisted_honor_reverse_proxy(request) # # url = URL() # for param in forward_parameters: # if param in bucket.tdata: # url = url.add(str(param), str(bucket.tdata[param])) # # for param, value in more_params.items(): # # # Special rule: Don't add any of "pad" or "backfill", if "interpolate" is true # do_interpolate = 'interpolate' in bucket.tdata and asbool(bucket.tdata.interpolate) # if do_interpolate and param in ['pad', 'backfill']: # continue # # url = url.add(str(param), str(value)) # # data_uri = str(request.URLPath().sibling(sibling.encode()).click(url._to_bytes())) # return data_uri # # Path: kotori/io/export/util.py # def dataframe_index_and_sort(df, column): # """ # Index and sort DataFrame on specified column. # """ # df = df.set_index([column]) # df = df.sort_index() # return df # # def make_timezone_unaware(df): # # Please ensure that datetimes are timezone unaware before writing to Excel. # # https://github.com/pandas-dev/pandas/pull/27129 # # https://github.com/pandas-dev/pandas/issues/28921 # # https://stackoverflow.com/questions/61802080/excelwriter-valueerror-excel-does-not-support-datetime-with-timezone-when-savin # # https://github.com/pandas-dev/pandas/issues/7056 # df['time'] = pandas.to_datetime( # df['time'], utc=True) \ # .dt.tz_convert('UTC') \ # .dt.tz_localize(None) . Output only the next line.
class UniversalTabularExporter(object):
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2014 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de> log = Logger() class CustomTemplate(Template): delimiter = '$$' class WebDashboard(Resource): def getChild(self, name, request): print('getChild:', name) if name == '': return WebDashboardIndex() else: document_root = resource_filename('kotori.web', '') return File(document_root) class WebDashboardIndex(Resource): def __init__(self, websocket_uri, filename): Resource.__init__(self) <|code_end|> using the current file's imports: from string import Template from pkg_resources import resource_filename from twisted.logger import Logger from twisted.internet import reactor from twisted.web.resource import Resource from twisted.web.server import Site from twisted.web.static import File from kotori.util.common import NodeId, get_hostname and any relevant context from other files: # Path: kotori/util/common.py # class NodeId(Singleton): # # config = None # NODE_ID = 'NODE_UNKNOWN' # # def __init__(self): # if not self.config: # self.config = ConfigStoreJson() # if 'uuid' not in self.config: # self.config['uuid'] = str(uuid4()) # self.NODE_ID = self.config['uuid'] # logger.debug("NODE ID: {}".format(self.NODE_ID)) # # def __str__(self): # return str(self.NODE_ID) # # def get_hostname(): # return socket.gethostname() . Output only the next line.
self.websocket_uri = websocket_uri
Given snippet: <|code_start|> document_root = resource_filename('kotori.web', '') return File(document_root) class WebDashboardIndex(Resource): def __init__(self, websocket_uri, filename): Resource.__init__(self) self.websocket_uri = websocket_uri self.filename = filename def render_GET(self, request): index = resource_filename('kotori.vendor.hydro2motion.web', self.filename) tpl = CustomTemplate(open(index).read()) response = tpl.substitute({ 'websocket_uri': self.websocket_uri, 'node_id': str(NodeId()), 'hostname': get_hostname(), }) return response.encode('utf-8') def boot_web(settings, debug=False): http_port = int(settings.hydro2motion.http_port) websocket_uri = str(settings.wamp.uri) dashboard = Resource() dashboard.putChild('', WebDashboardIndex(websocket_uri=websocket_uri, filename='index.html')) dashboard.putChild('fs.html', WebDashboardIndex(websocket_uri=websocket_uri, filename='fs.html')) <|code_end|> , continue by predicting the next line. Consider current file imports: from string import Template from pkg_resources import resource_filename from twisted.logger import Logger from twisted.internet import reactor from twisted.web.resource import Resource from twisted.web.server import Site from twisted.web.static import File from kotori.util.common import NodeId, get_hostname and context: # Path: kotori/util/common.py # class NodeId(Singleton): # # config = None # NODE_ID = 'NODE_UNKNOWN' # # def __init__(self): # if not self.config: # self.config = ConfigStoreJson() # if 'uuid' not in self.config: # self.config['uuid'] = str(uuid4()) # self.NODE_ID = self.config['uuid'] # logger.debug("NODE ID: {}".format(self.NODE_ID)) # # def __str__(self): # return str(self.NODE_ID) # # def get_hostname(): # return socket.gethostname() which might include code, classes, or functions. Output only the next line.
dashboard.putChild('poly.html', WebDashboardIndex(websocket_uri=websocket_uri, filename='poly.html'))
Next line prediction: <|code_start|> settings.setdefault('host', u'localhost') settings.setdefault('port', u'8086') settings.setdefault('username', u'root') settings.setdefault('password', u'root') settings.setdefault('database', database) settings.setdefault('pool_size', 10) settings.setdefault('use_udp', False) settings.setdefault('udp_port', u'4444') settings['port'] = int(settings['port']) settings['udp_port'] = int(settings['udp_port']) self.__dict__.update(**settings) # Bookeeping for all databases having been touched already self.databases_written_once = set() # Knowledge about all databases to be accessed using UDP # TODO: Refactor to configuration setting self.udp_databases = [ {'name': 'luftdaten_info', 'port': u'4445'}, ] self.host_uri = u'influxdb://{host}:{port}'.format(**self.__dict__) log.info(u'Storage target is {uri}, pool size is {pool_size}', uri=self.host_uri, pool_size=self.pool_size) self.influx_client = InfluxDBClient( host=self.host, port=self.port, username=self.username, password=self.password, database=self.database, pool_size=self.pool_size, <|code_end|> . Use current file imports: (import math import requests from copy import deepcopy from funcy import project from collections import OrderedDict from twisted.logger import Logger from influxdb.client import InfluxDBClient, InfluxDBClientError from kotori.io.protocol.util import parse_timestamp, is_number, convert_floats) and context including class names, function names, or small code snippets from other files: # Path: kotori/io/protocol/util.py # def parse_timestamp(timestamp): # # if isinstance(timestamp, text_type): # # # FIXME: Maybe use system timezone here by default. # # TODO: Make configurable via channel settings. # # # HACK: Assume CET (Europe/Berlin) for human readable timestamp w/o timezone offset # qualified = any([token in timestamp for token in ['Z', '+', ' CET', ' CEST']]) # if not qualified: # timestamp += ' CET' # # # Parse datetime string # # Remark: Maybe use pandas.tseries.tools.parse_time_string? # # TODO: Cache results of call to gettz to improve performance # berlin = gettz('Europe/Berlin') # tzinfos = {'CET': berlin, 'CEST': berlin} # timestamp = parse(timestamp, tzinfos=tzinfos) # # return timestamp # # def is_number(s): # """ # Check string for being a numeric value. # http://pythoncentral.io/how-to-check-if-a-string-is-a-number-in-python-including-unicode/ # """ # try: # float(s) # return True # except ValueError: # pass # # try: # import unicodedata # unicodedata.numeric(s) # return True # except (TypeError, ValueError): # pass # # return False # # def convert_floats(data, integers=None): # """ # Convert all numeric values in dictionary to float type. # """ # integers = integers or [] # delete_keys = [] # for key, value in data.items(): # try: # if isinstance(value, datetime.datetime): # continue # if is_number(value): # if key in integers: # data[key] = int(value) # else: # data[key] = float(value) # if math.isnan(data[key]): # delete_keys.append(key) # except: # pass # # for key in delete_keys: # del data[key] # # return data . Output only the next line.
timeout=10)
Next line prediction: <|code_start|> def write(self, meta, data): meta_copy = deepcopy(dict(meta)) data_copy = deepcopy(data) try: chunk = self.format_chunk(meta, data) except Exception as ex: log.failure(u'Could not format chunk (ex={ex_name}: {ex}): data={data}, meta={meta}', ex_name=ex.__class__.__name__, ex=ex, meta=meta_copy, data=data_copy) raise try: success = self.write_chunk(meta, chunk) return success except requests.exceptions.ConnectionError as ex: log.failure(u'Problem connecting to InfluxDB at {uri}: {ex}', uri=self.host_uri, ex=ex) raise except InfluxDBClientError as ex: if ex.code == 404 or 'database not found' in ex.content: log.info('Creating database "{database}"', database=meta.database) self.influx_client.create_database(meta.database) # Attempt second write <|code_end|> . Use current file imports: (import math import requests from copy import deepcopy from funcy import project from collections import OrderedDict from twisted.logger import Logger from influxdb.client import InfluxDBClient, InfluxDBClientError from kotori.io.protocol.util import parse_timestamp, is_number, convert_floats) and context including class names, function names, or small code snippets from other files: # Path: kotori/io/protocol/util.py # def parse_timestamp(timestamp): # # if isinstance(timestamp, text_type): # # # FIXME: Maybe use system timezone here by default. # # TODO: Make configurable via channel settings. # # # HACK: Assume CET (Europe/Berlin) for human readable timestamp w/o timezone offset # qualified = any([token in timestamp for token in ['Z', '+', ' CET', ' CEST']]) # if not qualified: # timestamp += ' CET' # # # Parse datetime string # # Remark: Maybe use pandas.tseries.tools.parse_time_string? # # TODO: Cache results of call to gettz to improve performance # berlin = gettz('Europe/Berlin') # tzinfos = {'CET': berlin, 'CEST': berlin} # timestamp = parse(timestamp, tzinfos=tzinfos) # # return timestamp # # def is_number(s): # """ # Check string for being a numeric value. # http://pythoncentral.io/how-to-check-if-a-string-is-a-number-in-python-including-unicode/ # """ # try: # float(s) # return True # except ValueError: # pass # # try: # import unicodedata # unicodedata.numeric(s) # return True # except (TypeError, ValueError): # pass # # return False # # def convert_floats(data, integers=None): # """ # Convert all numeric values in dictionary to float type. # """ # integers = integers or [] # delete_keys = [] # for key, value in data.items(): # try: # if isinstance(value, datetime.datetime): # continue # if is_number(value): # if key in integers: # data[key] = int(value) # else: # data[key] = float(value) # if math.isnan(data[key]): # delete_keys.append(key) # except: # pass # # for key in delete_keys: # del data[key] # # return data . Output only the next line.
success = self.write_chunk(meta, chunk)
Continue the code snippet: <|code_start|> # Bookeeping for all databases having been touched already self.databases_written_once = set() # Knowledge about all databases to be accessed using UDP # TODO: Refactor to configuration setting self.udp_databases = [ {'name': 'luftdaten_info', 'port': u'4445'}, ] self.host_uri = u'influxdb://{host}:{port}'.format(**self.__dict__) log.info(u'Storage target is {uri}, pool size is {pool_size}', uri=self.host_uri, pool_size=self.pool_size) self.influx_client = InfluxDBClient( host=self.host, port=self.port, username=self.username, password=self.password, database=self.database, pool_size=self.pool_size, timeout=10) # TODO: Hold references to multiple UDP databases using mapping "self.udp_databases". self.influx_client_udp = None if settings['use_udp']: self.influx_client_udp = InfluxDBClient( host=self.host, port=self.port, username=self.username, password=self.password, use_udp=settings['use_udp'], udp_port=settings['udp_port'], timeout=10) def is_udp_database(self, name): for entry in self.udp_databases: if entry['name'] == name: <|code_end|> . Use current file imports: import math import requests from copy import deepcopy from funcy import project from collections import OrderedDict from twisted.logger import Logger from influxdb.client import InfluxDBClient, InfluxDBClientError from kotori.io.protocol.util import parse_timestamp, is_number, convert_floats and context (classes, functions, or code) from other files: # Path: kotori/io/protocol/util.py # def parse_timestamp(timestamp): # # if isinstance(timestamp, text_type): # # # FIXME: Maybe use system timezone here by default. # # TODO: Make configurable via channel settings. # # # HACK: Assume CET (Europe/Berlin) for human readable timestamp w/o timezone offset # qualified = any([token in timestamp for token in ['Z', '+', ' CET', ' CEST']]) # if not qualified: # timestamp += ' CET' # # # Parse datetime string # # Remark: Maybe use pandas.tseries.tools.parse_time_string? # # TODO: Cache results of call to gettz to improve performance # berlin = gettz('Europe/Berlin') # tzinfos = {'CET': berlin, 'CEST': berlin} # timestamp = parse(timestamp, tzinfos=tzinfos) # # return timestamp # # def is_number(s): # """ # Check string for being a numeric value. # http://pythoncentral.io/how-to-check-if-a-string-is-a-number-in-python-including-unicode/ # """ # try: # float(s) # return True # except ValueError: # pass # # try: # import unicodedata # unicodedata.numeric(s) # return True # except (TypeError, ValueError): # pass # # return False # # def convert_floats(data, integers=None): # """ # Convert all numeric values in dictionary to float type. # """ # integers = integers or [] # delete_keys = [] # for key, value in data.items(): # try: # if isinstance(value, datetime.datetime): # continue # if is_number(value): # if key in integers: # data[key] = int(value) # else: # data[key] = float(value) # if math.isnan(data[key]): # delete_keys.append(key) # except: # pass # # for key in delete_keys: # del data[key] # # return data . Output only the next line.
return True
Given the following code snippet before the placeholder: <|code_start|> data_in = { "esp8266id": 12041741, "sensordatavalues": [ { "value_type": "SDS_P1", "value": "35.67" }, { "value_type": "SDS_P2", "value": "17.00" }, { "value_type": "BME280_temperature", "value": "-2.83" }, { "value_type": "BME280_humidity", "value": "66.73" }, { "value_type": "BME280_pressure", "value": "100535.97" }, { "value_type": "samples", "value": "3016882" }, { "value_type": "min_micro", <|code_end|> , predict the next line using imports from the current file: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.basic import settings, influx_sensors, create_influxdb, reset_influxdb, reset_grafana, PROCESS_DELAY_MQTT from test.util import http_json_sensor, sleep and context including class names, function names, and sometimes code from other files: # Path: test/settings/basic.py # PROCESS_DELAY_MQTT = 0.3 # class BasicSettings: # # Path: test/util.py # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
"value": "77"
Given the following code snippet before the placeholder: <|code_start|> data_in = { "esp8266id": 12041741, "sensordatavalues": [ { "value_type": "SDS_P1", "value": "35.67" }, { "value_type": "SDS_P2", "value": "17.00" }, { "value_type": "BME280_temperature", "value": "-2.83" }, { "value_type": "BME280_humidity", "value": "66.73" }, { "value_type": "BME280_pressure", "value": "100535.97" }, { "value_type": "samples", "value": "3016882" }, { <|code_end|> , predict the next line using imports from the current file: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.basic import settings, influx_sensors, create_influxdb, reset_influxdb, reset_grafana, PROCESS_DELAY_MQTT from test.util import http_json_sensor, sleep and context including class names, function names, and sometimes code from other files: # Path: test/settings/basic.py # PROCESS_DELAY_MQTT = 0.3 # class BasicSettings: # # Path: test/util.py # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
"value_type": "min_micro",
Given snippet: <|code_start|> logger = logging.getLogger(__name__) # https://community.hiveeyes.org/t/more-data-acquisition-payload-formats-for-kotori/1421/2 data_in = { "esp8266id": 12041741, "sensordatavalues": [ { "value_type": "SDS_P1", "value": "35.67" }, { "value_type": "SDS_P2", "value": "17.00" }, { "value_type": "BME280_temperature", "value": "-2.83" }, { "value_type": "BME280_humidity", "value": "66.73" }, { "value_type": "BME280_pressure", "value": "100535.97" <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.basic import settings, influx_sensors, create_influxdb, reset_influxdb, reset_grafana, PROCESS_DELAY_MQTT from test.util import http_json_sensor, sleep and context: # Path: test/settings/basic.py # PROCESS_DELAY_MQTT = 0.3 # class BasicSettings: # # Path: test/util.py # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) which might include code, classes, or functions. Output only the next line.
},
Based on the snippet: <|code_start|> logger = logging.getLogger(__name__) # https://community.hiveeyes.org/t/more-data-acquisition-payload-formats-for-kotori/1421/2 data_in = { "esp8266id": 12041741, "sensordatavalues": [ { "value_type": "SDS_P1", "value": "35.67" }, { "value_type": "SDS_P2", "value": "17.00" }, { "value_type": "BME280_temperature", "value": "-2.83" }, { "value_type": "BME280_humidity", "value": "66.73" }, { "value_type": "BME280_pressure", "value": "100535.97" <|code_end|> , predict the immediate next line with the help of imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.basic import settings, influx_sensors, create_influxdb, reset_influxdb, reset_grafana, PROCESS_DELAY_MQTT from test.util import http_json_sensor, sleep and context (classes, functions, sometimes code) from other files: # Path: test/settings/basic.py # PROCESS_DELAY_MQTT = 0.3 # class BasicSettings: # # Path: test/util.py # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
},
Predict the next line after this snippet: <|code_start|> }, { "value_type": "BME280_temperature", "value": "-2.83" }, { "value_type": "BME280_humidity", "value": "66.73" }, { "value_type": "BME280_pressure", "value": "100535.97" }, { "value_type": "samples", "value": "3016882" }, { "value_type": "min_micro", "value": "77" }, { "value_type": "max_micro", "value": "26303" }, { "value_type": "signal", "value": "-66" } ], <|code_end|> using the current file's imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.basic import settings, influx_sensors, create_influxdb, reset_influxdb, reset_grafana, PROCESS_DELAY_MQTT from test.util import http_json_sensor, sleep and any relevant context from other files: # Path: test/settings/basic.py # PROCESS_DELAY_MQTT = 0.3 # class BasicSettings: # # Path: test/util.py # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
"software_version": "NRZ-2018-123B"
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) # https://community.hiveeyes.org/t/more-data-acquisition-payload-formats-for-kotori/1421/2 data_in = { "esp8266id": 12041741, "sensordatavalues": [ { "value_type": "SDS_P1", "value": "35.67" }, { <|code_end|> . Use current file imports: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.basic import settings, influx_sensors, create_influxdb, reset_influxdb, reset_grafana, PROCESS_DELAY_MQTT from test.util import http_json_sensor, sleep and context (classes, functions, or code) from other files: # Path: test/settings/basic.py # PROCESS_DELAY_MQTT = 0.3 # class BasicSettings: # # Path: test/util.py # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
"value_type": "SDS_P2",
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # (c) 2020-2021 Andreas Motl <andreas@getkotori.org> logger = logging.getLogger(__name__) # https://community.hiveeyes.org/t/more-data-acquisition-payload-formats-for-kotori/1421/2 data_in = { "esp8266id": 12041741, "sensordatavalues": [ { "value_type": "SDS_P1", "value": "35.67" }, <|code_end|> , generate the next line using the imports in this file: import logging import pytest import pytest_twisted from twisted.internet import threads from test.settings.basic import settings, influx_sensors, create_influxdb, reset_influxdb, reset_grafana, PROCESS_DELAY_MQTT from test.util import http_json_sensor, sleep and context (functions, classes, or occasionally code) from other files: # Path: test/settings/basic.py # PROCESS_DELAY_MQTT = 0.3 # class BasicSettings: # # Path: test/util.py # def http_json_sensor(topic, data): # uri = 'http://localhost:24642/api{}'.format(topic) # logger.info('HTTP: Submitting reading to {} using JSON'.format(uri)) # return requests.post(uri, json=data) # # def sleep(secs): # # https://gist.github.com/jhorman/891717 # return deferLater(reactor, secs, lambda: None) . Output only the next line.
{