Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for this snippet: <|code_start|># Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl> # # This file is part of django-shopkit. # # django-shopkit is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. logger = logging.getLogger(__name__) try: logger.debug(u'Sorl-thumbnail found: using it.') except ImportError: ImageField = models.ImageField <|code_end|> with the help of current file imports: import logging from django.db import models from django.utils.translation import ugettext_lazy as _ from sorl.thumbnail import ImageField from shopkit.core.settings import PRODUCT_MODEL from shopkit.core.basemodels import OrderedInlineItemBase and context from other files: # Path: shopkit/core/settings.py # PRODUCT_MODEL = getattr(settings, 'SHOPKIT_PRODUCT_MODEL') # # Path: shopkit/core/basemodels.py # class OrderedInlineItemBase(models.Model): # """ # This base class does what, actually, order_with_respect_to should do # but (for now) doesn't implement very well: ordering of objects with # a fk-relation to some class. # # As we do not know what the class with the respective relation is, it # is important to note that something like the following is added:: # # class MyOrderedInline(OrderedInlineItemBase): # # <related> = models.ForeignKey(RelatedModel) # # class Meta(OrderedInlineItemBase.Meta): # unique_together = ('sort_order', '<related>') # # def get_related_ordering(self): # return self.__class__.objects.filter(<related>=self.<related>) # # # # ... Or we could simply wait for the Django developers to fix # `order_with_respect_to` once and for all. (Work in progress... # See `Ticket #13 <http://code.djangoproject.com/ticket/13>`.) # # # """ # # class Meta: # abstract = True # ordering = ('sort_order', ) # # def get_related_ordering(self): # """ # Get a :class:`QuerySet <django.db.models.QuerySet.QuerySet` # with related items to be considered for calculating the next # `sort_order`. # # As we do not know in this base class what the related field(s) # are, this raises a NotImplementedError. It should be subclassed # with something like:: # # return self.objects.filter(<related>=self.<related>) # # """ # raise NotImplementedError # # @staticmethod # def get_next_ordering(related): # """ # Get the next ordering based upon the :class:`QuerySet <django.db.models.QuerySet.QuerySet` # with related items. # """ # return get_next_ordering(related) # # def save(self): # """ # If no `sort_order` has been specified, make sure we calculate the # it based on the highest available current `sort_order`. # """ # # if not self.sort_order: # related = self.get_related_ordering() # self.sort_order = self.get_next_ordering(related) # # logger.debug( # u'Generated sort_order %d for object %s', # self.sort_order, self # ) # # super(OrderedInlineItemBase, self).save() # # sort_order = models.PositiveSmallIntegerField( # verbose_name=('sort order'), # blank=True, db_index=True, # help_text=_( # 'Change this to alter the order in which items are displayed.' # ) # ) , which may contain function names, class names, or code. Output only the next line.
logger.debug(u'Sorl-thumbnail not found. Skipping.')
Given snippet: <|code_start|># Copyright (C) 2010-2011 Mathijs de Bruin <mathijs@mathijsfietst.nl> # # This file is part of django-shopkit. # # django-shopkit is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. logger = logging.getLogger(__name__) try: logger.debug(u'Sorl-thumbnail found: using it.') except ImportError: <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from django.db import models from django.utils.translation import ugettext_lazy as _ from sorl.thumbnail import ImageField from shopkit.core.settings import PRODUCT_MODEL from shopkit.core.basemodels import OrderedInlineItemBase and context: # Path: shopkit/core/settings.py # PRODUCT_MODEL = getattr(settings, 'SHOPKIT_PRODUCT_MODEL') # # Path: shopkit/core/basemodels.py # class OrderedInlineItemBase(models.Model): # """ # This base class does what, actually, order_with_respect_to should do # but (for now) doesn't implement very well: ordering of objects with # a fk-relation to some class. # # As we do not know what the class with the respective relation is, it # is important to note that something like the following is added:: # # class MyOrderedInline(OrderedInlineItemBase): # # <related> = models.ForeignKey(RelatedModel) # # class Meta(OrderedInlineItemBase.Meta): # unique_together = ('sort_order', '<related>') # # def get_related_ordering(self): # return self.__class__.objects.filter(<related>=self.<related>) # # # # ... Or we could simply wait for the Django developers to fix # `order_with_respect_to` once and for all. (Work in progress... # See `Ticket #13 <http://code.djangoproject.com/ticket/13>`.) # # # """ # # class Meta: # abstract = True # ordering = ('sort_order', ) # # def get_related_ordering(self): # """ # Get a :class:`QuerySet <django.db.models.QuerySet.QuerySet` # with related items to be considered for calculating the next # `sort_order`. # # As we do not know in this base class what the related field(s) # are, this raises a NotImplementedError. It should be subclassed # with something like:: # # return self.objects.filter(<related>=self.<related>) # # """ # raise NotImplementedError # # @staticmethod # def get_next_ordering(related): # """ # Get the next ordering based upon the :class:`QuerySet <django.db.models.QuerySet.QuerySet` # with related items. # """ # return get_next_ordering(related) # # def save(self): # """ # If no `sort_order` has been specified, make sure we calculate the # it based on the highest available current `sort_order`. # """ # # if not self.sort_order: # related = self.get_related_ordering() # self.sort_order = self.get_next_ordering(related) # # logger.debug( # u'Generated sort_order %d for object %s', # self.sort_order, self # ) # # super(OrderedInlineItemBase, self).save() # # sort_order = models.PositiveSmallIntegerField( # verbose_name=('sort order'), # blank=True, db_index=True, # help_text=_( # 'Change this to alter the order in which items are displayed.' # ) # ) which might include code, classes, or functions. Output only the next line.
ImageField = models.ImageField
Given snippet: <|code_start|> listed. Feedback about this is welcomed. ..todo:: Write unittests for this piece of code. """ class Meta: abstract = True def get_vat(**kwargs): """ Gets the amount of VAT for the current item. """ kwargs.update({'with_vat': False}) return self.get_price(**kwargs) * 0.01 * VAT_PERCENTAGE def get_price(with_vat=VAT_DEFAULT_DISPLAY, **kwargs): """ If `with_vat=False`, simply returns the original price. Otherwise it takes the result of `get_vat()` and adds it to the original price. """ # Get the price without VAT without_kwargs = kwargs.copy() without_kwargs.update({'with_vat': False}) price_without = super(VATItemBase, self).get_price(**without_kwargs) if with_vat: return price_without + self.get_vat(**kwargs) return price_without <|code_end|> , continue by predicting the next line. Consider current file imports: from shopkit.core.basemodels import AbstractPricedItemBase from shopkit.vat.simple.settings import VAT_PERCENTAGE, VAT_DEFAULT_DISPLAY and context: # Path: shopkit/core/basemodels.py # class AbstractPricedItemBase(models.Model): # """ Abstract base class for items with a price. This only contains # a `get_price` dummy function yielding a NotImplementedError. An # actual `price` field is contained in the `PricedItemBase` class. # # This is because we might want to get our prices somewhere else, ie. # using some kind of algorithm, web API or database somewhere. # """ # # class Meta: # abstract = True # # def get_price(self, **kwargs): # """ Get price for the current product. # # This method _should_ be implemented in a subclass. """ # # raise NotImplementedError # # Path: shopkit/vat/simple/settings.py # VAT_PERCENTAGE = getattr(settings, 'SHOPKIT_VAT_PERCENTAGE') # # VAT_DEFAULT_DISPLAY = getattr(settings, 'SHOPKIT_VAT_DEFAULT_DISPLAY') which might include code, classes, or functions. Output only the next line.
def get_price_with_vat(**kwargs):
Here is a snippet: <|code_start|> def get_price(with_vat=VAT_DEFAULT_DISPLAY, **kwargs): """ If `with_vat=False`, simply returns the original price. Otherwise it takes the result of `get_vat()` and adds it to the original price. """ # Get the price without VAT without_kwargs = kwargs.copy() without_kwargs.update({'with_vat': False}) price_without = super(VATItemBase, self).get_price(**without_kwargs) if with_vat: return price_without + self.get_vat(**kwargs) return price_without def get_price_with_vat(**kwargs): """ Gets the price including VAT. This is a wrapper function around get_price as to allow for specific prices to be queried from within templates. """ kwargs.update({'with_vat': True}) return self.get_price(**kwargs) def get_price_without_vat(**kwargs): """ Gets the price excluding VAT. This is a wrapper function around get_price as to allow for specific prices to be queried from within templates. """ kwargs.update({'with_vat': False}) <|code_end|> . Write the next line using the current file imports: from shopkit.core.basemodels import AbstractPricedItemBase from shopkit.vat.simple.settings import VAT_PERCENTAGE, VAT_DEFAULT_DISPLAY and context from other files: # Path: shopkit/core/basemodels.py # class AbstractPricedItemBase(models.Model): # """ Abstract base class for items with a price. This only contains # a `get_price` dummy function yielding a NotImplementedError. An # actual `price` field is contained in the `PricedItemBase` class. # # This is because we might want to get our prices somewhere else, ie. # using some kind of algorithm, web API or database somewhere. # """ # # class Meta: # abstract = True # # def get_price(self, **kwargs): # """ Get price for the current product. # # This method _should_ be implemented in a subclass. """ # # raise NotImplementedError # # Path: shopkit/vat/simple/settings.py # VAT_PERCENTAGE = getattr(settings, 'SHOPKIT_VAT_PERCENTAGE') # # VAT_DEFAULT_DISPLAY = getattr(settings, 'SHOPKIT_VAT_DEFAULT_DISPLAY') , which may include functions, classes, or code. Output only the next line.
return self.get_price(**kwargs)
Given the following code snippet before the placeholder: <|code_start|> class VATItemBase(AbstractPricedItemBase): """ This item extends any priced item (subclasses of :class:`AbstractPricedItemBase`) with functions that yield the prices with and without VAT. In doing this, it might be imported in what order the base classes for the VAT'ed item are listed. Feedback about this is welcomed. ..todo:: Write unittests for this piece of code. """ class Meta: abstract = True def get_vat(**kwargs): """ Gets the amount of VAT for the current item. """ kwargs.update({'with_vat': False}) return self.get_price(**kwargs) * 0.01 * VAT_PERCENTAGE def get_price(with_vat=VAT_DEFAULT_DISPLAY, **kwargs): """ If `with_vat=False`, simply returns the original price. Otherwise it takes the result of `get_vat()` and adds it to the original price. """ # Get the price without VAT without_kwargs = kwargs.copy() without_kwargs.update({'with_vat': False}) price_without = super(VATItemBase, self).get_price(**without_kwargs) <|code_end|> , predict the next line using imports from the current file: from shopkit.core.basemodels import AbstractPricedItemBase from shopkit.vat.simple.settings import VAT_PERCENTAGE, VAT_DEFAULT_DISPLAY and context including class names, function names, and sometimes code from other files: # Path: shopkit/core/basemodels.py # class AbstractPricedItemBase(models.Model): # """ Abstract base class for items with a price. This only contains # a `get_price` dummy function yielding a NotImplementedError. An # actual `price` field is contained in the `PricedItemBase` class. # # This is because we might want to get our prices somewhere else, ie. # using some kind of algorithm, web API or database somewhere. # """ # # class Meta: # abstract = True # # def get_price(self, **kwargs): # """ Get price for the current product. # # This method _should_ be implemented in a subclass. """ # # raise NotImplementedError # # Path: shopkit/vat/simple/settings.py # VAT_PERCENTAGE = getattr(settings, 'SHOPKIT_VAT_PERCENTAGE') # # VAT_DEFAULT_DISPLAY = getattr(settings, 'SHOPKIT_VAT_DEFAULT_DISPLAY') . Output only the next line.
if with_vat:
Given the code snippet: <|code_start|> code = self.get_argument('code') if code: err = '' company = self.session.query(Company).filter(Company.code == code).first() self.render("fra_com_detail.html", auth_user=self.current_user, company=company, err=err) else: err = '公司编码不存在' self.render("fra_com_detail.html", auth_user=self.current_user, err=err) @tornado.web.authenticated def post(self): name = self.get_argument('name') code = self.get_argument('code') address = self.get_argument('address') parent = self.get_argument('parent') company = self.session.query(Company).filter(Company.code == code).first() if company: data = time.strftime("%Y-%m-%d") company = Company( id=company.id, name=name, code=code, address=address, parent=parent, data=data, ) self.session.merge(company) self.session.commit() self.redirect('/fra/com') else: <|code_end|> , generate the next line using the imports in this file: import hashlib import time import tornado import tornado.auth import tornado.web from handlers.base import BaseHandler from models.models import Company, User and context (functions, classes, or occasionally code) from other files: # Path: handlers/base.py # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # super(BaseHandler, self).__init__(application, request, **kwargs) # self.session = DB_Session() # # def data_received(self, chunk): # pass # # def get_current_user(self): # return self.get_secure_cookie("username") # # def on_finish(self): # self.session.close() # # Path: models/models.py # class Company(BaseModel): # __tablename__ = 'company' # # id = Column(Integer, Sequence('company_id_seq'), primary_key=True) # id # code = Column(String(11), unique=True, nullable=True) # 公司编码 # name = Column(String(32)) # 公司名称 # address = Column(String(64)) # 公司地址 # parent = Column(String(11)) # 公司母公司 # data = Column(DATE) # 新建时间 # user_group = relationship("UserGroup", backref="company") # 对应的用户组 # user = relationship("User", backref="company") # 对应的用户 # devices = relationship("Device", backref="company") # 对应的设备 # device_time_switch = relationship("DeviceTimeSwitch", backref="company") # 对应的定时开关机表 # device_week = relationship("DeviceWeek", backref="company") # 对应的定时开关每周 # device_day = relationship("DeviceDay", backref="company") # 对应的定时开关机每天 # device_group = relationship("DeviceGroup", backref="company") # 对应的设备组 # resources_group = relationship("ResGroup", backref="company") # 对应的资源组 # res_text = relationship("ResText", backref="company") # 对应的文字资源 # res_image = relationship("ResImage", backref="company") # 对应的图片资源 # res_video = relationship("ResVideo", backref="company") # 对应的视频资源 # my_task = relationship("MyTask", backref="company") # 对应的任务 # # class User(BaseModel): # __tablename__ = 'user' # # id = Column(Integer, Sequence('user_id_seq'), primary_key=True) # id # username = Column(String(32)) # 用户名 # password = Column(CHAR(64)) # 密码 # email = Column(String(32)) # 邮箱 # is_active = Column(BOOLEAN) # 是否激活 # is_admin = Column(BOOLEAN) # 是否管理员 # data = Column(DATE) # 新建时间 # tell_phone = Column(CHAR(11)) # 电话号码 # my_task = relationship("MyTask", backref="user") # 对应的任务 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # userGroup = relationship('UserGroup', secondary=user_userGroup, back_populates='user') . Output only the next line.
err = '公司编码不存在'
Given snippet: <|code_start|>#!/usr/bin/env python # _*_coding:utf-8_*_ # 公司管理 class CompanyHandler(BaseHandler): @tornado.web.authenticated def get(self): companys = self.session.query(Company).filter(Company.id == self.get_secure_cookie('company_id')).all() self.render("fra_com_list.html", auth_user=self.current_user, companys=companys) # 公司新增 class CompanyAddHandler(BaseHandler): @tornado.web.authenticated def get(self): err = '' self.render("fra_com_add.html", auth_user=self.current_user, err=err) @tornado.web.authenticated def post(self): name = self.get_argument('name') <|code_end|> , continue by predicting the next line. Consider current file imports: import hashlib import time import tornado import tornado.auth import tornado.web from handlers.base import BaseHandler from models.models import Company, User and context: # Path: handlers/base.py # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # super(BaseHandler, self).__init__(application, request, **kwargs) # self.session = DB_Session() # # def data_received(self, chunk): # pass # # def get_current_user(self): # return self.get_secure_cookie("username") # # def on_finish(self): # self.session.close() # # Path: models/models.py # class Company(BaseModel): # __tablename__ = 'company' # # id = Column(Integer, Sequence('company_id_seq'), primary_key=True) # id # code = Column(String(11), unique=True, nullable=True) # 公司编码 # name = Column(String(32)) # 公司名称 # address = Column(String(64)) # 公司地址 # parent = Column(String(11)) # 公司母公司 # data = Column(DATE) # 新建时间 # user_group = relationship("UserGroup", backref="company") # 对应的用户组 # user = relationship("User", backref="company") # 对应的用户 # devices = relationship("Device", backref="company") # 对应的设备 # device_time_switch = relationship("DeviceTimeSwitch", backref="company") # 对应的定时开关机表 # device_week = relationship("DeviceWeek", backref="company") # 对应的定时开关每周 # device_day = relationship("DeviceDay", backref="company") # 对应的定时开关机每天 # device_group = relationship("DeviceGroup", backref="company") # 对应的设备组 # resources_group = relationship("ResGroup", backref="company") # 对应的资源组 # res_text = relationship("ResText", backref="company") # 对应的文字资源 # res_image = relationship("ResImage", backref="company") # 对应的图片资源 # res_video = relationship("ResVideo", backref="company") # 对应的视频资源 # my_task = relationship("MyTask", backref="company") # 对应的任务 # # class User(BaseModel): # __tablename__ = 'user' # # id = Column(Integer, Sequence('user_id_seq'), primary_key=True) # id # username = Column(String(32)) # 用户名 # password = Column(CHAR(64)) # 密码 # email = Column(String(32)) # 邮箱 # is_active = Column(BOOLEAN) # 是否激活 # is_admin = Column(BOOLEAN) # 是否管理员 # data = Column(DATE) # 新建时间 # tell_phone = Column(CHAR(11)) # 电话号码 # my_task = relationship("MyTask", backref="user") # 对应的任务 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # userGroup = relationship('UserGroup', secondary=user_userGroup, back_populates='user') which might include code, classes, or functions. Output only the next line.
code = self.get_argument('code')
Predict the next line after this snippet: <|code_start|> @tornado.web.authenticated def get(self): code = self.get_argument('code') if code: company = self.session.query(Company).filter(Company.code == code).first() self.session.delete(company) self.session.commit() self.redirect('/fra/com') else: err = '公司编码不存在' self.render("fra_com_detail.html", auth_user=self.current_user, err=err) # 人员管理 class UserHandler(BaseHandler): @tornado.web.authenticated def get(self): users = self.session.query(User).filter(User.company_id == self.get_secure_cookie('company_id')).all() self.render("fra_user_list.html", auth_user=self.current_user, users=users) # 人员新增管理 class UserAddHandler(BaseHandler): @tornado.web.authenticated def get(self): err = '' companys = self.session.query(Company).filter().all() self.render("fra_user_add.html", auth_user=self.current_user, companys=companys, err=err) @tornado.web.authenticated <|code_end|> using the current file's imports: import hashlib import time import tornado import tornado.auth import tornado.web from handlers.base import BaseHandler from models.models import Company, User and any relevant context from other files: # Path: handlers/base.py # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # super(BaseHandler, self).__init__(application, request, **kwargs) # self.session = DB_Session() # # def data_received(self, chunk): # pass # # def get_current_user(self): # return self.get_secure_cookie("username") # # def on_finish(self): # self.session.close() # # Path: models/models.py # class Company(BaseModel): # __tablename__ = 'company' # # id = Column(Integer, Sequence('company_id_seq'), primary_key=True) # id # code = Column(String(11), unique=True, nullable=True) # 公司编码 # name = Column(String(32)) # 公司名称 # address = Column(String(64)) # 公司地址 # parent = Column(String(11)) # 公司母公司 # data = Column(DATE) # 新建时间 # user_group = relationship("UserGroup", backref="company") # 对应的用户组 # user = relationship("User", backref="company") # 对应的用户 # devices = relationship("Device", backref="company") # 对应的设备 # device_time_switch = relationship("DeviceTimeSwitch", backref="company") # 对应的定时开关机表 # device_week = relationship("DeviceWeek", backref="company") # 对应的定时开关每周 # device_day = relationship("DeviceDay", backref="company") # 对应的定时开关机每天 # device_group = relationship("DeviceGroup", backref="company") # 对应的设备组 # resources_group = relationship("ResGroup", backref="company") # 对应的资源组 # res_text = relationship("ResText", backref="company") # 对应的文字资源 # res_image = relationship("ResImage", backref="company") # 对应的图片资源 # res_video = relationship("ResVideo", backref="company") # 对应的视频资源 # my_task = relationship("MyTask", backref="company") # 对应的任务 # # class User(BaseModel): # __tablename__ = 'user' # # id = Column(Integer, Sequence('user_id_seq'), primary_key=True) # id # username = Column(String(32)) # 用户名 # password = Column(CHAR(64)) # 密码 # email = Column(String(32)) # 邮箱 # is_active = Column(BOOLEAN) # 是否激活 # is_admin = Column(BOOLEAN) # 是否管理员 # data = Column(DATE) # 新建时间 # tell_phone = Column(CHAR(11)) # 电话号码 # my_task = relationship("MyTask", backref="user") # 对应的任务 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # userGroup = relationship('UserGroup', secondary=user_userGroup, back_populates='user') . Output only the next line.
def post(self):
Here is a snippet: <|code_start|>#!/usr/bin/env python # _*_coding:utf-8_*_ class LoginHandler(BaseHandler): def get(self): self.render('sys_login.html', login_err='') def post(self): username = self.get_argument('username') password = hashlib.sha256(self.get_argument('password').encode('utf-8')).hexdigest() user = self.session.query(User).filter(and_(User.username == username, User.password == password)).first() if user: self.set_secure_cookie('user_id', str(user.id)) self.set_secure_cookie('username', username) self.set_secure_cookie('company_id', str(user.company_id)) logging.info(str(username) + ' : login success') self.redirect('/') <|code_end|> . Write the next line using the current file imports: import hashlib import tornado import tornado.gen import logging import time from sqlalchemy import and_ from handlers.base import BaseHandler from models.models import User and context from other files: # Path: handlers/base.py # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # super(BaseHandler, self).__init__(application, request, **kwargs) # self.session = DB_Session() # # def data_received(self, chunk): # pass # # def get_current_user(self): # return self.get_secure_cookie("username") # # def on_finish(self): # self.session.close() # # Path: models/models.py # class User(BaseModel): # __tablename__ = 'user' # # id = Column(Integer, Sequence('user_id_seq'), primary_key=True) # id # username = Column(String(32)) # 用户名 # password = Column(CHAR(64)) # 密码 # email = Column(String(32)) # 邮箱 # is_active = Column(BOOLEAN) # 是否激活 # is_admin = Column(BOOLEAN) # 是否管理员 # data = Column(DATE) # 新建时间 # tell_phone = Column(CHAR(11)) # 电话号码 # my_task = relationship("MyTask", backref="user") # 对应的任务 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # userGroup = relationship('UserGroup', secondary=user_userGroup, back_populates='user') , which may include functions, classes, or code. Output only the next line.
else:
Based on the snippet: <|code_start|>#!/usr/bin/env python # _*_coding:utf-8_*_ class LoginHandler(BaseHandler): def get(self): self.render('sys_login.html', login_err='') def post(self): username = self.get_argument('username') password = hashlib.sha256(self.get_argument('password').encode('utf-8')).hexdigest() user = self.session.query(User).filter(and_(User.username == username, User.password == password)).first() if user: self.set_secure_cookie('user_id', str(user.id)) self.set_secure_cookie('username', username) self.set_secure_cookie('company_id', str(user.company_id)) logging.info(str(username) + ' : login success') self.redirect('/') else: logging.info(str(username) + ' : login fail') self.render('sys_login.html', login_err='用户名或密码错误!') class LogoutHandler(BaseHandler): @tornado.web.authenticated <|code_end|> , predict the immediate next line with the help of imports: import hashlib import tornado import tornado.gen import logging import time from sqlalchemy import and_ from handlers.base import BaseHandler from models.models import User and context (classes, functions, sometimes code) from other files: # Path: handlers/base.py # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # super(BaseHandler, self).__init__(application, request, **kwargs) # self.session = DB_Session() # # def data_received(self, chunk): # pass # # def get_current_user(self): # return self.get_secure_cookie("username") # # def on_finish(self): # self.session.close() # # Path: models/models.py # class User(BaseModel): # __tablename__ = 'user' # # id = Column(Integer, Sequence('user_id_seq'), primary_key=True) # id # username = Column(String(32)) # 用户名 # password = Column(CHAR(64)) # 密码 # email = Column(String(32)) # 邮箱 # is_active = Column(BOOLEAN) # 是否激活 # is_admin = Column(BOOLEAN) # 是否管理员 # data = Column(DATE) # 新建时间 # tell_phone = Column(CHAR(11)) # 电话号码 # my_task = relationship("MyTask", backref="user") # 对应的任务 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # userGroup = relationship('UserGroup', secondary=user_userGroup, back_populates='user') . Output only the next line.
def get(self):
Given snippet: <|code_start|>#!/usr/bin/env python # _*_coding:utf-8_*_ class IndexHandler(BaseHandler): @tornado.web.authenticated def get(self): device_groups = self.session.query(DeviceGroup).filter(DeviceGroup.company_id == self.get_secure_cookie('company_id')).all() <|code_end|> , continue by predicting the next line. Consider current file imports: import tornado import tornado.auth import tornado.web from handlers.base import BaseHandler from models.models import DeviceGroup and context: # Path: handlers/base.py # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # super(BaseHandler, self).__init__(application, request, **kwargs) # self.session = DB_Session() # # def data_received(self, chunk): # pass # # def get_current_user(self): # return self.get_secure_cookie("username") # # def on_finish(self): # self.session.close() # # Path: models/models.py # class DeviceGroup(BaseModel): # __tablename__ = 'deviceGroup' # # id = Column(Integer, Sequence('deviceGroup_id_seq'), primary_key=True) # id # name = Column(String(32)) # 设备组名称 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # device_time_switch_id = Column(Integer, ForeignKey('device_timeSwitch.id')) # 外键 公司 # resGroup_id = Column(Integer, ForeignKey('resGroup.id')) # 外键 资源组 # device = relationship("Device", backref="deviceGroup") # 对应设备 # userGroup = relationship('UserGroup', secondary=userGroup_deviceGroup, back_populates='deviceGroup') which might include code, classes, or functions. Output only the next line.
self.render("sys_index.html", auth_user=self.current_user, device_groups=device_groups)
Continue the code snippet: <|code_start|>#!/usr/bin/env python # _*_coding:utf-8_*_ class IndexHandler(BaseHandler): @tornado.web.authenticated def get(self): device_groups = self.session.query(DeviceGroup).filter(DeviceGroup.company_id == self.get_secure_cookie('company_id')).all() <|code_end|> . Use current file imports: import tornado import tornado.auth import tornado.web from handlers.base import BaseHandler from models.models import DeviceGroup and context (classes, functions, or code) from other files: # Path: handlers/base.py # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # super(BaseHandler, self).__init__(application, request, **kwargs) # self.session = DB_Session() # # def data_received(self, chunk): # pass # # def get_current_user(self): # return self.get_secure_cookie("username") # # def on_finish(self): # self.session.close() # # Path: models/models.py # class DeviceGroup(BaseModel): # __tablename__ = 'deviceGroup' # # id = Column(Integer, Sequence('deviceGroup_id_seq'), primary_key=True) # id # name = Column(String(32)) # 设备组名称 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # device_time_switch_id = Column(Integer, ForeignKey('device_timeSwitch.id')) # 外键 公司 # resGroup_id = Column(Integer, ForeignKey('resGroup.id')) # 外键 资源组 # device = relationship("Device", backref="deviceGroup") # 对应设备 # userGroup = relationship('UserGroup', secondary=userGroup_deviceGroup, back_populates='deviceGroup') . Output only the next line.
self.render("sys_index.html", auth_user=self.current_user, device_groups=device_groups)
Next line prediction: <|code_start|> address = Column(String(64)) # 公司地址 parent = Column(String(11)) # 公司母公司 data = Column(DATE) # 新建时间 user_group = relationship("UserGroup", backref="company") # 对应的用户组 user = relationship("User", backref="company") # 对应的用户 devices = relationship("Device", backref="company") # 对应的设备 device_time_switch = relationship("DeviceTimeSwitch", backref="company") # 对应的定时开关机表 device_week = relationship("DeviceWeek", backref="company") # 对应的定时开关每周 device_day = relationship("DeviceDay", backref="company") # 对应的定时开关机每天 device_group = relationship("DeviceGroup", backref="company") # 对应的设备组 resources_group = relationship("ResGroup", backref="company") # 对应的资源组 res_text = relationship("ResText", backref="company") # 对应的文字资源 res_image = relationship("ResImage", backref="company") # 对应的图片资源 res_video = relationship("ResVideo", backref="company") # 对应的视频资源 my_task = relationship("MyTask", backref="company") # 对应的任务 # ---------------------------------------用户---------------------------------------------------- # 多对多 用户--用户组 user_userGroup = Table('user_userGroup', BaseModel.metadata, Column('user_id', ForeignKey('user.id'), primary_key=True), Column('userGroup_id', ForeignKey('userGroup.id'), primary_key=True) ) # 用户组表 class UserGroup(BaseModel): __tablename__ = 'userGroup' <|code_end|> . Use current file imports: (from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from handlers.base import engine) and context including class names, function names, or small code snippets from other files: # Path: handlers/base.py # DB_CONNECT_STRING = 'mysql://root:*****@localhost/bcloud?charset=utf8' # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # def data_received(self, chunk): # def get_current_user(self): # def on_finish(self): . Output only the next line.
id = Column(Integer, Sequence('userGroup_id_seq'), primary_key=True) # id
Next line prediction: <|code_start|> content=content, memo=memo ) try: self.session.merge(web_resource) self.session.commit() self.redirect('/res/web') except: err = "资源修改失败" web_resource = self.session.query(ResWeb).filter(ResWeb.id == id).first() self.render("res_web_detail.html", auth_user=self.current_user, web_resource=web_resource, err=err) # 网站资源--新增 class ResWebAddHandler(BaseHandler): @tornado.web.authenticated def get(self): action = '/res/web/add' err = '' web_resource = ResWeb() self.render("res_web_detail.html", auth_user=self.current_user, action=action, web_resource=web_resource, err=err) @tornado.web.authenticated def post(self): web_name = self.get_argument("name") web_content = self.get_argument("content") memo = self.get_argument("memo") web_resource = ResWeb( name=web_name, content=web_content, <|code_end|> . Use current file imports: (import os import time import tornado import tornado.auth import tornado.web from handlers.base import BaseHandler from models.models import ResText, ResImage, ResVideo, ResGroup, ResWeb) and context including class names, function names, or small code snippets from other files: # Path: handlers/base.py # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # super(BaseHandler, self).__init__(application, request, **kwargs) # self.session = DB_Session() # # def data_received(self, chunk): # pass # # def get_current_user(self): # return self.get_secure_cookie("username") # # def on_finish(self): # self.session.close() # # Path: models/models.py # class ResText(BaseModel): # __tablename__ = 'resText' # # id = Column(Integer, Sequence('resText_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # content = Column(String(255)) # 资源内容 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resText_resGroup, back_populates='resText') # # class ResImage(BaseModel): # __tablename__ = 'resImage' # # id = Column(Integer, Sequence('resImage_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # path = Column(String(128)) # 资源路径 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resImage_resGroup, back_populates='resImage') # # class ResVideo(BaseModel): # __tablename__ = 'resVideo' # # id = Column(Integer, Sequence('resVideo_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # path = Column(String(128)) # 资源路径 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resVideo_resGroup, back_populates='resVideo') # # class ResGroup(BaseModel): # __tablename__ = 'resGroup' # # id = Column(Integer, Sequence('resGroup_id_seq'), primary_key=True) # id # name = Column(String(32)) # 资源组名称 # data = Column(DATE) # 新建时间 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resText = relationship('ResText', secondary=resText_resGroup, back_populates='resGroup') # resImage = relationship('ResImage', secondary=resImage_resGroup, back_populates='resGroup') # resVideo = relationship('ResVideo', secondary=resVideo_resGroup, back_populates='resGroup') # resWeb = relationship('ResWeb', secondary=resWeb_resGroup, back_populates='resGroup') # userGroup = relationship('UserGroup', secondary=userGroup_resGroup, back_populates='resGroup') # deviceGroup = relationship("DeviceGroup", backref="resGroup") # 对应的设备组 # # class ResWeb(BaseModel): # __tablename__ = 'resWeb' # # id = Column(Integer, Sequence('resWeb_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # content = Column(String(128)) # 资源内容 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resWeb_resGroup, back_populates='resWeb') . Output only the next line.
memo=memo,
Continue the code snippet: <|code_start|> # 文字资源-删除 class ResTextDeleteHandler(BaseHandler): @tornado.web.authenticated def get(self): id = self.get_argument("id") text_resource = self.session.query(ResText).filter(ResText.id == id).first() self.session.delete(text_resource) self.session.commit() self.redirect('/res/text') # 网站资源 class ResWebHandler(BaseHandler): @tornado.web.authenticated def get(self): # page_now = self.get_argument('page_now') # page_size = PAGESIZE # text_resources = self.session.query(ResText).filter(ResText.company_id == self.get_secure_cookie('company_id')).all()[1:10] web_resources = self.session.query(ResWeb).filter(ResWeb.company_id == self.get_secure_cookie('company_id')).order_by(ResWeb.id.desc()).all() self.render("res_web.html", auth_user=self.current_user, web_resources=web_resources) # 网站资源--详细 class ResWebDetailHandler(BaseHandler): @tornado.web.authenticated def get(self): action = '/res/web/detail' err = "" <|code_end|> . Use current file imports: import os import time import tornado import tornado.auth import tornado.web from handlers.base import BaseHandler from models.models import ResText, ResImage, ResVideo, ResGroup, ResWeb and context (classes, functions, or code) from other files: # Path: handlers/base.py # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # super(BaseHandler, self).__init__(application, request, **kwargs) # self.session = DB_Session() # # def data_received(self, chunk): # pass # # def get_current_user(self): # return self.get_secure_cookie("username") # # def on_finish(self): # self.session.close() # # Path: models/models.py # class ResText(BaseModel): # __tablename__ = 'resText' # # id = Column(Integer, Sequence('resText_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # content = Column(String(255)) # 资源内容 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resText_resGroup, back_populates='resText') # # class ResImage(BaseModel): # __tablename__ = 'resImage' # # id = Column(Integer, Sequence('resImage_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # path = Column(String(128)) # 资源路径 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resImage_resGroup, back_populates='resImage') # # class ResVideo(BaseModel): # __tablename__ = 'resVideo' # # id = Column(Integer, Sequence('resVideo_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # path = Column(String(128)) # 资源路径 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resVideo_resGroup, back_populates='resVideo') # # class ResGroup(BaseModel): # __tablename__ = 'resGroup' # # id = Column(Integer, Sequence('resGroup_id_seq'), primary_key=True) # id # name = Column(String(32)) # 资源组名称 # data = Column(DATE) # 新建时间 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resText = relationship('ResText', secondary=resText_resGroup, back_populates='resGroup') # resImage = relationship('ResImage', secondary=resImage_resGroup, back_populates='resGroup') # resVideo = relationship('ResVideo', secondary=resVideo_resGroup, back_populates='resGroup') # resWeb = relationship('ResWeb', secondary=resWeb_resGroup, back_populates='resGroup') # userGroup = relationship('UserGroup', secondary=userGroup_resGroup, back_populates='resGroup') # deviceGroup = relationship("DeviceGroup", backref="resGroup") # 对应的设备组 # # class ResWeb(BaseModel): # __tablename__ = 'resWeb' # # id = Column(Integer, Sequence('resWeb_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # content = Column(String(128)) # 资源内容 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resWeb_resGroup, back_populates='resWeb') . Output only the next line.
web_id = self.get_argument("id")
Given snippet: <|code_start|> except: err = "资源组新增失败" res_group = ResGroup() self.render("res_group_detail.html", auth_user=self.current_user, action=action, res_group=res_group, err=err) # 资源组管理--修改资源组名称 class ResGroupUpdateHandler(BaseHandler): @tornado.web.authenticated def get(self): err = '' action = '/res/group/update' res_group_id = self.get_argument('res_group_id') res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first() self.render("res_group_detail.html", auth_user=self.current_user, action=action, res_group=res_group, err=err) @tornado.web.authenticated def post(self): id = self.get_argument('id') name = self.get_argument('name') res_group = self.session.query(ResGroup).filter(ResGroup.id == id).first() res_group.name = name self.session.merge(res_group) self.session.commit() self.redirect('/res/group?res_group_id=') # 资源组管理--删除资源组名称 class ResGroupDeleteHandler(BaseHandler): @tornado.web.authenticated <|code_end|> , continue by predicting the next line. Consider current file imports: import os import time import tornado import tornado.auth import tornado.web from handlers.base import BaseHandler from models.models import ResText, ResImage, ResVideo, ResGroup, ResWeb and context: # Path: handlers/base.py # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # super(BaseHandler, self).__init__(application, request, **kwargs) # self.session = DB_Session() # # def data_received(self, chunk): # pass # # def get_current_user(self): # return self.get_secure_cookie("username") # # def on_finish(self): # self.session.close() # # Path: models/models.py # class ResText(BaseModel): # __tablename__ = 'resText' # # id = Column(Integer, Sequence('resText_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # content = Column(String(255)) # 资源内容 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resText_resGroup, back_populates='resText') # # class ResImage(BaseModel): # __tablename__ = 'resImage' # # id = Column(Integer, Sequence('resImage_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # path = Column(String(128)) # 资源路径 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resImage_resGroup, back_populates='resImage') # # class ResVideo(BaseModel): # __tablename__ = 'resVideo' # # id = Column(Integer, Sequence('resVideo_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # path = Column(String(128)) # 资源路径 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resVideo_resGroup, back_populates='resVideo') # # class ResGroup(BaseModel): # __tablename__ = 'resGroup' # # id = Column(Integer, Sequence('resGroup_id_seq'), primary_key=True) # id # name = Column(String(32)) # 资源组名称 # data = Column(DATE) # 新建时间 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resText = relationship('ResText', secondary=resText_resGroup, back_populates='resGroup') # resImage = relationship('ResImage', secondary=resImage_resGroup, back_populates='resGroup') # resVideo = relationship('ResVideo', secondary=resVideo_resGroup, back_populates='resGroup') # resWeb = relationship('ResWeb', secondary=resWeb_resGroup, back_populates='resGroup') # userGroup = relationship('UserGroup', secondary=userGroup_resGroup, back_populates='resGroup') # deviceGroup = relationship("DeviceGroup", backref="resGroup") # 对应的设备组 # # class ResWeb(BaseModel): # __tablename__ = 'resWeb' # # id = Column(Integer, Sequence('resWeb_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # content = Column(String(128)) # 资源内容 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resWeb_resGroup, back_populates='resWeb') which might include code, classes, or functions. Output only the next line.
def get(self):
Predict the next line after this snippet: <|code_start|>class ResVideoAddHandler(BaseHandler): def check_xsrf_cookie(self): pass @tornado.web.authenticated def get(self): self.render("res_video_add.html", auth_user=self.current_user) @tornado.web.authenticated def post(self): username = self.get_secure_cookie("username") company_id = self.get_secure_cookie('company_id') data = time.strftime("%Y%m%d") upload_path = '/media/video/' + username + '/' + data if not os.path.isdir(upload_path): os.makedirs(upload_path) # 提取表单中‘name’为‘file’的文件元数据 file_metas = self.request.files['video_file'] for meta in file_metas: filename = meta['filename'] filepath = os.path.join(upload_path, filename) # 有些文件需要已二进制的形式存储,实际中可以更改 with open(filepath, 'wb') as up: up.write(meta['body']) video_resources = ResVideo() video_resources.name = filename video_resources.memo = filename video_resources.path = filepath video_resources.company_id = company_id <|code_end|> using the current file's imports: import os import time import tornado import tornado.auth import tornado.web from handlers.base import BaseHandler from models.models import ResText, ResImage, ResVideo, ResGroup, ResWeb and any relevant context from other files: # Path: handlers/base.py # class BaseHandler(tornado.web.RequestHandler): # def __init__(self, application, request, **kwargs): # super(BaseHandler, self).__init__(application, request, **kwargs) # self.session = DB_Session() # # def data_received(self, chunk): # pass # # def get_current_user(self): # return self.get_secure_cookie("username") # # def on_finish(self): # self.session.close() # # Path: models/models.py # class ResText(BaseModel): # __tablename__ = 'resText' # # id = Column(Integer, Sequence('resText_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # content = Column(String(255)) # 资源内容 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resText_resGroup, back_populates='resText') # # class ResImage(BaseModel): # __tablename__ = 'resImage' # # id = Column(Integer, Sequence('resImage_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # path = Column(String(128)) # 资源路径 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resImage_resGroup, back_populates='resImage') # # class ResVideo(BaseModel): # __tablename__ = 'resVideo' # # id = Column(Integer, Sequence('resVideo_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # path = Column(String(128)) # 资源路径 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resVideo_resGroup, back_populates='resVideo') # # class ResGroup(BaseModel): # __tablename__ = 'resGroup' # # id = Column(Integer, Sequence('resGroup_id_seq'), primary_key=True) # id # name = Column(String(32)) # 资源组名称 # data = Column(DATE) # 新建时间 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resText = relationship('ResText', secondary=resText_resGroup, back_populates='resGroup') # resImage = relationship('ResImage', secondary=resImage_resGroup, back_populates='resGroup') # resVideo = relationship('ResVideo', secondary=resVideo_resGroup, back_populates='resGroup') # resWeb = relationship('ResWeb', secondary=resWeb_resGroup, back_populates='resGroup') # userGroup = relationship('UserGroup', secondary=userGroup_resGroup, back_populates='resGroup') # deviceGroup = relationship("DeviceGroup", backref="resGroup") # 对应的设备组 # # class ResWeb(BaseModel): # __tablename__ = 'resWeb' # # id = Column(Integer, Sequence('resWeb_id_seq'), primary_key=True) # 资源id # name = Column(String(32)) # 资源名称 # content = Column(String(128)) # 资源内容 # memo = Column(String(255)) # 资源备注 # data = Column(DATE) # 资源新建时间 # is_able = Column(String(16)) # 是否审批通过 # company_id = Column(Integer, ForeignKey('company.id')) # 外键 公司 # resGroup = relationship('ResGroup', secondary=resWeb_resGroup, back_populates='resWeb') . Output only the next line.
video_resources.data = data
Next line prediction: <|code_start|>#!/usr/bin/env python # _*_coding:utf-8_*_ logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', # filename='logs/bcloud' + str(time.strftime("%Y%m%d%H%M%S")) + '.log', filename='logs/bcloud.log', filemode='w') settings = dict( template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), <|code_end|> . Use current file imports: (import logging import os.path import tornado.web from url import urls) and context including class names, function names, or small code snippets from other files: # Path: url.py . Output only the next line.
cookie_secret="bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=",
Predict the next line for this snippet: <|code_start|> log.debug(">> {0} {1}".format(data.encode("hex"), self.addr)) self.socket.sendto(data, self.addr) else: break if len(select.select([self.socket], [], [], 0.1)[0]) == 1: data, self.addr = self.socket.recvfrom(1024) log.debug("<< {0} {1}".format(data.encode("hex"), self.addr)) else: return None self.exchange = self.send_rsp_recv_cmd return target, cmd def listen_dep(self, target, timeout): assert type(target) is nfc.clf.DEP target.br = 424 target.idm = bytearray((0x01, 0xFE)) + os.urandom(6) target.pmm = bytearray(8) target.sys = bytearray((0xFF, 0xFF)) log.debug("bind socket to {0}".format(self.addr)) try: self.socket.bind(self.addr) except socket.error: return log.debug("bound socket to {0}".format(self.addr)) while True: data, self.addr = self.socket.recvfrom(1024) log.debug("<< {0} {1}".format(data.encode("hex"), self.addr)) if data.startswith("\x06\x00"): break while True: <|code_end|> with the help of current file imports: import logging import nfc.clf import nfc.dev import os import time import socket import select import platform from nfc.clf import ProtocolError, TransmissionError, TimeoutError and context from other files: # Path: nfc/clf.py # class ProtocolError(DigitalProtocolError): pass # # class TransmissionError(DigitalProtocolError): pass # # class TimeoutError(DigitalProtocolError): pass , which may contain function names, class names, or code. Output only the next line.
cmd = bytearray(data)
Continue the code snippet: <|code_start|> self.current_address) amount_str = self.format_btc_amount(amount) btc_uri = self.create_btc_uri(self.current_address, amount_str, self.bt_addr) imgdata = self.create_img_data(btc_uri) js = 'show_payment_info("%s", %s, "%s", "%s")' % \ ('%s BTC' % amount_str, conversion, self.current_address, imgdata) self.customer_display.evaluate_java_script(js) self.nfc_broadcast.set_btc_uri(btc_uri) def create_btc_uri(self, address, amount_str, bt_addr): btc_uri = "bitcoin:%s?amount=%s" % (address, amount_str) if bt_addr != None: bt_addr_stripped = bt_addr.translate(None, ':') btc_uri += "&bt=%s" % bt_addr_stripped return btc_uri def create_img_data(self, btc_uri): (_, size, img) = qrencode.encode(btc_uri) if size < 400: img = img.resize((400, 400), Image.NEAREST) buf = StringIO() img.save(buf, format='PNG') imgdata = "data:image/png,%s" % urllib.quote(buf.getvalue()) return imgdata def format_btc_amount(self, amount): <|code_end|> . Use current file imports: import qrencode import urllib import re from StringIO import StringIO from PIL import Image from PyQt4 import QtGui from PyQt4 import QtCore from authproxy import AuthServiceProxy, JSONRPCException from merchantgui import MerchantGUI from customerdisplay import CustomerDisplay and context (classes, functions, or code) from other files: # Path: authproxy.py # class AuthServiceProxy(object): # def __init__(self, serviceURL, serviceName=None): # self.__serviceURL = serviceURL # self.__serviceName = serviceName # self.__url = urlparse.urlparse(serviceURL) # if self.__url.port is None: # port = 80 # else: # port = self.__url.port # self.__idcnt = 0 # authpair = "%s:%s" % (self.__url.username, self.__url.password) # self.__authhdr = "Basic %s" % (base64.b64encode(authpair)) # self.__conn = httplib.HTTPConnection(self.__url.hostname, port, False, # HTTP_TIMEOUT) # # def __getattr__(self, name): # if self.__serviceName != None: # name = "%s.%s" % (self.__serviceName, name) # return AuthServiceProxy(self.__serviceURL, name) # # def __call__(self, *args): # self.__idcnt += 1 # # postdata = json.dumps({ # 'version': '1.1', # 'method': self.__serviceName, # 'params': args, # 'id': self.__idcnt}) # try: # self.__conn.request('POST', self.__url.path, postdata, # { 'Host' : self.__url.hostname, # 'User-Agent' : USER_AGENT, # 'Authorization' : self.__authhdr, # 'Content-type' : 'application/json' }) # except EnvironmentError as e: # if e.errno == errno.ECONNREFUSED: # raise JSONRPCException({ # 'code' : -341, 'message' : 'connection refused'}) # else: # raise # re-raise otherwise # # httpresp = self.__conn.getresponse() # if httpresp is None: # raise JSONRPCException({ # 'code' : -342, 'message' : 'missing HTTP response from server'}) # # resp = json.loads(httpresp.read(), parse_float=decimal.Decimal) # if resp['error'] != None: # raise JSONRPCException(resp['error']) # elif 'result' not in resp: # raise JSONRPCException({ # 'code' : -343, 'message' : 'missing JSON-RPC result'}) # else: # return resp['result'] # # class JSONRPCException(Exception): # def __init__(self, rpcError): # Exception.__init__(self) # self.error = rpcError . Output only the next line.
s = "%.8f" % amount
Here is a snippet: <|code_start|> self.customer_display = CustomerDisplay('data/customer_display.html', self.single_screen_mode) if not self.single_screen_mode: self.customer_display.show() self.app.exec_() def init_new_transaction(self, amount, currency): if self.single_screen_mode: self.customer_display.show() if not self.customer_display.isFullScreen(): self.customer_display.showFullScreen() if currency != "BTC": cur_amount = amount if self.exchange_rate != 0: amount = round(cur_amount / self.exchange_rate, 8) else: amount = 0 conversion = '["%.2f %s", "%.4f %s", "%s"]' % (cur_amount, currency, self.exchange_rate, currency, self.exchange_rate_source) else: conversion = '-1' self.current_address = self.bitcoind.getnewaddress("Point of Sale") self.merchant_gui.update_status("Looking for a transaction to %s..." % self.current_address) amount_str = self.format_btc_amount(amount) btc_uri = self.create_btc_uri(self.current_address, amount_str, self.bt_addr) <|code_end|> . Write the next line using the current file imports: import qrencode import urllib import re from StringIO import StringIO from PIL import Image from PyQt4 import QtGui from PyQt4 import QtCore from authproxy import AuthServiceProxy, JSONRPCException from merchantgui import MerchantGUI from customerdisplay import CustomerDisplay and context from other files: # Path: authproxy.py # class AuthServiceProxy(object): # def __init__(self, serviceURL, serviceName=None): # self.__serviceURL = serviceURL # self.__serviceName = serviceName # self.__url = urlparse.urlparse(serviceURL) # if self.__url.port is None: # port = 80 # else: # port = self.__url.port # self.__idcnt = 0 # authpair = "%s:%s" % (self.__url.username, self.__url.password) # self.__authhdr = "Basic %s" % (base64.b64encode(authpair)) # self.__conn = httplib.HTTPConnection(self.__url.hostname, port, False, # HTTP_TIMEOUT) # # def __getattr__(self, name): # if self.__serviceName != None: # name = "%s.%s" % (self.__serviceName, name) # return AuthServiceProxy(self.__serviceURL, name) # # def __call__(self, *args): # self.__idcnt += 1 # # postdata = json.dumps({ # 'version': '1.1', # 'method': self.__serviceName, # 'params': args, # 'id': self.__idcnt}) # try: # self.__conn.request('POST', self.__url.path, postdata, # { 'Host' : self.__url.hostname, # 'User-Agent' : USER_AGENT, # 'Authorization' : self.__authhdr, # 'Content-type' : 'application/json' }) # except EnvironmentError as e: # if e.errno == errno.ECONNREFUSED: # raise JSONRPCException({ # 'code' : -341, 'message' : 'connection refused'}) # else: # raise # re-raise otherwise # # httpresp = self.__conn.getresponse() # if httpresp is None: # raise JSONRPCException({ # 'code' : -342, 'message' : 'missing HTTP response from server'}) # # resp = json.loads(httpresp.read(), parse_float=decimal.Decimal) # if resp['error'] != None: # raise JSONRPCException(resp['error']) # elif 'result' not in resp: # raise JSONRPCException({ # 'code' : -343, 'message' : 'missing JSON-RPC result'}) # else: # return resp['result'] # # class JSONRPCException(Exception): # def __init__(self, rpcError): # Exception.__init__(self) # self.error = rpcError , which may include functions, classes, or code. Output only the next line.
imgdata = self.create_img_data(btc_uri)
Using the snippet: <|code_start|> gridi=30 comps_10full=[(a*1./gridi, b*1./gridi, c*1./gridi, (gridi-a-b-c)*1./gridi) for a in numpy.arange(0,1+gridi) for b in numpy.arange(0,1+gridi-a) for c in numpy.arange(0,1+gridi-a-b)] comps_10full=list(set(comps_10full)) print len(comps_10full) #plotpoints_cmyk comps_10full=numpy.array(comps_10full) fom=numpy.array([(c*numpy.arange(1, 5)).sum() for c in comps_10full]) fig=pylab.figure() ax=fig.add_axes([.3, .12, .6, .83])#add_subplot(111) insetax=fig.add_axes([0, .7, .2, .3], projection='3d') bl=binarylines(ax, insetax) bl.plotbinaryfom(comps_10full, fom) <|code_end|> , determine the next line of code. You have imports: import matplotlib.cm as cm import numpy import pylab import operator, copy, os from quaternary_binary_lines import binarylines and context (class names, function names, or code) available: # Path: quaternary_binary_lines.py # class binarylines: # def __init__(self, ax, insetax, ellabels=['A', 'B', 'C', 'D'], offset=0.02, numcomppts=21, view_azim=-159, view_elev=30, **kwargs): # self.ax=ax # self.insetax=insetax # self.ellabels=ellabels # self.stpq=QuaternaryPlot(insetax, ellabels=ellabels, offset=offset) # comppairs=[] # a=numpy.linspace(0, 1, 21) # count=-1 # for i in range(4): # for j in range(i+1, 4): # count+=1 # b=numpy.zeros((numcomppts, 4), dtype='float64') # b[:, i]=a # b[:, j]=1.-a # comppairs+=[(c1, c2) for c1, c2 in zip(b[:-1], b[1:])] # for (c1, c2) in comppairs: # self.stpq.line(c1, c2, fmt='-', c=self.stpq.rgb_comp([(c1+c2)/2.])[0], **kwargs) # self.stpq.set_projection(azim=view_azim, elev=view_elev) # self.stpq.label() # # # def plotbinaryfom(self, comps, fom, **kwargs): # cb=comps>.001 # # ms=['<','>','^','v','s','D'] # # count=-1 # for i in range(4): # for j in range(i+1, 4): # count+=1 # k, l=tuple(set(range(4))-set([i, j])) # barr=numpy.array([numpy.logical_not(b[k]|b[l]) for b in cb]) #numpy.logical_xor(b[i], b[j])& # if not numpy.any(barr): # continue # cmps=comps[barr] # inds=numpy.argsort(cmps[:, j]) # cmps=cmps[inds] # cols=self.stpq.rgb_comp(cmps) # ys=fom[barr][inds] # for count2, (c, col, y) in enumerate(zip(cmps, cols, ys)): # if count2==len(ys)//2: # self.ax.plot(c[j], y, marker=ms[count], c=col, markeredgecolor=col, label='%s,%s' %(self.ellabels[i], self.ellabels[j]), **kwargs) # else: # self.ax.plot(c[j], y, marker=ms[count], c=col, markeredgecolor=col, **kwargs) # #self.ax.plot(c[j], y, marker=ms[count], c=col, markeredgecolor='None') # for count3, (c1, col1, y1, c2, col2, y2) in enumerate(zip(cmps[:-1], cols[:-1], ys[:-1], cmps[1:], cols[1:], ys[1:])): # col=numpy.array([col1, col2]).mean(axis=0) # self.ax.plot([c1[j], c2[j]], [y1, y2], '-', c=col, **kwargs) # # def binarylineslegend(self, **kwargs): # try: # self.ax.legend(**kwargs) # except: # pass . Output only the next line.
bl.binarylineslegend(loc=7)
Given the following code snippet before the placeholder: <|code_start|> self.nn( lab.getSectByName('.reloc') ) def test_pe_putty64(self): with d_files.getTestFd('putty64.exe') as fd: self.true( d_pe.isMimePe(fd) ) fd.seek(0) lab = d_pe.PeLab(fd) self.eq( lab.get('pe:dllname'), None ) #lab.get('pe:IMAGE_DOS_HEADER').vsPrint() #lab.get('pe:IMAGE_NT_HEADERS').vsPrint() self.eq( lab.get('bex:arch'), 'amd64') self.eq( lab.get('bex:ptr:size'), 8 ) #lab.get('pe:sections').vsPrint() self.eq( lab.rvaToOff(0x10), 0x10 ) self.eq( lab.rvaToOff(0x7c010), 504848 ) self.nn( lab.getSectByName('.reloc') ) def test_pe_hello32(self): <|code_end|> , predict the next line using imports from the current file: import unittest import dissect.formats.pe as d_pe import dissect.tests.files as d_files from dissect.tests.common import DisTest and context including class names, function names, and sometimes code from other files: # Path: dissect/tests/common.py # class DisTest(unittest.TestCase): # # def eq(self, x, y): # self.assertEqual(x,y) # # def ne(self, x, y): # self.assertNotEqual(x,y) # # def nn(self, x): # self.assertIsNotNone(x) # # def true(self, x): # self.assertTrue(x) # # def false(self, x): # self.assertFalse(x) . Output only the next line.
with d_files.getTestFd('hello32.dll') as fd:
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import try: except ImportError: REQUEST_TIMEOUT = getattr(settings, 'REQUEST_TIMEOUT', 60) <|code_end|> using the current file's imports: from django.db import transaction from django.conf import settings from django_atomic_celery import task from requests.exceptions import InvalidURL from .utils import (ResultDict, logger, response_to_dict, InsecureHttpAdapter) from thezombies.models import URLInspection, Probe from urllib.parse import urlparse, urlunparse from urlparse import urlparse, urlunparse import requests and any relevant context from other files: # Path: thezombies/tasks/utils.py # COUNTDOWN_MODULO = 21 # class ResultDict(dict): # class InsecureHttpAdapter(HTTPAdapter): # def __init__(self, data=None, errors=None): # def add_error(self, error): # def errors(self): # def response_to_dict(resp, history=True): # def error_handler(uuid): # def init_poolmanager(self, connections, maxsize, block=False): # # Path: thezombies/models.py # class URLInspection(models.Model): # created_at = models.DateTimeField(auto_now_add=True) # url = models.TextField(blank=True, null=True) # We may get (and want to store) really long or invalid urls, so... # requested_url = models.TextField() # We may get (and want to store) really long or invalid urls, so... # encoding = models.CharField(max_length=120, blank=True, null=True) # apparent_encoding = models.CharField(max_length=120, blank=True, null=True) # content = models.OneToOneField(ResponseContent, null=True, related_name='content_for', editable=False) # history = hstore.ReferencesField(blank=True, null=True) # parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) # status_code = models.IntegerField(max_length=3, blank=True, null=True) # reason = models.CharField(blank=True, null=True, max_length=80, help_text='Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".') # headers = hstore.DictionaryField(default=dictionary_default) # timeout = models.BooleanField(default=False) # probe = models.ForeignKey('Probe', null=True, blank=True, related_name='url_inspections') # # objects = URLInspectionManager.from_queryset(URLInspectionQuerySet)() # # class Meta: # verbose_name = 'URL Inspection' # verbose_name_plural = 'URL Inspections' # get_latest_by = 'created_at' # ordering = ('-created_at', 'requested_url') # # def __repr__(self): # return '<URLInspection: {0} : {1}>'.format(self.requested_url, self.status_code) # # def __str__(self): # return self.__repr__() # # class Probe(models.Model): # """A component of an Audit that takes some initial data and # stores a result of some tasks performed on that data # """ # # GENERIC_PROBE = 0 # URL_PROBE = 1 # JSON_PROBE = 2 # VALIDATION_PROBE = 3 # # PROBE_TYPE_CHOICES = ( # (GENERIC_PROBE, 'Generic Probe'), # (URL_PROBE, 'URL Probe'), # (JSON_PROBE, 'JSON Probe'), # (VALIDATION_PROBE, 'Validation Probe'), # ) # # created_at = models.DateTimeField(auto_now_add=True) # updated_at = models.DateTimeField(auto_now=True) # probe_type = models.PositiveSmallIntegerField(choices=PROBE_TYPE_CHOICES, default=GENERIC_PROBE) # previous = models.ForeignKey('self', related_name='next', blank=True, null=True, on_delete=models.SET_NULL) # initial = hstore.DictionaryField(blank=True, null=True, default=dictionary_default) # result = hstore.DictionaryField(blank=True, null=True, default=dictionary_default) # errors = TextArrayField(blank=True, null=True, default=list_default) # audit = models.ForeignKey('Audit', null=True, blank=True) # # objects = ProbeQuerySet.as_manager() # # def __repr__(self): # return '<{0}: {1}>'.format(self.get_probe_type_display(), self.id) # # def __str__(self): # return self.__repr__() # # class Meta: # get_latest_by = 'created_at' # ordering = ('-created_at',) # # def error_count(self): # return len(self.errors) # # def get_absolute_url(self): # return reverse('probe-detail', kwargs={'pk': str(self.pk)}) . Output only the next line.
session = requests.Session()
Using the snippet: <|code_start|>from __future__ import absolute_import try: except ImportError: REQUEST_TIMEOUT = getattr(settings, 'REQUEST_TIMEOUT', 60) <|code_end|> , determine the next line of code. You have imports: from django.db import transaction from django.conf import settings from django_atomic_celery import task from requests.exceptions import InvalidURL from .utils import (ResultDict, logger, response_to_dict, InsecureHttpAdapter) from thezombies.models import URLInspection, Probe from urllib.parse import urlparse, urlunparse from urlparse import urlparse, urlunparse import requests and context (class names, function names, or code) available: # Path: thezombies/tasks/utils.py # COUNTDOWN_MODULO = 21 # class ResultDict(dict): # class InsecureHttpAdapter(HTTPAdapter): # def __init__(self, data=None, errors=None): # def add_error(self, error): # def errors(self): # def response_to_dict(resp, history=True): # def error_handler(uuid): # def init_poolmanager(self, connections, maxsize, block=False): # # Path: thezombies/models.py # class URLInspection(models.Model): # created_at = models.DateTimeField(auto_now_add=True) # url = models.TextField(blank=True, null=True) # We may get (and want to store) really long or invalid urls, so... # requested_url = models.TextField() # We may get (and want to store) really long or invalid urls, so... # encoding = models.CharField(max_length=120, blank=True, null=True) # apparent_encoding = models.CharField(max_length=120, blank=True, null=True) # content = models.OneToOneField(ResponseContent, null=True, related_name='content_for', editable=False) # history = hstore.ReferencesField(blank=True, null=True) # parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) # status_code = models.IntegerField(max_length=3, blank=True, null=True) # reason = models.CharField(blank=True, null=True, max_length=80, help_text='Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".') # headers = hstore.DictionaryField(default=dictionary_default) # timeout = models.BooleanField(default=False) # probe = models.ForeignKey('Probe', null=True, blank=True, related_name='url_inspections') # # objects = URLInspectionManager.from_queryset(URLInspectionQuerySet)() # # class Meta: # verbose_name = 'URL Inspection' # verbose_name_plural = 'URL Inspections' # get_latest_by = 'created_at' # ordering = ('-created_at', 'requested_url') # # def __repr__(self): # return '<URLInspection: {0} : {1}>'.format(self.requested_url, self.status_code) # # def __str__(self): # return self.__repr__() # # class Probe(models.Model): # """A component of an Audit that takes some initial data and # stores a result of some tasks performed on that data # """ # # GENERIC_PROBE = 0 # URL_PROBE = 1 # JSON_PROBE = 2 # VALIDATION_PROBE = 3 # # PROBE_TYPE_CHOICES = ( # (GENERIC_PROBE, 'Generic Probe'), # (URL_PROBE, 'URL Probe'), # (JSON_PROBE, 'JSON Probe'), # (VALIDATION_PROBE, 'Validation Probe'), # ) # # created_at = models.DateTimeField(auto_now_add=True) # updated_at = models.DateTimeField(auto_now=True) # probe_type = models.PositiveSmallIntegerField(choices=PROBE_TYPE_CHOICES, default=GENERIC_PROBE) # previous = models.ForeignKey('self', related_name='next', blank=True, null=True, on_delete=models.SET_NULL) # initial = hstore.DictionaryField(blank=True, null=True, default=dictionary_default) # result = hstore.DictionaryField(blank=True, null=True, default=dictionary_default) # errors = TextArrayField(blank=True, null=True, default=list_default) # audit = models.ForeignKey('Audit', null=True, blank=True) # # objects = ProbeQuerySet.as_manager() # # def __repr__(self): # return '<{0}: {1}>'.format(self.get_probe_type_display(), self.id) # # def __str__(self): # return self.__repr__() # # class Meta: # get_latest_by = 'created_at' # ordering = ('-created_at',) # # def error_count(self): # return len(self.errors) # # def get_absolute_url(self): # return reverse('probe-detail', kwargs={'pk': str(self.pk)}) . Output only the next line.
session = requests.Session()
Given the following code snippet before the placeholder: <|code_start|> urlpatterns = patterns('', url(r'^$', HomeView.as_view(), name='home'), url(r'^agency/$', AgencyList.as_view(), name='agency-list'), url(r'^agency/(?P<slug>[\w\-]+)/$', AgencyView.as_view(), name='agency-detail'), url(r'^audits/$', AuditListView.as_view(), name='audits-list'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', AuditDayArchiveView.as_view(), name='audits-list-day'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/$', AuditMonthArchiveView.as_view(), name='audits-list-month'), url(r'^audits/(?P<year>\d{4})/$', AuditYearArchiveView.as_view(), name='audits-list-year'), url(r'^audits/(?P<pk>\d+)/$', AuditView.as_view(), name='audit-detail'), url(r'^audits/(?P<audit_type>\w+)/$', AuditListView.as_view(), name='audits-list-filtered'), url(r'^probes/(?P<pk>\d+)/$', ProbeView.as_view(), name='probe-detail'), <|code_end|> , predict the next line using imports from the current file: from django.conf.urls import patterns, include, url from django.contrib import admin from thezombies.views import (HomeView, AgencyList, AgencyView, AuditListView, AuditView, AuditDayArchiveView, AuditMonthArchiveView, AuditYearArchiveView, ProbeView) and context including class names, function names, and sometimes code from other files: # Path: thezombies/views.py # class HomeView(RedirectView): # url = '/audits/' # pattern_name = 'audit-list' # # class AgencyList(ListView): # model = Agency # template_name = 'agency_list.html' # # class AgencyView(DetailView): # model = Agency # template_name = 'agency_detail.html' # # class AuditListView(ListView): # model = Audit # paginate_by = 50 # template_name = 'audits_list.html' # # def get_queryset(self, **kwargs): # audit_filter_kwargs = {} # self.audit_type_string = self.kwargs.get('audit_type', None) # if self.audit_type_string: # if self.audit_type_string == 'generic': # audit_filter_kwargs['audit_type'] = Audit.GENERIC_AUDIT # elif self.audit_type_string == 'validation': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_VALIDATION # elif self.audit_type_string == 'crawl': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_CRAWL # else: # raise Http404 # self.audit_list = Audit.objects.filter(**audit_filter_kwargs).prefetch_related('agency') # return self.audit_list # # def get_context_data(self, **kwargs): # context = super(AuditListView, self).get_context_data(**kwargs) # context['audit_type'] = self.audit_type_string # return context # # class AuditView(SingleObjectMixin, ListView): # paginate_by = 20 # template_name = 'audit_detail.html' # # def get(self, request, *args, **kwargs): # self.object = self.get_object(queryset=Audit.objects.all()) # return super(AuditView, self).get(request, *args, **kwargs) # # def get_context_data(self, **kwargs): # context = super(AuditView, self).get_context_data(**kwargs) # context['audit'] = self.object # return context # # def get_queryset(self): # # Paginate probe objects # return self.object.probe_set.order_by('id') # # def get_template_names(self): # template_names = super(AuditView, self).get_template_names() # template_choices = dict(AUDIT_TYPE_TEMPLATES) # template_addition = template_choices.get(self.object.audit_type, None) if self.object else None # if template_addition: # template_names.insert(0, template_addition) # return template_names # # class AuditDayArchiveView(DayArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditMonthArchiveView(MonthArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditYearArchiveView(YearArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # make_object_list = True # template_name = 'audits_list.html' # # class ProbeView(DetailView): # model = Probe # template_name = "probe_detail.html" . Output only the next line.
url(r'^admin/', include(admin.site.urls)),
Given the following code snippet before the placeholder: <|code_start|> urlpatterns = patterns('', url(r'^$', HomeView.as_view(), name='home'), url(r'^agency/$', AgencyList.as_view(), name='agency-list'), url(r'^agency/(?P<slug>[\w\-]+)/$', AgencyView.as_view(), name='agency-detail'), url(r'^audits/$', AuditListView.as_view(), name='audits-list'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', AuditDayArchiveView.as_view(), name='audits-list-day'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/$', AuditMonthArchiveView.as_view(), name='audits-list-month'), url(r'^audits/(?P<year>\d{4})/$', AuditYearArchiveView.as_view(), name='audits-list-year'), url(r'^audits/(?P<pk>\d+)/$', AuditView.as_view(), name='audit-detail'), url(r'^audits/(?P<audit_type>\w+)/$', AuditListView.as_view(), name='audits-list-filtered'), url(r'^probes/(?P<pk>\d+)/$', ProbeView.as_view(), name='probe-detail'), url(r'^admin/', include(admin.site.urls)), <|code_end|> , predict the next line using imports from the current file: from django.conf.urls import patterns, include, url from django.contrib import admin from thezombies.views import (HomeView, AgencyList, AgencyView, AuditListView, AuditView, AuditDayArchiveView, AuditMonthArchiveView, AuditYearArchiveView, ProbeView) and context including class names, function names, and sometimes code from other files: # Path: thezombies/views.py # class HomeView(RedirectView): # url = '/audits/' # pattern_name = 'audit-list' # # class AgencyList(ListView): # model = Agency # template_name = 'agency_list.html' # # class AgencyView(DetailView): # model = Agency # template_name = 'agency_detail.html' # # class AuditListView(ListView): # model = Audit # paginate_by = 50 # template_name = 'audits_list.html' # # def get_queryset(self, **kwargs): # audit_filter_kwargs = {} # self.audit_type_string = self.kwargs.get('audit_type', None) # if self.audit_type_string: # if self.audit_type_string == 'generic': # audit_filter_kwargs['audit_type'] = Audit.GENERIC_AUDIT # elif self.audit_type_string == 'validation': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_VALIDATION # elif self.audit_type_string == 'crawl': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_CRAWL # else: # raise Http404 # self.audit_list = Audit.objects.filter(**audit_filter_kwargs).prefetch_related('agency') # return self.audit_list # # def get_context_data(self, **kwargs): # context = super(AuditListView, self).get_context_data(**kwargs) # context['audit_type'] = self.audit_type_string # return context # # class AuditView(SingleObjectMixin, ListView): # paginate_by = 20 # template_name = 'audit_detail.html' # # def get(self, request, *args, **kwargs): # self.object = self.get_object(queryset=Audit.objects.all()) # return super(AuditView, self).get(request, *args, **kwargs) # # def get_context_data(self, **kwargs): # context = super(AuditView, self).get_context_data(**kwargs) # context['audit'] = self.object # return context # # def get_queryset(self): # # Paginate probe objects # return self.object.probe_set.order_by('id') # # def get_template_names(self): # template_names = super(AuditView, self).get_template_names() # template_choices = dict(AUDIT_TYPE_TEMPLATES) # template_addition = template_choices.get(self.object.audit_type, None) if self.object else None # if template_addition: # template_names.insert(0, template_addition) # return template_names # # class AuditDayArchiveView(DayArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditMonthArchiveView(MonthArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditYearArchiveView(YearArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # make_object_list = True # template_name = 'audits_list.html' # # class ProbeView(DetailView): # model = Probe # template_name = "probe_detail.html" . Output only the next line.
)
Based on the snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', HomeView.as_view(), name='home'), url(r'^agency/$', AgencyList.as_view(), name='agency-list'), url(r'^agency/(?P<slug>[\w\-]+)/$', AgencyView.as_view(), name='agency-detail'), url(r'^audits/$', AuditListView.as_view(), name='audits-list'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', AuditDayArchiveView.as_view(), name='audits-list-day'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/$', AuditMonthArchiveView.as_view(), name='audits-list-month'), url(r'^audits/(?P<year>\d{4})/$', AuditYearArchiveView.as_view(), name='audits-list-year'), url(r'^audits/(?P<pk>\d+)/$', AuditView.as_view(), name='audit-detail'), url(r'^audits/(?P<audit_type>\w+)/$', AuditListView.as_view(), name='audits-list-filtered'), url(r'^probes/(?P<pk>\d+)/$', ProbeView.as_view(), name='probe-detail'), <|code_end|> , predict the immediate next line with the help of imports: from django.conf.urls import patterns, include, url from django.contrib import admin from thezombies.views import (HomeView, AgencyList, AgencyView, AuditListView, AuditView, AuditDayArchiveView, AuditMonthArchiveView, AuditYearArchiveView, ProbeView) and context (classes, functions, sometimes code) from other files: # Path: thezombies/views.py # class HomeView(RedirectView): # url = '/audits/' # pattern_name = 'audit-list' # # class AgencyList(ListView): # model = Agency # template_name = 'agency_list.html' # # class AgencyView(DetailView): # model = Agency # template_name = 'agency_detail.html' # # class AuditListView(ListView): # model = Audit # paginate_by = 50 # template_name = 'audits_list.html' # # def get_queryset(self, **kwargs): # audit_filter_kwargs = {} # self.audit_type_string = self.kwargs.get('audit_type', None) # if self.audit_type_string: # if self.audit_type_string == 'generic': # audit_filter_kwargs['audit_type'] = Audit.GENERIC_AUDIT # elif self.audit_type_string == 'validation': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_VALIDATION # elif self.audit_type_string == 'crawl': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_CRAWL # else: # raise Http404 # self.audit_list = Audit.objects.filter(**audit_filter_kwargs).prefetch_related('agency') # return self.audit_list # # def get_context_data(self, **kwargs): # context = super(AuditListView, self).get_context_data(**kwargs) # context['audit_type'] = self.audit_type_string # return context # # class AuditView(SingleObjectMixin, ListView): # paginate_by = 20 # template_name = 'audit_detail.html' # # def get(self, request, *args, **kwargs): # self.object = self.get_object(queryset=Audit.objects.all()) # return super(AuditView, self).get(request, *args, **kwargs) # # def get_context_data(self, **kwargs): # context = super(AuditView, self).get_context_data(**kwargs) # context['audit'] = self.object # return context # # def get_queryset(self): # # Paginate probe objects # return self.object.probe_set.order_by('id') # # def get_template_names(self): # template_names = super(AuditView, self).get_template_names() # template_choices = dict(AUDIT_TYPE_TEMPLATES) # template_addition = template_choices.get(self.object.audit_type, None) if self.object else None # if template_addition: # template_names.insert(0, template_addition) # return template_names # # class AuditDayArchiveView(DayArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditMonthArchiveView(MonthArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditYearArchiveView(YearArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # make_object_list = True # template_name = 'audits_list.html' # # class ProbeView(DetailView): # model = Probe # template_name = "probe_detail.html" . Output only the next line.
url(r'^admin/', include(admin.site.urls)),
Given snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', HomeView.as_view(), name='home'), url(r'^agency/$', AgencyList.as_view(), name='agency-list'), url(r'^agency/(?P<slug>[\w\-]+)/$', AgencyView.as_view(), name='agency-detail'), url(r'^audits/$', AuditListView.as_view(), name='audits-list'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', AuditDayArchiveView.as_view(), name='audits-list-day'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/$', AuditMonthArchiveView.as_view(), name='audits-list-month'), url(r'^audits/(?P<year>\d{4})/$', AuditYearArchiveView.as_view(), name='audits-list-year'), url(r'^audits/(?P<pk>\d+)/$', AuditView.as_view(), name='audit-detail'), url(r'^audits/(?P<audit_type>\w+)/$', AuditListView.as_view(), name='audits-list-filtered'), url(r'^probes/(?P<pk>\d+)/$', ProbeView.as_view(), name='probe-detail'), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf.urls import patterns, include, url from django.contrib import admin from thezombies.views import (HomeView, AgencyList, AgencyView, AuditListView, AuditView, AuditDayArchiveView, AuditMonthArchiveView, AuditYearArchiveView, ProbeView) and context: # Path: thezombies/views.py # class HomeView(RedirectView): # url = '/audits/' # pattern_name = 'audit-list' # # class AgencyList(ListView): # model = Agency # template_name = 'agency_list.html' # # class AgencyView(DetailView): # model = Agency # template_name = 'agency_detail.html' # # class AuditListView(ListView): # model = Audit # paginate_by = 50 # template_name = 'audits_list.html' # # def get_queryset(self, **kwargs): # audit_filter_kwargs = {} # self.audit_type_string = self.kwargs.get('audit_type', None) # if self.audit_type_string: # if self.audit_type_string == 'generic': # audit_filter_kwargs['audit_type'] = Audit.GENERIC_AUDIT # elif self.audit_type_string == 'validation': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_VALIDATION # elif self.audit_type_string == 'crawl': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_CRAWL # else: # raise Http404 # self.audit_list = Audit.objects.filter(**audit_filter_kwargs).prefetch_related('agency') # return self.audit_list # # def get_context_data(self, **kwargs): # context = super(AuditListView, self).get_context_data(**kwargs) # context['audit_type'] = self.audit_type_string # return context # # class AuditView(SingleObjectMixin, ListView): # paginate_by = 20 # template_name = 'audit_detail.html' # # def get(self, request, *args, **kwargs): # self.object = self.get_object(queryset=Audit.objects.all()) # return super(AuditView, self).get(request, *args, **kwargs) # # def get_context_data(self, **kwargs): # context = super(AuditView, self).get_context_data(**kwargs) # context['audit'] = self.object # return context # # def get_queryset(self): # # Paginate probe objects # return self.object.probe_set.order_by('id') # # def get_template_names(self): # template_names = super(AuditView, self).get_template_names() # template_choices = dict(AUDIT_TYPE_TEMPLATES) # template_addition = template_choices.get(self.object.audit_type, None) if self.object else None # if template_addition: # template_names.insert(0, template_addition) # return template_names # # class AuditDayArchiveView(DayArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditMonthArchiveView(MonthArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditYearArchiveView(YearArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # make_object_list = True # template_name = 'audits_list.html' # # class ProbeView(DetailView): # model = Probe # template_name = "probe_detail.html" which might include code, classes, or functions. Output only the next line.
url(r'^admin/', include(admin.site.urls)),
Here is a snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', HomeView.as_view(), name='home'), url(r'^agency/$', AgencyList.as_view(), name='agency-list'), url(r'^agency/(?P<slug>[\w\-]+)/$', AgencyView.as_view(), name='agency-detail'), url(r'^audits/$', AuditListView.as_view(), name='audits-list'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', AuditDayArchiveView.as_view(), name='audits-list-day'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/$', AuditMonthArchiveView.as_view(), name='audits-list-month'), url(r'^audits/(?P<year>\d{4})/$', AuditYearArchiveView.as_view(), name='audits-list-year'), url(r'^audits/(?P<pk>\d+)/$', AuditView.as_view(), name='audit-detail'), url(r'^audits/(?P<audit_type>\w+)/$', AuditListView.as_view(), name='audits-list-filtered'), url(r'^probes/(?P<pk>\d+)/$', ProbeView.as_view(), name='probe-detail'), <|code_end|> . Write the next line using the current file imports: from django.conf.urls import patterns, include, url from django.contrib import admin from thezombies.views import (HomeView, AgencyList, AgencyView, AuditListView, AuditView, AuditDayArchiveView, AuditMonthArchiveView, AuditYearArchiveView, ProbeView) and context from other files: # Path: thezombies/views.py # class HomeView(RedirectView): # url = '/audits/' # pattern_name = 'audit-list' # # class AgencyList(ListView): # model = Agency # template_name = 'agency_list.html' # # class AgencyView(DetailView): # model = Agency # template_name = 'agency_detail.html' # # class AuditListView(ListView): # model = Audit # paginate_by = 50 # template_name = 'audits_list.html' # # def get_queryset(self, **kwargs): # audit_filter_kwargs = {} # self.audit_type_string = self.kwargs.get('audit_type', None) # if self.audit_type_string: # if self.audit_type_string == 'generic': # audit_filter_kwargs['audit_type'] = Audit.GENERIC_AUDIT # elif self.audit_type_string == 'validation': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_VALIDATION # elif self.audit_type_string == 'crawl': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_CRAWL # else: # raise Http404 # self.audit_list = Audit.objects.filter(**audit_filter_kwargs).prefetch_related('agency') # return self.audit_list # # def get_context_data(self, **kwargs): # context = super(AuditListView, self).get_context_data(**kwargs) # context['audit_type'] = self.audit_type_string # return context # # class AuditView(SingleObjectMixin, ListView): # paginate_by = 20 # template_name = 'audit_detail.html' # # def get(self, request, *args, **kwargs): # self.object = self.get_object(queryset=Audit.objects.all()) # return super(AuditView, self).get(request, *args, **kwargs) # # def get_context_data(self, **kwargs): # context = super(AuditView, self).get_context_data(**kwargs) # context['audit'] = self.object # return context # # def get_queryset(self): # # Paginate probe objects # return self.object.probe_set.order_by('id') # # def get_template_names(self): # template_names = super(AuditView, self).get_template_names() # template_choices = dict(AUDIT_TYPE_TEMPLATES) # template_addition = template_choices.get(self.object.audit_type, None) if self.object else None # if template_addition: # template_names.insert(0, template_addition) # return template_names # # class AuditDayArchiveView(DayArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditMonthArchiveView(MonthArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditYearArchiveView(YearArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # make_object_list = True # template_name = 'audits_list.html' # # class ProbeView(DetailView): # model = Probe # template_name = "probe_detail.html" , which may include functions, classes, or code. Output only the next line.
url(r'^admin/', include(admin.site.urls)),
Given snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', HomeView.as_view(), name='home'), url(r'^agency/$', AgencyList.as_view(), name='agency-list'), url(r'^agency/(?P<slug>[\w\-]+)/$', AgencyView.as_view(), name='agency-detail'), url(r'^audits/$', AuditListView.as_view(), name='audits-list'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', AuditDayArchiveView.as_view(), name='audits-list-day'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/$', AuditMonthArchiveView.as_view(), name='audits-list-month'), url(r'^audits/(?P<year>\d{4})/$', AuditYearArchiveView.as_view(), name='audits-list-year'), url(r'^audits/(?P<pk>\d+)/$', AuditView.as_view(), name='audit-detail'), url(r'^audits/(?P<audit_type>\w+)/$', AuditListView.as_view(), name='audits-list-filtered'), url(r'^probes/(?P<pk>\d+)/$', ProbeView.as_view(), name='probe-detail'), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf.urls import patterns, include, url from django.contrib import admin from thezombies.views import (HomeView, AgencyList, AgencyView, AuditListView, AuditView, AuditDayArchiveView, AuditMonthArchiveView, AuditYearArchiveView, ProbeView) and context: # Path: thezombies/views.py # class HomeView(RedirectView): # url = '/audits/' # pattern_name = 'audit-list' # # class AgencyList(ListView): # model = Agency # template_name = 'agency_list.html' # # class AgencyView(DetailView): # model = Agency # template_name = 'agency_detail.html' # # class AuditListView(ListView): # model = Audit # paginate_by = 50 # template_name = 'audits_list.html' # # def get_queryset(self, **kwargs): # audit_filter_kwargs = {} # self.audit_type_string = self.kwargs.get('audit_type', None) # if self.audit_type_string: # if self.audit_type_string == 'generic': # audit_filter_kwargs['audit_type'] = Audit.GENERIC_AUDIT # elif self.audit_type_string == 'validation': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_VALIDATION # elif self.audit_type_string == 'crawl': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_CRAWL # else: # raise Http404 # self.audit_list = Audit.objects.filter(**audit_filter_kwargs).prefetch_related('agency') # return self.audit_list # # def get_context_data(self, **kwargs): # context = super(AuditListView, self).get_context_data(**kwargs) # context['audit_type'] = self.audit_type_string # return context # # class AuditView(SingleObjectMixin, ListView): # paginate_by = 20 # template_name = 'audit_detail.html' # # def get(self, request, *args, **kwargs): # self.object = self.get_object(queryset=Audit.objects.all()) # return super(AuditView, self).get(request, *args, **kwargs) # # def get_context_data(self, **kwargs): # context = super(AuditView, self).get_context_data(**kwargs) # context['audit'] = self.object # return context # # def get_queryset(self): # # Paginate probe objects # return self.object.probe_set.order_by('id') # # def get_template_names(self): # template_names = super(AuditView, self).get_template_names() # template_choices = dict(AUDIT_TYPE_TEMPLATES) # template_addition = template_choices.get(self.object.audit_type, None) if self.object else None # if template_addition: # template_names.insert(0, template_addition) # return template_names # # class AuditDayArchiveView(DayArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditMonthArchiveView(MonthArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditYearArchiveView(YearArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # make_object_list = True # template_name = 'audits_list.html' # # class ProbeView(DetailView): # model = Probe # template_name = "probe_detail.html" which might include code, classes, or functions. Output only the next line.
url(r'^admin/', include(admin.site.urls)),
Given snippet: <|code_start|> urlpatterns = patterns('', url(r'^$', HomeView.as_view(), name='home'), url(r'^agency/$', AgencyList.as_view(), name='agency-list'), url(r'^agency/(?P<slug>[\w\-]+)/$', AgencyView.as_view(), name='agency-detail'), url(r'^audits/$', AuditListView.as_view(), name='audits-list'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', AuditDayArchiveView.as_view(), name='audits-list-day'), url(r'^audits/(?P<year>\d{4})/(?P<month>\d{2})/$', AuditMonthArchiveView.as_view(), name='audits-list-month'), url(r'^audits/(?P<year>\d{4})/$', AuditYearArchiveView.as_view(), name='audits-list-year'), url(r'^audits/(?P<pk>\d+)/$', AuditView.as_view(), name='audit-detail'), url(r'^audits/(?P<audit_type>\w+)/$', AuditListView.as_view(), name='audits-list-filtered'), url(r'^probes/(?P<pk>\d+)/$', ProbeView.as_view(), name='probe-detail'), url(r'^admin/', include(admin.site.urls)), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf.urls import patterns, include, url from django.contrib import admin from thezombies.views import (HomeView, AgencyList, AgencyView, AuditListView, AuditView, AuditDayArchiveView, AuditMonthArchiveView, AuditYearArchiveView, ProbeView) and context: # Path: thezombies/views.py # class HomeView(RedirectView): # url = '/audits/' # pattern_name = 'audit-list' # # class AgencyList(ListView): # model = Agency # template_name = 'agency_list.html' # # class AgencyView(DetailView): # model = Agency # template_name = 'agency_detail.html' # # class AuditListView(ListView): # model = Audit # paginate_by = 50 # template_name = 'audits_list.html' # # def get_queryset(self, **kwargs): # audit_filter_kwargs = {} # self.audit_type_string = self.kwargs.get('audit_type', None) # if self.audit_type_string: # if self.audit_type_string == 'generic': # audit_filter_kwargs['audit_type'] = Audit.GENERIC_AUDIT # elif self.audit_type_string == 'validation': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_VALIDATION # elif self.audit_type_string == 'crawl': # audit_filter_kwargs['audit_type'] = Audit.DATA_CATALOG_CRAWL # else: # raise Http404 # self.audit_list = Audit.objects.filter(**audit_filter_kwargs).prefetch_related('agency') # return self.audit_list # # def get_context_data(self, **kwargs): # context = super(AuditListView, self).get_context_data(**kwargs) # context['audit_type'] = self.audit_type_string # return context # # class AuditView(SingleObjectMixin, ListView): # paginate_by = 20 # template_name = 'audit_detail.html' # # def get(self, request, *args, **kwargs): # self.object = self.get_object(queryset=Audit.objects.all()) # return super(AuditView, self).get(request, *args, **kwargs) # # def get_context_data(self, **kwargs): # context = super(AuditView, self).get_context_data(**kwargs) # context['audit'] = self.object # return context # # def get_queryset(self): # # Paginate probe objects # return self.object.probe_set.order_by('id') # # def get_template_names(self): # template_names = super(AuditView, self).get_template_names() # template_choices = dict(AUDIT_TYPE_TEMPLATES) # template_addition = template_choices.get(self.object.audit_type, None) if self.object else None # if template_addition: # template_names.insert(0, template_addition) # return template_names # # class AuditDayArchiveView(DayArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditMonthArchiveView(MonthArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # month_format = "%m" # make_object_list = True # template_name = 'audits_list.html' # # class AuditYearArchiveView(YearArchiveView): # queryset = Audit.objects.all() # allow_empty = True # paginate_by = 50 # date_field = "created_at" # make_object_list = True # template_name = 'audits_list.html' # # class ProbeView(DetailView): # model = Probe # template_name = "probe_detail.html" which might include code, classes, or functions. Output only the next line.
)
Next line prediction: <|code_start|># Sistema de depuración VPOS_TYPES = ( ("ceca", _("TPV Virtual - Confederación Española de Cajas de Ahorros (CECA)")), ("paypal", _("Paypal")), ("redsys", _("TPV Redsys")), ("santanderelavon", _("TPV Santander Elavon")), ("bitpay", _("TPV Bitpay")), ) ## Relación entre tipos de TPVs y clases delegadas VPOS_CLASSES = { "ceca": "VPOSCeca", "redsys": "VPOSRedsys", "paypal": "VPOSPaypal", "santanderelavon": "VPOSSantanderElavon", "bitpay": "VPOSBitpay", } ######################################################################## ## Obtiene la clase delegada a partir del tipo de TPV. ## La clase delegada ha de estar definida en el ## diccionario TPV_CLASSES en vpos.models. <|code_end|> . Use current file imports: (import base64 import json import re import cgi import random import urllib2, urllib import urlparse import hashlib import datetime import time import requests from bs4 import BeautifulSoup from debug import dlprint from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.conf import settings from django.core.validators import MinLengthValidator, MaxLengthValidator, RegexValidator from django.db.models import Sum from django.http import HttpResponse from django.utils import timezone from django.shortcuts import redirect from django.core.urlresolvers import reverse from django.utils import translation from Crypto.Cipher import DES3 from Crypto.Hash import SHA256, HMAC from lxml import etree from decimal import Decimal from djangovirtualpos.util import dictlist, localize_datetime from django.utils.translation import ugettext_lazy as _ from bs4 import BeautifulSoup from forms import VPOSCecaForm from forms import VPOSRedsysForm from forms import VPOSPaypalForm from forms import VPOSSantanderElavonForm) and context including class names, function names, or small code snippets from other files: # Path: djangovirtualpos/util.py # def dictlist(node): # res = {} # res[node.tag] = [] # xmltodict(node, res[node.tag]) # reply = {} # reply[node.tag] = {'value': res[node.tag], 'attribs': node.attrib, 'tail': node.tail} # # return reply # # def localize_datetime(_datetime): # """Localiza la marca de tiempo en función de la zona de tiempo del servidor. Sólo y exclusivamente si no está localizada ya.""" # if timezone.is_naive(_datetime): # return as_server_datetime(_datetime) # return _datetime . Output only the next line.
def get_delegated_class(virtualpos_type):
Predict the next line after this snippet: <|code_start|> # Recogemos la respuesta dada, que vendrá en texto plano response = urllib2.urlopen(request) response_string = response.read().decode("utf8") dlprint(u"Response VOID: {0}".format(response_string)) # Almacenar respuesta en datos de operación extended_confirmation_data = u"{0}\n\nRespuesta void:\n{1}".format(self.parent.operation.confirmation_data, response_string) self.parent.operation.confirmation_data = extended_confirmation_data self.parent.operation.save() dlprint(u"Operation {0} actualizada en responseNok()".format(self.parent.operation.operation_number)) # La pasarela de pagos Santander Elavon "Redirect" no espera recibir ningún valor especial. dlprint(u"responseNok") # La pasarela de pagos Santander Elavon "Redirect" espera recibir una plantilla HTML que se le mostrará al # cliente. # Ya que dicho TPV no redirige al navegador del cliente a ninguna URL, se hace la redirección a la "url_ok" # mediante Javascript. return HttpResponse(u""" <html> <head> <title>Operación cancelada</title> <script type="text/javascript"> window.location.assign("{0}"); </script> </head> <body> <p><strong>Operación cancelada</strong></p> <|code_end|> using the current file's imports: import base64 import json import re import cgi import random import urllib2, urllib import urlparse import hashlib import datetime import time import requests from bs4 import BeautifulSoup from debug import dlprint from django.core.exceptions import ObjectDoesNotExist from django.db import models from django.conf import settings from django.core.validators import MinLengthValidator, MaxLengthValidator, RegexValidator from django.db.models import Sum from django.http import HttpResponse from django.utils import timezone from django.shortcuts import redirect from django.core.urlresolvers import reverse from django.utils import translation from Crypto.Cipher import DES3 from Crypto.Hash import SHA256, HMAC from lxml import etree from decimal import Decimal from djangovirtualpos.util import dictlist, localize_datetime from django.utils.translation import ugettext_lazy as _ from bs4 import BeautifulSoup from forms import VPOSCecaForm from forms import VPOSRedsysForm from forms import VPOSPaypalForm from forms import VPOSSantanderElavonForm and any relevant context from other files: # Path: djangovirtualpos/util.py # def dictlist(node): # res = {} # res[node.tag] = [] # xmltodict(node, res[node.tag]) # reply = {} # reply[node.tag] = {'value': res[node.tag], 'attribs': node.attrib, 'tail': node.tail} # # return reply # # def localize_datetime(_datetime): # """Localiza la marca de tiempo en función de la zona de tiempo del servidor. Sólo y exclusivamente si no está localizada ya.""" # if timezone.is_naive(_datetime): # return as_server_datetime(_datetime) # return _datetime . Output only the next line.
<p>Pulse <a href="{0}">este enlace</a> si su navegador no le redirige automáticamente</p>
Next line prediction: <|code_start|> options.XSD_DATETIME_FORMAT) # .replace(tzinfo=None) class EndTimeOption(usage.Options): optParameters = [[options.END_TIME, 'e', None, 'End time (UTC time)']] def postOptions(self): if self[options.END_TIME] is not None: self[options.END_TIME] = datetime.datetime.strptime(self[options.END_TIME], options.XSD_DATETIME_FORMAT) # .replace(tzinfo=None) class SecurityAttributeOptions(usage.Options): optParameters = [[options.SECURITY_ATTRIBUTES, 'j', None, 'Security attributes (format attr1=value1,attr2=value2)']] def postOptions(self): sats = [] if self[options.SECURITY_ATTRIBUTES]: for kv_split in self[options.SECURITY_ATTRIBUTES].split(','): if not '=' in kv_split: raise usage.UsageError('No = in key-value attribute %s' % kv_split) key, value = kv_split.split('=', 1) sats.append((key, value)) self[options.SECURITY_ATTRIBUTES] = sats class BandwidthOption(usage.Options): optParameters = [[options.BANDWIDTH, 'b', None, 'Bandwidth (Megabits)']] <|code_end|> . Use current file imports: (import datetime from twisted.python import usage from opennsa.cli import options from opennsa import __version__ from twisted import copyright) and context including class names, function names, or small code snippets from other files: # Path: opennsa/cli/options.py # VERBOSE = 'verbose' # DEFAULTS_FILE = 'defaults-file' # DUMP_PAYLOAD = 'dump-payload' # HOST = 'host' # PORT = 'port' # TOPOLOGY_FILE = 'topology' # NETWORK = 'network' # SERVICE_URL = 'service' # AUTHZ_HEADER = 'authzheader' # REQUESTER = 'requester' # PROVIDER = 'provider' # SECURITY_ATTRIBUTES = 'securityattributes' # CONNECTION_ID = 'connection-id' # GLOBAL_ID = 'global-id' # SOURCE_STP = 'source' # DEST_STP = 'dest' # BANDWIDTH = 'bandwidth' # START_TIME = 'starttime' # END_TIME = 'endtime' # ERO = 'ero' # TLS = config.TLS # KEY = config.KEY # CERTIFICATE = config.CERTIFICATE # CERTIFICATE_DIR = config.CERTIFICATE_DIR # NO_VERIFY_CERT = 'no-verify' # NOTIFICATION_WAIT = 'notification_wait' # XSD_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S" # NSA_SHORTHAND = 'nsa' # def parseTimestamp(value): # def readDefaults(file_): . Output only the next line.
class EroOption(usage.Options):
Predict the next line after this snippet: <|code_start|> def terminateConfirmed(self, header, connection_id): self.triggerCall(header.provider_nsa, header.correlation_id, TERMINATE, connection_id) def terminateFailed(self, header, connection_id, connection_states, err): self.triggerCall(header.provider_nsa, header.correlation_id, TERMINATE, err) def querySummary(self, header, connection_ids=None, global_reservation_ids=None): # we just use sync for this, keep it simple d = self.requester_client.querySummarySync(header, connection_ids, global_reservation_ids) return d ## As we use the sync version of querySummary these are not needed ## def queryConfirmed(self, header, result): ## ## self.triggerCall(header.provider_nsa, header.correlation_id, QUERY_SUMMARY, result) ## ## def queryFailed(self, header, err): ## ## self.triggerCall(header.provider_nsa, header.correlation_id, QUERY_SUMMARY, err) def queryRecursive(self, header, connection_ids, global_reservation_ids): <|code_end|> using the current file's imports: from zope.interface import implementer from twisted.python import log, failure from twisted.internet import reactor, defer from opennsa import error from opennsa.interface import INSIProvider and any relevant context from other files: # Path: opennsa/error.py # LOG_SYSTEM = 'error' # NSI_ERROR_CODE_TABLE = { # '00100' : PayloadError, # '00101' : MissingParameterError, # '00200' : ConnectionError, # '00201' : InvalidTransitionError, # '00202' : ConnectionExistsError, # '00203' : ConnectionNonExistentError, # '00204' : ConnectionGoneError, # '00205' : ConnectionCreateError, # '00300' : SecurityError, # '00301' : AuthenticationFailure, # '00302' : UnauthorizedError, # '00400' : TopologyError, # '00401' : UnknownSTPError, # compat # '00402' : STPResolutionError, # compat # '00403' : NoPathFoundError, # '00404' : VLANInterchangeNotSupportedError, # compat # '00500' : InternalServerError, # '00501' : InternalNRMError, # '00600' : ResourceUnavailableError, # '00601' : STPUnavailableError, # compat # '00602' : BandwidthUnavailableError, # compat # '00700' : ServiceError, # '00701' : UnknownSTPError, # '00702' : STPResolutionError, # '00703' : VLANInterchangeNotSupportedError, # '00704' : STPUnavailableError, # '00705' : BandwidthUnavailableError # compat # } # class CallbackTimeoutError(Exception): # class NSIError(Exception): # class UnknownNSIError(NSIError): # class PayloadError(NSIError): # class MissingParameterError(PayloadError): # class UnsupportedParameter(PayloadError): # class ConnectionError(NSIError): # class InvalidTransitionError(ConnectionError): # class ConnectionExistsError(ConnectionError): # class ConnectionNonExistentError(ConnectionError): # class ConnectionGoneError(ConnectionError): # class ConnectionCreateError(ConnectionError): # class SecurityError(NSIError): # class AuthenticationFailure(SecurityError): # class UnauthorizedError(SecurityError): # class TopologyError(NSIError): # class NoPathFoundError(NSIError): # class InternalServerError(NSIError): # class InternalNRMError(InternalServerError): # class DownstreamNSAError(InternalServerError): # class ResourceUnavailableError(NSIError): # class ServiceError(NSIError): # only use this if nothing else applies # class UnknownSTPError(ServiceError): # class STPResolutionError(NSIError): # class VLANInterchangeNotSupportedError(TopologyError): # class STPUnavailableError(ServiceError, TopologyError): # need this to be a topology error internally # class BandwidthUnavailableError(ServiceError): # NSI error name is CAPACITY_UNAVAILABLE # def __init__(self, message, nsa_id=None, connection_id=None, variables=None): # def lookup(error_code): . Output only the next line.
def queryRecursiveFailed(err):
Given the code snippet: <|code_start|> self.c.addReservation('r1', ds, de) def testDoubleCheckAdd(self): ds1 = datetime.datetime.utcnow() + datetime.timedelta(seconds=1) de1 = datetime.datetime.utcnow() + datetime.timedelta(seconds=3) ds2 = datetime.datetime.utcnow() + datetime.timedelta(seconds=5) de2 = datetime.datetime.utcnow() + datetime.timedelta(seconds=7) self.c.checkReservation('r1', ds1, de1) self.c.addReservation('r1', ds1, de1) self.c.checkReservation('r1', ds2, de2) self.c.addReservation('r1', ds2, de2) def testSimpleConflict(self): ds1 = datetime.datetime.utcnow() + datetime.timedelta(seconds=1) de1 = datetime.datetime.utcnow() + datetime.timedelta(seconds=5) ds2 = datetime.datetime.utcnow() + datetime.timedelta(seconds=4) de2 = datetime.datetime.utcnow() + datetime.timedelta(seconds=7) self.c.checkReservation('r1', ds1, de1) self.c.addReservation('r1', ds1, de2) self.failUnlessRaises(error.STPUnavailableError, self.c.checkReservation, 'r1', ds2, de2) <|code_end|> , generate the next line using the imports in this file: import datetime from twisted.trial import unittest from opennsa import error from opennsa.backends.common import calendar and context (functions, classes, or occasionally code) from other files: # Path: opennsa/error.py # LOG_SYSTEM = 'error' # NSI_ERROR_CODE_TABLE = { # '00100' : PayloadError, # '00101' : MissingParameterError, # '00200' : ConnectionError, # '00201' : InvalidTransitionError, # '00202' : ConnectionExistsError, # '00203' : ConnectionNonExistentError, # '00204' : ConnectionGoneError, # '00205' : ConnectionCreateError, # '00300' : SecurityError, # '00301' : AuthenticationFailure, # '00302' : UnauthorizedError, # '00400' : TopologyError, # '00401' : UnknownSTPError, # compat # '00402' : STPResolutionError, # compat # '00403' : NoPathFoundError, # '00404' : VLANInterchangeNotSupportedError, # compat # '00500' : InternalServerError, # '00501' : InternalNRMError, # '00600' : ResourceUnavailableError, # '00601' : STPUnavailableError, # compat # '00602' : BandwidthUnavailableError, # compat # '00700' : ServiceError, # '00701' : UnknownSTPError, # '00702' : STPResolutionError, # '00703' : VLANInterchangeNotSupportedError, # '00704' : STPUnavailableError, # '00705' : BandwidthUnavailableError # compat # } # class CallbackTimeoutError(Exception): # class NSIError(Exception): # class UnknownNSIError(NSIError): # class PayloadError(NSIError): # class MissingParameterError(PayloadError): # class UnsupportedParameter(PayloadError): # class ConnectionError(NSIError): # class InvalidTransitionError(ConnectionError): # class ConnectionExistsError(ConnectionError): # class ConnectionNonExistentError(ConnectionError): # class ConnectionGoneError(ConnectionError): # class ConnectionCreateError(ConnectionError): # class SecurityError(NSIError): # class AuthenticationFailure(SecurityError): # class UnauthorizedError(SecurityError): # class TopologyError(NSIError): # class NoPathFoundError(NSIError): # class InternalServerError(NSIError): # class InternalNRMError(InternalServerError): # class DownstreamNSAError(InternalServerError): # class ResourceUnavailableError(NSIError): # class ServiceError(NSIError): # only use this if nothing else applies # class UnknownSTPError(ServiceError): # class STPResolutionError(NSIError): # class VLANInterchangeNotSupportedError(TopologyError): # class STPUnavailableError(ServiceError, TopologyError): # need this to be a topology error internally # class BandwidthUnavailableError(ServiceError): # NSI error name is CAPACITY_UNAVAILABLE # def __init__(self, message, nsa_id=None, connection_id=None, variables=None): # def lookup(error_code): # # Path: opennsa/backends/common/calendar.py # class ReservationCalendar: # def __init__(self): # def _checkArgs(self, resource, start_time, end_time): # def addReservation(self, resource, start_time, end_time): # def removeReservation(self, resource, start_time, end_time): # def checkReservation(self, resource, start_time, end_time): # def _resourceOverlap(self, res1_start_time, res1_end_time, res2_start_time, res2_end_time): . Output only the next line.
def testStartNone(self):
Predict the next line after this snippet: <|code_start|> def testStartNone(self): ds1 = None de1 = datetime.datetime.utcnow() + datetime.timedelta(seconds=5) ds2 = None de2 = datetime.datetime.utcnow() + datetime.timedelta(seconds=7) self.c.checkReservation('r1', ds1, de1) self.c.addReservation('r1', ds1, de2) self.failUnlessRaises(error.STPUnavailableError, self.c.checkReservation, 'r1', ds2, de2) def testEndNone(self): ds1 = datetime.datetime.utcnow() + datetime.timedelta(seconds=1) de1 = None ds2 = datetime.datetime.utcnow() + datetime.timedelta(seconds=4) de2 = None self.c.checkReservation('r1', ds1, de1) self.c.addReservation('r1', ds1, de2) self.failUnlessRaises(error.STPUnavailableError, self.c.checkReservation, 'r1', ds2, de2) def testStartEndNone(self): <|code_end|> using the current file's imports: import datetime from twisted.trial import unittest from opennsa import error from opennsa.backends.common import calendar and any relevant context from other files: # Path: opennsa/error.py # LOG_SYSTEM = 'error' # NSI_ERROR_CODE_TABLE = { # '00100' : PayloadError, # '00101' : MissingParameterError, # '00200' : ConnectionError, # '00201' : InvalidTransitionError, # '00202' : ConnectionExistsError, # '00203' : ConnectionNonExistentError, # '00204' : ConnectionGoneError, # '00205' : ConnectionCreateError, # '00300' : SecurityError, # '00301' : AuthenticationFailure, # '00302' : UnauthorizedError, # '00400' : TopologyError, # '00401' : UnknownSTPError, # compat # '00402' : STPResolutionError, # compat # '00403' : NoPathFoundError, # '00404' : VLANInterchangeNotSupportedError, # compat # '00500' : InternalServerError, # '00501' : InternalNRMError, # '00600' : ResourceUnavailableError, # '00601' : STPUnavailableError, # compat # '00602' : BandwidthUnavailableError, # compat # '00700' : ServiceError, # '00701' : UnknownSTPError, # '00702' : STPResolutionError, # '00703' : VLANInterchangeNotSupportedError, # '00704' : STPUnavailableError, # '00705' : BandwidthUnavailableError # compat # } # class CallbackTimeoutError(Exception): # class NSIError(Exception): # class UnknownNSIError(NSIError): # class PayloadError(NSIError): # class MissingParameterError(PayloadError): # class UnsupportedParameter(PayloadError): # class ConnectionError(NSIError): # class InvalidTransitionError(ConnectionError): # class ConnectionExistsError(ConnectionError): # class ConnectionNonExistentError(ConnectionError): # class ConnectionGoneError(ConnectionError): # class ConnectionCreateError(ConnectionError): # class SecurityError(NSIError): # class AuthenticationFailure(SecurityError): # class UnauthorizedError(SecurityError): # class TopologyError(NSIError): # class NoPathFoundError(NSIError): # class InternalServerError(NSIError): # class InternalNRMError(InternalServerError): # class DownstreamNSAError(InternalServerError): # class ResourceUnavailableError(NSIError): # class ServiceError(NSIError): # only use this if nothing else applies # class UnknownSTPError(ServiceError): # class STPResolutionError(NSIError): # class VLANInterchangeNotSupportedError(TopologyError): # class STPUnavailableError(ServiceError, TopologyError): # need this to be a topology error internally # class BandwidthUnavailableError(ServiceError): # NSI error name is CAPACITY_UNAVAILABLE # def __init__(self, message, nsa_id=None, connection_id=None, variables=None): # def lookup(error_code): # # Path: opennsa/backends/common/calendar.py # class ReservationCalendar: # def __init__(self): # def _checkArgs(self, resource, start_time, end_time): # def addReservation(self, resource, start_time, end_time): # def removeReservation(self, resource, start_time, end_time): # def checkReservation(self, resource, start_time, end_time): # def _resourceOverlap(self, res1_start_time, res1_end_time, res2_start_time, res2_end_time): . Output only the next line.
ds1 = None
Using the snippet: <|code_start|># Fetches discovory documents from other nsas LOG_SYSTEM = 'discovery.Fetcher' # Exponenetial backoff (x2) is used, for fetch intervals FETCH_INTERVAL_MIN = 10 # seconds FETCH_INTERVAL_MAX = 3600 # seconds - 3600 seconds = 1 hour <|code_end|> , determine the next line of code. You have imports: from twisted.python import log from twisted.internet import defer, task, reactor from twisted.application import service from opennsa import nsa, constants as cnt from opennsa.protocols.shared import httpclient from opennsa.discovery.bindings import discovery from opennsa.topology.nmlxml import _baseName # nasty but I need it import traceback and context (class names, function names, or code) available: # Path: opennsa/nsa.py # LOG_SYSTEM = 'opennsa.nsa' # URN_UUID_PREFIX = 'urn:uuid:' # BIDIRECTIONAL = 'Bidirectional' # class NSIHeader(object): # class SecurityAttribute(object): # class EmptyLabelSet(Exception): # class Label(object): # class STP(object): # Service Termination Point # class Link(object): # class Path(object): # class NetworkServiceAgent(object): # class ConnectionInfo(object): # class Criteria(object): # class QueryCriteria(Criteria): # class Schedule(object): # class Point2PointService(object): # def __init__(self, requester_nsa, provider_nsa, correlation_id=None, reply_to=None, security_attributes=None, connection_trace=None): # def _createCorrelationId(self): # def newCorrelationId(self): # def __repr__(self): # def __init__(self, type_, value): # def __repr__(self): # def __init__(self, type_, values=None): # def _parseLabelValues(self, values): # def createValue(value): # def intersect(self, other): # def labelValue(self): # def singleValue(self): # def enumerateValues(self): # def randomLabel(self): # def canMatch(l1, l2): # def __eq__(self, other): # def __repr__(self): # def __init__(self, network, port, label=None): # def shortName(self): # def baseURN(self): # def urn(self): # def __eq__(self, other): # def __repr__(self): # def __init__(self, src_stp, dst_stp): # def sourceSTP(self): # def destSTP(self): # def __eq__(self, other): # def __repr__(self): # def __init__(self, network_links): # def links(self): # def sourceEndpoint(self): # def destEndpoint(self): # def __str__(self): # def __init__(self, identity, endpoint, service_type=None): # def getHostPort(self): # def urn(self): # def getServiceType(self): # def __str__(self): # def __init__(self, connection_id, global_reservation_id, description, service_type, criterias, provider_nsa, requester_nsa, states, notification_id, result_id): # def __init__(self, revision, schedule, service_def): # def __init__(self, revision, schedule, service_def, children=None): # def __init__(self, start_time, end_time): # def __str__(self): # def __init__(self, source_stp, dest_stp, capacity, directionality=BIDIRECTIONAL, symmetric=False, ero=None, parameters=None): # # Path: opennsa/constants.py # URN_OGF_PREFIX = 'urn:ogf:network:' # CS2_SERVICE_TYPE = 'application/vnd.org.ogf.nsi.cs.v2+soap' # NML_SERVICE_TYPE = 'application/vnd.ogf.nsi.topology.v2+xml' # CS2_REQUESTER = 'application/vnd.ogf.nsi.cs.v2.requester+soap' # CS2_PROVIDER = 'application/vnd.ogf.nsi.cs.v2.provider+soap' # OPENNSA_REST = 'application/vnd.net.nordu.opennsa+rest' # BIDIRECTIONAL = 'Bidirectional' # EVTS_AGOLE = 'http://services.ogf.org/nsi/2013/07/descriptions/EVTS.A-GOLE' # ETHERNET = 'ethernet' # bidirectional implied # ETHERNET_VLAN = 'vlan' # MPLS = 'mpls' # RESTRICTTRANSIT = 'restricttransit' # ETHERNET_NS = 'http://schemas.ogf.org/nml/2012/10/ethernet' # NML_ETHERNET_VLAN = '%s#vlan' % ETHERNET_NS # NML_MPLS = 'http://nsi.nordu.net/nml#mpls' # pretty much just made up # FEATURE_AGGREGATOR = 'vnd.ogf.nsi.cs.v2.role.aggregator' # FEATURE_UPA = 'vnd.ogf.nsi.cs.v2.role.uPA' # REQUIRE_USER = 'requireuser' # REQUIRE_TRACE = 'requiretrace' # AGGREGATOR = 'aggregator' # ALLOW_HAIRPIN = 'allowhairpin' # # Path: opennsa/protocols/shared/httpclient.py # LOG_SYSTEM = 'HTTPClient' # DEFAULT_TIMEOUT = 30 # seconds # class HTTPRequestError(Exception): # def soapRequest(url, soap_action, soap_envelope, timeout=DEFAULT_TIMEOUT, ctx_factory=None, headers=None): # def httpRequest(url, payload, headers, method=b'POST', timeout=DEFAULT_TIMEOUT, ctx_factory=None): # def invocationError(err): # def logReply(data): # # Path: opennsa/topology/nmlxml.py # def _baseName(urn_id): # assert urn_id.startswith(cnt.URN_OGF_PREFIX), 'Identifier %s must start with urn ogf network prefix' % urn_id # base_name = urn_id[len(cnt.URN_OGF_PREFIX):] # return base_name . Output only the next line.
class FetcherService(service.Service):
Predict the next line after this snippet: <|code_start|> class DatabaseTest(unittest.TestCase): def setUp(self): db.setupDatabase() @defer.inlineCallbacks def testReverseStartEndTimeConstraint(self): now = datetime.datetime.utcnow() start_time = now - datetime.timedelta(seconds=10) end_time = now - datetime.timedelta(seconds=1000) conn = genericbackend.GenericBackendConnections( connection_id='conn-123', <|code_end|> using the current file's imports: import datetime import psycopg2 from twisted.internet import defer from twisted.trial import unittest from opennsa import state from opennsa.backends.common import genericbackend from . import db and any relevant context from other files: # Path: opennsa/state.py # LOG_SYSTEM = 'opennsa.state' # RESERVE_START = 'ReserveStart' # RESERVE_CHECKING = 'ReserveChecking' # RESERVE_HELD = 'ReserveHeld' # RESERVE_COMMITTING = 'ReserveComitting' # RESERVE_FAILED = 'ReserveFailed' # RESERVE_ABORTING = 'ReserveAborting' # RESERVE_TIMEOUT = 'ReserveTimeout' # Only UPA # RELEASED = 'Released' # PROVISIONING = 'Provisioning' # PROVISIONED = 'Provisioned' # RELEASING = 'Releasing' # CREATED = 'Created' # FAILED = 'Failed' # PASSED_ENDTIME = 'PassedEndTime' # TERMINATING = 'Terminating' # TERMINATED = 'Terminated' # RESERVE_TRANSITIONS = { # RESERVE_START : [ RESERVE_CHECKING ], # RESERVE_CHECKING : [ RESERVE_HELD, RESERVE_FAILED ], # RESERVE_HELD : [ RESERVE_COMMITTING, RESERVE_ABORTING, RESERVE_TIMEOUT ], # RESERVE_COMMITTING : [ RESERVE_START ], # RESERVE_FAILED : [ RESERVE_ABORTING ], # RESERVE_TIMEOUT : [ RESERVE_ABORTING ], # RESERVE_ABORTING : [ RESERVE_START ] # } # PROVISION_TRANSITIONS = { # RELEASED : [ PROVISIONING ], # PROVISIONING : [ PROVISIONING, PROVISIONED ], # PROVISIONED : [ RELEASING ], # RELEASING : [ RELEASING, RELEASED ] # } # LIFECYCLE_TRANSITIONS = { # CREATED : [ FAILED, PASSED_ENDTIME, TERMINATING, TERMINATED ], # FAILED : [ TERMINATING ], # PASSED_ENDTIME : [ TERMINATING ], # TERMINATING : [ TERMINATING, TERMINATED ], # TERMINATED : [] # } # SUBSCRIPTIONS = {} # def subscribe(connection_id, f): # def desubscribe(connection_id, f): # def saveNotify(conn): # def notify(conn): # def _switchState(transition_schema, old_state, new_state): # def reserveChecking(conn): # def reserveHeld(conn): # def reserveFailed(conn): # def reserveCommit(conn): # def reserveAbort(conn): # def reserveTimeout(conn): # def reserved(conn): # def reserveMultiSwitch(conn, *states): # def provisioning(conn): # def provisioned(conn): # def releasing(conn): # def released(conn): # def passedEndtime(conn): # def failed(conn): # def terminating(conn): # def terminated(conn): # # Path: opennsa/backends/common/genericbackend.py # class GenericBackendConnections(DBObject): # class GenericBackend(service.Service): # TPC_TIMEOUT = 120 # seconds # def __init__(self, network, nrm_ports, connection_manager, parent_requester, log_system, minimum_duration=60): # def startService(self): # def stopService(self): # def getNotificationId(self): # def buildSchedule(self): # def _getConnection(self, connection_id, requester_nsa): # def _authorize(self, source_port, destination_port, header, request_info, start_time=None, end_time=None): # def logStateUpdate(self, conn, state_msg): # def reserve(self, header, connection_id, global_reservation_id, description, criteria, request_info=None): # def reserveCommit(self, header, connection_id, request_info=None): # def reserveAbort(self, header, connection_id, request_info=None): # def provision(self, header, connection_id, request_info=None): # def release(self, header, connection_id, request_info=None): # def terminate(self, header, connection_id, request_info=None): # def querySummary(self, header, connection_ids=None, global_reservation_ids=None, request_info=None): # def queryRecursive(self, header, connection_ids, global_reservation_ids, request_info=None): # def _query(self, header, connection_ids, global_reservation_ids, request_info=None): # def queryNotification(self, header, connection_id, start_notification=None, end_notification=None): # def _doReserve(self, conn, correlation_id): # def _doReserveTimeout(self, conn): # def _doReserveRollback(self, conn): # def _doActivate(self, conn): # def _doTeardown(self, conn): # def _doEndtime(self, conn): # def _doFreeResource(self, conn): . Output only the next line.
revision=0,
Given snippet: <|code_start|> class DatabaseTest(unittest.TestCase): def setUp(self): db.setupDatabase() @defer.inlineCallbacks def testReverseStartEndTimeConstraint(self): now = datetime.datetime.utcnow() start_time = now - datetime.timedelta(seconds=10) end_time = now - datetime.timedelta(seconds=1000) conn = genericbackend.GenericBackendConnections( connection_id='conn-123', <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import psycopg2 from twisted.internet import defer from twisted.trial import unittest from opennsa import state from opennsa.backends.common import genericbackend from . import db and context: # Path: opennsa/state.py # LOG_SYSTEM = 'opennsa.state' # RESERVE_START = 'ReserveStart' # RESERVE_CHECKING = 'ReserveChecking' # RESERVE_HELD = 'ReserveHeld' # RESERVE_COMMITTING = 'ReserveComitting' # RESERVE_FAILED = 'ReserveFailed' # RESERVE_ABORTING = 'ReserveAborting' # RESERVE_TIMEOUT = 'ReserveTimeout' # Only UPA # RELEASED = 'Released' # PROVISIONING = 'Provisioning' # PROVISIONED = 'Provisioned' # RELEASING = 'Releasing' # CREATED = 'Created' # FAILED = 'Failed' # PASSED_ENDTIME = 'PassedEndTime' # TERMINATING = 'Terminating' # TERMINATED = 'Terminated' # RESERVE_TRANSITIONS = { # RESERVE_START : [ RESERVE_CHECKING ], # RESERVE_CHECKING : [ RESERVE_HELD, RESERVE_FAILED ], # RESERVE_HELD : [ RESERVE_COMMITTING, RESERVE_ABORTING, RESERVE_TIMEOUT ], # RESERVE_COMMITTING : [ RESERVE_START ], # RESERVE_FAILED : [ RESERVE_ABORTING ], # RESERVE_TIMEOUT : [ RESERVE_ABORTING ], # RESERVE_ABORTING : [ RESERVE_START ] # } # PROVISION_TRANSITIONS = { # RELEASED : [ PROVISIONING ], # PROVISIONING : [ PROVISIONING, PROVISIONED ], # PROVISIONED : [ RELEASING ], # RELEASING : [ RELEASING, RELEASED ] # } # LIFECYCLE_TRANSITIONS = { # CREATED : [ FAILED, PASSED_ENDTIME, TERMINATING, TERMINATED ], # FAILED : [ TERMINATING ], # PASSED_ENDTIME : [ TERMINATING ], # TERMINATING : [ TERMINATING, TERMINATED ], # TERMINATED : [] # } # SUBSCRIPTIONS = {} # def subscribe(connection_id, f): # def desubscribe(connection_id, f): # def saveNotify(conn): # def notify(conn): # def _switchState(transition_schema, old_state, new_state): # def reserveChecking(conn): # def reserveHeld(conn): # def reserveFailed(conn): # def reserveCommit(conn): # def reserveAbort(conn): # def reserveTimeout(conn): # def reserved(conn): # def reserveMultiSwitch(conn, *states): # def provisioning(conn): # def provisioned(conn): # def releasing(conn): # def released(conn): # def passedEndtime(conn): # def failed(conn): # def terminating(conn): # def terminated(conn): # # Path: opennsa/backends/common/genericbackend.py # class GenericBackendConnections(DBObject): # class GenericBackend(service.Service): # TPC_TIMEOUT = 120 # seconds # def __init__(self, network, nrm_ports, connection_manager, parent_requester, log_system, minimum_duration=60): # def startService(self): # def stopService(self): # def getNotificationId(self): # def buildSchedule(self): # def _getConnection(self, connection_id, requester_nsa): # def _authorize(self, source_port, destination_port, header, request_info, start_time=None, end_time=None): # def logStateUpdate(self, conn, state_msg): # def reserve(self, header, connection_id, global_reservation_id, description, criteria, request_info=None): # def reserveCommit(self, header, connection_id, request_info=None): # def reserveAbort(self, header, connection_id, request_info=None): # def provision(self, header, connection_id, request_info=None): # def release(self, header, connection_id, request_info=None): # def terminate(self, header, connection_id, request_info=None): # def querySummary(self, header, connection_ids=None, global_reservation_ids=None, request_info=None): # def queryRecursive(self, header, connection_ids, global_reservation_ids, request_info=None): # def _query(self, header, connection_ids, global_reservation_ids, request_info=None): # def queryNotification(self, header, connection_id, start_notification=None, end_notification=None): # def _doReserve(self, conn, correlation_id): # def _doReserveTimeout(self, conn): # def _doReserveRollback(self, conn): # def _doActivate(self, conn): # def _doTeardown(self, conn): # def _doEndtime(self, conn): # def _doFreeResource(self, conn): which might include code, classes, or functions. Output only the next line.
revision=0,
Based on the snippet: <|code_start|> self.failUnlessEqual(self.rv.vector(CURACAO_TOPO, source=LOCAL_TOPO), (LOCAL_TOPO, ARUBA_PORT)) def testMultiNetworkReachability(self): self.rv = linkvector.LinkVector( [ LOCAL_TOPO ] ) self.rv.updateVector(LOCAL_TOPO, ARUBA_PORT, { ARUBA_TOPO : 1 } ) self.rv.updateVector(ARUBA_TOPO, BONAIRE_PORT, { BONAIRE_TOPO : 1 } ) self.failUnlessEqual(self.rv.vector(ARUBA_TOPO, source=LOCAL_TOPO), (LOCAL_TOPO, ARUBA_PORT)) self.failUnlessEqual(self.rv.vector(BONAIRE_TOPO, source=LOCAL_TOPO), (LOCAL_TOPO, ARUBA_PORT)) self.failUnlessEqual(self.rv.vector(CURACAO_TOPO, source=LOCAL_TOPO), (None, None)) self.rv.updateVector(BONAIRE_TOPO, CURACAO_PORT, { CURACAO_TOPO : 1 } ) self.failUnlessEqual(self.rv.vector(CURACAO_TOPO, source=LOCAL_TOPO), (LOCAL_TOPO, ARUBA_PORT)) def testLocalThenRemoteVector(self): ARUBA_OJS_NET = 'aruba:ojs' ARUBA_SAN_NET = 'aruba:san' self.rv = linkvector.LinkVector( [ ARUBA_OJS_NET, ARUBA_SAN_NET ] ) self.failUnlessEqual(self.rv.vector(ARUBA_OJS_NET, source=ARUBA_SAN_NET), (None, None)) self.failUnlessEqual(self.rv.vector(ARUBA_SAN_NET, source=ARUBA_OJS_NET), (None, None)) self.rv.updateVector(ARUBA_OJS_NET, 'san', { ARUBA_SAN_NET: 1 } ) <|code_end|> , predict the immediate next line with the help of imports: from twisted.trial import unittest from opennsa.topology import linkvector and context (classes, functions, sometimes code) from other files: # Path: opennsa/topology/linkvector.py # LOG_SYSTEM = 'topology' # DEFAULT_MAX_COST = 5 # class LinkVector: # def __init__(self, local_networks=None, blacklist_networks=None, max_cost=DEFAULT_MAX_COST): # def callOnUpdate(self, f): # def updated(self): # def localNetworks(self): # def addLocalNetwork(self, network): # def updateVector(self, network, port, vectors): # def deleteVector(self, network, port): # def _calculateVectors(self): # def _dijkstra(self, source_network): # def path(self, network, source): # def vector(self, network, source): . Output only the next line.
self.rv.updateVector(ARUBA_SAN_NET, 'ojs', { ARUBA_OJS_NET: 1 } )
Given the code snippet: <|code_start|>class ConnectionListResource(resource.Resource): def __init__(self): pass def render_GET(self, request): d = database.ServiceConnection.find() d.addCallback(self.renderPage, request) return server.NOT_DONE_YET def renderPage(self, connections, request): ib = 4 * ' ' body = """ <h3>Connections</h3> <p> <table style="width:95%" border=1> <thead> <tr> <th>Connection Id</th> <th>Lifecycle state</th> <th>Source</th> <th>Destination</th> <th>Start time</th> <th>End time</th> </tr> </thead> <|code_end|> , generate the next line using the imports in this file: from twisted.web import resource, server from opennsa import database and context (functions, classes, or occasionally code) from other files: # Path: opennsa/database.py # LOG_SYSTEM = 'opennsa.Database' # DT = psycopg2.extensions.new_type((timestamptz_oid,), "timestamptz", castDatetime) # HASMANY = ['SubConnections'] # BELONGSTO = ['ServiceConnection'] # TABLENAME = 'stp_authz' # TABLENAME = 'backend_connection_id' # def adaptLabel(label): # def adaptSecuritAttribute(label): # def adaptDatetime(dt): # def make(self, values): # def make(self, values): # def castDatetime(value, cur): # def setupDatabase(database, user, password=None, host=None, connection_id_start=None): # def getBackendConnectionId(): # def gotResult(rows): # class LabelComposite(CompositeCaster): # class SecuritAttributeComposite(CompositeCaster): # class ServiceConnection(DBObject): # class SubConnection(DBObject): # class STPAuthz(DBObject): # class BackendConnectionID(DBObject): . Output only the next line.
<tbody>"""
Predict the next line after this snippet: <|code_start|> def testPruningStart(self): sfn_link = nsa.Link( nsa.STP('surfnet.nl:1990:production7', 'ps', nsa.Label('vlan', '1784')), nsa.STP('surfnet.nl:1990:production7', 'sara-ndn1', nsa.Label('vlan', '1780-1799')) ) ndn_link = nsa.Link( nsa.STP('nordu.net:2013:topology', 'surfnet', nsa.Label('vlan', '1784-1789')), nsa.STP('nordu.net:2013:topology', 'deic1', nsa.Label('vlan', '1784-1789')) ) dec_link = nsa.Link( nsa.STP('deic.dk:2013:topology', 'ndn1', nsa.Label('vlan', '1784-1789')), nsa.STP('deic.dk:2013:topology', 'ps', nsa.Label('vlan', '1784')) ) path = [ sfn_link, ndn_link, dec_link ] pruned_path = pruner.pruneLabels(path) self.assertEquals(pruned_path[0].dst_stp.label.labelValue(), '1784') self.assertEquals(pruned_path[1].src_stp.label.labelValue(), '1784') def testPruningEnd(self): ndn_link = nsa.Link( nsa.STP('nordu.net:2013:topology', 'funet', nsa.Label('vlan', '2031-2035')), nsa.STP('nordu.net:2013:topology', 'surfnet', nsa.Label('vlan', '2-4094')) ) sfn_link = nsa.Link( nsa.STP('surfnet.nl:1990:production7', 'nordunet', nsa.Label('vlan', '2-4094')), nsa.STP('surfnet.nl:1990:production7', '19523', nsa.Label('vlan', '2077')) ) path = [ ndn_link, sfn_link ] pruned_path = pruner.pruneLabels(path) self.assertEquals(pruned_path[0].dst_stp.label.labelValue(), '2077') <|code_end|> using the current file's imports: from twisted.trial import unittest from opennsa import nsa from opennsa.plugins import pruner and any relevant context from other files: # Path: opennsa/nsa.py # LOG_SYSTEM = 'opennsa.nsa' # URN_UUID_PREFIX = 'urn:uuid:' # BIDIRECTIONAL = 'Bidirectional' # class NSIHeader(object): # class SecurityAttribute(object): # class EmptyLabelSet(Exception): # class Label(object): # class STP(object): # Service Termination Point # class Link(object): # class Path(object): # class NetworkServiceAgent(object): # class ConnectionInfo(object): # class Criteria(object): # class QueryCriteria(Criteria): # class Schedule(object): # class Point2PointService(object): # def __init__(self, requester_nsa, provider_nsa, correlation_id=None, reply_to=None, security_attributes=None, connection_trace=None): # def _createCorrelationId(self): # def newCorrelationId(self): # def __repr__(self): # def __init__(self, type_, value): # def __repr__(self): # def __init__(self, type_, values=None): # def _parseLabelValues(self, values): # def createValue(value): # def intersect(self, other): # def labelValue(self): # def singleValue(self): # def enumerateValues(self): # def randomLabel(self): # def canMatch(l1, l2): # def __eq__(self, other): # def __repr__(self): # def __init__(self, network, port, label=None): # def shortName(self): # def baseURN(self): # def urn(self): # def __eq__(self, other): # def __repr__(self): # def __init__(self, src_stp, dst_stp): # def sourceSTP(self): # def destSTP(self): # def __eq__(self, other): # def __repr__(self): # def __init__(self, network_links): # def links(self): # def sourceEndpoint(self): # def destEndpoint(self): # def __str__(self): # def __init__(self, identity, endpoint, service_type=None): # def getHostPort(self): # def urn(self): # def getServiceType(self): # def __str__(self): # def __init__(self, connection_id, global_reservation_id, description, service_type, criterias, provider_nsa, requester_nsa, states, notification_id, result_id): # def __init__(self, revision, schedule, service_def): # def __init__(self, revision, schedule, service_def, children=None): # def __init__(self, start_time, end_time): # def __str__(self): # def __init__(self, source_stp, dest_stp, capacity, directionality=BIDIRECTIONAL, symmetric=False, ero=None, parameters=None): # # Path: opennsa/plugins/pruner.py # NETWORKS = [] # def pruneLabels(path): # def prunePaths(self, paths): # class PrunerPlugin(BasePlugin): . Output only the next line.
self.assertEquals(pruned_path[1].src_stp.label.labelValue(), '2077')
Continue the code snippet: <|code_start|> class PrunerTest(unittest.TestCase): # These test cases assume that the pruner has surfnet as a prune target def setUp(self): pruner.NETWORKS = [ 'surfnet.nl' ] def testPruningStart(self): sfn_link = nsa.Link( nsa.STP('surfnet.nl:1990:production7', 'ps', nsa.Label('vlan', '1784')), nsa.STP('surfnet.nl:1990:production7', 'sara-ndn1', nsa.Label('vlan', '1780-1799')) ) ndn_link = nsa.Link( nsa.STP('nordu.net:2013:topology', 'surfnet', nsa.Label('vlan', '1784-1789')), nsa.STP('nordu.net:2013:topology', 'deic1', nsa.Label('vlan', '1784-1789')) ) dec_link = nsa.Link( nsa.STP('deic.dk:2013:topology', 'ndn1', nsa.Label('vlan', '1784-1789')), nsa.STP('deic.dk:2013:topology', 'ps', nsa.Label('vlan', '1784')) ) path = [ sfn_link, ndn_link, dec_link ] pruned_path = pruner.pruneLabels(path) self.assertEquals(pruned_path[0].dst_stp.label.labelValue(), '1784') self.assertEquals(pruned_path[1].src_stp.label.labelValue(), '1784') <|code_end|> . Use current file imports: from twisted.trial import unittest from opennsa import nsa from opennsa.plugins import pruner and context (classes, functions, or code) from other files: # Path: opennsa/nsa.py # LOG_SYSTEM = 'opennsa.nsa' # URN_UUID_PREFIX = 'urn:uuid:' # BIDIRECTIONAL = 'Bidirectional' # class NSIHeader(object): # class SecurityAttribute(object): # class EmptyLabelSet(Exception): # class Label(object): # class STP(object): # Service Termination Point # class Link(object): # class Path(object): # class NetworkServiceAgent(object): # class ConnectionInfo(object): # class Criteria(object): # class QueryCriteria(Criteria): # class Schedule(object): # class Point2PointService(object): # def __init__(self, requester_nsa, provider_nsa, correlation_id=None, reply_to=None, security_attributes=None, connection_trace=None): # def _createCorrelationId(self): # def newCorrelationId(self): # def __repr__(self): # def __init__(self, type_, value): # def __repr__(self): # def __init__(self, type_, values=None): # def _parseLabelValues(self, values): # def createValue(value): # def intersect(self, other): # def labelValue(self): # def singleValue(self): # def enumerateValues(self): # def randomLabel(self): # def canMatch(l1, l2): # def __eq__(self, other): # def __repr__(self): # def __init__(self, network, port, label=None): # def shortName(self): # def baseURN(self): # def urn(self): # def __eq__(self, other): # def __repr__(self): # def __init__(self, src_stp, dst_stp): # def sourceSTP(self): # def destSTP(self): # def __eq__(self, other): # def __repr__(self): # def __init__(self, network_links): # def links(self): # def sourceEndpoint(self): # def destEndpoint(self): # def __str__(self): # def __init__(self, identity, endpoint, service_type=None): # def getHostPort(self): # def urn(self): # def getServiceType(self): # def __str__(self): # def __init__(self, connection_id, global_reservation_id, description, service_type, criterias, provider_nsa, requester_nsa, states, notification_id, result_id): # def __init__(self, revision, schedule, service_def): # def __init__(self, revision, schedule, service_def, children=None): # def __init__(self, start_time, end_time): # def __str__(self): # def __init__(self, source_stp, dest_stp, capacity, directionality=BIDIRECTIONAL, symmetric=False, ero=None, parameters=None): # # Path: opennsa/plugins/pruner.py # NETWORKS = [] # def pruneLabels(path): # def prunePaths(self, paths): # class PrunerPlugin(BasePlugin): . Output only the next line.
def testPruningEnd(self):
Here is a snippet: <|code_start|> member.has_perm('view_member', member) def test_has_perms_exception(self): member = models.Member(first_name='Caio', last_name='Mario') with self.assertRaises(exceptions_gm.MemberDjangoUserSyncError): member.has_perms(['view_member'], member) def test_group_member_model(self): member = models.Member(first_name='Caio', last_name='Mario') self.assertEqual(member.group_member_model, models.GroupMember) class TestGroupType(TestCase): def setUp(self): self.maxDiff = None self.group_type = models.GroupType(label='Organization') def test_str(self): self.assertEqual(str(self.group_type), 'Organization') def test_unicode(self): if sys.version_info < (3, ): self.assertEqual(unicode(self.group_type), 'Organization') def test_save(self): self.group_type.codename = '' self.group_type.save() self.assertEqual(self.group_type.codename, 'organization') def test_save_with_codename(self): <|code_end|> . Write the next line using the current file imports: from copy import deepcopy from django.contrib.auth import get_user_model from django.contrib.auth.models import Group as DjangoGroup from django.test import TestCase from groups_manager import models, exceptions_gm from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings import re import sys and context from other files: # Path: groups_manager/models.py # def get_auth_models_sync_func_default(instance): # def group_model(self): # def group_member_model(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def full_name(self): # def groups(self): # def has_perm(self, perm, obj=None): # def has_perms(self, perm_list, obj=None): # def assign_object(self, group, obj, **kwargs): # def member_save(sender, instance, created, *args, **kwargs): # def member_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def member_model(self): # def group_member_model(self): # def group_members_attribute(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def _get_full_name(self): # def subgroups(self): # def get_members(self, subgroups=False): # def members(self): # def users(self): # def get_entities(self, subgroups=False): # def entities(self): # def add_member(self, member, roles=None, expiration_date=None): # def remove_member(self, member): # def assign_object(self, obj, **kwargs): # def group_save(sender, instance, created, *args, **kwargs): # def group_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def assign_object(self, obj, **kwargs): # def group_member_save(sender, instance, created, *args, **kwargs): # def group_member_delete(sender, instance, *args, **kwargs): # class MemberRelationsMixin(object): # class GroupsManagerMeta: # class MemberMixin(MemberRelationsMixin, models.Model): # class Meta: # class Member(MemberMixin): # class Meta(MemberMixin.Meta): # class GroupTypeMixin(models.Model): # class Meta: # class GroupType(GroupTypeMixin): # class Meta(GroupTypeMixin.Meta): # class GroupEntityMixin(models.Model): # class Meta: # class GroupEntity(GroupEntityMixin): # class Meta(GroupEntityMixin.Meta): # class GroupRelationsMixin(object): # class GroupsManagerMeta: # class GroupMixin(GroupRelationsMixin, MPTTModel): # class Meta: # class MPTTMeta: # class GroupsManagerMeta(GroupRelationsMixin.GroupsManagerMeta): # class Group(GroupMixin): # class Meta(GroupMixin.Meta): # class GroupMemberRoleMixin(models.Model): # class Meta: # class GroupMemberRole(GroupMemberRoleMixin): # class Meta(GroupMemberRoleMixin.Meta): # class GroupMemberMixin(models.Model): # class Meta: # class GroupMember(GroupMemberMixin): # class Meta(GroupMemberMixin.Meta): # # Path: groups_manager/exceptions_gm.py # class MemberDjangoUserSyncError(BaseException): # class GroupDjangoGroupSyncError(BaseException): # class GroupNotSavedError(BaseException): # class MemberNotSavedError(BaseException): # class GetGroupMemberError(BaseException): # class GetRoleError(BaseException): , which may include functions, classes, or code. Output only the next line.
self.group_type.codename = 'organization'
Continue the code snippet: <|code_start|> self.assertEqual(unicode(self.group_entity), 'Organization Partner') def test_save(self): self.group_entity.save() self.assertEqual(self.group_entity.codename, 'organization-partner') def test_save_with_codename(self): self.group_entity.codename = 'organization-partner' self.group_entity.save() self.assertEqual(self.group_entity.codename, 'organization-partner') def test_group_entity_groups_reverse(self): self.group_entity.save() g1 = models.Group.objects.create(name='Group 1') g1.group_entities.add(self.group_entity) self.assertEqual(list(self.group_entity.groups_manager_group_set.all()), [g1]) # Deprecated self.assertEqual(list(self.group_entity.groups.all()), [g1]) class TestGroup(TestCase): def setUp(self): self.maxDiff = None self.group = models.Group(name='Istituto di Genomica Applicata') def test_str(self): self.assertEqual(str(self.group), 'Istituto di Genomica Applicata') def test_unicode(self): <|code_end|> . Use current file imports: from copy import deepcopy from django.contrib.auth import get_user_model from django.contrib.auth.models import Group as DjangoGroup from django.test import TestCase from groups_manager import models, exceptions_gm from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings import re import sys and context (classes, functions, or code) from other files: # Path: groups_manager/models.py # def get_auth_models_sync_func_default(instance): # def group_model(self): # def group_member_model(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def full_name(self): # def groups(self): # def has_perm(self, perm, obj=None): # def has_perms(self, perm_list, obj=None): # def assign_object(self, group, obj, **kwargs): # def member_save(sender, instance, created, *args, **kwargs): # def member_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def member_model(self): # def group_member_model(self): # def group_members_attribute(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def _get_full_name(self): # def subgroups(self): # def get_members(self, subgroups=False): # def members(self): # def users(self): # def get_entities(self, subgroups=False): # def entities(self): # def add_member(self, member, roles=None, expiration_date=None): # def remove_member(self, member): # def assign_object(self, obj, **kwargs): # def group_save(sender, instance, created, *args, **kwargs): # def group_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def assign_object(self, obj, **kwargs): # def group_member_save(sender, instance, created, *args, **kwargs): # def group_member_delete(sender, instance, *args, **kwargs): # class MemberRelationsMixin(object): # class GroupsManagerMeta: # class MemberMixin(MemberRelationsMixin, models.Model): # class Meta: # class Member(MemberMixin): # class Meta(MemberMixin.Meta): # class GroupTypeMixin(models.Model): # class Meta: # class GroupType(GroupTypeMixin): # class Meta(GroupTypeMixin.Meta): # class GroupEntityMixin(models.Model): # class Meta: # class GroupEntity(GroupEntityMixin): # class Meta(GroupEntityMixin.Meta): # class GroupRelationsMixin(object): # class GroupsManagerMeta: # class GroupMixin(GroupRelationsMixin, MPTTModel): # class Meta: # class MPTTMeta: # class GroupsManagerMeta(GroupRelationsMixin.GroupsManagerMeta): # class Group(GroupMixin): # class Meta(GroupMixin.Meta): # class GroupMemberRoleMixin(models.Model): # class Meta: # class GroupMemberRole(GroupMemberRoleMixin): # class Meta(GroupMemberRoleMixin.Meta): # class GroupMemberMixin(models.Model): # class Meta: # class GroupMember(GroupMemberMixin): # class Meta(GroupMemberMixin.Meta): # # Path: groups_manager/exceptions_gm.py # class MemberDjangoUserSyncError(BaseException): # class GroupDjangoGroupSyncError(BaseException): # class GroupNotSavedError(BaseException): # class MemberNotSavedError(BaseException): # class GetGroupMemberError(BaseException): # class GetRoleError(BaseException): . Output only the next line.
if sys.version_info < (3, ):
Predict the next line for this snippet: <|code_start|> try: has_guardian = True except ImportError: has_guardian = False GROUPS_MANAGER_MOCK = { 'AUTH_MODELS_SYNC': True, 'AUTH_MODELS_GET_OR_CREATE': False, 'GROUP_NAME_PREFIX': '', 'GROUP_NAME_SUFFIX': '', 'USER_USERNAME_PREFIX': '', 'USER_USERNAME_SUFFIX': '', 'PERMISSIONS': { 'owner': ['view', 'change', 'delete'], 'group': ['view', 'change'], 'groups_upstream': ['view'], 'groups_downstream': [], <|code_end|> with the help of current file imports: from copy import deepcopy from django.contrib.auth import models as auth_models from django.test import TestCase from groups_manager import models, exceptions_gm from testproject import models as testproject_models from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings import re import unittest import guardian and context from other files: # Path: groups_manager/models.py # def get_auth_models_sync_func_default(instance): # def group_model(self): # def group_member_model(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def full_name(self): # def groups(self): # def has_perm(self, perm, obj=None): # def has_perms(self, perm_list, obj=None): # def assign_object(self, group, obj, **kwargs): # def member_save(sender, instance, created, *args, **kwargs): # def member_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def member_model(self): # def group_member_model(self): # def group_members_attribute(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def _get_full_name(self): # def subgroups(self): # def get_members(self, subgroups=False): # def members(self): # def users(self): # def get_entities(self, subgroups=False): # def entities(self): # def add_member(self, member, roles=None, expiration_date=None): # def remove_member(self, member): # def assign_object(self, obj, **kwargs): # def group_save(sender, instance, created, *args, **kwargs): # def group_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def assign_object(self, obj, **kwargs): # def group_member_save(sender, instance, created, *args, **kwargs): # def group_member_delete(sender, instance, *args, **kwargs): # class MemberRelationsMixin(object): # class GroupsManagerMeta: # class MemberMixin(MemberRelationsMixin, models.Model): # class Meta: # class Member(MemberMixin): # class Meta(MemberMixin.Meta): # class GroupTypeMixin(models.Model): # class Meta: # class GroupType(GroupTypeMixin): # class Meta(GroupTypeMixin.Meta): # class GroupEntityMixin(models.Model): # class Meta: # class GroupEntity(GroupEntityMixin): # class Meta(GroupEntityMixin.Meta): # class GroupRelationsMixin(object): # class GroupsManagerMeta: # class GroupMixin(GroupRelationsMixin, MPTTModel): # class Meta: # class MPTTMeta: # class GroupsManagerMeta(GroupRelationsMixin.GroupsManagerMeta): # class Group(GroupMixin): # class Meta(GroupMixin.Meta): # class GroupMemberRoleMixin(models.Model): # class Meta: # class GroupMemberRole(GroupMemberRoleMixin): # class Meta(GroupMemberRoleMixin.Meta): # class GroupMemberMixin(models.Model): # class Meta: # class GroupMember(GroupMemberMixin): # class Meta(GroupMemberMixin.Meta): # # Path: groups_manager/exceptions_gm.py # class MemberDjangoUserSyncError(BaseException): # class GroupDjangoGroupSyncError(BaseException): # class GroupNotSavedError(BaseException): # class MemberNotSavedError(BaseException): # class GetGroupMemberError(BaseException): # class GetRoleError(BaseException): , which may contain function names, class names, or code. Output only the next line.
'groups_siblings': ['view'],
Predict the next line after this snippet: <|code_start|> try: has_guardian = True except ImportError: has_guardian = False GROUPS_MANAGER_MOCK = { 'AUTH_MODELS_SYNC': True, 'AUTH_MODELS_GET_OR_CREATE': False, 'GROUP_NAME_PREFIX': '', 'GROUP_NAME_SUFFIX': '', 'USER_USERNAME_PREFIX': '', 'USER_USERNAME_SUFFIX': '', <|code_end|> using the current file's imports: from copy import deepcopy from django.contrib.auth import models as auth_models from django.test import TestCase from groups_manager import models, exceptions_gm from testproject import models as testproject_models from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings from groups_manager import settings import re import unittest import guardian and any relevant context from other files: # Path: groups_manager/models.py # def get_auth_models_sync_func_default(instance): # def group_model(self): # def group_member_model(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def full_name(self): # def groups(self): # def has_perm(self, perm, obj=None): # def has_perms(self, perm_list, obj=None): # def assign_object(self, group, obj, **kwargs): # def member_save(sender, instance, created, *args, **kwargs): # def member_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def member_model(self): # def group_member_model(self): # def group_members_attribute(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def _get_full_name(self): # def subgroups(self): # def get_members(self, subgroups=False): # def members(self): # def users(self): # def get_entities(self, subgroups=False): # def entities(self): # def add_member(self, member, roles=None, expiration_date=None): # def remove_member(self, member): # def assign_object(self, obj, **kwargs): # def group_save(sender, instance, created, *args, **kwargs): # def group_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def assign_object(self, obj, **kwargs): # def group_member_save(sender, instance, created, *args, **kwargs): # def group_member_delete(sender, instance, *args, **kwargs): # class MemberRelationsMixin(object): # class GroupsManagerMeta: # class MemberMixin(MemberRelationsMixin, models.Model): # class Meta: # class Member(MemberMixin): # class Meta(MemberMixin.Meta): # class GroupTypeMixin(models.Model): # class Meta: # class GroupType(GroupTypeMixin): # class Meta(GroupTypeMixin.Meta): # class GroupEntityMixin(models.Model): # class Meta: # class GroupEntity(GroupEntityMixin): # class Meta(GroupEntityMixin.Meta): # class GroupRelationsMixin(object): # class GroupsManagerMeta: # class GroupMixin(GroupRelationsMixin, MPTTModel): # class Meta: # class MPTTMeta: # class GroupsManagerMeta(GroupRelationsMixin.GroupsManagerMeta): # class Group(GroupMixin): # class Meta(GroupMixin.Meta): # class GroupMemberRoleMixin(models.Model): # class Meta: # class GroupMemberRole(GroupMemberRoleMixin): # class Meta(GroupMemberRoleMixin.Meta): # class GroupMemberMixin(models.Model): # class Meta: # class GroupMember(GroupMemberMixin): # class Meta(GroupMemberMixin.Meta): # # Path: groups_manager/exceptions_gm.py # class MemberDjangoUserSyncError(BaseException): # class GroupDjangoGroupSyncError(BaseException): # class GroupNotSavedError(BaseException): # class MemberNotSavedError(BaseException): # class GetGroupMemberError(BaseException): # class GetRoleError(BaseException): . Output only the next line.
'PERMISSIONS': {
Given snippet: <|code_start|>try: except ImportError: # keeping old behaviour instead of deprecating old django versions app_name = 'groups_manager' urlpatterns = [ re_path(r'^$', views.GroupsManagerView.as_view(), name='groups_manager', ), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.urls import re_path from django.conf.urls import url as re_path from groups_manager import views and context: # Path: groups_manager/views.py # TS = settings.GROUPS_MANAGER['TEMPLATE_STYLE'] # TS = '/%s' % TS # class GroupsManagerView(TemplateView): # class MemberMixin(object): # class MemberListView(LoginRequiredMixin, MemberMixin, ListView): # class MemberDetailView(LoginRequiredMixin, MemberMixin, DetailView): # class MemberCreateView(LoginRequiredMixin, MemberMixin, CreateView): # class MemberEditView(LoginRequiredMixin, MemberMixin, UpdateView): # class MemberDeleteView(LoginRequiredMixin, MemberMixin, DeleteView): # class GroupTypeMixin(object): # class GroupTypeListView(LoginRequiredMixin, GroupTypeMixin, ListView): # class GroupTypeDetailView(LoginRequiredMixin, GroupTypeMixin, DetailView): # class GroupTypeCreateView(LoginRequiredMixin, GroupTypeMixin, CreateView): # class GroupTypeEditView(LoginRequiredMixin, GroupTypeMixin, UpdateView): # class GroupTypeDeleteView(LoginRequiredMixin, GroupTypeMixin, DeleteView): # class GroupEntityMixin(object): # class GroupEntityListView(LoginRequiredMixin, GroupEntityMixin, ListView): # class GroupEntityDetailView(LoginRequiredMixin, GroupEntityMixin, DetailView): # class GroupEntityCreateView(LoginRequiredMixin, GroupEntityMixin, CreateView): # class GroupEntityEditView(LoginRequiredMixin, GroupEntityMixin, UpdateView): # class GroupEntityDeleteView(LoginRequiredMixin, GroupEntityMixin, DeleteView): # class GroupMixin(object): # class GroupListView(LoginRequiredMixin, GroupMixin, ListView): # class GroupDetailView(LoginRequiredMixin, GroupMixin, DetailView): # class GroupCreateView(LoginRequiredMixin, GroupMixin, CreateView): # class GroupEditView(LoginRequiredMixin, GroupMixin, UpdateView): # class GroupDeleteView(LoginRequiredMixin, GroupMixin, DeleteView): # class GroupMemberRoleMixin(object): # class GroupMemberRoleListView(LoginRequiredMixin, GroupMemberRoleMixin, ListView): # class GroupMemberRoleDetailView(LoginRequiredMixin, GroupMemberRoleMixin, DetailView): # class GroupMemberRoleCreateView(LoginRequiredMixin, GroupMemberRoleMixin, CreateView): # class GroupMemberRoleEditView(LoginRequiredMixin, GroupMemberRoleMixin, UpdateView): # class GroupMemberRoleDeleteView(LoginRequiredMixin, GroupMemberRoleMixin, DeleteView): # class GroupMemberMixin(object): # class GroupMemberEditView(LoginRequiredMixin, GroupMemberMixin, UpdateView): # class GroupMemberDeleteView(LoginRequiredMixin, GroupMemberMixin, DeleteView): # class GroupMemberAddMemberView(LoginRequiredMixin, GroupMemberMixin, CreateView): # class GroupMemberAddGroupView(LoginRequiredMixin, GroupMemberMixin, CreateView): # def get_success_url(self): # def get_queryset(self): # def get_success_url(self): # def get_queryset(self): # def get_success_url(self): # def get_queryset(self): # def get_success_url(self): # def get_queryset(self): # def get_success_url(self): # def get_success_url(self): # def get_queryset(self): # def get_context_data(self, **kwargs): # def get_success_url(self): # def get_context_data(self, **kwargs): # def get_success_url(self): # def get_initial(self): # def get_context_data(self, **kwargs): # def form_valid(self, form): # def get_initial(self): # def get_context_data(self, **kwargs): # def form_valid(self, form): which might include code, classes, or functions. Output only the next line.
re_path(r'^member/$',
Given the code snippet: <|code_start|> class MemberForm(forms.ModelForm): class Meta: model = models.Member exclude = set() class GroupTypeForm(forms.ModelForm): class Meta: model = models.GroupType exclude = set() class GroupEntityForm(forms.ModelForm): class Meta: model = models.GroupEntity exclude = set() class GroupForm(forms.ModelForm): class Meta: model = models.Group exclude = ('group_members', ) <|code_end|> , generate the next line using the imports in this file: from django import forms from groups_manager import models and context (functions, classes, or occasionally code) from other files: # Path: groups_manager/models.py # def get_auth_models_sync_func_default(instance): # def group_model(self): # def group_member_model(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def full_name(self): # def groups(self): # def has_perm(self, perm, obj=None): # def has_perms(self, perm_list, obj=None): # def assign_object(self, group, obj, **kwargs): # def member_save(sender, instance, created, *args, **kwargs): # def member_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def member_model(self): # def group_member_model(self): # def group_members_attribute(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def _get_full_name(self): # def subgroups(self): # def get_members(self, subgroups=False): # def members(self): # def users(self): # def get_entities(self, subgroups=False): # def entities(self): # def add_member(self, member, roles=None, expiration_date=None): # def remove_member(self, member): # def assign_object(self, obj, **kwargs): # def group_save(sender, instance, created, *args, **kwargs): # def group_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def assign_object(self, obj, **kwargs): # def group_member_save(sender, instance, created, *args, **kwargs): # def group_member_delete(sender, instance, *args, **kwargs): # class MemberRelationsMixin(object): # class GroupsManagerMeta: # class MemberMixin(MemberRelationsMixin, models.Model): # class Meta: # class Member(MemberMixin): # class Meta(MemberMixin.Meta): # class GroupTypeMixin(models.Model): # class Meta: # class GroupType(GroupTypeMixin): # class Meta(GroupTypeMixin.Meta): # class GroupEntityMixin(models.Model): # class Meta: # class GroupEntity(GroupEntityMixin): # class Meta(GroupEntityMixin.Meta): # class GroupRelationsMixin(object): # class GroupsManagerMeta: # class GroupMixin(GroupRelationsMixin, MPTTModel): # class Meta: # class MPTTMeta: # class GroupsManagerMeta(GroupRelationsMixin.GroupsManagerMeta): # class Group(GroupMixin): # class Meta(GroupMixin.Meta): # class GroupMemberRoleMixin(models.Model): # class Meta: # class GroupMemberRole(GroupMemberRoleMixin): # class Meta(GroupMemberRoleMixin.Meta): # class GroupMemberMixin(models.Model): # class Meta: # class GroupMember(GroupMemberMixin): # class Meta(GroupMemberMixin.Meta): . Output only the next line.
class GroupMemberRoleForm(forms.ModelForm):
Given snippet: <|code_start|> TS = settings.GROUPS_MANAGER['TEMPLATE_STYLE'] if TS: TS = '/%s' % TS class GroupsManagerView(TemplateView): <|code_end|> , continue by predicting the next line. Consider current file imports: import json from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.views.generic.base import TemplateView from groups_manager import models, forms, settings and context: # Path: groups_manager/models.py # def get_auth_models_sync_func_default(instance): # def group_model(self): # def group_member_model(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def full_name(self): # def groups(self): # def has_perm(self, perm, obj=None): # def has_perms(self, perm_list, obj=None): # def assign_object(self, group, obj, **kwargs): # def member_save(sender, instance, created, *args, **kwargs): # def member_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def member_model(self): # def group_member_model(self): # def group_members_attribute(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def _get_full_name(self): # def subgroups(self): # def get_members(self, subgroups=False): # def members(self): # def users(self): # def get_entities(self, subgroups=False): # def entities(self): # def add_member(self, member, roles=None, expiration_date=None): # def remove_member(self, member): # def assign_object(self, obj, **kwargs): # def group_save(sender, instance, created, *args, **kwargs): # def group_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def assign_object(self, obj, **kwargs): # def group_member_save(sender, instance, created, *args, **kwargs): # def group_member_delete(sender, instance, *args, **kwargs): # class MemberRelationsMixin(object): # class GroupsManagerMeta: # class MemberMixin(MemberRelationsMixin, models.Model): # class Meta: # class Member(MemberMixin): # class Meta(MemberMixin.Meta): # class GroupTypeMixin(models.Model): # class Meta: # class GroupType(GroupTypeMixin): # class Meta(GroupTypeMixin.Meta): # class GroupEntityMixin(models.Model): # class Meta: # class GroupEntity(GroupEntityMixin): # class Meta(GroupEntityMixin.Meta): # class GroupRelationsMixin(object): # class GroupsManagerMeta: # class GroupMixin(GroupRelationsMixin, MPTTModel): # class Meta: # class MPTTMeta: # class GroupsManagerMeta(GroupRelationsMixin.GroupsManagerMeta): # class Group(GroupMixin): # class Meta(GroupMixin.Meta): # class GroupMemberRoleMixin(models.Model): # class Meta: # class GroupMemberRole(GroupMemberRoleMixin): # class Meta(GroupMemberRoleMixin.Meta): # class GroupMemberMixin(models.Model): # class Meta: # class GroupMember(GroupMemberMixin): # class Meta(GroupMemberMixin.Meta): # # Path: groups_manager/forms.py # class MemberForm(forms.ModelForm): # class Meta: # class GroupTypeForm(forms.ModelForm): # class Meta: # class GroupEntityForm(forms.ModelForm): # class Meta: # class GroupForm(forms.ModelForm): # class Meta: # class GroupMemberRoleForm(forms.ModelForm): # class Meta: # class GroupMemberForm(forms.ModelForm): # class Meta: # class GroupMemberAddMemberForm(forms.ModelForm): # class Meta: # class GroupMemberAddGroupForm(forms.ModelForm): # class Meta: # # Path: groups_manager/settings.py # GROUPS_MANAGER_SETTINGS = getattr(settings, 'GROUPS_MANAGER', {}) # SETTINGS_PERMISSIONS = GROUPS_MANAGER_SETTINGS.get('PERMISSIONS', {}) # PERMISSIONS = { # 'owner': ['view', 'change', 'delete'], # 'group': ['view', 'change'], # 'groups_upstream': ['view'], # 'groups_downstream': [], # 'groups_siblings': ['view'], # } # GROUPS_MANAGER = { # # User and Groups sync settings # 'AUTH_MODELS_SYNC': GROUPS_MANAGER_SETTINGS.get('AUTH_MODELS_SYNC', False), # 'AUTH_MODELS_GET_OR_CREATE': GROUPS_MANAGER_SETTINGS.get('AUTH_MODELS_GET_OR_CREATE', True), # 'GROUP_NAME_PREFIX': GROUPS_MANAGER_SETTINGS.get('GROUP_NAME_PREFIX', 'DGM_'), # 'GROUP_NAME_SUFFIX': GROUPS_MANAGER_SETTINGS.get('GROUP_NAME_SUFFIX', '_$$random'), # 'USER_USERNAME_PREFIX': GROUPS_MANAGER_SETTINGS.get('USER_USERNAME_PREFIX', 'DGM_'), # 'USER_USERNAME_SUFFIX': GROUPS_MANAGER_SETTINGS.get('USER_USERNAME_SUFFIX', '_$$random'), # # Permissions # 'PERMISSIONS': PERMISSIONS, # # Templates # 'TEMPLATE_STYLE': GROUPS_MANAGER_SETTINGS.get('TEMPLATE_STYLE', 'bootstrap3'), # # Slugify function # 'SLUGIFY_FUNCTION': GROUPS_MANAGER_SETTINGS.get('SLUGIFY_FUNCTION', slugify_function), # 'SLUGIFY_USERNAME_FUNCTION': GROUPS_MANAGER_SETTINGS.get('SLUGIFY_USERNAME_FUNCTION', slugify_username_function), # } # def slugify_function(s): # def slugify_username_function(s): which might include code, classes, or functions. Output only the next line.
template_name = 'groups_manager%s/groups_manager_home.html' % TS
Given the code snippet: <|code_start|> TS = settings.GROUPS_MANAGER['TEMPLATE_STYLE'] if TS: TS = '/%s' % TS <|code_end|> , generate the next line using the imports in this file: import json from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.views.generic.base import TemplateView from groups_manager import models, forms, settings and context (functions, classes, or occasionally code) from other files: # Path: groups_manager/models.py # def get_auth_models_sync_func_default(instance): # def group_model(self): # def group_member_model(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def full_name(self): # def groups(self): # def has_perm(self, perm, obj=None): # def has_perms(self, perm_list, obj=None): # def assign_object(self, group, obj, **kwargs): # def member_save(sender, instance, created, *args, **kwargs): # def member_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def member_model(self): # def group_member_model(self): # def group_members_attribute(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def _get_full_name(self): # def subgroups(self): # def get_members(self, subgroups=False): # def members(self): # def users(self): # def get_entities(self, subgroups=False): # def entities(self): # def add_member(self, member, roles=None, expiration_date=None): # def remove_member(self, member): # def assign_object(self, obj, **kwargs): # def group_save(sender, instance, created, *args, **kwargs): # def group_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def assign_object(self, obj, **kwargs): # def group_member_save(sender, instance, created, *args, **kwargs): # def group_member_delete(sender, instance, *args, **kwargs): # class MemberRelationsMixin(object): # class GroupsManagerMeta: # class MemberMixin(MemberRelationsMixin, models.Model): # class Meta: # class Member(MemberMixin): # class Meta(MemberMixin.Meta): # class GroupTypeMixin(models.Model): # class Meta: # class GroupType(GroupTypeMixin): # class Meta(GroupTypeMixin.Meta): # class GroupEntityMixin(models.Model): # class Meta: # class GroupEntity(GroupEntityMixin): # class Meta(GroupEntityMixin.Meta): # class GroupRelationsMixin(object): # class GroupsManagerMeta: # class GroupMixin(GroupRelationsMixin, MPTTModel): # class Meta: # class MPTTMeta: # class GroupsManagerMeta(GroupRelationsMixin.GroupsManagerMeta): # class Group(GroupMixin): # class Meta(GroupMixin.Meta): # class GroupMemberRoleMixin(models.Model): # class Meta: # class GroupMemberRole(GroupMemberRoleMixin): # class Meta(GroupMemberRoleMixin.Meta): # class GroupMemberMixin(models.Model): # class Meta: # class GroupMember(GroupMemberMixin): # class Meta(GroupMemberMixin.Meta): # # Path: groups_manager/forms.py # class MemberForm(forms.ModelForm): # class Meta: # class GroupTypeForm(forms.ModelForm): # class Meta: # class GroupEntityForm(forms.ModelForm): # class Meta: # class GroupForm(forms.ModelForm): # class Meta: # class GroupMemberRoleForm(forms.ModelForm): # class Meta: # class GroupMemberForm(forms.ModelForm): # class Meta: # class GroupMemberAddMemberForm(forms.ModelForm): # class Meta: # class GroupMemberAddGroupForm(forms.ModelForm): # class Meta: # # Path: groups_manager/settings.py # GROUPS_MANAGER_SETTINGS = getattr(settings, 'GROUPS_MANAGER', {}) # SETTINGS_PERMISSIONS = GROUPS_MANAGER_SETTINGS.get('PERMISSIONS', {}) # PERMISSIONS = { # 'owner': ['view', 'change', 'delete'], # 'group': ['view', 'change'], # 'groups_upstream': ['view'], # 'groups_downstream': [], # 'groups_siblings': ['view'], # } # GROUPS_MANAGER = { # # User and Groups sync settings # 'AUTH_MODELS_SYNC': GROUPS_MANAGER_SETTINGS.get('AUTH_MODELS_SYNC', False), # 'AUTH_MODELS_GET_OR_CREATE': GROUPS_MANAGER_SETTINGS.get('AUTH_MODELS_GET_OR_CREATE', True), # 'GROUP_NAME_PREFIX': GROUPS_MANAGER_SETTINGS.get('GROUP_NAME_PREFIX', 'DGM_'), # 'GROUP_NAME_SUFFIX': GROUPS_MANAGER_SETTINGS.get('GROUP_NAME_SUFFIX', '_$$random'), # 'USER_USERNAME_PREFIX': GROUPS_MANAGER_SETTINGS.get('USER_USERNAME_PREFIX', 'DGM_'), # 'USER_USERNAME_SUFFIX': GROUPS_MANAGER_SETTINGS.get('USER_USERNAME_SUFFIX', '_$$random'), # # Permissions # 'PERMISSIONS': PERMISSIONS, # # Templates # 'TEMPLATE_STYLE': GROUPS_MANAGER_SETTINGS.get('TEMPLATE_STYLE', 'bootstrap3'), # # Slugify function # 'SLUGIFY_FUNCTION': GROUPS_MANAGER_SETTINGS.get('SLUGIFY_FUNCTION', slugify_function), # 'SLUGIFY_USERNAME_FUNCTION': GROUPS_MANAGER_SETTINGS.get('SLUGIFY_USERNAME_FUNCTION', slugify_username_function), # } # def slugify_function(s): # def slugify_username_function(s): . Output only the next line.
class GroupsManagerView(TemplateView):
Given the code snippet: <|code_start|> TS = settings.GROUPS_MANAGER['TEMPLATE_STYLE'] if TS: TS = '/%s' % TS class GroupsManagerView(TemplateView): <|code_end|> , generate the next line using the imports in this file: import json from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.views.generic.base import TemplateView from groups_manager import models, forms, settings and context (functions, classes, or occasionally code) from other files: # Path: groups_manager/models.py # def get_auth_models_sync_func_default(instance): # def group_model(self): # def group_member_model(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def full_name(self): # def groups(self): # def has_perm(self, perm, obj=None): # def has_perms(self, perm_list, obj=None): # def assign_object(self, group, obj, **kwargs): # def member_save(sender, instance, created, *args, **kwargs): # def member_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def groups(self): # def member_model(self): # def group_member_model(self): # def group_members_attribute(self): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def _get_full_name(self): # def subgroups(self): # def get_members(self, subgroups=False): # def members(self): # def users(self): # def get_entities(self, subgroups=False): # def entities(self): # def add_member(self, member, roles=None, expiration_date=None): # def remove_member(self, member): # def assign_object(self, obj, **kwargs): # def group_save(sender, instance, created, *args, **kwargs): # def group_delete(sender, instance, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def save(self, *args, **kwargs): # def __unicode__(self): # def __str__(self): # def assign_object(self, obj, **kwargs): # def group_member_save(sender, instance, created, *args, **kwargs): # def group_member_delete(sender, instance, *args, **kwargs): # class MemberRelationsMixin(object): # class GroupsManagerMeta: # class MemberMixin(MemberRelationsMixin, models.Model): # class Meta: # class Member(MemberMixin): # class Meta(MemberMixin.Meta): # class GroupTypeMixin(models.Model): # class Meta: # class GroupType(GroupTypeMixin): # class Meta(GroupTypeMixin.Meta): # class GroupEntityMixin(models.Model): # class Meta: # class GroupEntity(GroupEntityMixin): # class Meta(GroupEntityMixin.Meta): # class GroupRelationsMixin(object): # class GroupsManagerMeta: # class GroupMixin(GroupRelationsMixin, MPTTModel): # class Meta: # class MPTTMeta: # class GroupsManagerMeta(GroupRelationsMixin.GroupsManagerMeta): # class Group(GroupMixin): # class Meta(GroupMixin.Meta): # class GroupMemberRoleMixin(models.Model): # class Meta: # class GroupMemberRole(GroupMemberRoleMixin): # class Meta(GroupMemberRoleMixin.Meta): # class GroupMemberMixin(models.Model): # class Meta: # class GroupMember(GroupMemberMixin): # class Meta(GroupMemberMixin.Meta): # # Path: groups_manager/forms.py # class MemberForm(forms.ModelForm): # class Meta: # class GroupTypeForm(forms.ModelForm): # class Meta: # class GroupEntityForm(forms.ModelForm): # class Meta: # class GroupForm(forms.ModelForm): # class Meta: # class GroupMemberRoleForm(forms.ModelForm): # class Meta: # class GroupMemberForm(forms.ModelForm): # class Meta: # class GroupMemberAddMemberForm(forms.ModelForm): # class Meta: # class GroupMemberAddGroupForm(forms.ModelForm): # class Meta: # # Path: groups_manager/settings.py # GROUPS_MANAGER_SETTINGS = getattr(settings, 'GROUPS_MANAGER', {}) # SETTINGS_PERMISSIONS = GROUPS_MANAGER_SETTINGS.get('PERMISSIONS', {}) # PERMISSIONS = { # 'owner': ['view', 'change', 'delete'], # 'group': ['view', 'change'], # 'groups_upstream': ['view'], # 'groups_downstream': [], # 'groups_siblings': ['view'], # } # GROUPS_MANAGER = { # # User and Groups sync settings # 'AUTH_MODELS_SYNC': GROUPS_MANAGER_SETTINGS.get('AUTH_MODELS_SYNC', False), # 'AUTH_MODELS_GET_OR_CREATE': GROUPS_MANAGER_SETTINGS.get('AUTH_MODELS_GET_OR_CREATE', True), # 'GROUP_NAME_PREFIX': GROUPS_MANAGER_SETTINGS.get('GROUP_NAME_PREFIX', 'DGM_'), # 'GROUP_NAME_SUFFIX': GROUPS_MANAGER_SETTINGS.get('GROUP_NAME_SUFFIX', '_$$random'), # 'USER_USERNAME_PREFIX': GROUPS_MANAGER_SETTINGS.get('USER_USERNAME_PREFIX', 'DGM_'), # 'USER_USERNAME_SUFFIX': GROUPS_MANAGER_SETTINGS.get('USER_USERNAME_SUFFIX', '_$$random'), # # Permissions # 'PERMISSIONS': PERMISSIONS, # # Templates # 'TEMPLATE_STYLE': GROUPS_MANAGER_SETTINGS.get('TEMPLATE_STYLE', 'bootstrap3'), # # Slugify function # 'SLUGIFY_FUNCTION': GROUPS_MANAGER_SETTINGS.get('SLUGIFY_FUNCTION', slugify_function), # 'SLUGIFY_USERNAME_FUNCTION': GROUPS_MANAGER_SETTINGS.get('SLUGIFY_USERNAME_FUNCTION', slugify_username_function), # } # def slugify_function(s): # def slugify_username_function(s): . Output only the next line.
template_name = 'groups_manager%s/groups_manager_home.html' % TS
Given the following code snippet before the placeholder: <|code_start|> try: except ImportError: def assign_perm(perm_name, group_or_user, obj): pass <|code_end|> , predict the next line using imports from the current file: import copy from guardian.shortcuts import assign_perm from groups_manager.utils import get_permission_name from groups_manager.settings import GROUPS_MANAGER from groups_manager.settings import GROUPS_MANAGER and context including class names, function names, and sometimes code from other files: # Path: groups_manager/utils.py # def get_permission_name(action, obj): # if action in ['add', 'view', 'change', 'delete']: # return get_permission_codename(action, obj._meta) # return action . Output only the next line.
def assign_related(related_groups, perms, obj):
Given the code snippet: <|code_start|> class AlexNet(models.AlexNet): def __init__(self, shape, dim_out=None, fully_connected_layers=None, nonlinearity='ReLU', n_steps=None, **layer_args): super(AlexNet, self).__init__() fully_connected_layers = fully_connected_layers or [] self.fc = nn.Sequential() dim_out_ = (256 * ((shape[0] + 4 - 10) // 32) * ((shape[1] + 4 - 10) // 32)) nonlinearity = get_nonlinearity(nonlinearity) for dim_h in fully_connected_layers: dim_in = dim_out_ dim_out_ = dim_h <|code_end|> , generate the next line using the imports in this file: from torch import nn from torchvision import models from .utils import finish_layer_1d, get_nonlinearity and context (functions, classes, or occasionally code) from other files: # Path: cortex/built_ins/networks/utils.py # def finish_layer_1d(models, name, dim_out, # dropout=False, layer_norm=False, batch_norm=False, # nonlinearity=None): # if layer_norm and batch_norm: # logger.warning('Ignoring layer_norm because batch_norm is True') # # if dropout: # models.add_module(name + '_do', nn.Dropout(p=dropout)) # # if layer_norm: # models.add_module(name + '_ln', nn.LayerNorm(dim_out)) # elif batch_norm: # models.add_module(name + '_bn', nn.BatchNorm1d(dim_out)) # # if nonlinearity: # nonlinearity = get_nonlinearity(nonlinearity) # models.add_module( # '{}_{}'.format(name, nonlinearity.__class__.__name__), # nonlinearity) # # def get_nonlinearity(nonlinearity=None): # if not nonlinearity: # pass # elif callable(nonlinearity): # if nonlinearity == nn.LeakyReLU: # nonlinearity = nonlinearity(0.02, inplace=True) # elif hasattr(nn, nonlinearity): # nonlinearity = getattr(nn, nonlinearity) # if nonlinearity == 'LeakyReLU': # nonlinearity = nonlinearity(0.02, inplace=True) # else: # nonlinearity = nonlinearity() # elif hasattr(nn.functional, nonlinearity): # nonlinearity = getattr(nn.functional, nonlinearity) # else: # raise ValueError(nonlinearity) # return nonlinearity . Output only the next line.
name = 'linear_%s_%s' % (dim_in, dim_out_)
Given the code snippet: <|code_start|> class AlexNet(models.AlexNet): def __init__(self, shape, dim_out=None, fully_connected_layers=None, nonlinearity='ReLU', n_steps=None, **layer_args): super(AlexNet, self).__init__() fully_connected_layers = fully_connected_layers or [] self.fc = nn.Sequential() dim_out_ = (256 * ((shape[0] + 4 - 10) // 32) * ((shape[1] + 4 - 10) // 32)) nonlinearity = get_nonlinearity(nonlinearity) for dim_h in fully_connected_layers: dim_in = dim_out_ dim_out_ = dim_h name = 'linear_%s_%s' % (dim_in, dim_out_) self.fc.add_module(name, nn.Linear(dim_in, dim_out_)) finish_layer_1d(self.fc, name, dim_out_, nonlinearity=nonlinearity, **layer_args) if dim_out: name = 'dim_out' self.fc.add_module(name, nn.Linear(dim_out_, dim_out)) def forward(self, x): x = self.features(x) <|code_end|> , generate the next line using the imports in this file: from torch import nn from torchvision import models from .utils import finish_layer_1d, get_nonlinearity and context (functions, classes, or occasionally code) from other files: # Path: cortex/built_ins/networks/utils.py # def finish_layer_1d(models, name, dim_out, # dropout=False, layer_norm=False, batch_norm=False, # nonlinearity=None): # if layer_norm and batch_norm: # logger.warning('Ignoring layer_norm because batch_norm is True') # # if dropout: # models.add_module(name + '_do', nn.Dropout(p=dropout)) # # if layer_norm: # models.add_module(name + '_ln', nn.LayerNorm(dim_out)) # elif batch_norm: # models.add_module(name + '_bn', nn.BatchNorm1d(dim_out)) # # if nonlinearity: # nonlinearity = get_nonlinearity(nonlinearity) # models.add_module( # '{}_{}'.format(name, nonlinearity.__class__.__name__), # nonlinearity) # # def get_nonlinearity(nonlinearity=None): # if not nonlinearity: # pass # elif callable(nonlinearity): # if nonlinearity == nn.LeakyReLU: # nonlinearity = nonlinearity(0.02, inplace=True) # elif hasattr(nn, nonlinearity): # nonlinearity = getattr(nn, nonlinearity) # if nonlinearity == 'LeakyReLU': # nonlinearity = nonlinearity(0.02, inplace=True) # else: # nonlinearity = nonlinearity() # elif hasattr(nn.functional, nonlinearity): # nonlinearity = getattr(nn.functional, nonlinearity) # else: # raise ValueError(nonlinearity) # return nonlinearity . Output only the next line.
x = x.view(x.size()[0], -1)
Predict the next line after this snippet: <|code_start|> return w, b, out def _MLP2(net, inp_dim, hid_dim, out_dim): inp = net.portal((inp_dim,)) w1, b1, fc1 = _fc(net, inp, inp_dim, hid_dim, net.relu) w2, b2, fc2 = _fc(net, fc1, hid_dim, out_dim, lambda x: x) return inp, [w1, b1], [w2, b2], fc2 class Qfunction(object): def __init__(self, is_target, inp_dim, hid_dim, out_dim): self._net = Net() self._inp, fc1_param, fc2_param, self._out = \ _MLP2(self._net, inp_dim, hid_dim, out_dim) self._vars = fc1_param + fc2_param if is_target: self._feed = list() self._assign_ops = list() self._build_assign(fc1_param, (inp_dim, hid_dim)) self._build_assign(fc2_param, (hid_dim, out_dim)) elif not is_target: self._build_loss() def forward(self, inp_feed): out = self._net.forward( [self._out], {self._inp: inp_feed})[0] return out[0, 0] def train(self, x_feed, y_feed): <|code_end|> using the current file's imports: from src.net import Net from src.utils.misc import uniform, xavier import numpy as np and any relevant context from other files: # Path: src/net.py # class Net(object): # # Sugar syntax # def __init__(self): # self._server = ParameterServer() # self._finalized = False # self._dagraph = DAG() # coated = sugar.__dict__ # for name, fun in coated.items(): # if callable(fun): setattr(Net, name, fun) # # # To be sugar coated # def _x(self, name, *args): # assert not self._finalized, \ # 'Graph is finalized by setting an optimizer' # return self._dagraph.register_for_slot( # name, self._server, *args) # # def optimize(self, ptr, optimizer, # *args, **kwargs): # self._finalized = True # self._dagraph.set_closure(ptr) # self._server.set_optimizer( # optimizer, *args, **kwargs) # # def forward(self, fetches, feed): # return self._dagraph.forward(fetches, feed) # # def train(self, fetches, feed): # val = self._dagraph.forward_to_leaf(fetches, feed) # self._dagraph.backward() # self._server.apply_optimizer() # return val # # def save_checkpoint(self, file_name): # self._server.save(file_name) # # def load_checkpoint(self, file_name, *args, **kwargs): # self._server.load(file_name, *args, **kwargs) # # Path: src/utils/misc.py # def accuracy(predict, truth): # def read_mnist(): # def xavier(shape): # def extract(name, dfault, **kwargs): # def nxshape(volume, shape): # def parse_for(class_type, *args): . Output only the next line.
loss, = self._net.train([], {
Predict the next line after this snippet: <|code_start|>def _MLP2(net, inp_dim, hid_dim, out_dim): inp = net.portal((inp_dim,)) w1, b1, fc1 = _fc(net, inp, inp_dim, hid_dim, net.relu) w2, b2, fc2 = _fc(net, fc1, hid_dim, out_dim, lambda x: x) return inp, [w1, b1], [w2, b2], fc2 class Qfunction(object): def __init__(self, is_target, inp_dim, hid_dim, out_dim): self._net = Net() self._inp, fc1_param, fc2_param, self._out = \ _MLP2(self._net, inp_dim, hid_dim, out_dim) self._vars = fc1_param + fc2_param if is_target: self._feed = list() self._assign_ops = list() self._build_assign(fc1_param, (inp_dim, hid_dim)) self._build_assign(fc2_param, (hid_dim, out_dim)) elif not is_target: self._build_loss() def forward(self, inp_feed): out = self._net.forward( [self._out], {self._inp: inp_feed})[0] return out[0, 0] def train(self, x_feed, y_feed): loss, = self._net.train([], { self._inp: x_feed, <|code_end|> using the current file's imports: from src.net import Net from src.utils.misc import uniform, xavier import numpy as np and any relevant context from other files: # Path: src/net.py # class Net(object): # # Sugar syntax # def __init__(self): # self._server = ParameterServer() # self._finalized = False # self._dagraph = DAG() # coated = sugar.__dict__ # for name, fun in coated.items(): # if callable(fun): setattr(Net, name, fun) # # # To be sugar coated # def _x(self, name, *args): # assert not self._finalized, \ # 'Graph is finalized by setting an optimizer' # return self._dagraph.register_for_slot( # name, self._server, *args) # # def optimize(self, ptr, optimizer, # *args, **kwargs): # self._finalized = True # self._dagraph.set_closure(ptr) # self._server.set_optimizer( # optimizer, *args, **kwargs) # # def forward(self, fetches, feed): # return self._dagraph.forward(fetches, feed) # # def train(self, fetches, feed): # val = self._dagraph.forward_to_leaf(fetches, feed) # self._dagraph.backward() # self._server.apply_optimizer() # return val # # def save_checkpoint(self, file_name): # self._server.save(file_name) # # def load_checkpoint(self, file_name, *args, **kwargs): # self._server.load(file_name, *args, **kwargs) # # Path: src/utils/misc.py # def accuracy(predict, truth): # def read_mnist(): # def xavier(shape): # def extract(name, dfault, **kwargs): # def nxshape(volume, shape): # def parse_for(class_type, *args): . Output only the next line.
self._y: y_feed })
Next line prediction: <|code_start|> def act(self, observe, epsilon): rand = uniform() if rand <= epsilon: # exploration best_act = None q_val = None elif rand > epsilon: # exploitation best_act, q_val = \ self._best_act( self._moving_q, observe) return best_act, q_val def store_and_learn(self, transition): self._exreplay.append(transition) shuffle = perm(len(self._exreplay))[:self._batch] mini_batch = [self._exreplay[i] for i in shuffle] observe_action_t, \ reward_t , \ observe_tplus1 , \ = map(np.array, zip(*mini_batch)) best_q_tplus1 = np.array(list(map( lambda x: self._best_act(self._target_q, x)[1], observe_tplus1 ))) reward_t += best_q_tplus1 * self._gamma loss = self._moving_q.train( <|code_end|> . Use current file imports: (from src.net import Net from src.utils.misc import uniform, xavier, perm from .qfunction import Qfunction import numpy as np) and context including class names, function names, or small code snippets from other files: # Path: src/net.py # class Net(object): # # Sugar syntax # def __init__(self): # self._server = ParameterServer() # self._finalized = False # self._dagraph = DAG() # coated = sugar.__dict__ # for name, fun in coated.items(): # if callable(fun): setattr(Net, name, fun) # # # To be sugar coated # def _x(self, name, *args): # assert not self._finalized, \ # 'Graph is finalized by setting an optimizer' # return self._dagraph.register_for_slot( # name, self._server, *args) # # def optimize(self, ptr, optimizer, # *args, **kwargs): # self._finalized = True # self._dagraph.set_closure(ptr) # self._server.set_optimizer( # optimizer, *args, **kwargs) # # def forward(self, fetches, feed): # return self._dagraph.forward(fetches, feed) # # def train(self, fetches, feed): # val = self._dagraph.forward_to_leaf(fetches, feed) # self._dagraph.backward() # self._server.apply_optimizer() # return val # # def save_checkpoint(self, file_name): # self._server.save(file_name) # # def load_checkpoint(self, file_name, *args, **kwargs): # self._server.load(file_name, *args, **kwargs) # # Path: src/utils/misc.py # def accuracy(predict, truth): # def read_mnist(): # def xavier(shape): # def extract(name, dfault, **kwargs): # def nxshape(volume, shape): # def parse_for(class_type, *args): # # Path: src/agents/qfunction.py # class Qfunction(object): # def __init__(self, is_target, # inp_dim, hid_dim, out_dim): # self._net = Net() # self._inp, fc1_param, fc2_param, self._out = \ # _MLP2(self._net, inp_dim, hid_dim, out_dim) # self._vars = fc1_param + fc2_param # if is_target: # self._feed = list() # self._assign_ops = list() # self._build_assign(fc1_param, (inp_dim, hid_dim)) # self._build_assign(fc2_param, (hid_dim, out_dim)) # elif not is_target: # self._build_loss() # # def forward(self, inp_feed): # out = self._net.forward( # [self._out], # {self._inp: inp_feed})[0] # return out[0, 0] # # def train(self, x_feed, y_feed): # loss, = self._net.train([], { # self._inp: x_feed, # self._y: y_feed }) # return loss # # def _build_loss(self): # self._y = self._net.portal((1,)) # self._loss = self._net.l2(self._out, self._y) # self._net.optimize(self._loss, 'adam', 1e-3) # # def _build_assign(self, fc_weights, shape): # pw, pb = ( # self._net.portal(shape), # self._net.portal(shape[1:2])) # self._feed += [pw, pb] # self._assign_ops += [ # self._net.assign(fc_weights[0], pw), # self._net.assign(fc_weights[1], pb)] # # def yield_params_values(self): # returns = list() # for var in self._vars: # returns.append( # self._net.forward([var], {})[0]) # return returns # # def assign(self, values): # feed_dict = dict(zip(self._feed, values)) # self._net.forward(self._assign_ops, feed_dict) # # def save(self, file_name): # self._net.save_checkpoint(file_name) # # def load(self, file_name): # self._net.load_checkpoint(file_name) . Output only the next line.
observe_action_t, reward_t[:, None])
Given the code snippet: <|code_start|> class Agent(object): def __init__(self, mlp_dims, action_space, batch = 32, gamma = .987): self._batch = batch self._gamma = gamma self._action_space = action_space self._exreplay = list() # experience replay self._moving_q = Qfunction(False, *mlp_dims) self._target_q = Qfunction(True, *mlp_dims) def _best_act(self, qfunc, observe): max_q_out = None observe = list(observe) for action in self._action_space: q_inp = np.array([observe + action]) q_out = qfunc.forward(q_inp) if not max_q_out or max_q_out < q_out: best_act = action max_q_out = q_out <|code_end|> , generate the next line using the imports in this file: from src.net import Net from src.utils.misc import uniform, xavier, perm from .qfunction import Qfunction import numpy as np and context (functions, classes, or occasionally code) from other files: # Path: src/net.py # class Net(object): # # Sugar syntax # def __init__(self): # self._server = ParameterServer() # self._finalized = False # self._dagraph = DAG() # coated = sugar.__dict__ # for name, fun in coated.items(): # if callable(fun): setattr(Net, name, fun) # # # To be sugar coated # def _x(self, name, *args): # assert not self._finalized, \ # 'Graph is finalized by setting an optimizer' # return self._dagraph.register_for_slot( # name, self._server, *args) # # def optimize(self, ptr, optimizer, # *args, **kwargs): # self._finalized = True # self._dagraph.set_closure(ptr) # self._server.set_optimizer( # optimizer, *args, **kwargs) # # def forward(self, fetches, feed): # return self._dagraph.forward(fetches, feed) # # def train(self, fetches, feed): # val = self._dagraph.forward_to_leaf(fetches, feed) # self._dagraph.backward() # self._server.apply_optimizer() # return val # # def save_checkpoint(self, file_name): # self._server.save(file_name) # # def load_checkpoint(self, file_name, *args, **kwargs): # self._server.load(file_name, *args, **kwargs) # # Path: src/utils/misc.py # def accuracy(predict, truth): # def read_mnist(): # def xavier(shape): # def extract(name, dfault, **kwargs): # def nxshape(volume, shape): # def parse_for(class_type, *args): # # Path: src/agents/qfunction.py # class Qfunction(object): # def __init__(self, is_target, # inp_dim, hid_dim, out_dim): # self._net = Net() # self._inp, fc1_param, fc2_param, self._out = \ # _MLP2(self._net, inp_dim, hid_dim, out_dim) # self._vars = fc1_param + fc2_param # if is_target: # self._feed = list() # self._assign_ops = list() # self._build_assign(fc1_param, (inp_dim, hid_dim)) # self._build_assign(fc2_param, (hid_dim, out_dim)) # elif not is_target: # self._build_loss() # # def forward(self, inp_feed): # out = self._net.forward( # [self._out], # {self._inp: inp_feed})[0] # return out[0, 0] # # def train(self, x_feed, y_feed): # loss, = self._net.train([], { # self._inp: x_feed, # self._y: y_feed }) # return loss # # def _build_loss(self): # self._y = self._net.portal((1,)) # self._loss = self._net.l2(self._out, self._y) # self._net.optimize(self._loss, 'adam', 1e-3) # # def _build_assign(self, fc_weights, shape): # pw, pb = ( # self._net.portal(shape), # self._net.portal(shape[1:2])) # self._feed += [pw, pb] # self._assign_ops += [ # self._net.assign(fc_weights[0], pw), # self._net.assign(fc_weights[1], pb)] # # def yield_params_values(self): # returns = list() # for var in self._vars: # returns.append( # self._net.forward([var], {})[0]) # return returns # # def assign(self, values): # feed_dict = dict(zip(self._feed, values)) # self._net.forward(self._assign_ops, feed_dict) # # def save(self, file_name): # self._net.save_checkpoint(file_name) # # def load(self, file_name): # self._net.load_checkpoint(file_name) . Output only the next line.
return best_act, max_q_out
Based on the snippet: <|code_start|> self._action_space = action_space self._exreplay = list() # experience replay self._moving_q = Qfunction(False, *mlp_dims) self._target_q = Qfunction(True, *mlp_dims) def _best_act(self, qfunc, observe): max_q_out = None observe = list(observe) for action in self._action_space: q_inp = np.array([observe + action]) q_out = qfunc.forward(q_inp) if not max_q_out or max_q_out < q_out: best_act = action max_q_out = q_out return best_act, max_q_out def act(self, observe, epsilon): rand = uniform() if rand <= epsilon: # exploration best_act = None q_val = None elif rand > epsilon: # exploitation best_act, q_val = \ self._best_act( self._moving_q, observe) return best_act, q_val def store_and_learn(self, transition): <|code_end|> , predict the immediate next line with the help of imports: from src.net import Net from src.utils.misc import uniform, xavier, perm from .qfunction import Qfunction import numpy as np and context (classes, functions, sometimes code) from other files: # Path: src/net.py # class Net(object): # # Sugar syntax # def __init__(self): # self._server = ParameterServer() # self._finalized = False # self._dagraph = DAG() # coated = sugar.__dict__ # for name, fun in coated.items(): # if callable(fun): setattr(Net, name, fun) # # # To be sugar coated # def _x(self, name, *args): # assert not self._finalized, \ # 'Graph is finalized by setting an optimizer' # return self._dagraph.register_for_slot( # name, self._server, *args) # # def optimize(self, ptr, optimizer, # *args, **kwargs): # self._finalized = True # self._dagraph.set_closure(ptr) # self._server.set_optimizer( # optimizer, *args, **kwargs) # # def forward(self, fetches, feed): # return self._dagraph.forward(fetches, feed) # # def train(self, fetches, feed): # val = self._dagraph.forward_to_leaf(fetches, feed) # self._dagraph.backward() # self._server.apply_optimizer() # return val # # def save_checkpoint(self, file_name): # self._server.save(file_name) # # def load_checkpoint(self, file_name, *args, **kwargs): # self._server.load(file_name, *args, **kwargs) # # Path: src/utils/misc.py # def accuracy(predict, truth): # def read_mnist(): # def xavier(shape): # def extract(name, dfault, **kwargs): # def nxshape(volume, shape): # def parse_for(class_type, *args): # # Path: src/agents/qfunction.py # class Qfunction(object): # def __init__(self, is_target, # inp_dim, hid_dim, out_dim): # self._net = Net() # self._inp, fc1_param, fc2_param, self._out = \ # _MLP2(self._net, inp_dim, hid_dim, out_dim) # self._vars = fc1_param + fc2_param # if is_target: # self._feed = list() # self._assign_ops = list() # self._build_assign(fc1_param, (inp_dim, hid_dim)) # self._build_assign(fc2_param, (hid_dim, out_dim)) # elif not is_target: # self._build_loss() # # def forward(self, inp_feed): # out = self._net.forward( # [self._out], # {self._inp: inp_feed})[0] # return out[0, 0] # # def train(self, x_feed, y_feed): # loss, = self._net.train([], { # self._inp: x_feed, # self._y: y_feed }) # return loss # # def _build_loss(self): # self._y = self._net.portal((1,)) # self._loss = self._net.l2(self._out, self._y) # self._net.optimize(self._loss, 'adam', 1e-3) # # def _build_assign(self, fc_weights, shape): # pw, pb = ( # self._net.portal(shape), # self._net.portal(shape[1:2])) # self._feed += [pw, pb] # self._assign_ops += [ # self._net.assign(fc_weights[0], pw), # self._net.assign(fc_weights[1], pb)] # # def yield_params_values(self): # returns = list() # for var in self._vars: # returns.append( # self._net.forward([var], {})[0]) # return returns # # def assign(self, values): # feed_dict = dict(zip(self._feed, values)) # self._net.forward(self._assign_ops, feed_dict) # # def save(self, file_name): # self._net.save_checkpoint(file_name) # # def load(self, file_name): # self._net.load_checkpoint(file_name) . Output only the next line.
self._exreplay.append(transition)
Predict the next line for this snippet: <|code_start|> class Net(object): # Sugar syntax def __init__(self): self._server = ParameterServer() self._finalized = False self._dagraph = DAG() coated = sugar.__dict__ for name, fun in coated.items(): if callable(fun): setattr(Net, name, fun) # To be sugar coated def _x(self, name, *args): assert not self._finalized, \ 'Graph is finalized by setting an optimizer' return self._dagraph.register_for_slot( name, self._server, *args) def optimize(self, ptr, optimizer, *args, **kwargs): self._finalized = True self._dagraph.set_closure(ptr) self._server.set_optimizer( optimizer, *args, **kwargs) def forward(self, fetches, feed): return self._dagraph.forward(fetches, feed) <|code_end|> with the help of current file imports: from src.server import ParameterServer from src.graph import DAG import src.sugar as sugar and context from other files: # Path: src/server.py # class ParameterServer(object): # """ # A server of variables, consists of slots # each slot contains variables of one module, thus # each slot can have zero, one or more variables. # """ # # def __init__(self): # self._slots = list() # self._optimizer = None # # def issue_movingvar_slot(self, shape, momen): # slot = MovingVariableSlot(shape, momen) # self._slots.append(slot) # return slot # # def issue_var_slot(self, val, trainable): # slot = VariableSlot(val, trainable) # self._slots.append(slot) # return slot # # def set_optimizer(self, name, *args, **kwargs): # optimizer = optimizer_factory( # name, *args, **kwargs) # self._optimizer = optimizer # # def apply_optimizer(self): # for slot in self._slots: # self._optimizer.apply(slot) # self._optimizer.finalize_step() # # def save(self, file_name): # with open(file_name, 'wb') as f: # pickle.dump( # [self._slots, self._optimizer], f, protocol = -1) # # def load(self, file_name, *args, **kwargs): # with open(file_name, 'rb') as f: # slots, self._optimizer = \ # pickle.load(f, *args, **kwargs) # assert len(slots) == len(self._slots) # for i, slot in enumerate(self._slots): # slot.load(slots[i]) # # Path: src/graph.py # class DAG(object): # def __init__(self): # self._node_pool = dict() # # key : val = Ptr : Node # # def register_for_slot(self, name, server, *args): # # Step 1, extract dependencies from arguments # dep_parsed = parse_for(ptr, *args) # dep_list, parameters = dep_parsed # # # Step 2, Get shapes from dependencies # dep_nodes = list() # dep_shapes = list() # for i in range(len(dep_list)): # node = self._node_pool[dep_list[i]] # dep_shapes.append(node.out_shape()) # dep_nodes.append(node) # # # Step 3, Create module, wrap by a node, add to pool # module = module_class_factory(name)( # server, *(dep_shapes + parameters)) # new_ptr = ptr() # new_node = Node(module, *dep_nodes) # self._node_pool[new_ptr] = new_node # return new_ptr # # def get_module(self, ptr): # return self._node_pool[ptr].get_module() # # def forward_to_leaf(self, fetches, feed): # fetch = fetches + [self._leaf] # return self.forward(fetch, feed) # # def forward(self, fetches, feed): # assert type(fetches) is list,\ # 'Fetches must be a list' # # forward_id = object() # vals = list() # for ptr in feed: # node = self._node_pool[ptr] # node.set_feed(feed[ptr]) # for ptr in fetches: # node = self._node_pool[ptr] # vals.append(node.forward(forward_id)) # return vals # # def set_closure(self, ptr): # self._leaf = ptr # leaf_node = self._node_pool[self._leaf] # leaf_node.inc_counter(ptr) # # def backward(self): # leaf_node = self._node_pool[self._leaf] # leaf_node.backward(1.0, self._leaf) , which may contain function names, class names, or code. Output only the next line.
def train(self, fetches, feed):
Using the snippet: <|code_start|> class Net(object): # Sugar syntax def __init__(self): self._server = ParameterServer() self._finalized = False self._dagraph = DAG() coated = sugar.__dict__ for name, fun in coated.items(): if callable(fun): setattr(Net, name, fun) # To be sugar coated def _x(self, name, *args): assert not self._finalized, \ 'Graph is finalized by setting an optimizer' return self._dagraph.register_for_slot( <|code_end|> , determine the next line of code. You have imports: from src.server import ParameterServer from src.graph import DAG import src.sugar as sugar and context (class names, function names, or code) available: # Path: src/server.py # class ParameterServer(object): # """ # A server of variables, consists of slots # each slot contains variables of one module, thus # each slot can have zero, one or more variables. # """ # # def __init__(self): # self._slots = list() # self._optimizer = None # # def issue_movingvar_slot(self, shape, momen): # slot = MovingVariableSlot(shape, momen) # self._slots.append(slot) # return slot # # def issue_var_slot(self, val, trainable): # slot = VariableSlot(val, trainable) # self._slots.append(slot) # return slot # # def set_optimizer(self, name, *args, **kwargs): # optimizer = optimizer_factory( # name, *args, **kwargs) # self._optimizer = optimizer # # def apply_optimizer(self): # for slot in self._slots: # self._optimizer.apply(slot) # self._optimizer.finalize_step() # # def save(self, file_name): # with open(file_name, 'wb') as f: # pickle.dump( # [self._slots, self._optimizer], f, protocol = -1) # # def load(self, file_name, *args, **kwargs): # with open(file_name, 'rb') as f: # slots, self._optimizer = \ # pickle.load(f, *args, **kwargs) # assert len(slots) == len(self._slots) # for i, slot in enumerate(self._slots): # slot.load(slots[i]) # # Path: src/graph.py # class DAG(object): # def __init__(self): # self._node_pool = dict() # # key : val = Ptr : Node # # def register_for_slot(self, name, server, *args): # # Step 1, extract dependencies from arguments # dep_parsed = parse_for(ptr, *args) # dep_list, parameters = dep_parsed # # # Step 2, Get shapes from dependencies # dep_nodes = list() # dep_shapes = list() # for i in range(len(dep_list)): # node = self._node_pool[dep_list[i]] # dep_shapes.append(node.out_shape()) # dep_nodes.append(node) # # # Step 3, Create module, wrap by a node, add to pool # module = module_class_factory(name)( # server, *(dep_shapes + parameters)) # new_ptr = ptr() # new_node = Node(module, *dep_nodes) # self._node_pool[new_ptr] = new_node # return new_ptr # # def get_module(self, ptr): # return self._node_pool[ptr].get_module() # # def forward_to_leaf(self, fetches, feed): # fetch = fetches + [self._leaf] # return self.forward(fetch, feed) # # def forward(self, fetches, feed): # assert type(fetches) is list,\ # 'Fetches must be a list' # # forward_id = object() # vals = list() # for ptr in feed: # node = self._node_pool[ptr] # node.set_feed(feed[ptr]) # for ptr in fetches: # node = self._node_pool[ptr] # vals.append(node.forward(forward_id)) # return vals # # def set_closure(self, ptr): # self._leaf = ptr # leaf_node = self._node_pool[self._leaf] # leaf_node.inc_counter(ptr) # # def backward(self): # leaf_node = self._node_pool[self._leaf] # leaf_node.backward(1.0, self._leaf) . Output only the next line.
name, self._server, *args)
Based on the snippet: <|code_start|> @property def out_shape(self): return tuple(self._out_shape) def unit_test(self, x, y): GradientChecker.check(self, x, y) class portal(Module): def __init__(self, server, shape): self._inp_shape = tuple(shape) self._out_shape = tuple(shape) def forward(self, x): return x def backward(self, grad): return grad class variable(Module): def __init__(self, server, val, trainable): self._var = server.issue_var_slot(val, trainable) self._out_shape = val.shape def assign(self, new_val): self._var.assign(new_val) def forward(self): return self._var.val def backward(self, grad): self._var.set_grad(grad) class lookup(Module): <|code_end|> , predict the immediate next line with the help of imports: from .gradcheck import GradientChecker and context (classes, functions, sometimes code) from other files: # Path: src/modules/gradcheck.py # class GradientChecker(object): # threshold = np.float64(1e-3) # epsilon = np.float64(1e-3) # check_round = int(8) # current = None # # @classmethod # def tolist(cls, obj): # if type(obj) not in (list, tuple): obj = [obj] # return obj # # @classmethod # def check(cls, module, args, outputs): # if module == cls.current: return # print('Checking', module) # cls.current = module # outputs = cls.tolist(outputs) # for out_idx in range(len(outputs)): # cls.check_against_output( # module, args, outputs, out_idx) # cls.current = None # # @classmethod # def check_against_output( # cls, module, args, outs, out_idx): # target = outs[out_idx] # simulated_target = guass( # target.mean(), target.std() + 1., target.shape) # out_grads = [np.zeros(o.shape) for o in outs] # out_grads[out_idx] = 2 * (target - simulated_target) # inp_grads = module.backward(*out_grads) # if inp_grads is None: return # # print('\tChecking w.r.t output #', out_idx) # inp_grads = cls.tolist(inp_grads) # for inp_idx, inp_grad in enumerate(inp_grads): # if type(inp_grad) is np.ndarray: # cls.check_against_input( # module, args, inp_idx, inp_grad, # out_idx, simulated_target) # # @classmethod # def check_against_input(cls, module, args, inp_idx, # grad, out_idx, y): # print('\t\tChecking input #', inp_idx) # # x = args[inp_idx]; relates = list() # assert x.shape == grad.shape, \ # 'Gradient shape mismatch: {} and {}'.format(x.shape, grad.shape) # # for each in range(cls.check_round): # pick = tuple(randint(dim) for dim in x.shape) # x1, x2 = x.copy(), x.copy() # x1[pick] -= cls.epsilon # x2[pick] += cls.epsilon # # args[inp_idx] = x1 # y1 = cls.tolist(module.forward(*args))[out_idx] # L1 = (y1 - y) * (y1 - y) # # args[inp_idx] = x2 # y2 = cls.tolist(module.forward(*args))[out_idx] # L2 = (y2 - y) * (y2 - y) # # grad_pick = (L2.sum() - L1.sum()) # grad_pick /= (2. * cls.epsilon) # # if grad_pick == grad[pick]: # print('\t\t', grad_pick, grad[pick]) # continue # relate = abs(grad_pick - grad[pick]) # relate /= max(abs(grad_pick), abs(grad[pick])) # print('\t\t', grad_pick, grad[pick], relate) # relates.append(relate) # # if len(relates) == 0: return # relate = np.mean(relates) # # assert relate < cls.threshold, \ # # 'Gradcheck failed at {}'.format(module) . Output only the next line.
def __init__(self, server, pos_shape, val, trainable):
Predict the next line for this snippet: <|code_start|> self._log_soft = x - np.log(sum_e_x) crossed = - np.multiply(self._t, self._log_soft) return crossed.sum(1).mean() def _cal_grad(self, grad): scalar = 1. / self._t.shape[0] * grad return scalar * (np.exp(self._log_soft) - self._t) class crossent(Loss): def _cal_loss(self, x): self._x = x crossed = - np.multiply(self._t, np.log(x)) return crossed.sum(-1).mean() def _cal_grad(self, grad): dLdp = - np.divide(self._t, self._x + 1e-20) return 1./self._t.shape[0] * grad * dLdp class logistic(Loss): def _cal_loss(self, x): gain = self._t * np.log(x) + (1 - self._t) * np.log(1 - x) self._x = x return (-1 * gain).mean() def _cal_grad(self, grad): div = self._x * (1 - self._x) + 1e-8 return grad * (self._x - self._t) / div class l2(Loss): def _cal_loss(self, x): <|code_end|> with the help of current file imports: from .module import Module import numpy as np and context from other files: # Path: src/modules/module.py # class Module(object): # def __init__(self, *args): pass # # def forward(self, *args): pass # # def backward(self, grad): pass # # @property # def out_shape(self): # return tuple(self._out_shape) # # def unit_test(self, x, y): # GradientChecker.check(self, x, y) , which may contain function names, class names, or code. Output only the next line.
self._diff = x - self._t
Given snippet: <|code_start|> self._moments = dict() def _rule(self, v, g): c = self._current m = self._moments if c not in m: m[c] = 0 r = m[c] r = self._p * r + (1. - self._p) * g * g m[c] = r dv = self._lr * np.divide(g, np.sqrt(1e-8 + r)) return v - dv class AdamOptimizer(Optimizer): def _construct(self, p1 = .9, p2 = .999): self._p1, self._p2 = p1, p2 self._moments = dict() def _rule(self, v, g): c = self._current m = self._moments if c not in m: m[c] = dict({'s': 0, 'r': 0, 't': 0}) s, r, t = m[c]['s'], m[c]['r'], m[c]['t'] s = s * self._p1 + (1. - self._p1) * g r = r * self._p2 + (1. - self._p2) * g * g <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from .utils import extract and context: # Path: src/utils/extract.py # def VGG_16(weights_path = None): # def yield_weights(model): which might include code, classes, or functions. Output only the next line.
m[c]['s'], m[c]['r'], m[c]['t'] = s, r, (t + 1)
Using the snippet: <|code_start|> self._gates = dict({ 'k': gate(server, (lstm_size, vec_size), None, sigmoid), # key gate 'b': gate(server, (lstm_size, 1), None, softplus), # strength gate 'i': gate(server, (lstm_size, 1), None, sigmoid), # interpolate gate 'r': gate(server, (lstm_size, 2 * shift + 1), None, softmax), # rotate gate 's': gate(server, (lstm_size, 1), None, relu) # sharpen gate }) self._mechanic = dict({ # mechanics 'cos': cosine_sim(), # similarity 'soft': normalise(), # softmax 'inter': interpolate(), # interpolate 'rotate': circular_conv(), # circular conv 'sharp': sharpen(), # sharpen }) def _flush(self): for g in self._gates: self._gates[g].flush() for m in self._mechanic: self._mechanic[m].flush() def forward(self, memory, lstm_h, w_prev): gates_vals = list() for name in 'kbirs': gates_vals.append( self._gates[name].forward(lstm_h)) k, b, i, r, s = gates_vals sim = self._mechanic['cos'].forward(memory, k) self._push(b, sim) # b x 1 and b x n <|code_end|> , determine the next line of code. You have imports: from .recurring import Recurring, gate from .activations import softplus, tanh, sigmoid, softmax, relu from .mechanics import * and context (class names, function names, or code) available: # Path: src/modules/recurring.py # class Recurring(Module): # """ # Recurring is a type of module that cache intermediate # activations in a stack during unrolling of recurrent layers # Its backward() is expected to be called several times during # Back Propagation Through Time, either full or truncated. # """ # def __init__(self, *args, **kwargs): # self._stack = list() # self._setup(*args, **kwargs) # # def _setup(*args, **kwargs): # pass # # def _push(self, *objs): # objs = list(objs) # if len(objs) == 1: # objs = objs[0] # self._stack.append(objs) # # def _pop(self): # objs = self._stack[-1] # del self._stack[-1] # return objs # # def flush(self): # self._stack = list() # self._flush() # # def _flush(self): pass # # class gate(Recurring): # """ # Gates are special case of Recurring modules # It starts with a linear transformation (matmul) # And ends with a (typically) nonlinear activation # """ # def _setup(self, server, w_shape, bias = None, # act_class = sigmoid, transfer = None): # if transfer is None: # b_shape = (w_shape[-1],) # w_init = xavier(w_shape) # if bias is not None: # b_init = np.ones(b_shape) * bias # elif bias is None: # b_init = guass(0., 1e-1, b_shape) # else: w_init, b_init = transfer # # self._act_class = act_class # self._w = server.issue_var_slot(w_init, True) # self._b = server.issue_var_slot(b_init, True) # # def forward(self, x): # linear = x.dot(self._w.val) + self._b.val # act = self._act_class(None, None) # self._push(x, act) # return act.forward(linear) # # def backward(self, grad): # x, act = self._pop() # linear_grad = act.backward(grad) # # self._b.set_grad(linear_grad.sum(0)) # self._w.set_grad(x.T.dot(linear_grad)) # return linear_grad.dot(self._w.val.T) # # Path: src/modules/activations.py # class softplus(Activate): # def transform(self, x): # self.activation = np.log(1 + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = 1 - np.exp(-a) # return np.multiply(grad, p) # # class tanh(Activate): # def transform(self, x): # self.activation = np.tanh(x) # # def backward(self, grad): # a = self.activation # p = 1 - np.multiply(a, a) # return np.multiply(grad, p) # # class sigmoid(Activate): # def transform(self, x): # self.activation = 1. / (1. + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = np.multiply(a, 1. - a) # return np.multiply(grad, p) # # class softmax(Activate): # def transform(self, x): # row_max = x.max(1, keepdims = True) # e_x = np.exp(x - row_max) # e_sum = e_x.sum(1, keepdims = True) # self.activation = np.divide(e_x, e_sum) # # def backward(self, grad): # a = self.activation # m = np.multiply(grad, a) # g = grad - m.sum(1, keepdims = True) # return np.multiply(g, a) # # class relu(Activate): # def transform(self, x): # self.activation = x * (x > 0.) # # def backward(self, grad): # p = self.activation > 0. # return np.multiply(grad, p) . Output only the next line.
w_c = self._mechanic['soft'].forward(b * sim)
Using the snippet: <|code_start|> }) self._mechanic = dict({ # mechanics 'cos': cosine_sim(), # similarity 'soft': normalise(), # softmax 'inter': interpolate(), # interpolate 'rotate': circular_conv(), # circular conv 'sharp': sharpen(), # sharpen }) def _flush(self): for g in self._gates: self._gates[g].flush() for m in self._mechanic: self._mechanic[m].flush() def forward(self, memory, lstm_h, w_prev): gates_vals = list() for name in 'kbirs': gates_vals.append( self._gates[name].forward(lstm_h)) k, b, i, r, s = gates_vals sim = self._mechanic['cos'].forward(memory, k) self._push(b, sim) # b x 1 and b x n w_c = self._mechanic['soft'].forward(b * sim) w_i = self._mechanic['inter'].forward(w_c, w_prev, i) w_r = self._mechanic['rotate'].forward(w_i, r) w_new = self._mechanic['sharp'].forward(w_r, s + 1.) return w_new def backward(self, g_wnew): <|code_end|> , determine the next line of code. You have imports: from .recurring import Recurring, gate from .activations import softplus, tanh, sigmoid, softmax, relu from .mechanics import * and context (class names, function names, or code) available: # Path: src/modules/recurring.py # class Recurring(Module): # """ # Recurring is a type of module that cache intermediate # activations in a stack during unrolling of recurrent layers # Its backward() is expected to be called several times during # Back Propagation Through Time, either full or truncated. # """ # def __init__(self, *args, **kwargs): # self._stack = list() # self._setup(*args, **kwargs) # # def _setup(*args, **kwargs): # pass # # def _push(self, *objs): # objs = list(objs) # if len(objs) == 1: # objs = objs[0] # self._stack.append(objs) # # def _pop(self): # objs = self._stack[-1] # del self._stack[-1] # return objs # # def flush(self): # self._stack = list() # self._flush() # # def _flush(self): pass # # class gate(Recurring): # """ # Gates are special case of Recurring modules # It starts with a linear transformation (matmul) # And ends with a (typically) nonlinear activation # """ # def _setup(self, server, w_shape, bias = None, # act_class = sigmoid, transfer = None): # if transfer is None: # b_shape = (w_shape[-1],) # w_init = xavier(w_shape) # if bias is not None: # b_init = np.ones(b_shape) * bias # elif bias is None: # b_init = guass(0., 1e-1, b_shape) # else: w_init, b_init = transfer # # self._act_class = act_class # self._w = server.issue_var_slot(w_init, True) # self._b = server.issue_var_slot(b_init, True) # # def forward(self, x): # linear = x.dot(self._w.val) + self._b.val # act = self._act_class(None, None) # self._push(x, act) # return act.forward(linear) # # def backward(self, grad): # x, act = self._pop() # linear_grad = act.backward(grad) # # self._b.set_grad(linear_grad.sum(0)) # self._w.set_grad(x.T.dot(linear_grad)) # return linear_grad.dot(self._w.val.T) # # Path: src/modules/activations.py # class softplus(Activate): # def transform(self, x): # self.activation = np.log(1 + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = 1 - np.exp(-a) # return np.multiply(grad, p) # # class tanh(Activate): # def transform(self, x): # self.activation = np.tanh(x) # # def backward(self, grad): # a = self.activation # p = 1 - np.multiply(a, a) # return np.multiply(grad, p) # # class sigmoid(Activate): # def transform(self, x): # self.activation = 1. / (1. + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = np.multiply(a, 1. - a) # return np.multiply(grad, p) # # class softmax(Activate): # def transform(self, x): # row_max = x.max(1, keepdims = True) # e_x = np.exp(x - row_max) # e_sum = e_x.sum(1, keepdims = True) # self.activation = np.divide(e_x, e_sum) # # def backward(self, grad): # a = self.activation # m = np.multiply(grad, a) # g = grad - m.sum(1, keepdims = True) # return np.multiply(g, a) # # class relu(Activate): # def transform(self, x): # self.activation = x * (x > 0.) # # def backward(self, grad): # p = self.activation > 0. # return np.multiply(grad, p) . Output only the next line.
g_wr, gs = self._mechanic['sharp'].backward(g_wnew)
Here is a snippet: <|code_start|> 'b': gate(server, (lstm_size, 1), None, softplus), # strength gate 'i': gate(server, (lstm_size, 1), None, sigmoid), # interpolate gate 'r': gate(server, (lstm_size, 2 * shift + 1), None, softmax), # rotate gate 's': gate(server, (lstm_size, 1), None, relu) # sharpen gate }) self._mechanic = dict({ # mechanics 'cos': cosine_sim(), # similarity 'soft': normalise(), # softmax 'inter': interpolate(), # interpolate 'rotate': circular_conv(), # circular conv 'sharp': sharpen(), # sharpen }) def _flush(self): for g in self._gates: self._gates[g].flush() for m in self._mechanic: self._mechanic[m].flush() def forward(self, memory, lstm_h, w_prev): gates_vals = list() for name in 'kbirs': gates_vals.append( self._gates[name].forward(lstm_h)) k, b, i, r, s = gates_vals sim = self._mechanic['cos'].forward(memory, k) self._push(b, sim) # b x 1 and b x n w_c = self._mechanic['soft'].forward(b * sim) w_i = self._mechanic['inter'].forward(w_c, w_prev, i) <|code_end|> . Write the next line using the current file imports: from .recurring import Recurring, gate from .activations import softplus, tanh, sigmoid, softmax, relu from .mechanics import * and context from other files: # Path: src/modules/recurring.py # class Recurring(Module): # """ # Recurring is a type of module that cache intermediate # activations in a stack during unrolling of recurrent layers # Its backward() is expected to be called several times during # Back Propagation Through Time, either full or truncated. # """ # def __init__(self, *args, **kwargs): # self._stack = list() # self._setup(*args, **kwargs) # # def _setup(*args, **kwargs): # pass # # def _push(self, *objs): # objs = list(objs) # if len(objs) == 1: # objs = objs[0] # self._stack.append(objs) # # def _pop(self): # objs = self._stack[-1] # del self._stack[-1] # return objs # # def flush(self): # self._stack = list() # self._flush() # # def _flush(self): pass # # class gate(Recurring): # """ # Gates are special case of Recurring modules # It starts with a linear transformation (matmul) # And ends with a (typically) nonlinear activation # """ # def _setup(self, server, w_shape, bias = None, # act_class = sigmoid, transfer = None): # if transfer is None: # b_shape = (w_shape[-1],) # w_init = xavier(w_shape) # if bias is not None: # b_init = np.ones(b_shape) * bias # elif bias is None: # b_init = guass(0., 1e-1, b_shape) # else: w_init, b_init = transfer # # self._act_class = act_class # self._w = server.issue_var_slot(w_init, True) # self._b = server.issue_var_slot(b_init, True) # # def forward(self, x): # linear = x.dot(self._w.val) + self._b.val # act = self._act_class(None, None) # self._push(x, act) # return act.forward(linear) # # def backward(self, grad): # x, act = self._pop() # linear_grad = act.backward(grad) # # self._b.set_grad(linear_grad.sum(0)) # self._w.set_grad(x.T.dot(linear_grad)) # return linear_grad.dot(self._w.val.T) # # Path: src/modules/activations.py # class softplus(Activate): # def transform(self, x): # self.activation = np.log(1 + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = 1 - np.exp(-a) # return np.multiply(grad, p) # # class tanh(Activate): # def transform(self, x): # self.activation = np.tanh(x) # # def backward(self, grad): # a = self.activation # p = 1 - np.multiply(a, a) # return np.multiply(grad, p) # # class sigmoid(Activate): # def transform(self, x): # self.activation = 1. / (1. + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = np.multiply(a, 1. - a) # return np.multiply(grad, p) # # class softmax(Activate): # def transform(self, x): # row_max = x.max(1, keepdims = True) # e_x = np.exp(x - row_max) # e_sum = e_x.sum(1, keepdims = True) # self.activation = np.divide(e_x, e_sum) # # def backward(self, grad): # a = self.activation # m = np.multiply(grad, a) # g = grad - m.sum(1, keepdims = True) # return np.multiply(g, a) # # class relu(Activate): # def transform(self, x): # self.activation = x * (x > 0.) # # def backward(self, grad): # p = self.activation > 0. # return np.multiply(grad, p) , which may include functions, classes, or code. Output only the next line.
w_r = self._mechanic['rotate'].forward(w_i, r)
Next line prediction: <|code_start|> class ntm_attend(Recurring): def _setup(self, server, lstm_size, vec_size, shift): self._gates = dict({ 'k': gate(server, (lstm_size, vec_size), None, sigmoid), # key gate 'b': gate(server, (lstm_size, 1), None, softplus), # strength gate 'i': gate(server, (lstm_size, 1), None, sigmoid), # interpolate gate 'r': gate(server, (lstm_size, 2 * shift + 1), None, softmax), # rotate gate 's': gate(server, (lstm_size, 1), None, relu) # sharpen gate }) <|code_end|> . Use current file imports: (from .recurring import Recurring, gate from .activations import softplus, tanh, sigmoid, softmax, relu from .mechanics import * ) and context including class names, function names, or small code snippets from other files: # Path: src/modules/recurring.py # class Recurring(Module): # """ # Recurring is a type of module that cache intermediate # activations in a stack during unrolling of recurrent layers # Its backward() is expected to be called several times during # Back Propagation Through Time, either full or truncated. # """ # def __init__(self, *args, **kwargs): # self._stack = list() # self._setup(*args, **kwargs) # # def _setup(*args, **kwargs): # pass # # def _push(self, *objs): # objs = list(objs) # if len(objs) == 1: # objs = objs[0] # self._stack.append(objs) # # def _pop(self): # objs = self._stack[-1] # del self._stack[-1] # return objs # # def flush(self): # self._stack = list() # self._flush() # # def _flush(self): pass # # class gate(Recurring): # """ # Gates are special case of Recurring modules # It starts with a linear transformation (matmul) # And ends with a (typically) nonlinear activation # """ # def _setup(self, server, w_shape, bias = None, # act_class = sigmoid, transfer = None): # if transfer is None: # b_shape = (w_shape[-1],) # w_init = xavier(w_shape) # if bias is not None: # b_init = np.ones(b_shape) * bias # elif bias is None: # b_init = guass(0., 1e-1, b_shape) # else: w_init, b_init = transfer # # self._act_class = act_class # self._w = server.issue_var_slot(w_init, True) # self._b = server.issue_var_slot(b_init, True) # # def forward(self, x): # linear = x.dot(self._w.val) + self._b.val # act = self._act_class(None, None) # self._push(x, act) # return act.forward(linear) # # def backward(self, grad): # x, act = self._pop() # linear_grad = act.backward(grad) # # self._b.set_grad(linear_grad.sum(0)) # self._w.set_grad(x.T.dot(linear_grad)) # return linear_grad.dot(self._w.val.T) # # Path: src/modules/activations.py # class softplus(Activate): # def transform(self, x): # self.activation = np.log(1 + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = 1 - np.exp(-a) # return np.multiply(grad, p) # # class tanh(Activate): # def transform(self, x): # self.activation = np.tanh(x) # # def backward(self, grad): # a = self.activation # p = 1 - np.multiply(a, a) # return np.multiply(grad, p) # # class sigmoid(Activate): # def transform(self, x): # self.activation = 1. / (1. + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = np.multiply(a, 1. - a) # return np.multiply(grad, p) # # class softmax(Activate): # def transform(self, x): # row_max = x.max(1, keepdims = True) # e_x = np.exp(x - row_max) # e_sum = e_x.sum(1, keepdims = True) # self.activation = np.divide(e_x, e_sum) # # def backward(self, grad): # a = self.activation # m = np.multiply(grad, a) # g = grad - m.sum(1, keepdims = True) # return np.multiply(g, a) # # class relu(Activate): # def transform(self, x): # self.activation = x * (x > 0.) # # def backward(self, grad): # p = self.activation > 0. # return np.multiply(grad, p) . Output only the next line.
self._mechanic = dict({ # mechanics
Next line prediction: <|code_start|> class ntm_attend(Recurring): def _setup(self, server, lstm_size, vec_size, shift): self._gates = dict({ 'k': gate(server, (lstm_size, vec_size), None, sigmoid), # key gate 'b': gate(server, (lstm_size, 1), None, softplus), # strength gate 'i': gate(server, (lstm_size, 1), None, sigmoid), # interpolate gate 'r': gate(server, (lstm_size, 2 * shift + 1), None, softmax), # rotate gate 's': gate(server, (lstm_size, 1), None, relu) # sharpen gate }) self._mechanic = dict({ # mechanics 'cos': cosine_sim(), # similarity 'soft': normalise(), # softmax 'inter': interpolate(), # interpolate 'rotate': circular_conv(), # circular conv <|code_end|> . Use current file imports: (from .recurring import Recurring, gate from .activations import softplus, tanh, sigmoid, softmax, relu from .mechanics import * ) and context including class names, function names, or small code snippets from other files: # Path: src/modules/recurring.py # class Recurring(Module): # """ # Recurring is a type of module that cache intermediate # activations in a stack during unrolling of recurrent layers # Its backward() is expected to be called several times during # Back Propagation Through Time, either full or truncated. # """ # def __init__(self, *args, **kwargs): # self._stack = list() # self._setup(*args, **kwargs) # # def _setup(*args, **kwargs): # pass # # def _push(self, *objs): # objs = list(objs) # if len(objs) == 1: # objs = objs[0] # self._stack.append(objs) # # def _pop(self): # objs = self._stack[-1] # del self._stack[-1] # return objs # # def flush(self): # self._stack = list() # self._flush() # # def _flush(self): pass # # class gate(Recurring): # """ # Gates are special case of Recurring modules # It starts with a linear transformation (matmul) # And ends with a (typically) nonlinear activation # """ # def _setup(self, server, w_shape, bias = None, # act_class = sigmoid, transfer = None): # if transfer is None: # b_shape = (w_shape[-1],) # w_init = xavier(w_shape) # if bias is not None: # b_init = np.ones(b_shape) * bias # elif bias is None: # b_init = guass(0., 1e-1, b_shape) # else: w_init, b_init = transfer # # self._act_class = act_class # self._w = server.issue_var_slot(w_init, True) # self._b = server.issue_var_slot(b_init, True) # # def forward(self, x): # linear = x.dot(self._w.val) + self._b.val # act = self._act_class(None, None) # self._push(x, act) # return act.forward(linear) # # def backward(self, grad): # x, act = self._pop() # linear_grad = act.backward(grad) # # self._b.set_grad(linear_grad.sum(0)) # self._w.set_grad(x.T.dot(linear_grad)) # return linear_grad.dot(self._w.val.T) # # Path: src/modules/activations.py # class softplus(Activate): # def transform(self, x): # self.activation = np.log(1 + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = 1 - np.exp(-a) # return np.multiply(grad, p) # # class tanh(Activate): # def transform(self, x): # self.activation = np.tanh(x) # # def backward(self, grad): # a = self.activation # p = 1 - np.multiply(a, a) # return np.multiply(grad, p) # # class sigmoid(Activate): # def transform(self, x): # self.activation = 1. / (1. + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = np.multiply(a, 1. - a) # return np.multiply(grad, p) # # class softmax(Activate): # def transform(self, x): # row_max = x.max(1, keepdims = True) # e_x = np.exp(x - row_max) # e_sum = e_x.sum(1, keepdims = True) # self.activation = np.divide(e_x, e_sum) # # def backward(self, grad): # a = self.activation # m = np.multiply(grad, a) # g = grad - m.sum(1, keepdims = True) # return np.multiply(g, a) # # class relu(Activate): # def transform(self, x): # self.activation = x * (x > 0.) # # def backward(self, grad): # p = self.activation > 0. # return np.multiply(grad, p) . Output only the next line.
'sharp': sharpen(), # sharpen
Given snippet: <|code_start|> class ntm_attend(Recurring): def _setup(self, server, lstm_size, vec_size, shift): self._gates = dict({ 'k': gate(server, (lstm_size, vec_size), None, sigmoid), # key gate 'b': gate(server, (lstm_size, 1), None, softplus), # strength gate 'i': gate(server, (lstm_size, 1), None, sigmoid), # interpolate gate 'r': gate(server, (lstm_size, 2 * shift + 1), None, softmax), # rotate gate 's': gate(server, (lstm_size, 1), None, relu) # sharpen gate }) self._mechanic = dict({ # mechanics 'cos': cosine_sim(), # similarity 'soft': normalise(), # softmax 'inter': interpolate(), # interpolate 'rotate': circular_conv(), # circular conv 'sharp': sharpen(), # sharpen }) def _flush(self): for g in self._gates: self._gates[g].flush() for m in self._mechanic: self._mechanic[m].flush() def forward(self, memory, lstm_h, w_prev): <|code_end|> , continue by predicting the next line. Consider current file imports: from .recurring import Recurring, gate from .activations import softplus, tanh, sigmoid, softmax, relu from .mechanics import * and context: # Path: src/modules/recurring.py # class Recurring(Module): # """ # Recurring is a type of module that cache intermediate # activations in a stack during unrolling of recurrent layers # Its backward() is expected to be called several times during # Back Propagation Through Time, either full or truncated. # """ # def __init__(self, *args, **kwargs): # self._stack = list() # self._setup(*args, **kwargs) # # def _setup(*args, **kwargs): # pass # # def _push(self, *objs): # objs = list(objs) # if len(objs) == 1: # objs = objs[0] # self._stack.append(objs) # # def _pop(self): # objs = self._stack[-1] # del self._stack[-1] # return objs # # def flush(self): # self._stack = list() # self._flush() # # def _flush(self): pass # # class gate(Recurring): # """ # Gates are special case of Recurring modules # It starts with a linear transformation (matmul) # And ends with a (typically) nonlinear activation # """ # def _setup(self, server, w_shape, bias = None, # act_class = sigmoid, transfer = None): # if transfer is None: # b_shape = (w_shape[-1],) # w_init = xavier(w_shape) # if bias is not None: # b_init = np.ones(b_shape) * bias # elif bias is None: # b_init = guass(0., 1e-1, b_shape) # else: w_init, b_init = transfer # # self._act_class = act_class # self._w = server.issue_var_slot(w_init, True) # self._b = server.issue_var_slot(b_init, True) # # def forward(self, x): # linear = x.dot(self._w.val) + self._b.val # act = self._act_class(None, None) # self._push(x, act) # return act.forward(linear) # # def backward(self, grad): # x, act = self._pop() # linear_grad = act.backward(grad) # # self._b.set_grad(linear_grad.sum(0)) # self._w.set_grad(x.T.dot(linear_grad)) # return linear_grad.dot(self._w.val.T) # # Path: src/modules/activations.py # class softplus(Activate): # def transform(self, x): # self.activation = np.log(1 + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = 1 - np.exp(-a) # return np.multiply(grad, p) # # class tanh(Activate): # def transform(self, x): # self.activation = np.tanh(x) # # def backward(self, grad): # a = self.activation # p = 1 - np.multiply(a, a) # return np.multiply(grad, p) # # class sigmoid(Activate): # def transform(self, x): # self.activation = 1. / (1. + np.exp(-x)) # # def backward(self, grad): # a = self.activation # p = np.multiply(a, 1. - a) # return np.multiply(grad, p) # # class softmax(Activate): # def transform(self, x): # row_max = x.max(1, keepdims = True) # e_x = np.exp(x - row_max) # e_sum = e_x.sum(1, keepdims = True) # self.activation = np.divide(e_x, e_sum) # # def backward(self, grad): # a = self.activation # m = np.multiply(grad, a) # g = grad - m.sum(1, keepdims = True) # return np.multiply(g, a) # # class relu(Activate): # def transform(self, x): # self.activation = x * (x > 0.) # # def backward(self, grad): # p = self.activation > 0. # return np.multiply(grad, p) which might include code, classes, or functions. Output only the next line.
gates_vals = list()
Using the snippet: <|code_start|> return result def backward(self, grad): a = self._pop() m = np.multiply(grad, a) g = grad - m.sum(-1, keepdims = True) return np.multiply(g, a) class interpolate(Recurring): def forward(self, new, prev, alpha): self._push(new, prev, alpha) result = alpha * new + (1. - alpha) * prev return result def backward(self, grad): new, prev, alpha = self._pop() grad_alpha = (grad * (new - prev)).sum(-1, keepdims = True) grad_prev = grad * (1. - alpha) grad_new = grad * alpha return grad_new, grad_prev, grad_alpha class circular_conv(Recurring): def forward(self, x, kernel): s = kernel.shape[1] // 2 k = np.arange(-s, s + 1) patches = list() M = x.shape[-1] for i in range(M): patches += [x[:, (k + i) % M]] self._push(patches, kernel, k) <|code_end|> , determine the next line of code. You have imports: from .recurring import Recurring import numpy as np and context (class names, function names, or code) available: # Path: src/modules/recurring.py # class Recurring(Module): # """ # Recurring is a type of module that cache intermediate # activations in a stack during unrolling of recurrent layers # Its backward() is expected to be called several times during # Back Propagation Through Time, either full or truncated. # """ # def __init__(self, *args, **kwargs): # self._stack = list() # self._setup(*args, **kwargs) # # def _setup(*args, **kwargs): # pass # # def _push(self, *objs): # objs = list(objs) # if len(objs) == 1: # objs = objs[0] # self._stack.append(objs) # # def _pop(self): # objs = self._stack[-1] # del self._stack[-1] # return objs # # def flush(self): # self._stack = list() # self._flush() # # def _flush(self): pass . Output only the next line.
cols = list()
Based on the snippet: <|code_start|> class linear(Activate): def transform(self, x): self.activation = x def backward(self, grad): return grad class relu(Activate): def transform(self, x): self.activation = x * (x > 0.) def backward(self, grad): p = self.activation > 0. return np.multiply(grad, p) class softmax(Activate): def transform(self, x): row_max = x.max(1, keepdims = True) e_x = np.exp(x - row_max) e_sum = e_x.sum(1, keepdims = True) self.activation = np.divide(e_x, e_sum) def backward(self, grad): a = self.activation m = np.multiply(grad, a) g = grad - m.sum(1, keepdims = True) <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from .module import Module and context (classes, functions, sometimes code) from other files: # Path: src/modules/module.py # class Module(object): # def __init__(self, *args): pass # # def forward(self, *args): pass # # def backward(self, grad): pass # # @property # def out_shape(self): # return tuple(self._out_shape) # # def unit_test(self, x, y): # GradientChecker.check(self, x, y) . Output only the next line.
return np.multiply(g, a)
Given the code snippet: <|code_start|> class Slider(Environment): def __init__(self): self._trace = list() self._reset() @property def ball_colour(self): return self._colour def react(self, control_left, control_right): self._slide = (control_left, control_right) acceleration = control_left - control_right self._controls = (control_left, control_right) self._ball_x += 1e-3 * self._ball_v <|code_end|> , generate the next line using the imports in this file: from src.utils.misc import uniform from .env import Environment import numpy as np import cv2 and context (functions, classes, or occasionally code) from other files: # Path: src/utils/misc.py # def accuracy(predict, truth): # def read_mnist(): # def xavier(shape): # def extract(name, dfault, **kwargs): # def nxshape(volume, shape): # def parse_for(class_type, *args): # # Path: src/gyms/env.py # class Environment(object): # # _w = _h = 256 # _canvas = np.ones((_w, _h, 3)) # _canvas *= 255. # # def __init__(self): # pass # # def react(self): # pass # # def appearance(self): # pass # # def _reset(self): # pass # # def viz(self, waitKey = 1): # self.visualize() # return cv2.waitKey(waitKey) . Output only the next line.
self._ball_v += .1 * acceleration
Predict the next line after this snippet: <|code_start|> class Slider(Environment): def __init__(self): self._trace = list() self._reset() @property def ball_colour(self): return self._colour def react(self, control_left, control_right): self._slide = (control_left, control_right) acceleration = control_left - control_right self._controls = (control_left, control_right) self._ball_x += 1e-3 * self._ball_v self._ball_v += .1 * acceleration x = self._ball_x if x < 0. or x > 1.: if (0.5 - x) * (0.5 - self._colour) > 0.: self._trace.append(str(self._colour)) else: <|code_end|> using the current file's imports: from src.utils.misc import uniform from .env import Environment import numpy as np import cv2 and any relevant context from other files: # Path: src/utils/misc.py # def accuracy(predict, truth): # def read_mnist(): # def xavier(shape): # def extract(name, dfault, **kwargs): # def nxshape(volume, shape): # def parse_for(class_type, *args): # # Path: src/gyms/env.py # class Environment(object): # # _w = _h = 256 # _canvas = np.ones((_w, _h, 3)) # _canvas *= 255. # # def __init__(self): # pass # # def react(self): # pass # # def appearance(self): # pass # # def _reset(self): # pass # # def viz(self, waitKey = 1): # self.visualize() # return cv2.waitKey(waitKey) . Output only the next line.
self._trace.append('_')
Next line prediction: <|code_start|> erase_comp = 1. - erase new_mem = memory * erase_comp + write # push to recurrent stack self._push( memory, e, a, w_read, w_write, erase_comp) return mem_read, new_mem def backward(self, g_memread, g_newmem): memory, e, a, w_read, w_write, erase_comp = self._pop() gm = np.einsum('bn,bm->bnm', w_read, g_memread) gr = np.einsum('bnm,bm->bn', memory, g_memread) # grad flow through new_mem ge_m = g_newmem * erase_comp g_erase = -1. * g_newmem * memory # grad flow through eraser g_e = np.einsum('bnm,bn->bm', g_erase, w_write) g_ew = np.einsum('bnm,bm->bn', g_erase, e) # grad flow through writer g_a = np.einsum('bnm,bn->bm', g_newmem, w_write) g_aw = np.einsum('bnm,bm->bn', g_newmem, a) # grad flow though gates g_he = self._gates['f'].backward(g_e) g_ha = self._gates['a'].backward(g_a) # summing grads gm = gm + ge_m gw = g_ew + g_aw gh = g_he + g_ha <|code_end|> . Use current file imports: (from .recurring import Recurring, gate from .activations import * import numpy as np) and context including class names, function names, or small code snippets from other files: # Path: src/modules/recurring.py # class Recurring(Module): # """ # Recurring is a type of module that cache intermediate # activations in a stack during unrolling of recurrent layers # Its backward() is expected to be called several times during # Back Propagation Through Time, either full or truncated. # """ # def __init__(self, *args, **kwargs): # self._stack = list() # self._setup(*args, **kwargs) # # def _setup(*args, **kwargs): # pass # # def _push(self, *objs): # objs = list(objs) # if len(objs) == 1: # objs = objs[0] # self._stack.append(objs) # # def _pop(self): # objs = self._stack[-1] # del self._stack[-1] # return objs # # def flush(self): # self._stack = list() # self._flush() # # def _flush(self): pass # # class gate(Recurring): # """ # Gates are special case of Recurring modules # It starts with a linear transformation (matmul) # And ends with a (typically) nonlinear activation # """ # def _setup(self, server, w_shape, bias = None, # act_class = sigmoid, transfer = None): # if transfer is None: # b_shape = (w_shape[-1],) # w_init = xavier(w_shape) # if bias is not None: # b_init = np.ones(b_shape) * bias # elif bias is None: # b_init = guass(0., 1e-1, b_shape) # else: w_init, b_init = transfer # # self._act_class = act_class # self._w = server.issue_var_slot(w_init, True) # self._b = server.issue_var_slot(b_init, True) # # def forward(self, x): # linear = x.dot(self._w.val) + self._b.val # act = self._act_class(None, None) # self._push(x, act) # return act.forward(linear) # # def backward(self, grad): # x, act = self._pop() # linear_grad = act.backward(grad) # # self._b.set_grad(linear_grad.sum(0)) # self._w.set_grad(x.T.dot(linear_grad)) # return linear_grad.dot(self._w.val.T) . Output only the next line.
return gh, gr, gw, gm
Given the following code snippet before the placeholder: <|code_start|>class ntm_memory(Recurring): def _setup(self, server, lstm_size, mem_size, vec_size): self._size = (mem_size, vec_size) self._gates = dict({ 'f': gate(server, (lstm_size, vec_size), 1.5, sigmoid), # forget 'a': gate(server, (lstm_size, vec_size), None, tanh) # add }) def _flush(self): self._gates['f'].flush() self._gates['a'].flush() def forward(self, h_lstm, w_read, w_write, memory): # read mem_read = np.einsum('bnm,bn->bm', memory, w_read) # erase & add e = self._gates['f'].forward(h_lstm) # vec_size a = self._gates['a'].forward(h_lstm) # vec_size erase = w_write[:, :, None] * e[:, None, :] write = w_write[:, :, None] * a[:, None, :] erase_comp = 1. - erase new_mem = memory * erase_comp + write # push to recurrent stack self._push( memory, e, a, w_read, w_write, erase_comp) return mem_read, new_mem def backward(self, g_memread, g_newmem): <|code_end|> , predict the next line using imports from the current file: from .recurring import Recurring, gate from .activations import * import numpy as np and context including class names, function names, and sometimes code from other files: # Path: src/modules/recurring.py # class Recurring(Module): # """ # Recurring is a type of module that cache intermediate # activations in a stack during unrolling of recurrent layers # Its backward() is expected to be called several times during # Back Propagation Through Time, either full or truncated. # """ # def __init__(self, *args, **kwargs): # self._stack = list() # self._setup(*args, **kwargs) # # def _setup(*args, **kwargs): # pass # # def _push(self, *objs): # objs = list(objs) # if len(objs) == 1: # objs = objs[0] # self._stack.append(objs) # # def _pop(self): # objs = self._stack[-1] # del self._stack[-1] # return objs # # def flush(self): # self._stack = list() # self._flush() # # def _flush(self): pass # # class gate(Recurring): # """ # Gates are special case of Recurring modules # It starts with a linear transformation (matmul) # And ends with a (typically) nonlinear activation # """ # def _setup(self, server, w_shape, bias = None, # act_class = sigmoid, transfer = None): # if transfer is None: # b_shape = (w_shape[-1],) # w_init = xavier(w_shape) # if bias is not None: # b_init = np.ones(b_shape) * bias # elif bias is None: # b_init = guass(0., 1e-1, b_shape) # else: w_init, b_init = transfer # # self._act_class = act_class # self._w = server.issue_var_slot(w_init, True) # self._b = server.issue_var_slot(b_init, True) # # def forward(self, x): # linear = x.dot(self._w.val) + self._b.val # act = self._act_class(None, None) # self._push(x, act) # return act.forward(linear) # # def backward(self, grad): # x, act = self._pop() # linear_grad = act.backward(grad) # # self._b.set_grad(linear_grad.sum(0)) # self._w.set_grad(x.T.dot(linear_grad)) # return linear_grad.dot(self._w.val.T) . Output only the next line.
memory, e, a, w_read, w_write, erase_comp = self._pop()
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # Copyright 2015 Cyan, Inc. # Copyright 2017, 2018 Ciena Corporation. class TestUtil(unittest.TestCase): def test_write_int_string(self): self.assertEqual( util.write_int_string(b'some string'), b'\x00\x00\x00\x0bsome string', ) def test_write_int_string__empty(self): self.assertEqual( util.write_int_string(b''), b'\x00\x00\x00\x00', ) def test_write_int_string__null(self): <|code_end|> , predict the next line using imports from the current file: import struct import unittest import afkak.common from afkak import _util as util from afkak.common import BufferUnderflowError and context including class names, function names, and sometimes code from other files: # Path: afkak/_util.py # _NULL_SHORT_STRING = struct.pack('>h', -1) # def _buffer_underflow(what, buf, offset, size): # def _coerce_topic(topic): # def _coerce_consumer_group(consumer_group): # def _coerce_client_id(client_id): # def write_int_string(s): # def write_short_ascii(s): # def write_short_text(s): # def write_short_bytes(b): # def read_short_bytes(data, cur): # def read_short_ascii(data, cur): # def read_short_text(data, cur): # def read_int_string(data, cur): # def relative_unpack(fmt, data, cur): # def group_by_topic_and_partition(tuples): # # Path: afkak/common.py # class BufferUnderflowError(KafkaError): # pass . Output only the next line.
self.assertEqual(
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (C) 2015 Cyan, Inc. # Copyright 2018, 2019, 2021 Ciena Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class TestCodec(unittest.TestCase): @unittest.skipUnless(has_gzip(), "Gzip not available") def test_gzip(self): <|code_end|> . Write the next line using the current file imports: import importlib import os import struct import unittest import afkak import sys from unittest.mock import patch from afkak.codec import ( gzip_decode, gzip_encode, has_gzip, has_snappy, snappy_decode, snappy_encode, ) and context from other files: # Path: afkak/codec.py # def gzip_decode(payload): # buffer = BytesIO(payload) # handle = gzip.GzipFile(fileobj=buffer, mode='r') # result = handle.read() # handle.close() # buffer.close() # return result # # def gzip_encode(payload): # buffer = BytesIO() # handle = gzip.GzipFile(fileobj=buffer, mode="w") # handle.write(payload) # handle.close() # return buffer.getvalue() # # def has_gzip(): # return True # # def has_snappy(): # return _has_snappy # # def snappy_decode(payload): # if not has_snappy(): # raise NotImplementedError("Snappy codec is not available") # # if payload.startswith(_XERIAL_HEADER): # # TODO ? Should become a fileobj ? # view = memoryview(payload) # out = [] # length = len(payload) # # cursor = 16 # while cursor < length: # block_size = struct.unpack_from('!i', view, cursor)[0] # # Skip the block size # cursor += 4 # end = cursor + block_size # # XXX snappy requires a bytes-like object but doesn't accept # # a memoryview, so we must copy. # out.append(snappy.decompress(view[cursor:end].tobytes())) # cursor = end # # # See https://atleastfornow.net/blog/not-all-bytes/ # return b''.join(out) # else: # return snappy.decompress(payload) # # def snappy_encode(payload, xerial_compatible=False, # xerial_blocksize=32 * 1024): # """ # Compress the given data with the Snappy algorithm. # # :param bytes payload: Data to compress. # :param bool xerial_compatible: # If set then the stream is broken into length-prefixed blocks in # a fashion compatible with the xerial snappy library. # # The format winds up being:: # # +-------------+------------+--------------+------------+--------------+ # | Header | Block1_len | Block1 data | BlockN len | BlockN data | # |-------------+------------+--------------+------------+--------------| # | 16 bytes | BE int32 | snappy bytes | BE int32 | snappy bytes | # +-------------+------------+--------------+------------+--------------+ # # :param int xerial_blocksize: # Number of bytes per chunk to independently Snappy encode. 32k is the # default in the xerial library. # # :returns: Compressed bytes. # :rtype: :class:`bytes` # """ # if not has_snappy(): # FIXME This should be static, not checked every call. # raise NotImplementedError("Snappy codec is not available") # # if xerial_compatible: # def _chunker(): # for i in range(0, len(payload), xerial_blocksize): # yield payload[i:i+xerial_blocksize] # # out = BytesIO() # out.write(_XERIAL_HEADER) # # for chunk in _chunker(): # block = snappy.compress(chunk) # out.write(struct.pack('!i', len(block))) # out.write(block) # # out.seek(0) # return out.read() # # else: # return snappy.compress(payload) , which may include functions, classes, or code. Output only the next line.
for _i in range(100):
Based on the snippet: <|code_start|> block_len2 = len(random_snappy2) to_test = header \ + struct.pack('!i', block_len) + random_snappy \ + struct.pack('!i', block_len2) + random_snappy2 \ self.assertEqual( snappy_decode(to_test), (b'SNAPPY' * 50) + (b'XERIAL' * 50)) @unittest.skipUnless(has_snappy(), "Snappy not available") def test_snappy_encode_xerial(self): to_ensure = ( b'\x82SNAPPY\x00\x00\x00\x00\x01\x00\x00\x00\x01' b'\x00\x00\x00\x18' b'\xac\x02\x14SNAPPY\xfe\x06\x00\xfe\x06' b'\x00\xfe\x06\x00\xfe\x06\x00\x96\x06\x00' b'\x00\x00\x00\x18' b'\xac\x02\x14XERIAL\xfe\x06\x00\xfe\x06\x00' b'\xfe\x06\x00\xfe\x06\x00\x96\x06\x00') to_test = (b'SNAPPY' * 50) + (b'XERIAL' * 50) compressed = snappy_encode( to_test, xerial_compatible=True, xerial_blocksize=300) self.assertEqual(compressed, to_ensure) @unittest.skipUnless(has_snappy(), "Snappy not available") def test_snappy_raises_when_not_present(self): with patch.object(afkak.codec, 'has_snappy', return_value=False): <|code_end|> , predict the immediate next line with the help of imports: import importlib import os import struct import unittest import afkak import sys from unittest.mock import patch from afkak.codec import ( gzip_decode, gzip_encode, has_gzip, has_snappy, snappy_decode, snappy_encode, ) and context (classes, functions, sometimes code) from other files: # Path: afkak/codec.py # def gzip_decode(payload): # buffer = BytesIO(payload) # handle = gzip.GzipFile(fileobj=buffer, mode='r') # result = handle.read() # handle.close() # buffer.close() # return result # # def gzip_encode(payload): # buffer = BytesIO() # handle = gzip.GzipFile(fileobj=buffer, mode="w") # handle.write(payload) # handle.close() # return buffer.getvalue() # # def has_gzip(): # return True # # def has_snappy(): # return _has_snappy # # def snappy_decode(payload): # if not has_snappy(): # raise NotImplementedError("Snappy codec is not available") # # if payload.startswith(_XERIAL_HEADER): # # TODO ? Should become a fileobj ? # view = memoryview(payload) # out = [] # length = len(payload) # # cursor = 16 # while cursor < length: # block_size = struct.unpack_from('!i', view, cursor)[0] # # Skip the block size # cursor += 4 # end = cursor + block_size # # XXX snappy requires a bytes-like object but doesn't accept # # a memoryview, so we must copy. # out.append(snappy.decompress(view[cursor:end].tobytes())) # cursor = end # # # See https://atleastfornow.net/blog/not-all-bytes/ # return b''.join(out) # else: # return snappy.decompress(payload) # # def snappy_encode(payload, xerial_compatible=False, # xerial_blocksize=32 * 1024): # """ # Compress the given data with the Snappy algorithm. # # :param bytes payload: Data to compress. # :param bool xerial_compatible: # If set then the stream is broken into length-prefixed blocks in # a fashion compatible with the xerial snappy library. # # The format winds up being:: # # +-------------+------------+--------------+------------+--------------+ # | Header | Block1_len | Block1 data | BlockN len | BlockN data | # |-------------+------------+--------------+------------+--------------| # | 16 bytes | BE int32 | snappy bytes | BE int32 | snappy bytes | # +-------------+------------+--------------+------------+--------------+ # # :param int xerial_blocksize: # Number of bytes per chunk to independently Snappy encode. 32k is the # default in the xerial library. # # :returns: Compressed bytes. # :rtype: :class:`bytes` # """ # if not has_snappy(): # FIXME This should be static, not checked every call. # raise NotImplementedError("Snappy codec is not available") # # if xerial_compatible: # def _chunker(): # for i in range(0, len(payload), xerial_blocksize): # yield payload[i:i+xerial_blocksize] # # out = BytesIO() # out.write(_XERIAL_HEADER) # # for chunk in _chunker(): # block = snappy.compress(chunk) # out.write(struct.pack('!i', len(block))) # out.write(block) # # out.seek(0) # return out.read() # # else: # return snappy.compress(payload) . Output only the next line.
with self.assertRaises(NotImplementedError):
Using the snippet: <|code_start|> to_test = header \ + struct.pack('!i', block_len) + random_snappy \ + struct.pack('!i', block_len2) + random_snappy2 \ self.assertEqual( snappy_decode(to_test), (b'SNAPPY' * 50) + (b'XERIAL' * 50)) @unittest.skipUnless(has_snappy(), "Snappy not available") def test_snappy_encode_xerial(self): to_ensure = ( b'\x82SNAPPY\x00\x00\x00\x00\x01\x00\x00\x00\x01' b'\x00\x00\x00\x18' b'\xac\x02\x14SNAPPY\xfe\x06\x00\xfe\x06' b'\x00\xfe\x06\x00\xfe\x06\x00\x96\x06\x00' b'\x00\x00\x00\x18' b'\xac\x02\x14XERIAL\xfe\x06\x00\xfe\x06\x00' b'\xfe\x06\x00\xfe\x06\x00\x96\x06\x00') to_test = (b'SNAPPY' * 50) + (b'XERIAL' * 50) compressed = snappy_encode( to_test, xerial_compatible=True, xerial_blocksize=300) self.assertEqual(compressed, to_ensure) @unittest.skipUnless(has_snappy(), "Snappy not available") def test_snappy_raises_when_not_present(self): with patch.object(afkak.codec, 'has_snappy', return_value=False): with self.assertRaises(NotImplementedError): snappy_encode(b"Snappy not available") <|code_end|> , determine the next line of code. You have imports: import importlib import os import struct import unittest import afkak import sys from unittest.mock import patch from afkak.codec import ( gzip_decode, gzip_encode, has_gzip, has_snappy, snappy_decode, snappy_encode, ) and context (class names, function names, or code) available: # Path: afkak/codec.py # def gzip_decode(payload): # buffer = BytesIO(payload) # handle = gzip.GzipFile(fileobj=buffer, mode='r') # result = handle.read() # handle.close() # buffer.close() # return result # # def gzip_encode(payload): # buffer = BytesIO() # handle = gzip.GzipFile(fileobj=buffer, mode="w") # handle.write(payload) # handle.close() # return buffer.getvalue() # # def has_gzip(): # return True # # def has_snappy(): # return _has_snappy # # def snappy_decode(payload): # if not has_snappy(): # raise NotImplementedError("Snappy codec is not available") # # if payload.startswith(_XERIAL_HEADER): # # TODO ? Should become a fileobj ? # view = memoryview(payload) # out = [] # length = len(payload) # # cursor = 16 # while cursor < length: # block_size = struct.unpack_from('!i', view, cursor)[0] # # Skip the block size # cursor += 4 # end = cursor + block_size # # XXX snappy requires a bytes-like object but doesn't accept # # a memoryview, so we must copy. # out.append(snappy.decompress(view[cursor:end].tobytes())) # cursor = end # # # See https://atleastfornow.net/blog/not-all-bytes/ # return b''.join(out) # else: # return snappy.decompress(payload) # # def snappy_encode(payload, xerial_compatible=False, # xerial_blocksize=32 * 1024): # """ # Compress the given data with the Snappy algorithm. # # :param bytes payload: Data to compress. # :param bool xerial_compatible: # If set then the stream is broken into length-prefixed blocks in # a fashion compatible with the xerial snappy library. # # The format winds up being:: # # +-------------+------------+--------------+------------+--------------+ # | Header | Block1_len | Block1 data | BlockN len | BlockN data | # |-------------+------------+--------------+------------+--------------| # | 16 bytes | BE int32 | snappy bytes | BE int32 | snappy bytes | # +-------------+------------+--------------+------------+--------------+ # # :param int xerial_blocksize: # Number of bytes per chunk to independently Snappy encode. 32k is the # default in the xerial library. # # :returns: Compressed bytes. # :rtype: :class:`bytes` # """ # if not has_snappy(): # FIXME This should be static, not checked every call. # raise NotImplementedError("Snappy codec is not available") # # if xerial_compatible: # def _chunker(): # for i in range(0, len(payload), xerial_blocksize): # yield payload[i:i+xerial_blocksize] # # out = BytesIO() # out.write(_XERIAL_HEADER) # # for chunk in _chunker(): # block = snappy.compress(chunk) # out.write(struct.pack('!i', len(block))) # out.write(block) # # out.seek(0) # return out.read() # # else: # return snappy.compress(payload) . Output only the next line.
with self.assertRaises(NotImplementedError):
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (C) 2015 Cyan, Inc. # Copyright 2018, 2019, 2021 Ciena Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class TestCodec(unittest.TestCase): @unittest.skipUnless(has_gzip(), "Gzip not available") def test_gzip(self): for _i in range(100): s1 = os.urandom(100) s2 = gzip_decode(gzip_encode(s1)) self.assertEqual(s1, s2) @unittest.skipUnless(has_snappy(), "Snappy not available") def test_snappy(self): <|code_end|> with the help of current file imports: import importlib import os import struct import unittest import afkak import sys from unittest.mock import patch from afkak.codec import ( gzip_decode, gzip_encode, has_gzip, has_snappy, snappy_decode, snappy_encode, ) and context from other files: # Path: afkak/codec.py # def gzip_decode(payload): # buffer = BytesIO(payload) # handle = gzip.GzipFile(fileobj=buffer, mode='r') # result = handle.read() # handle.close() # buffer.close() # return result # # def gzip_encode(payload): # buffer = BytesIO() # handle = gzip.GzipFile(fileobj=buffer, mode="w") # handle.write(payload) # handle.close() # return buffer.getvalue() # # def has_gzip(): # return True # # def has_snappy(): # return _has_snappy # # def snappy_decode(payload): # if not has_snappy(): # raise NotImplementedError("Snappy codec is not available") # # if payload.startswith(_XERIAL_HEADER): # # TODO ? Should become a fileobj ? # view = memoryview(payload) # out = [] # length = len(payload) # # cursor = 16 # while cursor < length: # block_size = struct.unpack_from('!i', view, cursor)[0] # # Skip the block size # cursor += 4 # end = cursor + block_size # # XXX snappy requires a bytes-like object but doesn't accept # # a memoryview, so we must copy. # out.append(snappy.decompress(view[cursor:end].tobytes())) # cursor = end # # # See https://atleastfornow.net/blog/not-all-bytes/ # return b''.join(out) # else: # return snappy.decompress(payload) # # def snappy_encode(payload, xerial_compatible=False, # xerial_blocksize=32 * 1024): # """ # Compress the given data with the Snappy algorithm. # # :param bytes payload: Data to compress. # :param bool xerial_compatible: # If set then the stream is broken into length-prefixed blocks in # a fashion compatible with the xerial snappy library. # # The format winds up being:: # # +-------------+------------+--------------+------------+--------------+ # | Header | Block1_len | Block1 data | BlockN len | BlockN data | # |-------------+------------+--------------+------------+--------------| # | 16 bytes | BE int32 | snappy bytes | BE int32 | snappy bytes | # +-------------+------------+--------------+------------+--------------+ # # :param int xerial_blocksize: # Number of bytes per chunk to independently Snappy encode. 32k is the # default in the xerial library. # # :returns: Compressed bytes. # :rtype: :class:`bytes` # """ # if not has_snappy(): # FIXME This should be static, not checked every call. # raise NotImplementedError("Snappy codec is not available") # # if xerial_compatible: # def _chunker(): # for i in range(0, len(payload), xerial_blocksize): # yield payload[i:i+xerial_blocksize] # # out = BytesIO() # out.write(_XERIAL_HEADER) # # for chunk in _chunker(): # block = snappy.compress(chunk) # out.write(struct.pack('!i', len(block))) # out.write(block) # # out.seek(0) # return out.read() # # else: # return snappy.compress(payload) , which may contain function names, class names, or code. Output only the next line.
for _i in range(100):
Predict the next line after this snippet: <|code_start|># See the License for the specific language governing permissions and # limitations under the License. class TestCodec(unittest.TestCase): @unittest.skipUnless(has_gzip(), "Gzip not available") def test_gzip(self): for _i in range(100): s1 = os.urandom(100) s2 = gzip_decode(gzip_encode(s1)) self.assertEqual(s1, s2) @unittest.skipUnless(has_snappy(), "Snappy not available") def test_snappy(self): for _i in range(100): s1 = os.urandom(120) s2 = snappy_decode(snappy_encode(s1)) self.assertEqual(s1, s2) @unittest.skipUnless(has_snappy(), "Snappy not available") def test_snappy_decode_xerial(self): header = b'\x82SNAPPY\x00\x00\x00\x00\x01\x00\x00\x00\x01' random_snappy = snappy_encode(b'SNAPPY' * 50) block_len = len(random_snappy) random_snappy2 = snappy_encode(b'XERIAL' * 50) block_len2 = len(random_snappy2) to_test = header \ <|code_end|> using the current file's imports: import importlib import os import struct import unittest import afkak import sys from unittest.mock import patch from afkak.codec import ( gzip_decode, gzip_encode, has_gzip, has_snappy, snappy_decode, snappy_encode, ) and any relevant context from other files: # Path: afkak/codec.py # def gzip_decode(payload): # buffer = BytesIO(payload) # handle = gzip.GzipFile(fileobj=buffer, mode='r') # result = handle.read() # handle.close() # buffer.close() # return result # # def gzip_encode(payload): # buffer = BytesIO() # handle = gzip.GzipFile(fileobj=buffer, mode="w") # handle.write(payload) # handle.close() # return buffer.getvalue() # # def has_gzip(): # return True # # def has_snappy(): # return _has_snappy # # def snappy_decode(payload): # if not has_snappy(): # raise NotImplementedError("Snappy codec is not available") # # if payload.startswith(_XERIAL_HEADER): # # TODO ? Should become a fileobj ? # view = memoryview(payload) # out = [] # length = len(payload) # # cursor = 16 # while cursor < length: # block_size = struct.unpack_from('!i', view, cursor)[0] # # Skip the block size # cursor += 4 # end = cursor + block_size # # XXX snappy requires a bytes-like object but doesn't accept # # a memoryview, so we must copy. # out.append(snappy.decompress(view[cursor:end].tobytes())) # cursor = end # # # See https://atleastfornow.net/blog/not-all-bytes/ # return b''.join(out) # else: # return snappy.decompress(payload) # # def snappy_encode(payload, xerial_compatible=False, # xerial_blocksize=32 * 1024): # """ # Compress the given data with the Snappy algorithm. # # :param bytes payload: Data to compress. # :param bool xerial_compatible: # If set then the stream is broken into length-prefixed blocks in # a fashion compatible with the xerial snappy library. # # The format winds up being:: # # +-------------+------------+--------------+------------+--------------+ # | Header | Block1_len | Block1 data | BlockN len | BlockN data | # |-------------+------------+--------------+------------+--------------| # | 16 bytes | BE int32 | snappy bytes | BE int32 | snappy bytes | # +-------------+------------+--------------+------------+--------------+ # # :param int xerial_blocksize: # Number of bytes per chunk to independently Snappy encode. 32k is the # default in the xerial library. # # :returns: Compressed bytes. # :rtype: :class:`bytes` # """ # if not has_snappy(): # FIXME This should be static, not checked every call. # raise NotImplementedError("Snappy codec is not available") # # if xerial_compatible: # def _chunker(): # for i in range(0, len(payload), xerial_blocksize): # yield payload[i:i+xerial_blocksize] # # out = BytesIO() # out.write(_XERIAL_HEADER) # # for chunk in _chunker(): # block = snappy.compress(chunk) # out.write(struct.pack('!i', len(block))) # out.write(block) # # out.seek(0) # return out.read() # # else: # return snappy.compress(payload) . Output only the next line.
+ struct.pack('!i', block_len) + random_snappy \
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (C) 2015 Cyan, Inc. # Copyright 2018, 2019, 2021 Ciena Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class TestCodec(unittest.TestCase): @unittest.skipUnless(has_gzip(), "Gzip not available") def test_gzip(self): <|code_end|> with the help of current file imports: import importlib import os import struct import unittest import afkak import sys from unittest.mock import patch from afkak.codec import ( gzip_decode, gzip_encode, has_gzip, has_snappy, snappy_decode, snappy_encode, ) and context from other files: # Path: afkak/codec.py # def gzip_decode(payload): # buffer = BytesIO(payload) # handle = gzip.GzipFile(fileobj=buffer, mode='r') # result = handle.read() # handle.close() # buffer.close() # return result # # def gzip_encode(payload): # buffer = BytesIO() # handle = gzip.GzipFile(fileobj=buffer, mode="w") # handle.write(payload) # handle.close() # return buffer.getvalue() # # def has_gzip(): # return True # # def has_snappy(): # return _has_snappy # # def snappy_decode(payload): # if not has_snappy(): # raise NotImplementedError("Snappy codec is not available") # # if payload.startswith(_XERIAL_HEADER): # # TODO ? Should become a fileobj ? # view = memoryview(payload) # out = [] # length = len(payload) # # cursor = 16 # while cursor < length: # block_size = struct.unpack_from('!i', view, cursor)[0] # # Skip the block size # cursor += 4 # end = cursor + block_size # # XXX snappy requires a bytes-like object but doesn't accept # # a memoryview, so we must copy. # out.append(snappy.decompress(view[cursor:end].tobytes())) # cursor = end # # # See https://atleastfornow.net/blog/not-all-bytes/ # return b''.join(out) # else: # return snappy.decompress(payload) # # def snappy_encode(payload, xerial_compatible=False, # xerial_blocksize=32 * 1024): # """ # Compress the given data with the Snappy algorithm. # # :param bytes payload: Data to compress. # :param bool xerial_compatible: # If set then the stream is broken into length-prefixed blocks in # a fashion compatible with the xerial snappy library. # # The format winds up being:: # # +-------------+------------+--------------+------------+--------------+ # | Header | Block1_len | Block1 data | BlockN len | BlockN data | # |-------------+------------+--------------+------------+--------------| # | 16 bytes | BE int32 | snappy bytes | BE int32 | snappy bytes | # +-------------+------------+--------------+------------+--------------+ # # :param int xerial_blocksize: # Number of bytes per chunk to independently Snappy encode. 32k is the # default in the xerial library. # # :returns: Compressed bytes. # :rtype: :class:`bytes` # """ # if not has_snappy(): # FIXME This should be static, not checked every call. # raise NotImplementedError("Snappy codec is not available") # # if xerial_compatible: # def _chunker(): # for i in range(0, len(payload), xerial_blocksize): # yield payload[i:i+xerial_blocksize] # # out = BytesIO() # out.write(_XERIAL_HEADER) # # for chunk in _chunker(): # block = snappy.compress(chunk) # out.write(struct.pack('!i', len(block))) # out.write(block) # # out.seek(0) # return out.read() # # else: # return snappy.compress(payload) , which may contain function names, class names, or code. Output only the next line.
for _i in range(100):
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright 2014, 2015 Cyan, Inc. # Copyright 2018, 2019, 2021 Ciena Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def get_open_port(): sock = socket.socket() sock.bind(("", 0)) port = sock.getsockname()[1] <|code_end|> with the help of current file imports: import logging import os import os.path import re import shutil import socket import subprocess import tempfile import uuid from datetime import datetime from urllib.parse import urlparse from afkak.test.int.service import ExternalService, SpawnedService from afkak.test.testutil import random_string and context from other files: # Path: afkak/test/int/service.py # class ExternalService(object): # pragma: no cover # def __init__(self, host, port): # log.info("Using already running service at %s:%d", host, port) # self.host = host # self.port = port # # def open(self): # pass # # def close(self): # pass # # class SpawnedService(object): # _thread = None # # def __init__(self, name, log, args, env, start_re): # self._name = name # self._log = log # self._args = args # self._env = env # self._start_re = start_re # self._started = threading.Event() # self._should_die = threading.Event() # # def _run(self): # self._log.debug("Starting args=%r env=%s", self._args, pformat(self._env)) # proc = subprocess.Popen( # self._args, # env=self._env, # bufsize=1, # Line buffered. # stdout=subprocess.PIPE, # stderr=subprocess.STDOUT, # ) # # stop_deadline = None # closed = False # killed = False # while True: # if closed: # proc.wait() # else: # (rds, _, _) = select.select([proc.stdout], [], [], 0.01) # # if proc.stdout in rds: # line = proc.stdout.readline().decode('utf-8', 'backslashescape') # if line: # self._log.debug(line.rstrip('\r\n')) # if self._start_re.search(line): # self._log.debug("Marking subprocess started") # self._started.set() # else: # proc.stdout.close() # closed = True # self._log.debug("Subprocess stdout closed") # continue # Loop around to read any more output. # # returncode = proc.poll() # if stop_deadline is None: # if self._should_die.is_set(): # self._log.info("Terminating subprocess") # proc.terminate() # stop_deadline = datetime.utcnow() + _STOP_TIMEOUT # # if returncode is not None: # self._log.critical("Subprocess with args=%r, env=%r has died unexpectedly: returncode=%d", # self._args, self._env, returncode) # raise Exception("Subprocess died unexpectedly with status {!r}".format(returncode)) # else: # if returncode is not None: # self._log.info("Subprocess exited: returncode=%d", returncode) # break # # if not killed and datetime.utcnow() > stop_deadline: # log.error( # 'Child process %r failed to exit within %d. Resorting to kill.', # proc, _STOP_TIMEOUT, # ) # proc.kill() # killed = True # # def start(self, timeout=10): # assert self._thread is None # # def run(): # try: # self._run() # except BaseException: # self._log.exception("Unhandled exception in fixture thread %r", self._thread) # os.kill(os.getpid(), 9) # # self._thread = threading.Thread(target=run, name=self._name) # self._thread.start() # started = self._started.wait(timeout) # if not started: # self._log.error("Waiting for start timed out after %.2fs: terminating.", timeout) # self.stop() # raise Exception("start() timed out after {:.2f}s".format(timeout)) # # def stop(self): # assert self._thread is not None # self._should_die.set() # self._thread.join() # # Path: afkak/test/testutil.py # def random_string(length): # # Random.choice can be very slow for large amounts of data, so 'cheat' # if length <= 50: # s = "".join(random.choice(string.ascii_letters) for _i in range(length)) # else: # r = random_string(50) # s = "".join(r for i in range(length // 50)) # if length % 50: # s += r[0:(length % 50)] # assert len(s) == length # return s , which may contain function names, class names, or code. Output only the next line.
sock.close()
Given the following code snippet before the placeholder: <|code_start|> type=int, default=(100 if mode == tf.contrib.learn.ModeKeys.EVAL else None), help="Maximum number of {} steps".format(mode)) adder.add_flag( "min_eval_frequency", type=int, default=1, help="Minimum evaluation frequency in number of train steps") estimator = def_estimator(distributed) def_train_input_fn = def_def_train_input_fn(batch_inputs, prepare_filename_queues) def_eval_input_fn = def_def_eval_input_fn(batch_inputs, prepare_filename_queues) def def_experiment_fn(model_fn, train_input_fn, eval_input_fn=None, serving_input_fn=None): def experiment_fn(output_dir): return tf.contrib.learn.Experiment( estimator(model_fn, output_dir), def_train_input_fn(train_input_fn), def_eval_input_fn(eval_input_fn or train_input_fn), export_strategies=(serving_input_fn and [ tf.contrib.learn.make_export_strategy(serving_input_fn), ]), **adder.flags) return experiment_fn <|code_end|> , predict the next line using imports from the current file: import tensorflow as tf from .flag import FlagAdder from .estimator import def_estimator from .inputs import def_def_train_input_fn, def_def_eval_input_fn and context including class names, function names, and sometimes code from other files: # Path: qnd/flag.py # class FlagAdder: # """Manage addition of flags.""" # # def __init__(self): # """Create a `FlagAdder` instance.""" # self._flags = [] # # def add_flag(self, name, *args, **kwargs): # """Add a flag. # # See `add_flag()`. # """ # add_flag(name, *args, **kwargs) # self._flags.append(kwargs.get("dest") or name) # # def add_required_flag(self, name, *args, **kwargs): # """Add a required flag. # # See `add_required_flag()`. # """ # self.add_flag(name, *args, required=True, **kwargs) # # @property # def flags(self): # """Get added flags. # # - Returns # - `dict` of flag names to values added by a `FlagAdder` instance. # """ # return {flag: getattr(FLAGS, flag) for flag in self._flags} # # Path: qnd/estimator.py # def def_estimator(distributed=False): # config = def_config(distributed) # # @util.func_scope # def estimator(model_fn, model_dir): # return tf.contrib.learn.Estimator(_wrap_model_fn(model_fn), # config=config(), # model_dir=model_dir) # # return estimator # # Path: qnd/inputs.py # DEFAULT_BATCH_SIZE = 64 # MODES = [tf.contrib.learn.ModeKeys.TRAIN, # tf.contrib.learn.ModeKeys.EVAL, # tf.contrib.learn.ModeKeys.INFER] # def _add_file_flag(mode): # def def_def_def_input_fn(mode): # def def_def_input_fn(batch_inputs=True, prepare_filename_queues=True): # def def_input_fn(user_input_fn): # def input_fn(): # def _batch_inputs(inputs, mode): # def _batch_merged_inputs(inputs, mode): # def _shuffle(inputs, capacity, min_after_dequeue, num_threads): # def _merge_dicts(*dicts): # def _check_inputs(inputs): # def def_filenames_to_queue(mode): # def filenames_to_queue(filenames): . Output only the next line.
return def_experiment_fn
Using the snippet: <|code_start|> distributed=False): adder = FlagAdder() for mode in [tf.contrib.learn.ModeKeys.TRAIN, tf.contrib.learn.ModeKeys.EVAL]: adder.add_flag( "{}_steps".format(mode), type=int, default=(100 if mode == tf.contrib.learn.ModeKeys.EVAL else None), help="Maximum number of {} steps".format(mode)) adder.add_flag( "min_eval_frequency", type=int, default=1, help="Minimum evaluation frequency in number of train steps") estimator = def_estimator(distributed) def_train_input_fn = def_def_train_input_fn(batch_inputs, prepare_filename_queues) def_eval_input_fn = def_def_eval_input_fn(batch_inputs, prepare_filename_queues) def def_experiment_fn(model_fn, train_input_fn, eval_input_fn=None, serving_input_fn=None): def experiment_fn(output_dir): return tf.contrib.learn.Experiment( estimator(model_fn, output_dir), def_train_input_fn(train_input_fn), def_eval_input_fn(eval_input_fn or train_input_fn), <|code_end|> , determine the next line of code. You have imports: import tensorflow as tf from .flag import FlagAdder from .estimator import def_estimator from .inputs import def_def_train_input_fn, def_def_eval_input_fn and context (class names, function names, or code) available: # Path: qnd/flag.py # class FlagAdder: # """Manage addition of flags.""" # # def __init__(self): # """Create a `FlagAdder` instance.""" # self._flags = [] # # def add_flag(self, name, *args, **kwargs): # """Add a flag. # # See `add_flag()`. # """ # add_flag(name, *args, **kwargs) # self._flags.append(kwargs.get("dest") or name) # # def add_required_flag(self, name, *args, **kwargs): # """Add a required flag. # # See `add_required_flag()`. # """ # self.add_flag(name, *args, required=True, **kwargs) # # @property # def flags(self): # """Get added flags. # # - Returns # - `dict` of flag names to values added by a `FlagAdder` instance. # """ # return {flag: getattr(FLAGS, flag) for flag in self._flags} # # Path: qnd/estimator.py # def def_estimator(distributed=False): # config = def_config(distributed) # # @util.func_scope # def estimator(model_fn, model_dir): # return tf.contrib.learn.Estimator(_wrap_model_fn(model_fn), # config=config(), # model_dir=model_dir) # # return estimator # # Path: qnd/inputs.py # DEFAULT_BATCH_SIZE = 64 # MODES = [tf.contrib.learn.ModeKeys.TRAIN, # tf.contrib.learn.ModeKeys.EVAL, # tf.contrib.learn.ModeKeys.INFER] # def _add_file_flag(mode): # def def_def_def_input_fn(mode): # def def_def_input_fn(batch_inputs=True, prepare_filename_queues=True): # def def_input_fn(user_input_fn): # def input_fn(): # def _batch_inputs(inputs, mode): # def _batch_merged_inputs(inputs, mode): # def _shuffle(inputs, capacity, min_after_dequeue, num_threads): # def _merge_dicts(*dicts): # def _check_inputs(inputs): # def def_filenames_to_queue(mode): # def filenames_to_queue(filenames): . Output only the next line.
export_strategies=(serving_input_fn and [
Predict the next line for this snippet: <|code_start|> adder.add_flag( "{}_steps".format(mode), type=int, default=(100 if mode == tf.contrib.learn.ModeKeys.EVAL else None), help="Maximum number of {} steps".format(mode)) adder.add_flag( "min_eval_frequency", type=int, default=1, help="Minimum evaluation frequency in number of train steps") estimator = def_estimator(distributed) def_train_input_fn = def_def_train_input_fn(batch_inputs, prepare_filename_queues) def_eval_input_fn = def_def_eval_input_fn(batch_inputs, prepare_filename_queues) def def_experiment_fn(model_fn, train_input_fn, eval_input_fn=None, serving_input_fn=None): def experiment_fn(output_dir): return tf.contrib.learn.Experiment( estimator(model_fn, output_dir), def_train_input_fn(train_input_fn), def_eval_input_fn(eval_input_fn or train_input_fn), export_strategies=(serving_input_fn and [ tf.contrib.learn.make_export_strategy(serving_input_fn), ]), **adder.flags) <|code_end|> with the help of current file imports: import tensorflow as tf from .flag import FlagAdder from .estimator import def_estimator from .inputs import def_def_train_input_fn, def_def_eval_input_fn and context from other files: # Path: qnd/flag.py # class FlagAdder: # """Manage addition of flags.""" # # def __init__(self): # """Create a `FlagAdder` instance.""" # self._flags = [] # # def add_flag(self, name, *args, **kwargs): # """Add a flag. # # See `add_flag()`. # """ # add_flag(name, *args, **kwargs) # self._flags.append(kwargs.get("dest") or name) # # def add_required_flag(self, name, *args, **kwargs): # """Add a required flag. # # See `add_required_flag()`. # """ # self.add_flag(name, *args, required=True, **kwargs) # # @property # def flags(self): # """Get added flags. # # - Returns # - `dict` of flag names to values added by a `FlagAdder` instance. # """ # return {flag: getattr(FLAGS, flag) for flag in self._flags} # # Path: qnd/estimator.py # def def_estimator(distributed=False): # config = def_config(distributed) # # @util.func_scope # def estimator(model_fn, model_dir): # return tf.contrib.learn.Estimator(_wrap_model_fn(model_fn), # config=config(), # model_dir=model_dir) # # return estimator # # Path: qnd/inputs.py # DEFAULT_BATCH_SIZE = 64 # MODES = [tf.contrib.learn.ModeKeys.TRAIN, # tf.contrib.learn.ModeKeys.EVAL, # tf.contrib.learn.ModeKeys.INFER] # def _add_file_flag(mode): # def def_def_def_input_fn(mode): # def def_def_input_fn(batch_inputs=True, prepare_filename_queues=True): # def def_input_fn(user_input_fn): # def input_fn(): # def _batch_inputs(inputs, mode): # def _batch_merged_inputs(inputs, mode): # def _shuffle(inputs, capacity, min_after_dequeue, num_threads): # def _merge_dicts(*dicts): # def _check_inputs(inputs): # def def_filenames_to_queue(mode): # def filenames_to_queue(filenames): , which may contain function names, class names, or code. Output only the next line.
return experiment_fn
Here is a snippet: <|code_start|> def def_def_experiment_fn(batch_inputs=True, prepare_filename_queues=True, distributed=False): adder = FlagAdder() for mode in [tf.contrib.learn.ModeKeys.TRAIN, tf.contrib.learn.ModeKeys.EVAL]: adder.add_flag( "{}_steps".format(mode), type=int, default=(100 if mode == tf.contrib.learn.ModeKeys.EVAL else None), help="Maximum number of {} steps".format(mode)) adder.add_flag( "min_eval_frequency", type=int, default=1, help="Minimum evaluation frequency in number of train steps") estimator = def_estimator(distributed) def_train_input_fn = def_def_train_input_fn(batch_inputs, <|code_end|> . Write the next line using the current file imports: import tensorflow as tf from .flag import FlagAdder from .estimator import def_estimator from .inputs import def_def_train_input_fn, def_def_eval_input_fn and context from other files: # Path: qnd/flag.py # class FlagAdder: # """Manage addition of flags.""" # # def __init__(self): # """Create a `FlagAdder` instance.""" # self._flags = [] # # def add_flag(self, name, *args, **kwargs): # """Add a flag. # # See `add_flag()`. # """ # add_flag(name, *args, **kwargs) # self._flags.append(kwargs.get("dest") or name) # # def add_required_flag(self, name, *args, **kwargs): # """Add a required flag. # # See `add_required_flag()`. # """ # self.add_flag(name, *args, required=True, **kwargs) # # @property # def flags(self): # """Get added flags. # # - Returns # - `dict` of flag names to values added by a `FlagAdder` instance. # """ # return {flag: getattr(FLAGS, flag) for flag in self._flags} # # Path: qnd/estimator.py # def def_estimator(distributed=False): # config = def_config(distributed) # # @util.func_scope # def estimator(model_fn, model_dir): # return tf.contrib.learn.Estimator(_wrap_model_fn(model_fn), # config=config(), # model_dir=model_dir) # # return estimator # # Path: qnd/inputs.py # DEFAULT_BATCH_SIZE = 64 # MODES = [tf.contrib.learn.ModeKeys.TRAIN, # tf.contrib.learn.ModeKeys.EVAL, # tf.contrib.learn.ModeKeys.INFER] # def _add_file_flag(mode): # def def_def_def_input_fn(mode): # def def_def_input_fn(batch_inputs=True, prepare_filename_queues=True): # def def_input_fn(user_input_fn): # def input_fn(): # def _batch_inputs(inputs, mode): # def _batch_merged_inputs(inputs, mode): # def _shuffle(inputs, capacity, min_after_dequeue, num_threads): # def _merge_dicts(*dicts): # def _check_inputs(inputs): # def def_filenames_to_queue(mode): # def filenames_to_queue(filenames): , which may include functions, classes, or code. Output only the next line.
prepare_filename_queues)
Based on the snippet: <|code_start|> class TestOmxplayer(unittest.TestCase): omxplayer = None testfilepath1 = "TEST VIDEO-1.mp4" testfilepath2 = "TEST VIDEO-2.mp4" def setUp(self): self.omxplayer = Omxplayer("-o both") def tearDown(self): self.omxplayer.stop() <|code_end|> , predict the immediate next line with the help of imports: from simpleMediaCenter.player.Omxplayer import Omxplayer import unittest import time and context (classes, functions, sometimes code) from other files: # Path: simpleMediaCenter/player/Omxplayer.py # class Omxplayer(Player): # __logger=logging.getLogger(__name__) # __cmdline="-o both" # __playerline="omxplayer -b" # __playerstatus=0 # 0 stopped, 1 playing, 2 paused # __currentfile="" # __process=None # # keymapping = { # 'pause' : 'p', # 'quit' : 'q', # 'volume': { # 'up' : '+', # 'down' : '-' # } # } # # # def __init__(self, cmdline = "-o both"): # self.__logger.debug("Omxplayer init") # self.cmdline=cmdline # # def __resetplayer(self): # self.__logger.debug("reset Player") # self.__playerstatus=0 # self.__currentfile="" # self.__paused=False # self.__process=None # # def poll(self): # self.__logger.debug("polling") # if(self.__process is not None): # self.__logger.debug("process is not none") # self.__process.poll() # if(self.__process.returncode is not None): # self.__logger.debug("process ended") # for line in self.__process.stdout: # self.__logger.debug("stdout" + line.decode('utf-8')) # self.__resetplayer() # # # def send(self, str): # self.__logger.debug("Player send %s", str) # self.poll() # if(self.__process is not None): # self.__process.stdin.write(bytes(str, 'UTF-8')) # self.__process.stdin.flush() # # def getcmdline(self,file): # finished_cmdline = self.__playerline + " " + self.__cmdline + " '" + file + "'" # self.__logger.debug('omxplayer cmdline: ' + finished_cmdline) # return self.__playerline + " " + self.__cmdline + " '" + file + "'" # # def play(self, file): # self.poll() # self.__logger.debug("playing: %s",file) # if(self.__process is not None): # self.stop() # # line = self.getcmdline(file) # self.__process = subprocess.Popen( # shlex.split(line), # stdout=subprocess.PIPE, # stdin=subprocess.PIPE, # stderr=subprocess.STDOUT, # close_fds=True) # self.__playerstatus=1 # self.__currentfile = file # self.__paused=False # # def pause(self): # self.poll() # self.__logger.debug("pause called") # if(self.__process is not None): # self.send(self.keymapping['pause']) # if(self.__playerstatus==1): # self.__playerstatus=2 # else: # self.__playerstatus=1 # # def stop(self): # self.poll() # self.__logger.debug("stopping") # if(self.__process is not None): # self.send(self.keymapping['quit']) # try: # self.__logger.debug("waiting for process to close") # self.__process.wait(timeout=5) # except subprocess.TimeoutExpired: # self.__logger.debug("timeout occured, killing") # #self.__process.kill() # subprocess.Popen(shlex.split("killall omxplayer.bin")).wait() ##quickhack # self.__resetplayer() # self.__logger.debug("player stopped") # # def volumeUp(self): # self.poll() # self.__logger.debug("increase vol") # if(self.__process is not None): # self.send(self.keymapping['volume']['up']) # # def volumeDown(self): # self.poll() # self.__logger.debug("decrease vol") # if(self.__process is not None): # self.send(self.keymapping['volume']['down']) # # def getDict(self): # self.poll() # tempDict={} # tempDict['activePlayer'] = self.getName() # tempDict['playerStatus'] = self.__playerstatus # tempDict['currentFile'] = self.__currentfile # return tempDict . Output only the next line.
self.omxplayer=None
Here is a snippet: <|code_start|> class TestTwitchplayer(unittest.TestCase): twitchplayer = None twitchurl= "https://api.twitch.tv/kraken/streams/featured?limit=1" playurl= None def setUp(self): self.twitchplayer = Twitchplayer() tempjson = requests.get(self.twitchurl).json() #self.playurl = "twitch.tv/" self.playurl = tempjson['featured'][0]['stream']['channel']['name'] def tearDown(self): self.twitchplayer.stop() self.twitchplayer=None <|code_end|> . Write the next line using the current file imports: from simpleMediaCenter.player.Twitchplayer import Twitchplayer import unittest import time import requests and context from other files: # Path: simpleMediaCenter/player/Twitchplayer.py # class Twitchplayer(Omxplayer): # __logger=logging.getLogger(__name__) # __cmdline="-o both" # __playerline="omxplayer -b" # __playlist="twitchplaylist.m3u8" # # # def __init__(self, cmdline = "-o both"): # self.__logger.debug("Twitchplayer init") # self.__cmdline=cmdline # # # def getcmdline(self,file): # tvr = TwitchVideoResolver(self.__logger) # tvr.saveHLSToPlaylist(file, 0, self.__playlist) # cmdline = self.__playerline + " " + self.__cmdline + " '" + self.__playlist + "'" # self.__logger.debug('twitchplayer cmdline: ' + cmdline) # return cmdline # # def stop(self): # super(Twitchplayer, self).stop() # if (os.path.isfile(self.__playlist)): # os.remove(self.__playlist) , which may include functions, classes, or code. Output only the next line.
def test_playback(self):
Next line prediction: <|code_start|> class MPlayer(Omxplayer): __logger=logging.getLogger(__name__) __playerline="mplayer -slave -fs -vo xv -zoom" keymapping = { 'pause' : 'pause\n', <|code_end|> . Use current file imports: (from simpleMediaCenter.player.Omxplayer import Omxplayer import logging import os) and context including class names, function names, or small code snippets from other files: # Path: simpleMediaCenter/player/Omxplayer.py # class Omxplayer(Player): # __logger=logging.getLogger(__name__) # __cmdline="-o both" # __playerline="omxplayer -b" # __playerstatus=0 # 0 stopped, 1 playing, 2 paused # __currentfile="" # __process=None # # keymapping = { # 'pause' : 'p', # 'quit' : 'q', # 'volume': { # 'up' : '+', # 'down' : '-' # } # } # # # def __init__(self, cmdline = "-o both"): # self.__logger.debug("Omxplayer init") # self.cmdline=cmdline # # def __resetplayer(self): # self.__logger.debug("reset Player") # self.__playerstatus=0 # self.__currentfile="" # self.__paused=False # self.__process=None # # def poll(self): # self.__logger.debug("polling") # if(self.__process is not None): # self.__logger.debug("process is not none") # self.__process.poll() # if(self.__process.returncode is not None): # self.__logger.debug("process ended") # for line in self.__process.stdout: # self.__logger.debug("stdout" + line.decode('utf-8')) # self.__resetplayer() # # # def send(self, str): # self.__logger.debug("Player send %s", str) # self.poll() # if(self.__process is not None): # self.__process.stdin.write(bytes(str, 'UTF-8')) # self.__process.stdin.flush() # # def getcmdline(self,file): # finished_cmdline = self.__playerline + " " + self.__cmdline + " '" + file + "'" # self.__logger.debug('omxplayer cmdline: ' + finished_cmdline) # return self.__playerline + " " + self.__cmdline + " '" + file + "'" # # def play(self, file): # self.poll() # self.__logger.debug("playing: %s",file) # if(self.__process is not None): # self.stop() # # line = self.getcmdline(file) # self.__process = subprocess.Popen( # shlex.split(line), # stdout=subprocess.PIPE, # stdin=subprocess.PIPE, # stderr=subprocess.STDOUT, # close_fds=True) # self.__playerstatus=1 # self.__currentfile = file # self.__paused=False # # def pause(self): # self.poll() # self.__logger.debug("pause called") # if(self.__process is not None): # self.send(self.keymapping['pause']) # if(self.__playerstatus==1): # self.__playerstatus=2 # else: # self.__playerstatus=1 # # def stop(self): # self.poll() # self.__logger.debug("stopping") # if(self.__process is not None): # self.send(self.keymapping['quit']) # try: # self.__logger.debug("waiting for process to close") # self.__process.wait(timeout=5) # except subprocess.TimeoutExpired: # self.__logger.debug("timeout occured, killing") # #self.__process.kill() # subprocess.Popen(shlex.split("killall omxplayer.bin")).wait() ##quickhack # self.__resetplayer() # self.__logger.debug("player stopped") # # def volumeUp(self): # self.poll() # self.__logger.debug("increase vol") # if(self.__process is not None): # self.send(self.keymapping['volume']['up']) # # def volumeDown(self): # self.poll() # self.__logger.debug("decrease vol") # if(self.__process is not None): # self.send(self.keymapping['volume']['down']) # # def getDict(self): # self.poll() # tempDict={} # tempDict['activePlayer'] = self.getName() # tempDict['playerStatus'] = self.__playerstatus # tempDict['currentFile'] = self.__currentfile # return tempDict . Output only the next line.
'quit' : 'quit\n',
Given the code snippet: <|code_start|> def add(self, filePath): raise NotImplementedError def getNext(self ): raise NotImplementedError class FiFo(Playlist): queue = deque([]) def __init__(self): pass def add(self, filePath): logging.debug("try to add: %s", filePath) if(os.path.isfile(filePath)): self.queue.append(filePath) else: raise Exception def getNext(self): logging.debug("getNext called") if(len(self.queue) > 0): return self.queue.popleft() else: raise Exception def getDict(self): raise NotImplementedError class Single(Playlist): <|code_end|> , generate the next line using the imports in this file: import os import logging from collections import deque from simpleMediaCenter.interface.Interface import Displayable and context (functions, classes, or occasionally code) from other files: # Path: simpleMediaCenter/interface/Interface.py # class Displayable(): # def getDict(self): # raise NotImplementedError # # def getName(self): # return self.__class__.__name__ . Output only the next line.
filePath = None
Predict the next line for this snippet: <|code_start|> class TestMPlayer(unittest.TestCase): testfilepath1 = "TEST VIDEO-1.mp4" testfilepath2 = "TEST VIDEO-2.mp4" def setUp(self): self.mplayer = MPlayer() def tearDown(self): self.mplayer.stop() self.mplayer=None def test_playback(self): self.mplayer.play(self.testfilepath1) #time.sleep(2) self.assertEqual(self.mplayer.getDict()['playerStatus'], 1) self.assertEqual(self.mplayer.getDict()['currentFile'], self.testfilepath1) self.mplayer.pause() self.assertEqual(self.mplayer.getDict()['playerStatus'], 2) self.mplayer.pause() self.assertEqual(self.mplayer.getDict()['playerStatus'], 1) self.mplayer.stop() self.assertEqual(self.mplayer.getDict()['playerStatus'], 0) def test_play_while_play(self): <|code_end|> with the help of current file imports: from simpleMediaCenter.player.MPlayer import MPlayer import unittest import time and context from other files: # Path: simpleMediaCenter/player/MPlayer.py # class MPlayer(Omxplayer): # __logger=logging.getLogger(__name__) # __playerline="mplayer -slave -fs -vo xv -zoom" # # keymapping = { # 'pause' : 'pause\n', # 'quit' : 'quit\n', # 'volume': { # 'up' : 'volume +5\n', # 'down' : 'volume -5\n' # } # } # # def __init__(self): # self.__logger.debug("init") # # def getcmdline(self,file): # return self.__playerline + " " + " '" + file + "'" , which may contain function names, class names, or code. Output only the next line.
self.mplayer.play(self.testfilepath1)
Continue the code snippet: <|code_start|> class Omxplayer(Player): __logger=logging.getLogger(__name__) __cmdline="-o both" __playerline="omxplayer -b" __playerstatus=0 # 0 stopped, 1 playing, 2 paused __currentfile="" __process=None keymapping = { 'pause' : 'p', 'quit' : 'q', 'volume': { 'up' : '+', 'down' : '-' } } def __init__(self, cmdline = "-o both"): self.__logger.debug("Omxplayer init") self.cmdline=cmdline def __resetplayer(self): self.__logger.debug("reset Player") <|code_end|> . Use current file imports: from simpleMediaCenter.player.Player import Player import logging import subprocess import shlex import time and context (classes, functions, or code) from other files: # Path: simpleMediaCenter/player/Player.py # class Player(Displayable): # # def __init__(self, cmdline): # raise NotImplementedError # # def send(self, str): # raise NotImplementedError # # def play(self, file): # raise NotImplementedError # # def pause(self): # raise NotImplementedError # # def stop(self): # raise NotImplementedError # # def volumeUp(self): # raise NotImplementedError # # def volumeDown(self): # raise NotImplementedError # # def getName(self): # return self.__class__.__name__ . Output only the next line.
self.__playerstatus=0
Here is a snippet: <|code_start|> class Player(Displayable): def __init__(self, cmdline): raise NotImplementedError def send(self, str): raise NotImplementedError def play(self, file): raise NotImplementedError def pause(self): raise NotImplementedError def stop(self): raise NotImplementedError def volumeUp(self): raise NotImplementedError def volumeDown(self): <|code_end|> . Write the next line using the current file imports: from simpleMediaCenter.interface.Interface import Displayable and context from other files: # Path: simpleMediaCenter/interface/Interface.py # class Displayable(): # def getDict(self): # raise NotImplementedError # # def getName(self): # return self.__class__.__name__ , which may include functions, classes, or code. Output only the next line.
raise NotImplementedError
Predict the next line for this snippet: <|code_start|># Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. DRIVERS = { Provider.DUMMY: ('libcloud.storage.drivers.dummy', 'DummyStorageDriver'), Provider.CLOUDFILES_US: <|code_end|> with the help of current file imports: from libcloud.utils import get_driver as get_provider_driver from libcloud.storage.types import Provider and context from other files: # Path: libcloud/utils.py # def get_driver(drivers, provider): # """ # Get a driver. # # @param drivers: Dictionary containing valid providers. # @param provider: Id of provider to get driver # @type provider: L{libcloud.types.Provider} # """ # if provider in drivers: # mod_name, driver_name = drivers[provider] # _mod = __import__(mod_name, globals(), locals(), [driver_name]) # return getattr(_mod, driver_name) # # raise AttributeError('Provider %s does not exist' % (provider)) # # Path: libcloud/storage/types.py # class Provider(object): # """ # Defines for each of the supported providers # # @cvar DUMMY: Example provider # @cvar CLOUDFILES_US: CloudFiles US # @cvar CLOUDFILES_UK: CloudFiles UK # """ # DUMMY = 0 # CLOUDFILES_US = 1 # CLOUDFILES_UK = 2 , which may contain function names, class names, or code. Output only the next line.
('libcloud.storage.drivers.cloudfiles', 'CloudFilesUSStorageDriver'),
Predict the next line after this snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class RawResponse(object): def __init__(self, response=None): self._status = None self._response = None self._headers = {} self._error = None self._reason = None @property def response(self): if not self._response: self._response = self.connection.connection.getresponse() return self._response @property def status(self): if not self._status: self._status = self.response.status <|code_end|> using the current file's imports: import httplib import urllib import time import hashlib import StringIO import ssl import os import socket import struct import libcloud from pipes import quote as pquote from libcloud.httplib_ssl import LibcloudHTTPSConnection from httplib import HTTPConnection as LibcloudHTTPConnection and any relevant context from other files: # Path: libcloud/httplib_ssl.py # class LibcloudHTTPSConnection(httplib.HTTPSConnection): # """LibcloudHTTPSConnection # # Subclass of HTTPSConnection which verifies certificate names # if and only if CA certificates are available. # """ # verify = False # does not verify # ca_cert = None # no default CA Certificate # # def __init__(self, *args, **kwargs): # """Constructor # """ # self._setup_verify() # httplib.HTTPSConnection.__init__(self, *args, **kwargs) # # def _setup_verify(self): # """Setup Verify SSL or not # # Reads security module's VERIFY_SSL_CERT and toggles whether # the class overrides the connect() class method or runs the # inherited httplib.HTTPSConnection connect() # """ # self.verify = libcloud.security.VERIFY_SSL_CERT # # if self.verify: # self._setup_ca_cert() # else: # warnings.warn(libcloud.security.VERIFY_SSL_DISABLED_MSG) # # def _setup_ca_cert(self): # """Setup CA Certs # # Search in CA_CERTS_PATH for valid candidates and # return first match. Otherwise, complain about certs # not being available. # """ # if not self.verify: # return # # ca_certs_available = [cert # for cert in libcloud.security.CA_CERTS_PATH # if os.path.exists(cert)] # if ca_certs_available: # # use first available certificate # self.ca_cert = ca_certs_available[0] # else: # # no certificates found; toggle verify to False # warnings.warn(libcloud.security.CA_CERTS_UNAVAILABLE_MSG) # self.ca_cert = None # self.verify = False # # def connect(self): # """Connect # # Checks if verification is toggled; if not, just call # httplib.HTTPSConnection's connect # """ # if not self.verify: # return httplib.HTTPSConnection.connect(self) # # # otherwise, create a connection and verify the hostname # # use socket.create_connection (in 2.6+) if possible # if getattr(socket, 'create_connection', None): # sock = socket.create_connection((self.host, self.port), # self.timeout) # else: # sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # sock.connect((self.host, self.port)) # self.sock = ssl.wrap_socket(sock, # self.key_file, # self.cert_file, # cert_reqs=ssl.CERT_REQUIRED, # ca_certs=self.ca_cert, # ssl_version=ssl.PROTOCOL_TLSv1) # cert = self.sock.getpeercert() # if not self._verify_hostname(self.host, cert): # raise ssl.SSLError('Failed to verify hostname') # # def _verify_hostname(self, hostname, cert): # """Verify hostname against peer cert # # Check both commonName and entries in subjectAltName, using a # rudimentary glob to dns regex check to find matches # """ # common_name = self._get_common_name(cert) # alt_names = self._get_subject_alt_names(cert) # # # replace * with alphanumeric and dash # # replace . with literal . # valid_patterns = [ # re.compile( # pattern.replace( # r".", r"\." # ).replace( # r"*", r"[0-9A-Za-z]+" # ) # ) # for pattern # in (set(common_name) | set(alt_names)) # ] # # return any( # pattern.search(hostname) # for pattern in valid_patterns # ) # # def _get_subject_alt_names(self, cert): # """Get SubjectAltNames # # Retrieve 'subjectAltName' attributes from cert data structure # """ # if 'subjectAltName' not in cert: # values = [] # else: # values = [value # for field, value in cert['subjectAltName'] # if field == 'DNS'] # return values # # def _get_common_name(self, cert): # """Get Common Name # # Retrieve 'commonName' attribute from cert data structure # """ # if 'subject' not in cert: # return None # values = [value[0][1] # for value in cert['subject'] # if value[0][0] == 'commonName'] # return values . Output only the next line.
return self._status