Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|>from __future__ import with_statement config = context.config config.set_main_option('sqlalchemy.url', app.config['SQLALCHEMY_DATABASE_URI']) target_metadata = db.metadata def run_migrations_offline(): url = config.get_main_option("sqlalchemy.url") context.configure(url=url) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): engine = engine_from_config( config.get_section(config.config_ini_section), <|code_end|> , predict the immediate next line with the help of imports: from alembic import context from sqlalchemy import engine_from_config, pool from datawire.core import app from datawire.model import db and context (classes, functions, sometimes code) from other files: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/core.py # def url_for(*a, **kw): . Output only the next line.
prefix='sqlalchemy.',
Predict the next line after this snippet: <|code_start|> def authz_collections(action): if action == 'read' and request.authz_lists.get('read') is None: request.authz_lists['read'] = Collection.user_ids(current_user) if action == 'write' and request.authz_lists.get('write') is None: request.authz_lists['write'] = Collection.user_ids(current_user, include_public=False) # noqa return request.authz_lists[action] or [] <|code_end|> using the current file's imports: from flask import request from flask.ext.login import current_user from werkzeug.exceptions import Forbidden from datawire.model import Collection and any relevant context from other files: # Path: datawire/model/collection.py # class Collection(db.Model): # id = db.Column(db.Unicode(50), primary_key=True) # slug = db.Column(db.Unicode(250)) # public = db.Column(db.Boolean, default=False) # # owner_id = db.Column(db.Integer(), db.ForeignKey('user.id'), # nullable=True) # owner = db.relationship(User) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def to_dict(self): # return { # 'id': self.id, # 'api_url': url_for('collections.view', id=self.id), # 'entities_api_url': url_for('entities.index', list=self.id), # 'slug': self.slug, # 'public': self.public, # 'owner': self.owner, # 'created_at': self.created_at, # 'updated_at': self.updated_at # } # # @classmethod # def create(cls, data, user): # lst = cls() # lst.update(data, user) # lst.owner = user # db.session.add(lst) # return lst # # def update(self, data, user): # data = CollectionForm().deserialize(data) # self.slug = data.get('slug') # if data.get('public') is not None: # self.public = data.get('public') # # def delete(self): # # for entity in self.entities: # # entity.delete() # db.session.delete(self) # # @classmethod # def by_slug(cls, login, slug): # q = db.session.query(cls).filter_by(slug=slug) # q = q.filter(cls.owner.login == login) # return q.first() # # @classmethod # def by_id(cls, id): # q = db.session.query(cls).filter_by(id=id) # return q.first() # # @classmethod # def user_ids(cls, user, include_public=True): # logged_in = user is not None and user.is_authenticated() # q = db.session.query(cls.id) # conds = [] # if include_public: # conds.append(cls.public == True) # noqa # if logged_in: # conds.append(cls.owner_id == user.id) # if not len(conds): # return [] # if not (logged_in and user.is_admin): # q = q.filter(or_(*conds)) # return [c.id for c in q.all()] # # @classmethod # def all_by_user(cls, user): # q = db.session.query(cls) # q = q.filter(cls.id.in_(cls.user_ids(user))) # q = q.order_by(cls.id.desc()) # return q # # @property # def terms(self): # from aleph.model.entity import Entity # from aleph.model.selector import Selector # q = db.session.query(Selector.normalized) # q = q.join(Entity, Entity.id == Selector.entity_id) # q = q.filter(Entity.watchlist_id == self.id) # q = q.distinct() # return set([r[0] for r in q]) # # def __repr__(self): # return '<Watchlist(%r, %r)>' % (self.id, self.slug) # # def __unicode__(self): # return self.slug . Output only the next line.
def collection_read(id):
Given the code snippet: <|code_start|>def index(): q = Collection.all_by_user(current_user) data = Pager(q).to_dict() results = [] for lst in data.pop('results'): ldata = lst.to_dict() ldata['permissions'] = { 'write': authz.collection_write(lst.id) } results.append(ldata) data['results'] = results return jsonify(data) @blueprint.route('/api/1/collections', methods=['POST', 'PUT']) def create(): authz.require(authz.logged_in()) data = request_data() data['creator'] = current_user lst = Collection.create(data, current_user) db.session.commit() return view(lst.id) @blueprint.route('/api/1/collections/<id>', methods=['GET']) def view(id): authz.require(authz.collection_read(id)) coll = obj_or_404(Collection.by_id(id)) data = coll.to_dict() data['can_write'] = authz.collection_write(id) <|code_end|> , generate the next line using the imports in this file: from flask import Blueprint # , request from flask.ext.login import current_user from apikit import obj_or_404, jsonify, Pager, request_data from datawire.model import Collection, db from datawire import authz and context (functions, classes, or occasionally code) from other files: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/collection.py # class Collection(db.Model): # id = db.Column(db.Unicode(50), primary_key=True) # slug = db.Column(db.Unicode(250)) # public = db.Column(db.Boolean, default=False) # # owner_id = db.Column(db.Integer(), db.ForeignKey('user.id'), # nullable=True) # owner = db.relationship(User) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def to_dict(self): # return { # 'id': self.id, # 'api_url': url_for('collections.view', id=self.id), # 'entities_api_url': url_for('entities.index', list=self.id), # 'slug': self.slug, # 'public': self.public, # 'owner': self.owner, # 'created_at': self.created_at, # 'updated_at': self.updated_at # } # # @classmethod # def create(cls, data, user): # lst = cls() # lst.update(data, user) # lst.owner = user # db.session.add(lst) # return lst # # def update(self, data, user): # data = CollectionForm().deserialize(data) # self.slug = data.get('slug') # if data.get('public') is not None: # self.public = data.get('public') # # def delete(self): # # for entity in self.entities: # # entity.delete() # db.session.delete(self) # # @classmethod # def by_slug(cls, login, slug): # q = db.session.query(cls).filter_by(slug=slug) # q = q.filter(cls.owner.login == login) # return q.first() # # @classmethod # def by_id(cls, id): # q = db.session.query(cls).filter_by(id=id) # return q.first() # # @classmethod # def user_ids(cls, user, include_public=True): # logged_in = user is not None and user.is_authenticated() # q = db.session.query(cls.id) # conds = [] # if include_public: # conds.append(cls.public == True) # noqa # if logged_in: # conds.append(cls.owner_id == user.id) # if not len(conds): # return [] # if not (logged_in and user.is_admin): # q = q.filter(or_(*conds)) # return [c.id for c in q.all()] # # @classmethod # def all_by_user(cls, user): # q = db.session.query(cls) # q = q.filter(cls.id.in_(cls.user_ids(user))) # q = q.order_by(cls.id.desc()) # return q # # @property # def terms(self): # from aleph.model.entity import Entity # from aleph.model.selector import Selector # q = db.session.query(Selector.normalized) # q = q.join(Entity, Entity.id == Selector.entity_id) # q = q.filter(Entity.watchlist_id == self.id) # q = q.distinct() # return set([r[0] for r in q]) # # def __repr__(self): # return '<Watchlist(%r, %r)>' % (self.id, self.slug) # # def __unicode__(self): # return self.slug # # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): . Output only the next line.
return jsonify(data)
Predict the next line after this snippet: <|code_start|> blueprint = Blueprint('collections', __name__) @blueprint.route('/api/1/collections', methods=['GET']) def index(): q = Collection.all_by_user(current_user) data = Pager(q).to_dict() results = [] for lst in data.pop('results'): ldata = lst.to_dict() <|code_end|> using the current file's imports: from flask import Blueprint # , request from flask.ext.login import current_user from apikit import obj_or_404, jsonify, Pager, request_data from datawire.model import Collection, db from datawire import authz and any relevant context from other files: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/collection.py # class Collection(db.Model): # id = db.Column(db.Unicode(50), primary_key=True) # slug = db.Column(db.Unicode(250)) # public = db.Column(db.Boolean, default=False) # # owner_id = db.Column(db.Integer(), db.ForeignKey('user.id'), # nullable=True) # owner = db.relationship(User) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def to_dict(self): # return { # 'id': self.id, # 'api_url': url_for('collections.view', id=self.id), # 'entities_api_url': url_for('entities.index', list=self.id), # 'slug': self.slug, # 'public': self.public, # 'owner': self.owner, # 'created_at': self.created_at, # 'updated_at': self.updated_at # } # # @classmethod # def create(cls, data, user): # lst = cls() # lst.update(data, user) # lst.owner = user # db.session.add(lst) # return lst # # def update(self, data, user): # data = CollectionForm().deserialize(data) # self.slug = data.get('slug') # if data.get('public') is not None: # self.public = data.get('public') # # def delete(self): # # for entity in self.entities: # # entity.delete() # db.session.delete(self) # # @classmethod # def by_slug(cls, login, slug): # q = db.session.query(cls).filter_by(slug=slug) # q = q.filter(cls.owner.login == login) # return q.first() # # @classmethod # def by_id(cls, id): # q = db.session.query(cls).filter_by(id=id) # return q.first() # # @classmethod # def user_ids(cls, user, include_public=True): # logged_in = user is not None and user.is_authenticated() # q = db.session.query(cls.id) # conds = [] # if include_public: # conds.append(cls.public == True) # noqa # if logged_in: # conds.append(cls.owner_id == user.id) # if not len(conds): # return [] # if not (logged_in and user.is_admin): # q = q.filter(or_(*conds)) # return [c.id for c in q.all()] # # @classmethod # def all_by_user(cls, user): # q = db.session.query(cls) # q = q.filter(cls.id.in_(cls.user_ids(user))) # q = q.order_by(cls.id.desc()) # return q # # @property # def terms(self): # from aleph.model.entity import Entity # from aleph.model.selector import Selector # q = db.session.query(Selector.normalized) # q = q.join(Entity, Entity.id == Selector.entity_id) # q = q.filter(Entity.watchlist_id == self.id) # q = q.distinct() # return set([r[0] for r in q]) # # def __repr__(self): # return '<Watchlist(%r, %r)>' % (self.id, self.slug) # # def __unicode__(self): # return self.slug # # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): . Output only the next line.
ldata['permissions'] = {
Given the code snippet: <|code_start|> blueprint = Blueprint('collections', __name__) @blueprint.route('/api/1/collections', methods=['GET']) def index(): q = Collection.all_by_user(current_user) data = Pager(q).to_dict() results = [] for lst in data.pop('results'): ldata = lst.to_dict() ldata['permissions'] = { 'write': authz.collection_write(lst.id) } <|code_end|> , generate the next line using the imports in this file: from flask import Blueprint # , request from flask.ext.login import current_user from apikit import obj_or_404, jsonify, Pager, request_data from datawire.model import Collection, db from datawire import authz and context (functions, classes, or occasionally code) from other files: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/collection.py # class Collection(db.Model): # id = db.Column(db.Unicode(50), primary_key=True) # slug = db.Column(db.Unicode(250)) # public = db.Column(db.Boolean, default=False) # # owner_id = db.Column(db.Integer(), db.ForeignKey('user.id'), # nullable=True) # owner = db.relationship(User) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def to_dict(self): # return { # 'id': self.id, # 'api_url': url_for('collections.view', id=self.id), # 'entities_api_url': url_for('entities.index', list=self.id), # 'slug': self.slug, # 'public': self.public, # 'owner': self.owner, # 'created_at': self.created_at, # 'updated_at': self.updated_at # } # # @classmethod # def create(cls, data, user): # lst = cls() # lst.update(data, user) # lst.owner = user # db.session.add(lst) # return lst # # def update(self, data, user): # data = CollectionForm().deserialize(data) # self.slug = data.get('slug') # if data.get('public') is not None: # self.public = data.get('public') # # def delete(self): # # for entity in self.entities: # # entity.delete() # db.session.delete(self) # # @classmethod # def by_slug(cls, login, slug): # q = db.session.query(cls).filter_by(slug=slug) # q = q.filter(cls.owner.login == login) # return q.first() # # @classmethod # def by_id(cls, id): # q = db.session.query(cls).filter_by(id=id) # return q.first() # # @classmethod # def user_ids(cls, user, include_public=True): # logged_in = user is not None and user.is_authenticated() # q = db.session.query(cls.id) # conds = [] # if include_public: # conds.append(cls.public == True) # noqa # if logged_in: # conds.append(cls.owner_id == user.id) # if not len(conds): # return [] # if not (logged_in and user.is_admin): # q = q.filter(or_(*conds)) # return [c.id for c in q.all()] # # @classmethod # def all_by_user(cls, user): # q = db.session.query(cls) # q = q.filter(cls.id.in_(cls.user_ids(user))) # q = q.order_by(cls.id.desc()) # return q # # @property # def terms(self): # from aleph.model.entity import Entity # from aleph.model.selector import Selector # q = db.session.query(Selector.normalized) # q = q.join(Entity, Entity.id == Selector.entity_id) # q = q.filter(Entity.watchlist_id == self.id) # q = q.distinct() # return set([r[0] for r in q]) # # def __repr__(self): # return '<Watchlist(%r, %r)>' % (self.id, self.slug) # # def __unicode__(self): # return self.slug # # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): . Output only the next line.
results.append(ldata)
Next line prediction: <|code_start|> log = logging.getLogger(__name__) class Selector(db.Model): id = db.Column(db.Integer, primary_key=True) _text = db.Column('text', db.Unicode, index=True) normalized = db.Column(db.Unicode, index=True) created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) entity_id = db.Column(db.Unicode(50), db.ForeignKey('entity.id')) entity = db.relationship('Entity', backref=db.backref('selectors', lazy='dynamic', cascade='all, delete-orphan')) @hybrid_property <|code_end|> . Use current file imports: (import logging from datetime import datetime from sqlalchemy.ext.hybrid import hybrid_property from normality import normalize from datawire.core import db) and context including class names, function names, or small code snippets from other files: # Path: datawire/core.py # def url_for(*a, **kw): . Output only the next line.
def text(self):
Given the following code snippet before the placeholder: <|code_start|> } @classmethod def create(cls, data, user): lst = cls() lst.update(data, user) lst.owner = user db.session.add(lst) return lst def update(self, data, user): data = CollectionForm().deserialize(data) self.slug = data.get('slug') if data.get('public') is not None: self.public = data.get('public') def delete(self): # for entity in self.entities: # entity.delete() db.session.delete(self) @classmethod def by_slug(cls, login, slug): q = db.session.query(cls).filter_by(slug=slug) q = q.filter(cls.owner.login == login) return q.first() @classmethod def by_id(cls, id): q = db.session.query(cls).filter_by(id=id) <|code_end|> , predict the next line using imports from the current file: import logging from datetime import datetime from sqlalchemy import or_ from datawire.core import db, url_for from datawire.model.user import User from datawire.model.forms import CollectionForm from aleph.model.entity import Entity from aleph.model.selector import Selector and context including class names, function names, and sometimes code from other files: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() # # Path: datawire/model/forms.py # class CollectionForm(colander.MappingSchema): # slug = colander.SchemaNode(colander.String()) # public = colander.SchemaNode(colander.Boolean()) . Output only the next line.
return q.first()
Predict the next line after this snippet: <|code_start|> 'id': self.id, 'api_url': url_for('collections.view', id=self.id), 'entities_api_url': url_for('entities.index', list=self.id), 'slug': self.slug, 'public': self.public, 'owner': self.owner, 'created_at': self.created_at, 'updated_at': self.updated_at } @classmethod def create(cls, data, user): lst = cls() lst.update(data, user) lst.owner = user db.session.add(lst) return lst def update(self, data, user): data = CollectionForm().deserialize(data) self.slug = data.get('slug') if data.get('public') is not None: self.public = data.get('public') def delete(self): # for entity in self.entities: # entity.delete() db.session.delete(self) @classmethod <|code_end|> using the current file's imports: import logging from datetime import datetime from sqlalchemy import or_ from datawire.core import db, url_for from datawire.model.user import User from datawire.model.forms import CollectionForm from aleph.model.entity import Entity from aleph.model.selector import Selector and any relevant context from other files: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() # # Path: datawire/model/forms.py # class CollectionForm(colander.MappingSchema): # slug = colander.SchemaNode(colander.String()) # public = colander.SchemaNode(colander.Boolean()) . Output only the next line.
def by_slug(cls, login, slug):
Using the snippet: <|code_start|> self.slug = data.get('slug') if data.get('public') is not None: self.public = data.get('public') def delete(self): # for entity in self.entities: # entity.delete() db.session.delete(self) @classmethod def by_slug(cls, login, slug): q = db.session.query(cls).filter_by(slug=slug) q = q.filter(cls.owner.login == login) return q.first() @classmethod def by_id(cls, id): q = db.session.query(cls).filter_by(id=id) return q.first() @classmethod def user_ids(cls, user, include_public=True): logged_in = user is not None and user.is_authenticated() q = db.session.query(cls.id) conds = [] if include_public: conds.append(cls.public == True) # noqa if logged_in: conds.append(cls.owner_id == user.id) if not len(conds): <|code_end|> , determine the next line of code. You have imports: import logging from datetime import datetime from sqlalchemy import or_ from datawire.core import db, url_for from datawire.model.user import User from datawire.model.forms import CollectionForm from aleph.model.entity import Entity from aleph.model.selector import Selector and context (class names, function names, or code) available: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() # # Path: datawire/model/forms.py # class CollectionForm(colander.MappingSchema): # slug = colander.SchemaNode(colander.String()) # public = colander.SchemaNode(colander.Boolean()) . Output only the next line.
return []
Using the snippet: <|code_start|> log = logging.getLogger(__name__) class Collection(db.Model): id = db.Column(db.Unicode(50), primary_key=True) slug = db.Column(db.Unicode(250)) public = db.Column(db.Boolean, default=False) owner_id = db.Column(db.Integer(), db.ForeignKey('user.id'), nullable=True) owner = db.relationship(User) created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) def to_dict(self): return { 'id': self.id, 'api_url': url_for('collections.view', id=self.id), 'entities_api_url': url_for('entities.index', list=self.id), 'slug': self.slug, 'public': self.public, 'owner': self.owner, 'created_at': self.created_at, 'updated_at': self.updated_at <|code_end|> , determine the next line of code. You have imports: import logging from datetime import datetime from sqlalchemy import or_ from datawire.core import db, url_for from datawire.model.user import User from datawire.model.forms import CollectionForm from aleph.model.entity import Entity from aleph.model.selector import Selector and context (class names, function names, or code) available: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() # # Path: datawire/model/forms.py # class CollectionForm(colander.MappingSchema): # slug = colander.SchemaNode(colander.String()) # public = colander.SchemaNode(colander.Boolean()) . Output only the next line.
}
Here is a snippet: <|code_start|> login = db.Column(db.Unicode(255)) email = db.Column(db.Unicode, nullable=True) oauth_id = db.Column(db.Unicode) api_key = db.Column(db.Unicode, default=make_token) is_admin = db.Column(db.Boolean, nullable=False, default=False) created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) def is_active(self): return True def is_authenticated(self): return True def is_anonymous(self): return False def get_id(self): return self.login def __repr__(self): return '<User(%r,%r)>' % (self.id, self.login) def __unicode__(self): return self.login def to_dict(self): <|code_end|> . Write the next line using the current file imports: import logging from datetime import datetime from datawire.core import db, login_manager, url_for from datawire.model.util import make_token from datawire.model.forms import UserForm and context from other files: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/util.py # def make_token(): # num = uuid.uuid4().int # s = [] # while True: # num, r = divmod(num, len(ALPHABET)) # s.append(ALPHABET[r]) # if num == 0: # break # return ''.join(reversed(s)) # # Path: datawire/model/forms.py # class UserForm(colander.MappingSchema): # email = colander.SchemaNode(colander.String(), # validator=colander.Email()) # login = colander.SchemaNode(colander.String()) , which may include functions, classes, or code. Output only the next line.
return {
Given the code snippet: <|code_start|> def to_dict(self): return { 'id': self.id, 'login': self.login, 'is_admin': self.is_admin, 'created_at': self.created_at, 'updated_at': self.updated_at, 'api_url': url_for('users.view', login=self.login) } def update(self, data): data = UserForm().deserialize(data) self.email = data.get('email') @classmethod def load(cls, data): user = cls.by_oauth_id(data.get('oauth_id')) if user is None: user = cls() user.login = data.get('login') user.oauth_id = data.get('oauth_id') if data.get('email'): # FIXME: better to overwrite with upstream or keep? user.email = data.get('email') db.session.add(user) return user <|code_end|> , generate the next line using the imports in this file: import logging from datetime import datetime from datawire.core import db, login_manager, url_for from datawire.model.util import make_token from datawire.model.forms import UserForm and context (functions, classes, or occasionally code) from other files: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/util.py # def make_token(): # num = uuid.uuid4().int # s = [] # while True: # num, r = divmod(num, len(ALPHABET)) # s.append(ALPHABET[r]) # if num == 0: # break # return ''.join(reversed(s)) # # Path: datawire/model/forms.py # class UserForm(colander.MappingSchema): # email = colander.SchemaNode(colander.String(), # validator=colander.Email()) # login = colander.SchemaNode(colander.String()) . Output only the next line.
@classmethod
Given the following code snippet before the placeholder: <|code_start|> def is_active(self): return True def is_authenticated(self): return True def is_anonymous(self): return False def get_id(self): return self.login def __repr__(self): return '<User(%r,%r)>' % (self.id, self.login) def __unicode__(self): return self.login def to_dict(self): return { 'id': self.id, 'login': self.login, 'is_admin': self.is_admin, 'created_at': self.created_at, 'updated_at': self.updated_at, 'api_url': url_for('users.view', login=self.login) } def update(self, data): data = UserForm().deserialize(data) <|code_end|> , predict the next line using imports from the current file: import logging from datetime import datetime from datawire.core import db, login_manager, url_for from datawire.model.util import make_token from datawire.model.forms import UserForm and context including class names, function names, and sometimes code from other files: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/util.py # def make_token(): # num = uuid.uuid4().int # s = [] # while True: # num, r = divmod(num, len(ALPHABET)) # s.append(ALPHABET[r]) # if num == 0: # break # return ''.join(reversed(s)) # # Path: datawire/model/forms.py # class UserForm(colander.MappingSchema): # email = colander.SchemaNode(colander.String(), # validator=colander.Email()) # login = colander.SchemaNode(colander.String()) . Output only the next line.
self.email = data.get('email')
Given the following code snippet before the placeholder: <|code_start|> def update(self, data): data = UserForm().deserialize(data) self.email = data.get('email') @classmethod def load(cls, data): user = cls.by_oauth_id(data.get('oauth_id')) if user is None: user = cls() user.login = data.get('login') user.oauth_id = data.get('oauth_id') if data.get('email'): # FIXME: better to overwrite with upstream or keep? user.email = data.get('email') db.session.add(user) return user @classmethod def all(cls): q = db.session.query(cls) return q @classmethod def by_login(cls, login): q = db.session.query(cls).filter_by(login=login) return q.first() @classmethod <|code_end|> , predict the next line using imports from the current file: import logging from datetime import datetime from datawire.core import db, login_manager, url_for from datawire.model.util import make_token from datawire.model.forms import UserForm and context including class names, function names, and sometimes code from other files: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/util.py # def make_token(): # num = uuid.uuid4().int # s = [] # while True: # num, r = divmod(num, len(ALPHABET)) # s.append(ALPHABET[r]) # if num == 0: # break # return ''.join(reversed(s)) # # Path: datawire/model/forms.py # class UserForm(colander.MappingSchema): # email = colander.SchemaNode(colander.String(), # validator=colander.Email()) # login = colander.SchemaNode(colander.String()) . Output only the next line.
def by_api_key(cls, api_key):
Next line prediction: <|code_start|># from kombu import Exchange, Queue # from celery import Celery logging.basicConfig(level=logging.DEBUG) # specific loggers logging.getLogger('requests').setLevel(logging.WARNING) logging.getLogger('urllib3').setLevel(logging.WARNING) <|code_end|> . Use current file imports: (import logging from flask import Flask from flask import url_for as _url_for from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.migrate import Migrate from flask.ext.oauth import OAuth from datawire import default_settings) and context including class names, function names, or small code snippets from other files: # Path: datawire/default_settings.py # DEBUG = True # ASSETS_DEBUG = DEBUG # APP_TITLE = 'datawire.local' # APP_NAME = 'datwire' # SECRET_KEY = env.get('SECRET_KEY', 'banana umbrella') # SQLALCHEMY_DATABASE_URI = env.get('DATABASE_URL', 'sqlite:////Users/fl/Code/datawi.re/db.sqlite3') # ALEMBIC_DIR = path.join(path.dirname(__file__), 'migrate') # ALEMBIC_DIR = path.abspath(ALEMBIC_DIR) # TWITTER_API_KEY = None # TWITTER_API_SECRET = None # CELERY_ALWAYS_EAGER = False # CELERY_TASK_SERIALIZER = 'json' # CELERY_ACCEPT_CONTENT = ['json'] # CELERY_TIMEZONE = 'UTC' # CELERY_BROKER_URL = env.get('RABBITMQ_BIGWIG_URL', # 'amqp://guest:guest@localhost:5672//') # CELERY_IMPORTS = ('datawire.queue') . Output only the next line.
logging.getLogger('amqp').setLevel(logging.INFO)
Predict the next line after this snippet: <|code_start|> blueprint = Blueprint('users', __name__) @blueprint.route('/api/1/users', methods=['GET']) def index(): authz.require(authz.logged_in()) q = User.all() return jsonify(Pager(q)) @blueprint.route('/api/1/users/<login>', methods=['GET']) def view(login): user = obj_or_404(User.by_login(login)) <|code_end|> using the current file's imports: from flask import Blueprint from flask.ext.login import current_user from apikit import obj_or_404, request_data, Pager, jsonify from datawire.model import User from datawire.core import db from datawire import authz and any relevant context from other files: # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() # # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): . Output only the next line.
data = user.to_dict()
Next line prediction: <|code_start|> blueprint = Blueprint('users', __name__) @blueprint.route('/api/1/users', methods=['GET']) def index(): authz.require(authz.logged_in()) q = User.all() return jsonify(Pager(q)) @blueprint.route('/api/1/users/<login>', methods=['GET']) def view(login): user = obj_or_404(User.by_login(login)) data = user.to_dict() <|code_end|> . Use current file imports: (from flask import Blueprint from flask.ext.login import current_user from apikit import obj_or_404, request_data, Pager, jsonify from datawire.model import User from datawire.core import db from datawire import authz) and context including class names, function names, or small code snippets from other files: # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() # # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): . Output only the next line.
if user.id == current_user.id:
Next line prediction: <|code_start|> blueprint = Blueprint('users', __name__) @blueprint.route('/api/1/users', methods=['GET']) def index(): authz.require(authz.logged_in()) q = User.all() return jsonify(Pager(q)) @blueprint.route('/api/1/users/<login>', methods=['GET']) def view(login): user = obj_or_404(User.by_login(login)) data = user.to_dict() if user.id == current_user.id: data['email'] = user.email return jsonify(data) @blueprint.route('/api/1/users/<login>', methods=['POST', 'PUT']) def update(login): user = obj_or_404(User.by_login(login)) authz.require(user.id == current_user.id) user.update(request_data()) db.session.add(user) db.session.commit() <|code_end|> . Use current file imports: (from flask import Blueprint from flask.ext.login import current_user from apikit import obj_or_404, request_data, Pager, jsonify from datawire.model import User from datawire.core import db from datawire import authz) and context including class names, function names, or small code snippets from other files: # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() # # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): . Output only the next line.
return view(login)
Given snippet: <|code_start|> blueprint = Blueprint('sessions', __name__) twitter = oauth.remote_app('twitter', base_url='https://api.twitter.com/1.1/', request_token_url='https://api.twitter.com/oauth/request_token', access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authenticate', consumer_key=app.config.get('TWITTER_API_KEY'), consumer_secret=app.config.get('TWITTER_API_SECRET')) @twitter.tokengetter def get_twitter_token(token=None): return session.get('twitter_token') @blueprint.route('/api/1/sessions') def status(): return jsonify({ 'logged_in': authz.logged_in(), 'api_key': current_user.api_key if authz.logged_in() else None, 'user': current_user if authz.logged_in() else None, 'logout': url_for('.logout') }) <|code_end|> , continue by predicting the next line. Consider current file imports: from flask import session, Blueprint, redirect, request from flask.ext.login import login_user, logout_user, current_user from apikit import jsonify from datawire import authz from datawire.core import db, app, oauth, url_for from datawire.model import User and context: # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): # # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() which might include code, classes, or functions. Output only the next line.
@blueprint.route('/api/1/sessions/logout', methods=['POST'])
Given the following code snippet before the placeholder: <|code_start|> @blueprint.route('/api/1/sessions/logout', methods=['POST']) def logout(): logout_user() return redirect(request.args.get('next_url', url_for('ui'))) @blueprint.route('/api/1/sessions/login') def login(): if current_user.is_authenticated(): return redirect(url_for('ui')) session.clear() callback = url_for('.authorized') session['next_url'] = request.args.get('next_url', url_for('ui')) return twitter.authorize(callback=callback) @blueprint.route('/api/1/sessions/callback') @twitter.authorized_handler def authorized(resp): next_url = session.get('next_url', url_for('ui')) if resp is None or 'oauth_token' not in resp: return redirect(next_url) session['twitter_token'] = (resp['oauth_token'], resp['oauth_token_secret']) res = twitter.get('users/show.json?user_id=%s' % resp.get('user_id')) data = { 'login': res.data.get('screen_name'), 'oauth_id': res.data.get('id') <|code_end|> , predict the next line using imports from the current file: from flask import session, Blueprint, redirect, request from flask.ext.login import login_user, logout_user, current_user from apikit import jsonify from datawire import authz from datawire.core import db, app, oauth, url_for from datawire.model import User and context including class names, function names, and sometimes code from other files: # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): # # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() . Output only the next line.
}
Here is a snippet: <|code_start|> blueprint = Blueprint('sessions', __name__) twitter = oauth.remote_app('twitter', base_url='https://api.twitter.com/1.1/', request_token_url='https://api.twitter.com/oauth/request_token', access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authenticate', consumer_key=app.config.get('TWITTER_API_KEY'), consumer_secret=app.config.get('TWITTER_API_SECRET')) @twitter.tokengetter def get_twitter_token(token=None): return session.get('twitter_token') @blueprint.route('/api/1/sessions') def status(): return jsonify({ 'logged_in': authz.logged_in(), 'api_key': current_user.api_key if authz.logged_in() else None, 'user': current_user if authz.logged_in() else None, 'logout': url_for('.logout') }) @blueprint.route('/api/1/sessions/logout', methods=['POST']) def logout(): <|code_end|> . Write the next line using the current file imports: from flask import session, Blueprint, redirect, request from flask.ext.login import login_user, logout_user, current_user from apikit import jsonify from datawire import authz from datawire.core import db, app, oauth, url_for from datawire.model import User and context from other files: # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): # # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() , which may include functions, classes, or code. Output only the next line.
logout_user()
Next line prediction: <|code_start|> blueprint = Blueprint('sessions', __name__) twitter = oauth.remote_app('twitter', base_url='https://api.twitter.com/1.1/', request_token_url='https://api.twitter.com/oauth/request_token', access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authenticate', consumer_key=app.config.get('TWITTER_API_KEY'), consumer_secret=app.config.get('TWITTER_API_SECRET')) @twitter.tokengetter def get_twitter_token(token=None): <|code_end|> . Use current file imports: (from flask import session, Blueprint, redirect, request from flask.ext.login import login_user, logout_user, current_user from apikit import jsonify from datawire import authz from datawire.core import db, app, oauth, url_for from datawire.model import User) and context including class names, function names, or small code snippets from other files: # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): # # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() . Output only the next line.
return session.get('twitter_token')
Using the snippet: <|code_start|> 'api_key': current_user.api_key if authz.logged_in() else None, 'user': current_user if authz.logged_in() else None, 'logout': url_for('.logout') }) @blueprint.route('/api/1/sessions/logout', methods=['POST']) def logout(): logout_user() return redirect(request.args.get('next_url', url_for('ui'))) @blueprint.route('/api/1/sessions/login') def login(): if current_user.is_authenticated(): return redirect(url_for('ui')) session.clear() callback = url_for('.authorized') session['next_url'] = request.args.get('next_url', url_for('ui')) return twitter.authorize(callback=callback) @blueprint.route('/api/1/sessions/callback') @twitter.authorized_handler def authorized(resp): next_url = session.get('next_url', url_for('ui')) if resp is None or 'oauth_token' not in resp: return redirect(next_url) session['twitter_token'] = (resp['oauth_token'], resp['oauth_token_secret']) <|code_end|> , determine the next line of code. You have imports: from flask import session, Blueprint, redirect, request from flask.ext.login import login_user, logout_user, current_user from apikit import jsonify from datawire import authz from datawire.core import db, app, oauth, url_for from datawire.model import User and context (class names, function names, or code) available: # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): # # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() . Output only the next line.
res = twitter.get('users/show.json?user_id=%s' % resp.get('user_id'))
Predict the next line for this snippet: <|code_start|> 'logout': url_for('.logout') }) @blueprint.route('/api/1/sessions/logout', methods=['POST']) def logout(): logout_user() return redirect(request.args.get('next_url', url_for('ui'))) @blueprint.route('/api/1/sessions/login') def login(): if current_user.is_authenticated(): return redirect(url_for('ui')) session.clear() callback = url_for('.authorized') session['next_url'] = request.args.get('next_url', url_for('ui')) return twitter.authorize(callback=callback) @blueprint.route('/api/1/sessions/callback') @twitter.authorized_handler def authorized(resp): next_url = session.get('next_url', url_for('ui')) if resp is None or 'oauth_token' not in resp: return redirect(next_url) session['twitter_token'] = (resp['oauth_token'], resp['oauth_token_secret']) res = twitter.get('users/show.json?user_id=%s' % resp.get('user_id')) data = { <|code_end|> with the help of current file imports: from flask import session, Blueprint, redirect, request from flask.ext.login import login_user, logout_user, current_user from apikit import jsonify from datawire import authz from datawire.core import db, app, oauth, url_for from datawire.model import User and context from other files: # Path: datawire/authz.py # def authz_collections(action): # def collection_read(id): # def collection_write(id): # def logged_in(): # def require(pred): # # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() , which may contain function names, class names, or code. Output only the next line.
'login': res.data.get('screen_name'),
Here is a snippet: <|code_start|> self.category = data.get('category') selectors = set(data.get('selectors')) selectors.add(self.label) existing = list(self.selectors) for sel in list(existing): if sel.text in selectors: selectors.remove(sel.text) existing.remove(sel) for sel in existing: db.session.delete(sel) for text in selectors: sel = Selector() sel.entity = self sel.text = text db.session.add(sel) @classmethod def by_normalized_label(cls, label, collection): q = db.session.query(cls) q = q.filter_by(collection=collection) q = q.filter(db_compare(cls.label, label)) return q.first() @classmethod def by_id(cls, id): q = db.session.query(cls).filter_by(id=id) return q.first() @classmethod <|code_end|> . Write the next line using the current file imports: import logging from datetime import datetime from sqlalchemy import or_ from sqlalchemy.orm import aliased from datawire.core import db, url_for from datawire.model.user import User from datawire.model.selector import Selector from datawire.model.forms import EntityForm, CATEGORIES from datawire.model.util import make_textid, db_compare and context from other files: # Path: datawire/core.py # def url_for(*a, **kw): # # Path: datawire/model/user.py # class User(db.Model): # id = db.Column(db.Integer, primary_key=True) # login = db.Column(db.Unicode(255)) # email = db.Column(db.Unicode, nullable=True) # oauth_id = db.Column(db.Unicode) # api_key = db.Column(db.Unicode, default=make_token) # # is_admin = db.Column(db.Boolean, nullable=False, default=False) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # def is_active(self): # return True # # def is_authenticated(self): # return True # # def is_anonymous(self): # return False # # def get_id(self): # return self.login # # def __repr__(self): # return '<User(%r,%r)>' % (self.id, self.login) # # def __unicode__(self): # return self.login # # def to_dict(self): # return { # 'id': self.id, # 'login': self.login, # 'is_admin': self.is_admin, # 'created_at': self.created_at, # 'updated_at': self.updated_at, # 'api_url': url_for('users.view', login=self.login) # } # # def update(self, data): # data = UserForm().deserialize(data) # self.email = data.get('email') # # @classmethod # def load(cls, data): # user = cls.by_oauth_id(data.get('oauth_id')) # # if user is None: # user = cls() # user.login = data.get('login') # user.oauth_id = data.get('oauth_id') # # if data.get('email'): # # FIXME: better to overwrite with upstream or keep? # user.email = data.get('email') # db.session.add(user) # return user # # @classmethod # def all(cls): # q = db.session.query(cls) # return q # # @classmethod # def by_login(cls, login): # q = db.session.query(cls).filter_by(login=login) # return q.first() # # @classmethod # def by_api_key(cls, api_key): # q = db.session.query(cls).filter_by(api_key=api_key) # return q.first() # # @classmethod # def by_oauth_id(cls, oauth_id): # q = db.session.query(cls).filter_by(oauth_id=unicode(oauth_id)) # return q.first() # # Path: datawire/model/selector.py # class Selector(db.Model): # id = db.Column(db.Integer, primary_key=True) # _text = db.Column('text', db.Unicode, index=True) # normalized = db.Column(db.Unicode, index=True) # # created_at = db.Column(db.DateTime, default=datetime.utcnow) # updated_at = db.Column(db.DateTime, default=datetime.utcnow, # onupdate=datetime.utcnow) # # entity_id = db.Column(db.Unicode(50), db.ForeignKey('entity.id')) # entity = db.relationship('Entity', backref=db.backref('selectors', # lazy='dynamic', cascade='all, delete-orphan')) # # @hybrid_property # def text(self): # return self._text # # @text.setter # def text(self, text): # self._text = text # self.normalized = self.normalize(text) # # @classmethod # def normalize(cls, text): # return normalize(text) # # def __repr__(self): # return '<Selector(%r, %r)>' % (self.entity_id, self.text) # # def __unicode__(self): # return self.text # # Path: datawire/model/forms.py # class EntityForm(colander.MappingSchema): # label = colander.SchemaNode(colander.String()) # category = colander.SchemaNode(colander.String(), # validator=colander.OneOf(CATEGORIES)) # selectors = EntitySelectors() # collection = colander.SchemaNode(CollectionRef()) # # CATEGORIES = [PERSON, COMPANY, ORGANIZATION, OTHER] # # Path: datawire/model/util.py # def make_textid(): # return uuid.uuid4().hex # # def db_compare(col, text): # if text is None: # return col == text # text_ = text.lower().strip() # return db_norm(col) == text_ , which may include functions, classes, or code. Output only the next line.
def by_collections(cls, collections, prefix=None):
Based on the snippet: <|code_start|># FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # HyperKitty. If not, see <http://www.gnu.org/licenses/>. # # Author: Aurelien Bompard <abompard@fedoraproject.org> # from __future__ import absolute_import, unicode_literals, print_function PORT_IN_URL = re.compile(r':\d+$') def get_list_by_name(list_name, domain): matching = list(MailingList.objects.filter(name__startswith=list_name+"@")) if len(matching) == 0: # no candidate found raise Http404("No archived mailinglist by that name") if len(matching) == 1: # only one candidate return matching[0] # more than one result, try using the hostname domain = PORT_IN_URL.sub('', domain) list_fqdn = "%s@%s" % (list_name, domain) try: return MailingList.objects.get(name=list_fqdn) except MailingList.DoesNotExist: # return the first match, arbitrarily <|code_end|> , predict the immediate next line with the help of imports: import re import datetime from django.http import Http404 from hyperkitty.models import MailingList and context (classes, functions, sometimes code) from other files: # Path: hyperkitty/models.py # class MailingList(models.Model): # """ # An archived mailing-list. # """ # name = models.CharField(max_length=254, primary_key=True) # display_name = models.CharField(max_length=255) # description = models.TextField() # subject_prefix = models.CharField(max_length=255) # archive_policy = models.IntegerField( # choices=[ (p.value, p.name) for p in ArchivePolicy ], # default=ArchivePolicy.public.value) # created_at = models.DateTimeField(default=now) # # MAILMAN_ATTRIBUTES = ( # "display_name", "description", "subject_prefix", # "archive_policy", "created_at", # ) # # @property # def is_private(self): # return self.archive_policy == ArchivePolicy.private.value # # @property # def is_new(self): # return self.created_at and \ # now() - self.created_at <= datetime.timedelta(days=30) # # def get_recent_dates(self): # today = now() # #today -= datetime.timedelta(days=400) #debug # # the upper boundary is excluded in the search, add one day # end_date = today + datetime.timedelta(days=1) # begin_date = end_date - datetime.timedelta(days=32) # return begin_date, end_date # # def get_participants_count_between(self, begin_date, end_date): # # We filter on emails dates instead of threads dates because that would # # also include last month's participants when threads carry from one # # month to the next # # TODO: caching? # return self.emails.filter( # date__gte=begin_date, date__lt=end_date # ).values("sender_id").distinct().count() # # def get_threads_between(self, begin_date, end_date): # return self.threads.filter( # starting_email__date__lt=end_date, # date_active__gte=begin_date # ).order_by("-date_active") # # @property # def recent_participants_count(self): # begin_date, end_date = self.get_recent_dates() # return cache.get_or_set( # "MailingList:%s:recent_participants_count" % self.name, # lambda: self.get_participants_count_between(begin_date, end_date), # 3600 * 6) # 6 hours # # @property # def recent_threads(self): # begin_date, end_date = self.get_recent_dates() # return cache.get_or_set( # "MailingList:%s:recent_threads" % self.name, # lambda: self.get_threads_between(begin_date, end_date), # 3600 * 6) # 6 hours # # def get_participants_count_for_month(self, year, month): # def _get_value(): # begin_date = datetime.datetime(year, month, 1, tzinfo=utc) # end_date = begin_date + datetime.timedelta(days=32) # end_date = end_date.replace(day=1) # return self.get_participants_count_between(begin_date, end_date) # return cache.get_or_set( # "MailingList:%s:p_count_for:%s:%s" % (self.name, year, month), # _get_value, None) # # @property # def top_posters(self): # begin_date, end_date = self.get_recent_dates() # query = Sender.objects.filter( # emails__mailinglist=self, # emails__date__gte=begin_date, # emails__date__lt=end_date, # ).annotate(count=models.Count("emails") # ).order_by("-count") # # Because of South, ResultSets are not pickleizable directly, they must # # be converted to lists (there's an extra field without the _deferred # # attribute that causes tracebacks) # return cache.get_or_set( # "MailingList:%s:top_posters" % self.name, # lambda: list(query[:5]), # 3600 * 6) # 6 hours # # It's not actually necessary to convert back to instances since it's # # only used in templates where access to instance attributes or # # dictionnary keys is identical # #return [ Sender.objects.get(address=data["address"]) for data in sender_ids ] # #return sender_ids # # def update_from_mailman(self): # try: # client = get_mailman_client() # mm_list = client.get_list(self.name) # except MailmanConnectionError: # return # except HTTPError: # return # can't update at this time # if not mm_list: # return # converters = { # "created_at": dateutil.parser.parse, # "archive_policy": lambda p: ArchivePolicy[p].value, # } # for propname in self.MAILMAN_ATTRIBUTES: # try: # value = getattr(mm_list, propname) # except AttributeError: # value = mm_list.settings[propname] # if propname in converters: # value = converters[propname](value) # setattr(self, propname, value) # self.save() . Output only the next line.
return matching[0]
Based on the snippet: <|code_start|># # You should have received a copy of the GNU General Public License along with # HyperKitty. If not, see <http://www.gnu.org/licenses/>. # # Author: Aurelien Bompard <abompard@fedoraproject.org> # class PostingFailed(Exception): pass def post_to_list(request, mlist, subject, message, headers=None, attachments=None): if not mlist: # Make sure the list exists to avoid posting to any email addess raise SuspiciousOperation("I don't know this mailing-list") if headers is None: headers = {} # Check that the user is subscribed try: mailman.subscribe(mlist.name, request.user) except MailmanConnectionError: raise PostingFailed("Can't connect to Mailman's REST server, " "your message has not been sent.") # send the message headers["User-Agent"] = "HyperKitty on %s" % request.build_absolute_uri("/") <|code_end|> , predict the immediate next line with the help of imports: from django.core.exceptions import SuspiciousOperation from django.core.mail import EmailMessage from mailmanclient import MailmanConnectionError from hyperkitty.lib import mailman and context (classes, functions, sometimes code) from other files: # Path: hyperkitty/lib/mailman.py # def get_mailman_client(): # def subscribe(list_address, user): # def __init__(self, name): # def sync_with_mailman(): # class FakeMMList: . Output only the next line.
if not request.user.first_name and not request.user.last_name:
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (C) 1998-2012 by the Free Software Foundation, Inc. # # This file is part of HyperKitty. # # HyperKitty is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # HyperKitty is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # HyperKitty. If not, see <http://www.gnu.org/licenses/>. # # Author: Aurelien Bompard <abompard@fedoraproject.org> # from __future__ import with_statement, absolute_import, unicode_literals, print_function def summary(request, list_name=None): if list_name is None: <|code_end|> . Use current file imports: import os import mailbox import datetime import tempfile import gzip from cStringIO import StringIO from django.core.urlresolvers import reverse from django.http import HttpResponse, Http404 from django.shortcuts import redirect from hyperkitty.models import Email from hyperkitty.lib.compat import get_list_by_name, month_name_to_num and context (classes, functions, or code) from other files: # Path: hyperkitty/models.py # class Email(models.Model): # """ # An archived email, from a mailing-list. It is identified by both the list # name and the message id. # """ # mailinglist = models.ForeignKey("MailingList", related_name="emails") # message_id = models.CharField(max_length=255, db_index=True) # message_id_hash = models.CharField(max_length=255, db_index=True) # sender = models.ForeignKey("Sender", related_name="emails") # subject = models.CharField(max_length="512", db_index=True) # content = models.TextField() # date = models.DateTimeField(db_index=True) # timezone = models.SmallIntegerField() # in_reply_to = models.CharField( # max_length=255, null=True, blank=True, db_index=True) # parent = models.ForeignKey("self", # blank=True, null=True, on_delete=models.SET_NULL, # related_name="children") # thread = models.ForeignKey("Thread", related_name="emails") # archived_date = models.DateTimeField(auto_now_add=True, db_index=True) # thread_depth = models.IntegerField(default=0) # thread_order = models.IntegerField(default=0, db_index=True) # # class Meta: # unique_together = ("mailinglist", "message_id") # # # def get_votes(self): # return get_votes(self) # # def vote(self, value, user): # # Checks if the user has already voted for this message. # existing = self.votes.filter(user=user).first() # if existing is not None and existing.value == value: # return # Vote already recorded (should I raise an exception?) # if value not in (0, 1, -1): # raise ValueError("A vote can only be +1 or -1 (or 0 to cancel)") # if existing is not None: # # vote changed or cancelled # if value == 0: # existing.delete() # else: # existing.value = value # existing.save() # else: # # new vote # vote = Vote(email=self, user=user, value=value) # vote.save() # # def set_parent(self, parent): # if self.id == parent.id: # raise ValueError("An email can't be its own parent") # # Compute the subthread # subthread = [self] # def _collect_children(current_email): # children = list(current_email.children.all()) # if not children: # return # subthread.extend(children) # for child in children: # _collect_children(child) # _collect_children(self) # # now set my new parent value # old_parent_id = self.parent_id # self.parent = parent # self.save(update_fields=["parent_id"]) # # If my future parent is in my current subthread, I need to set its # # parent to my current parent # if parent in subthread: # parent.parent_id = old_parent_id # parent.save(update_fields=["parent_id"]) # # do it after setting the new parent_id to avoid having two # # parent_ids set to None at the same time (IntegrityError) # if self.thread_id != parent.thread_id: # # we changed the thread, reattach the subthread # former_thread = self.thread # for child in subthread: # child.thread = parent.thread # child.save(update_fields=["thread_id"]) # if child.date > parent.thread.date_active: # parent.thread.date_active = child.date # parent.thread.save() # # if we were the starting email, or former thread may be empty # if former_thread.emails.count() == 0: # former_thread.delete() # compute_thread_order_and_depth(parent.thread) # # Path: hyperkitty/lib/compat.py # def get_list_by_name(list_name, domain): # matching = list(MailingList.objects.filter(name__startswith=list_name+"@")) # if len(matching) == 0: # no candidate found # raise Http404("No archived mailinglist by that name") # if len(matching) == 1: # only one candidate # return matching[0] # # # more than one result, try using the hostname # domain = PORT_IN_URL.sub('', domain) # list_fqdn = "%s@%s" % (list_name, domain) # try: # return MailingList.objects.get(name=list_fqdn) # except MailingList.DoesNotExist: # # return the first match, arbitrarily # return matching[0] # # def month_name_to_num(month_name): # """map month names to months numbers""" # today = datetime.date.today() # months = dict( (today.replace(month=num).strftime('%B'), num) # for num in range(1, 12) ) # return months[month_name] . Output only the next line.
return redirect(reverse('hk_root'))
Continue the code snippet: <|code_start|># HyperKitty is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # HyperKitty. If not, see <http://www.gnu.org/licenses/>. # # Author: Aurelien Bompard <abompard@fedoraproject.org> # from __future__ import with_statement, absolute_import, unicode_literals, print_function def summary(request, list_name=None): if list_name is None: return redirect(reverse('hk_root')) mlist = get_list_by_name(list_name, request.get_host()) return redirect(reverse('hk_list_overview', kwargs={'mlist_fqdn': mlist.name})) def arch_month(request, list_name, year, month_name, summary_type="thread"): # pylint: disable=unused-argument mlist = get_list_by_name(list_name, request.get_host()) return redirect(reverse('hk_archives_with_month', kwargs={ 'mlist_fqdn': mlist.name, <|code_end|> . Use current file imports: import os import mailbox import datetime import tempfile import gzip from cStringIO import StringIO from django.core.urlresolvers import reverse from django.http import HttpResponse, Http404 from django.shortcuts import redirect from hyperkitty.models import Email from hyperkitty.lib.compat import get_list_by_name, month_name_to_num and context (classes, functions, or code) from other files: # Path: hyperkitty/models.py # class Email(models.Model): # """ # An archived email, from a mailing-list. It is identified by both the list # name and the message id. # """ # mailinglist = models.ForeignKey("MailingList", related_name="emails") # message_id = models.CharField(max_length=255, db_index=True) # message_id_hash = models.CharField(max_length=255, db_index=True) # sender = models.ForeignKey("Sender", related_name="emails") # subject = models.CharField(max_length="512", db_index=True) # content = models.TextField() # date = models.DateTimeField(db_index=True) # timezone = models.SmallIntegerField() # in_reply_to = models.CharField( # max_length=255, null=True, blank=True, db_index=True) # parent = models.ForeignKey("self", # blank=True, null=True, on_delete=models.SET_NULL, # related_name="children") # thread = models.ForeignKey("Thread", related_name="emails") # archived_date = models.DateTimeField(auto_now_add=True, db_index=True) # thread_depth = models.IntegerField(default=0) # thread_order = models.IntegerField(default=0, db_index=True) # # class Meta: # unique_together = ("mailinglist", "message_id") # # # def get_votes(self): # return get_votes(self) # # def vote(self, value, user): # # Checks if the user has already voted for this message. # existing = self.votes.filter(user=user).first() # if existing is not None and existing.value == value: # return # Vote already recorded (should I raise an exception?) # if value not in (0, 1, -1): # raise ValueError("A vote can only be +1 or -1 (or 0 to cancel)") # if existing is not None: # # vote changed or cancelled # if value == 0: # existing.delete() # else: # existing.value = value # existing.save() # else: # # new vote # vote = Vote(email=self, user=user, value=value) # vote.save() # # def set_parent(self, parent): # if self.id == parent.id: # raise ValueError("An email can't be its own parent") # # Compute the subthread # subthread = [self] # def _collect_children(current_email): # children = list(current_email.children.all()) # if not children: # return # subthread.extend(children) # for child in children: # _collect_children(child) # _collect_children(self) # # now set my new parent value # old_parent_id = self.parent_id # self.parent = parent # self.save(update_fields=["parent_id"]) # # If my future parent is in my current subthread, I need to set its # # parent to my current parent # if parent in subthread: # parent.parent_id = old_parent_id # parent.save(update_fields=["parent_id"]) # # do it after setting the new parent_id to avoid having two # # parent_ids set to None at the same time (IntegrityError) # if self.thread_id != parent.thread_id: # # we changed the thread, reattach the subthread # former_thread = self.thread # for child in subthread: # child.thread = parent.thread # child.save(update_fields=["thread_id"]) # if child.date > parent.thread.date_active: # parent.thread.date_active = child.date # parent.thread.save() # # if we were the starting email, or former thread may be empty # if former_thread.emails.count() == 0: # former_thread.delete() # compute_thread_order_and_depth(parent.thread) # # Path: hyperkitty/lib/compat.py # def get_list_by_name(list_name, domain): # matching = list(MailingList.objects.filter(name__startswith=list_name+"@")) # if len(matching) == 0: # no candidate found # raise Http404("No archived mailinglist by that name") # if len(matching) == 1: # only one candidate # return matching[0] # # # more than one result, try using the hostname # domain = PORT_IN_URL.sub('', domain) # list_fqdn = "%s@%s" % (list_name, domain) # try: # return MailingList.objects.get(name=list_fqdn) # except MailingList.DoesNotExist: # # return the first match, arbitrarily # return matching[0] # # def month_name_to_num(month_name): # """map month names to months numbers""" # today = datetime.date.today() # months = dict( (today.replace(month=num).strftime('%B'), num) # for num in range(1, 12) ) # return months[month_name] . Output only the next line.
'year': year,
Given snippet: <|code_start|># Copyright (C) 1998-2012 by the Free Software Foundation, Inc. # # This file is part of HyperKitty. # # HyperKitty is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # HyperKitty is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # HyperKitty. If not, see <http://www.gnu.org/licenses/>. # # Author: Aurelien Bompard <abompard@fedoraproject.org> # from __future__ import with_statement, absolute_import, unicode_literals, print_function def summary(request, list_name=None): if list_name is None: return redirect(reverse('hk_root')) mlist = get_list_by_name(list_name, request.get_host()) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import mailbox import datetime import tempfile import gzip from cStringIO import StringIO from django.core.urlresolvers import reverse from django.http import HttpResponse, Http404 from django.shortcuts import redirect from hyperkitty.models import Email from hyperkitty.lib.compat import get_list_by_name, month_name_to_num and context: # Path: hyperkitty/models.py # class Email(models.Model): # """ # An archived email, from a mailing-list. It is identified by both the list # name and the message id. # """ # mailinglist = models.ForeignKey("MailingList", related_name="emails") # message_id = models.CharField(max_length=255, db_index=True) # message_id_hash = models.CharField(max_length=255, db_index=True) # sender = models.ForeignKey("Sender", related_name="emails") # subject = models.CharField(max_length="512", db_index=True) # content = models.TextField() # date = models.DateTimeField(db_index=True) # timezone = models.SmallIntegerField() # in_reply_to = models.CharField( # max_length=255, null=True, blank=True, db_index=True) # parent = models.ForeignKey("self", # blank=True, null=True, on_delete=models.SET_NULL, # related_name="children") # thread = models.ForeignKey("Thread", related_name="emails") # archived_date = models.DateTimeField(auto_now_add=True, db_index=True) # thread_depth = models.IntegerField(default=0) # thread_order = models.IntegerField(default=0, db_index=True) # # class Meta: # unique_together = ("mailinglist", "message_id") # # # def get_votes(self): # return get_votes(self) # # def vote(self, value, user): # # Checks if the user has already voted for this message. # existing = self.votes.filter(user=user).first() # if existing is not None and existing.value == value: # return # Vote already recorded (should I raise an exception?) # if value not in (0, 1, -1): # raise ValueError("A vote can only be +1 or -1 (or 0 to cancel)") # if existing is not None: # # vote changed or cancelled # if value == 0: # existing.delete() # else: # existing.value = value # existing.save() # else: # # new vote # vote = Vote(email=self, user=user, value=value) # vote.save() # # def set_parent(self, parent): # if self.id == parent.id: # raise ValueError("An email can't be its own parent") # # Compute the subthread # subthread = [self] # def _collect_children(current_email): # children = list(current_email.children.all()) # if not children: # return # subthread.extend(children) # for child in children: # _collect_children(child) # _collect_children(self) # # now set my new parent value # old_parent_id = self.parent_id # self.parent = parent # self.save(update_fields=["parent_id"]) # # If my future parent is in my current subthread, I need to set its # # parent to my current parent # if parent in subthread: # parent.parent_id = old_parent_id # parent.save(update_fields=["parent_id"]) # # do it after setting the new parent_id to avoid having two # # parent_ids set to None at the same time (IntegrityError) # if self.thread_id != parent.thread_id: # # we changed the thread, reattach the subthread # former_thread = self.thread # for child in subthread: # child.thread = parent.thread # child.save(update_fields=["thread_id"]) # if child.date > parent.thread.date_active: # parent.thread.date_active = child.date # parent.thread.save() # # if we were the starting email, or former thread may be empty # if former_thread.emails.count() == 0: # former_thread.delete() # compute_thread_order_and_depth(parent.thread) # # Path: hyperkitty/lib/compat.py # def get_list_by_name(list_name, domain): # matching = list(MailingList.objects.filter(name__startswith=list_name+"@")) # if len(matching) == 0: # no candidate found # raise Http404("No archived mailinglist by that name") # if len(matching) == 1: # only one candidate # return matching[0] # # # more than one result, try using the hostname # domain = PORT_IN_URL.sub('', domain) # list_fqdn = "%s@%s" % (list_name, domain) # try: # return MailingList.objects.get(name=list_fqdn) # except MailingList.DoesNotExist: # # return the first match, arbitrarily # return matching[0] # # def month_name_to_num(month_name): # """map month names to months numbers""" # today = datetime.date.today() # months = dict( (today.replace(month=num).strftime('%B'), num) # for num in range(1, 12) ) # return months[month_name] which might include code, classes, or functions. Output only the next line.
return redirect(reverse('hk_list_overview',
Predict the next line for this snippet: <|code_start|> from __future__ import absolute_import, print_function __all__ = ['READABLE', 'WRITABLE'] READABLE = pyuv.UV_READABLE WRITABLE = pyuv.UV_WRITABLE if __debug__: def dump(mp): print('== Dumping MultiPoll {!r}'.format(mp)) # [total, nreaders, nwriters, nreadwrite, disabled] stats = [0, 0, 0, 0, 0] def walker(callback, args): stats[0] += 1 if args == READABLE: stats[1] += 1 elif args == WRITABLE: stats[2] += 1 elif args == READABLE|WRITABLE: stats[3] += 1 elif not args: stats[4] += 1 return True walk_callbacks(mp, walker) print('Using Poll: {!r}'.format(mp._poll)) <|code_end|> with the help of current file imports: import pyuv from .callbacks import add_callback, remove_callback, walk_callbacks from .callbacks import has_callback, clear_callbacks and context from other files: # Path: lib/gruvi/callbacks.py # def add_callback(obj, callback, args=()): # """Add a callback to an object.""" # callbacks = obj._callbacks # node = Node(callback, args) # # Store a single callback directly in _callbacks # if callbacks is None: # obj._callbacks = node # return node # # Otherwise use a dllist. # if not isinstance(callbacks, dllist): # obj._callbacks = dllist() # obj._callbacks.insert(callbacks) # callbacks = obj._callbacks # callbacks.insert(node) # return node # # def remove_callback(obj, handle): # """Remove a callback from an object.""" # callbacks = obj._callbacks # if callbacks is handle: # obj._callbacks = None # elif isinstance(callbacks, dllist): # callbacks.remove(handle) # if not callbacks: # obj._callbacks = None # # def walk_callbacks(obj, func, log=None): # """Call func(callback, args) for all callbacks and keep only those # callbacks for which the function returns True.""" # callbacks = obj._callbacks # if isinstance(callbacks, Node): # node = callbacks # try: # if not func(node.data, node.extra): # obj._callbacks = None # except Exception: # if log is None: # log = logging.get_logger() # log.exception('uncaught exception in callback') # elif isinstance(callbacks, dllist): # for node in callbacks: # try: # if func(node.data, node.extra): # continue # callbacks.remove(node) # except Exception: # if log is None: # log = logging.get_logger() # log.exception('uncaught exception in callback') # if not callbacks: # obj._callbacks = None # # Path: lib/gruvi/callbacks.py # def has_callback(obj, handle): # """Return whether a callback is currently registered for an object.""" # callbacks = obj._callbacks # if not callbacks: # return False # if isinstance(callbacks, Node): # return handle is callbacks # else: # return handle in callbacks # # def clear_callbacks(obj): # """Remove all callbacks from an object.""" # callbacks = obj._callbacks # if isinstance(callbacks, dllist): # # Help the garbage collector by clearing all links. # callbacks.clear() # obj._callbacks = None , which may contain function names, class names, or code. Output only the next line.
print('Poll FD: {}'.format(mp._poll.fileno()))
Next line prediction: <|code_start|># # This file is part of Gruvi. Gruvi is free software available under the # terms of the MIT license. See the file "LICENSE" that was provided # together with this source file for the licensing terms. # # Copyright (c) 2012-2014 the Gruvi authors. See the file "AUTHORS" for a # complete list. from __future__ import absolute_import, print_function __all__ = ['READABLE', 'WRITABLE'] READABLE = pyuv.UV_READABLE WRITABLE = pyuv.UV_WRITABLE if __debug__: def dump(mp): print('== Dumping MultiPoll {!r}'.format(mp)) # [total, nreaders, nwriters, nreadwrite, disabled] stats = [0, 0, 0, 0, 0] def walker(callback, args): stats[0] += 1 if args == READABLE: <|code_end|> . Use current file imports: (import pyuv from .callbacks import add_callback, remove_callback, walk_callbacks from .callbacks import has_callback, clear_callbacks) and context including class names, function names, or small code snippets from other files: # Path: lib/gruvi/callbacks.py # def add_callback(obj, callback, args=()): # """Add a callback to an object.""" # callbacks = obj._callbacks # node = Node(callback, args) # # Store a single callback directly in _callbacks # if callbacks is None: # obj._callbacks = node # return node # # Otherwise use a dllist. # if not isinstance(callbacks, dllist): # obj._callbacks = dllist() # obj._callbacks.insert(callbacks) # callbacks = obj._callbacks # callbacks.insert(node) # return node # # def remove_callback(obj, handle): # """Remove a callback from an object.""" # callbacks = obj._callbacks # if callbacks is handle: # obj._callbacks = None # elif isinstance(callbacks, dllist): # callbacks.remove(handle) # if not callbacks: # obj._callbacks = None # # def walk_callbacks(obj, func, log=None): # """Call func(callback, args) for all callbacks and keep only those # callbacks for which the function returns True.""" # callbacks = obj._callbacks # if isinstance(callbacks, Node): # node = callbacks # try: # if not func(node.data, node.extra): # obj._callbacks = None # except Exception: # if log is None: # log = logging.get_logger() # log.exception('uncaught exception in callback') # elif isinstance(callbacks, dllist): # for node in callbacks: # try: # if func(node.data, node.extra): # continue # callbacks.remove(node) # except Exception: # if log is None: # log = logging.get_logger() # log.exception('uncaught exception in callback') # if not callbacks: # obj._callbacks = None # # Path: lib/gruvi/callbacks.py # def has_callback(obj, handle): # """Return whether a callback is currently registered for an object.""" # callbacks = obj._callbacks # if not callbacks: # return False # if isinstance(callbacks, Node): # return handle is callbacks # else: # return handle in callbacks # # def clear_callbacks(obj): # """Remove all callbacks from an object.""" # callbacks = obj._callbacks # if isinstance(callbacks, dllist): # # Help the garbage collector by clearing all links. # callbacks.clear() # obj._callbacks = None . Output only the next line.
stats[1] += 1
Given the code snippet: <|code_start|># # This file is part of Gruvi. Gruvi is free software available under the # terms of the MIT license. See the file "LICENSE" that was provided # together with this source file for the licensing terms. # # Copyright (c) 2012-2014 the Gruvi authors. See the file "AUTHORS" for a # complete list. from __future__ import absolute_import, print_function __all__ = ['READABLE', 'WRITABLE'] READABLE = pyuv.UV_READABLE WRITABLE = pyuv.UV_WRITABLE if __debug__: def dump(mp): print('== Dumping MultiPoll {!r}'.format(mp)) # [total, nreaders, nwriters, nreadwrite, disabled] <|code_end|> , generate the next line using the imports in this file: import pyuv from .callbacks import add_callback, remove_callback, walk_callbacks from .callbacks import has_callback, clear_callbacks and context (functions, classes, or occasionally code) from other files: # Path: lib/gruvi/callbacks.py # def add_callback(obj, callback, args=()): # """Add a callback to an object.""" # callbacks = obj._callbacks # node = Node(callback, args) # # Store a single callback directly in _callbacks # if callbacks is None: # obj._callbacks = node # return node # # Otherwise use a dllist. # if not isinstance(callbacks, dllist): # obj._callbacks = dllist() # obj._callbacks.insert(callbacks) # callbacks = obj._callbacks # callbacks.insert(node) # return node # # def remove_callback(obj, handle): # """Remove a callback from an object.""" # callbacks = obj._callbacks # if callbacks is handle: # obj._callbacks = None # elif isinstance(callbacks, dllist): # callbacks.remove(handle) # if not callbacks: # obj._callbacks = None # # def walk_callbacks(obj, func, log=None): # """Call func(callback, args) for all callbacks and keep only those # callbacks for which the function returns True.""" # callbacks = obj._callbacks # if isinstance(callbacks, Node): # node = callbacks # try: # if not func(node.data, node.extra): # obj._callbacks = None # except Exception: # if log is None: # log = logging.get_logger() # log.exception('uncaught exception in callback') # elif isinstance(callbacks, dllist): # for node in callbacks: # try: # if func(node.data, node.extra): # continue # callbacks.remove(node) # except Exception: # if log is None: # log = logging.get_logger() # log.exception('uncaught exception in callback') # if not callbacks: # obj._callbacks = None # # Path: lib/gruvi/callbacks.py # def has_callback(obj, handle): # """Return whether a callback is currently registered for an object.""" # callbacks = obj._callbacks # if not callbacks: # return False # if isinstance(callbacks, Node): # return handle is callbacks # else: # return handle in callbacks # # def clear_callbacks(obj): # """Remove all callbacks from an object.""" # callbacks = obj._callbacks # if isinstance(callbacks, dllist): # # Help the garbage collector by clearing all links. # callbacks.clear() # obj._callbacks = None . Output only the next line.
stats = [0, 0, 0, 0, 0]
Predict the next line for this snippet: <|code_start|># # This file is part of Gruvi. Gruvi is free software available under the # terms of the MIT license. See the file "LICENSE" that was provided # together with this source file for the licensing terms. # # Copyright (c) 2012-2014 the Gruvi authors. See the file "AUTHORS" for a # complete list. from __future__ import absolute_import, print_function __all__ = ['READABLE', 'WRITABLE'] READABLE = pyuv.UV_READABLE WRITABLE = pyuv.UV_WRITABLE if __debug__: def dump(mp): print('== Dumping MultiPoll {!r}'.format(mp)) # [total, nreaders, nwriters, nreadwrite, disabled] stats = [0, 0, 0, 0, 0] def walker(callback, args): stats[0] += 1 if args == READABLE: <|code_end|> with the help of current file imports: import pyuv from .callbacks import add_callback, remove_callback, walk_callbacks from .callbacks import has_callback, clear_callbacks and context from other files: # Path: lib/gruvi/callbacks.py # def add_callback(obj, callback, args=()): # """Add a callback to an object.""" # callbacks = obj._callbacks # node = Node(callback, args) # # Store a single callback directly in _callbacks # if callbacks is None: # obj._callbacks = node # return node # # Otherwise use a dllist. # if not isinstance(callbacks, dllist): # obj._callbacks = dllist() # obj._callbacks.insert(callbacks) # callbacks = obj._callbacks # callbacks.insert(node) # return node # # def remove_callback(obj, handle): # """Remove a callback from an object.""" # callbacks = obj._callbacks # if callbacks is handle: # obj._callbacks = None # elif isinstance(callbacks, dllist): # callbacks.remove(handle) # if not callbacks: # obj._callbacks = None # # def walk_callbacks(obj, func, log=None): # """Call func(callback, args) for all callbacks and keep only those # callbacks for which the function returns True.""" # callbacks = obj._callbacks # if isinstance(callbacks, Node): # node = callbacks # try: # if not func(node.data, node.extra): # obj._callbacks = None # except Exception: # if log is None: # log = logging.get_logger() # log.exception('uncaught exception in callback') # elif isinstance(callbacks, dllist): # for node in callbacks: # try: # if func(node.data, node.extra): # continue # callbacks.remove(node) # except Exception: # if log is None: # log = logging.get_logger() # log.exception('uncaught exception in callback') # if not callbacks: # obj._callbacks = None # # Path: lib/gruvi/callbacks.py # def has_callback(obj, handle): # """Return whether a callback is currently registered for an object.""" # callbacks = obj._callbacks # if not callbacks: # return False # if isinstance(callbacks, Node): # return handle is callbacks # else: # return handle in callbacks # # def clear_callbacks(obj): # """Remove all callbacks from an object.""" # callbacks = obj._callbacks # if isinstance(callbacks, dllist): # # Help the garbage collector by clearing all links. # callbacks.clear() # obj._callbacks = None , which may contain function names, class names, or code. Output only the next line.
stats[1] += 1
Given snippet: <|code_start|> READABLE = pyuv.UV_READABLE WRITABLE = pyuv.UV_WRITABLE if __debug__: def dump(mp): print('== Dumping MultiPoll {!r}'.format(mp)) # [total, nreaders, nwriters, nreadwrite, disabled] stats = [0, 0, 0, 0, 0] def walker(callback, args): stats[0] += 1 if args == READABLE: stats[1] += 1 elif args == WRITABLE: stats[2] += 1 elif args == READABLE|WRITABLE: stats[3] += 1 elif not args: stats[4] += 1 return True walk_callbacks(mp, walker) print('Using Poll: {!r}'.format(mp._poll)) print('Poll FD: {}'.format(mp._poll.fileno())) print('Total callbacks: {}'.format(stats[0])) print('Callbacks registered for read: {}'.format(stats[1])) print('Callbacks registered for write: {}'.format(stats[2])) print('Callbacks registered for read|write: {}'.format(stats[3])) <|code_end|> , continue by predicting the next line. Consider current file imports: import pyuv from .callbacks import add_callback, remove_callback, walk_callbacks from .callbacks import has_callback, clear_callbacks and context: # Path: lib/gruvi/callbacks.py # def add_callback(obj, callback, args=()): # """Add a callback to an object.""" # callbacks = obj._callbacks # node = Node(callback, args) # # Store a single callback directly in _callbacks # if callbacks is None: # obj._callbacks = node # return node # # Otherwise use a dllist. # if not isinstance(callbacks, dllist): # obj._callbacks = dllist() # obj._callbacks.insert(callbacks) # callbacks = obj._callbacks # callbacks.insert(node) # return node # # def remove_callback(obj, handle): # """Remove a callback from an object.""" # callbacks = obj._callbacks # if callbacks is handle: # obj._callbacks = None # elif isinstance(callbacks, dllist): # callbacks.remove(handle) # if not callbacks: # obj._callbacks = None # # def walk_callbacks(obj, func, log=None): # """Call func(callback, args) for all callbacks and keep only those # callbacks for which the function returns True.""" # callbacks = obj._callbacks # if isinstance(callbacks, Node): # node = callbacks # try: # if not func(node.data, node.extra): # obj._callbacks = None # except Exception: # if log is None: # log = logging.get_logger() # log.exception('uncaught exception in callback') # elif isinstance(callbacks, dllist): # for node in callbacks: # try: # if func(node.data, node.extra): # continue # callbacks.remove(node) # except Exception: # if log is None: # log = logging.get_logger() # log.exception('uncaught exception in callback') # if not callbacks: # obj._callbacks = None # # Path: lib/gruvi/callbacks.py # def has_callback(obj, handle): # """Return whether a callback is currently registered for an object.""" # callbacks = obj._callbacks # if not callbacks: # return False # if isinstance(callbacks, Node): # return handle is callbacks # else: # return handle in callbacks # # def clear_callbacks(obj): # """Remove all callbacks from an object.""" # callbacks = obj._callbacks # if isinstance(callbacks, dllist): # # Help the garbage collector by clearing all links. # callbacks.clear() # obj._callbacks = None which might include code, classes, or functions. Output only the next line.
print('Callbacks that are inactive: {}'.format(stats[4]))
Predict the next line for this snippet: <|code_start|>#! -*- coding:utf-8 -*- class Adres(models.Model): kullanici = models.ForeignKey(IsVeren,related_name="adres") adres_basligi = models.CharField(max_length=50) adres = models.CharField(max_length=80) sehir = models.CharField(max_length=40) ilce = models.CharField(max_length=40,blank=True, null=True) semt = models.CharField(max_length=40,blank=True, null=True) mahalle = models.CharField(max_length=40,blank=True, null=True) sokak = models.CharField(max_length=40,blank=True, null=True) no = models.CharField(max_length=10,blank=True, null=True) posta_kodu = models.CharField(max_length=40,blank=True, null=True) def __str__(self): <|code_end|> with the help of current file imports: from django.db import models from django.contrib.auth.models import User from kullanici.models import IsVeren and context from other files: # Path: kullanici/models.py # class IsVeren(models.Model): # kullanici = models.OneToOneField(User,related_name="is_veren") # cinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # cinsiyet = models.CharField(max_length=1, choices=cinsiyetSecenekleri,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="users") # # def __str__(self): # return self.kullanici.username # # def getIsveren(kullaniciID): # return IsVeren.objects.get(pk=kullaniciID) # # class Meta: # verbose_name ="İş Veren Profili" # verbose_name_plural="İş Veren Profilleri" , which may contain function names, class names, or code. Output only the next line.
return self.kullanici.kullanici.username + " " + self.adres_basligi
Given the code snippet: <|code_start|> # Register your models here. admin.site.register(IsArayan) class IsVerenInline(admin.StackedInline): model = Adres <|code_end|> , generate the next line using the imports in this file: from django.contrib import admin from .models import IsArayan,IsVeren from adres.models import Adres and context (functions, classes, or occasionally code) from other files: # Path: kullanici/models.py # class IsArayan(models.Model): # kullanici = models.OneToOneField(User,related_name="is_arayan") # hizmetler = models.ManyToManyField(Hizmet,related_name="hizmetler") # CinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # ISARAYANTIPI = ( # ('S', 'Şirket'), # ('B', 'Bireysel'), # ) # cinsiyet = models.CharField(max_length=1, choices=CinsiyetSecenekleri,blank=True, null=True) # isArayanTipi = models.CharField(max_length=1, choices=ISARAYANTIPI,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="kullanicilar") # # def getIsArayan(kullaniciID): # return IsArayan.objects.get(pk=kullaniciID) # # def __str__(self): # return self.kullanici.username # # class Meta: # verbose_name ="İş Arayan Profili" # verbose_name_plural="İş Arayan Profilleri" # # class IsVeren(models.Model): # kullanici = models.OneToOneField(User,related_name="is_veren") # cinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # cinsiyet = models.CharField(max_length=1, choices=cinsiyetSecenekleri,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="users") # # def __str__(self): # return self.kullanici.username # # def getIsveren(kullaniciID): # return IsVeren.objects.get(pk=kullaniciID) # # class Meta: # verbose_name ="İş Veren Profili" # verbose_name_plural="İş Veren Profilleri" # # Path: adres/models.py # class Adres(models.Model): # kullanici = models.ForeignKey(IsVeren,related_name="adres") # adres_basligi = models.CharField(max_length=50) # adres = models.CharField(max_length=80) # sehir = models.CharField(max_length=40) # ilce = models.CharField(max_length=40,blank=True, null=True) # semt = models.CharField(max_length=40,blank=True, null=True) # mahalle = models.CharField(max_length=40,blank=True, null=True) # sokak = models.CharField(max_length=40,blank=True, null=True) # no = models.CharField(max_length=10,blank=True, null=True) # posta_kodu = models.CharField(max_length=40,blank=True, null=True) # # def __str__(self): # return self.kullanici.kullanici.username + " " + self.adres_basligi # # class Meta: # verbose_name ="İş Veren Adresi" # verbose_name_plural="İş Veren Adresleri" # # def adresSec(adresID): # return Adres.objects.get(pk=adresID) . Output only the next line.
class ExtendedVendorAdmin(admin.ModelAdmin):
Given the following code snippet before the placeholder: <|code_start|> # Register your models here. admin.site.register(IsArayan) class IsVerenInline(admin.StackedInline): model = Adres class ExtendedVendorAdmin(admin.ModelAdmin): <|code_end|> , predict the next line using imports from the current file: from django.contrib import admin from .models import IsArayan,IsVeren from adres.models import Adres and context including class names, function names, and sometimes code from other files: # Path: kullanici/models.py # class IsArayan(models.Model): # kullanici = models.OneToOneField(User,related_name="is_arayan") # hizmetler = models.ManyToManyField(Hizmet,related_name="hizmetler") # CinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # ISARAYANTIPI = ( # ('S', 'Şirket'), # ('B', 'Bireysel'), # ) # cinsiyet = models.CharField(max_length=1, choices=CinsiyetSecenekleri,blank=True, null=True) # isArayanTipi = models.CharField(max_length=1, choices=ISARAYANTIPI,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="kullanicilar") # # def getIsArayan(kullaniciID): # return IsArayan.objects.get(pk=kullaniciID) # # def __str__(self): # return self.kullanici.username # # class Meta: # verbose_name ="İş Arayan Profili" # verbose_name_plural="İş Arayan Profilleri" # # class IsVeren(models.Model): # kullanici = models.OneToOneField(User,related_name="is_veren") # cinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # cinsiyet = models.CharField(max_length=1, choices=cinsiyetSecenekleri,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="users") # # def __str__(self): # return self.kullanici.username # # def getIsveren(kullaniciID): # return IsVeren.objects.get(pk=kullaniciID) # # class Meta: # verbose_name ="İş Veren Profili" # verbose_name_plural="İş Veren Profilleri" # # Path: adres/models.py # class Adres(models.Model): # kullanici = models.ForeignKey(IsVeren,related_name="adres") # adres_basligi = models.CharField(max_length=50) # adres = models.CharField(max_length=80) # sehir = models.CharField(max_length=40) # ilce = models.CharField(max_length=40,blank=True, null=True) # semt = models.CharField(max_length=40,blank=True, null=True) # mahalle = models.CharField(max_length=40,blank=True, null=True) # sokak = models.CharField(max_length=40,blank=True, null=True) # no = models.CharField(max_length=10,blank=True, null=True) # posta_kodu = models.CharField(max_length=40,blank=True, null=True) # # def __str__(self): # return self.kullanici.kullanici.username + " " + self.adres_basligi # # class Meta: # verbose_name ="İş Veren Adresi" # verbose_name_plural="İş Veren Adresleri" # # def adresSec(adresID): # return Adres.objects.get(pk=adresID) . Output only the next line.
inlines = (IsVerenInline,)
Using the snippet: <|code_start|> class Ilan(models.Model): kullanici = models.ForeignKey(IsVeren,related_name="is_veren") hizmetDescr = models.ForeignKey(HizmetDescription,related_name="hizmet_descr") hizmet = models.ForeignKey(Hizmet,blank=True,null=True,related_name="hizmet_tipi") adres = models.ForeignKey(Adres,blank=True,null=True,related_name="is_veren_adresi") ilan_basligi = models.CharField(max_length=40) <|code_end|> , determine the next line of code. You have imports: from django.db import models from django.contrib.auth.models import User from kullanici.models import IsVeren from adres.models import Adres from hizmet.models import HizmetDescription,Hizmet from register.models import Register and context (class names, function names, or code) available: # Path: kullanici/models.py # class IsVeren(models.Model): # kullanici = models.OneToOneField(User,related_name="is_veren") # cinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # cinsiyet = models.CharField(max_length=1, choices=cinsiyetSecenekleri,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="users") # # def __str__(self): # return self.kullanici.username # # def getIsveren(kullaniciID): # return IsVeren.objects.get(pk=kullaniciID) # # class Meta: # verbose_name ="İş Veren Profili" # verbose_name_plural="İş Veren Profilleri" # # Path: adres/models.py # class Adres(models.Model): # kullanici = models.ForeignKey(IsVeren,related_name="adres") # adres_basligi = models.CharField(max_length=50) # adres = models.CharField(max_length=80) # sehir = models.CharField(max_length=40) # ilce = models.CharField(max_length=40,blank=True, null=True) # semt = models.CharField(max_length=40,blank=True, null=True) # mahalle = models.CharField(max_length=40,blank=True, null=True) # sokak = models.CharField(max_length=40,blank=True, null=True) # no = models.CharField(max_length=10,blank=True, null=True) # posta_kodu = models.CharField(max_length=40,blank=True, null=True) # # def __str__(self): # return self.kullanici.kullanici.username + " " + self.adres_basligi # # class Meta: # verbose_name ="İş Veren Adresi" # verbose_name_plural="İş Veren Adresleri" # # def adresSec(adresID): # return Adres.objects.get(pk=adresID) # # Path: hizmet/models.py # class HizmetDescription(models.Model): # hizmetBasligi = models.CharField(max_length=50) # hizmet = models.ForeignKey(Hizmet) # yolMasrafi = models.BooleanField(default=True) # yemekMasrafi = models.BooleanField(default=True) # calismaTipleri = ( # ('U', 'Uzaktan'), # ('A', 'Çalışma Alanında'), # ) # calismaTipi = models.CharField(max_length=1, choices=calismaTipleri,blank=True, null=True) # # def hizmetSec(kategoriID): # return HizmetDescription.objects.get(pk=kategoriID) # # def __str__(self): # return self.hizmetBasligi # # class Meta: # verbose_name ="Hizmet" # verbose_name_plural="Hizmetler" # # class Hizmet(models.Model): # hizmetAdi = models.CharField(max_length=50) # # def __str__(self): # return self.hizmetAdi # # class Meta: # verbose_name ="Hizmet Türü" # verbose_name_plural="Hizmet Türleri" . Output only the next line.
butceTipleri = (
Continue the code snippet: <|code_start|> sureUzunlugu = models.CharField(max_length=3, choices=sureUzunluklari,default="G") sure = models.IntegerField() butceTipi = models.CharField(max_length=3, choices=butceTipleri,default="TL") butce = models.IntegerField() yayin_tarihi = models.DateTimeField(auto_now_add=True) duzenlenme_tarihi = models.DateField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return self.ilan_basligi class Meta: verbose_name ="İlan" verbose_name_plural="İlanlar" def adresSec(adresID): return Adres.objects.get(pk=adresID) def save(self, *args, **kwargs): ilan = Register.ilanVermeBaslat() ilan = self ilan.kullanici = Register.getIsveren(self.kullanici.pk) ilan.hizmetDescr = Register.hizmetKategorisiSec(self.hizmetDescr.pk) ilan.adres = Ilan.adresSec(self.adres.pk) ilan.hizmet = ilan.hizmetDescr.hizmet ilan.ilan_basligi = self.ilan_basligi <|code_end|> . Use current file imports: from django.db import models from django.contrib.auth.models import User from kullanici.models import IsVeren from adres.models import Adres from hizmet.models import HizmetDescription,Hizmet from register.models import Register and context (classes, functions, or code) from other files: # Path: kullanici/models.py # class IsVeren(models.Model): # kullanici = models.OneToOneField(User,related_name="is_veren") # cinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # cinsiyet = models.CharField(max_length=1, choices=cinsiyetSecenekleri,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="users") # # def __str__(self): # return self.kullanici.username # # def getIsveren(kullaniciID): # return IsVeren.objects.get(pk=kullaniciID) # # class Meta: # verbose_name ="İş Veren Profili" # verbose_name_plural="İş Veren Profilleri" # # Path: adres/models.py # class Adres(models.Model): # kullanici = models.ForeignKey(IsVeren,related_name="adres") # adres_basligi = models.CharField(max_length=50) # adres = models.CharField(max_length=80) # sehir = models.CharField(max_length=40) # ilce = models.CharField(max_length=40,blank=True, null=True) # semt = models.CharField(max_length=40,blank=True, null=True) # mahalle = models.CharField(max_length=40,blank=True, null=True) # sokak = models.CharField(max_length=40,blank=True, null=True) # no = models.CharField(max_length=10,blank=True, null=True) # posta_kodu = models.CharField(max_length=40,blank=True, null=True) # # def __str__(self): # return self.kullanici.kullanici.username + " " + self.adres_basligi # # class Meta: # verbose_name ="İş Veren Adresi" # verbose_name_plural="İş Veren Adresleri" # # def adresSec(adresID): # return Adres.objects.get(pk=adresID) # # Path: hizmet/models.py # class HizmetDescription(models.Model): # hizmetBasligi = models.CharField(max_length=50) # hizmet = models.ForeignKey(Hizmet) # yolMasrafi = models.BooleanField(default=True) # yemekMasrafi = models.BooleanField(default=True) # calismaTipleri = ( # ('U', 'Uzaktan'), # ('A', 'Çalışma Alanında'), # ) # calismaTipi = models.CharField(max_length=1, choices=calismaTipleri,blank=True, null=True) # # def hizmetSec(kategoriID): # return HizmetDescription.objects.get(pk=kategoriID) # # def __str__(self): # return self.hizmetBasligi # # class Meta: # verbose_name ="Hizmet" # verbose_name_plural="Hizmetler" # # class Hizmet(models.Model): # hizmetAdi = models.CharField(max_length=50) # # def __str__(self): # return self.hizmetAdi # # class Meta: # verbose_name ="Hizmet Türü" # verbose_name_plural="Hizmet Türleri" . Output only the next line.
ilan.sureUzunlugu = self.sureUzunlugu
Given snippet: <|code_start|> class Ilan(models.Model): kullanici = models.ForeignKey(IsVeren,related_name="is_veren") hizmetDescr = models.ForeignKey(HizmetDescription,related_name="hizmet_descr") hizmet = models.ForeignKey(Hizmet,blank=True,null=True,related_name="hizmet_tipi") adres = models.ForeignKey(Adres,blank=True,null=True,related_name="is_veren_adresi") ilan_basligi = models.CharField(max_length=40) butceTipleri = ( ('TL', 'Türk Lirası'), ('DLR', 'DOLAR'), ('EUR', 'EURO'), ) sureUzunluklari = ( ('S', 'Saat'), ('G', 'Gün'), ('A', 'Ay'), ('H', 'Hafta'), ('Y', 'Yıl'), ) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.db import models from django.contrib.auth.models import User from kullanici.models import IsVeren from adres.models import Adres from hizmet.models import HizmetDescription,Hizmet from register.models import Register and context: # Path: kullanici/models.py # class IsVeren(models.Model): # kullanici = models.OneToOneField(User,related_name="is_veren") # cinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # cinsiyet = models.CharField(max_length=1, choices=cinsiyetSecenekleri,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="users") # # def __str__(self): # return self.kullanici.username # # def getIsveren(kullaniciID): # return IsVeren.objects.get(pk=kullaniciID) # # class Meta: # verbose_name ="İş Veren Profili" # verbose_name_plural="İş Veren Profilleri" # # Path: adres/models.py # class Adres(models.Model): # kullanici = models.ForeignKey(IsVeren,related_name="adres") # adres_basligi = models.CharField(max_length=50) # adres = models.CharField(max_length=80) # sehir = models.CharField(max_length=40) # ilce = models.CharField(max_length=40,blank=True, null=True) # semt = models.CharField(max_length=40,blank=True, null=True) # mahalle = models.CharField(max_length=40,blank=True, null=True) # sokak = models.CharField(max_length=40,blank=True, null=True) # no = models.CharField(max_length=10,blank=True, null=True) # posta_kodu = models.CharField(max_length=40,blank=True, null=True) # # def __str__(self): # return self.kullanici.kullanici.username + " " + self.adres_basligi # # class Meta: # verbose_name ="İş Veren Adresi" # verbose_name_plural="İş Veren Adresleri" # # def adresSec(adresID): # return Adres.objects.get(pk=adresID) # # Path: hizmet/models.py # class HizmetDescription(models.Model): # hizmetBasligi = models.CharField(max_length=50) # hizmet = models.ForeignKey(Hizmet) # yolMasrafi = models.BooleanField(default=True) # yemekMasrafi = models.BooleanField(default=True) # calismaTipleri = ( # ('U', 'Uzaktan'), # ('A', 'Çalışma Alanında'), # ) # calismaTipi = models.CharField(max_length=1, choices=calismaTipleri,blank=True, null=True) # # def hizmetSec(kategoriID): # return HizmetDescription.objects.get(pk=kategoriID) # # def __str__(self): # return self.hizmetBasligi # # class Meta: # verbose_name ="Hizmet" # verbose_name_plural="Hizmetler" # # class Hizmet(models.Model): # hizmetAdi = models.CharField(max_length=50) # # def __str__(self): # return self.hizmetAdi # # class Meta: # verbose_name ="Hizmet Türü" # verbose_name_plural="Hizmet Türleri" which might include code, classes, or functions. Output only the next line.
sureUzunlugu = models.CharField(max_length=3, choices=sureUzunluklari,default="G")
Next line prediction: <|code_start|> class Ilan(models.Model): kullanici = models.ForeignKey(IsVeren,related_name="is_veren") hizmetDescr = models.ForeignKey(HizmetDescription,related_name="hizmet_descr") hizmet = models.ForeignKey(Hizmet,blank=True,null=True,related_name="hizmet_tipi") adres = models.ForeignKey(Adres,blank=True,null=True,related_name="is_veren_adresi") ilan_basligi = models.CharField(max_length=40) butceTipleri = ( ('TL', 'Türk Lirası'), ('DLR', 'DOLAR'), ('EUR', 'EURO'), ) sureUzunluklari = ( ('S', 'Saat'), ('G', 'Gün'), ('A', 'Ay'), ('H', 'Hafta'), ('Y', 'Yıl'), ) sureUzunlugu = models.CharField(max_length=3, choices=sureUzunluklari,default="G") <|code_end|> . Use current file imports: (from django.db import models from django.contrib.auth.models import User from kullanici.models import IsVeren from adres.models import Adres from hizmet.models import HizmetDescription,Hizmet from register.models import Register) and context including class names, function names, or small code snippets from other files: # Path: kullanici/models.py # class IsVeren(models.Model): # kullanici = models.OneToOneField(User,related_name="is_veren") # cinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # cinsiyet = models.CharField(max_length=1, choices=cinsiyetSecenekleri,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="users") # # def __str__(self): # return self.kullanici.username # # def getIsveren(kullaniciID): # return IsVeren.objects.get(pk=kullaniciID) # # class Meta: # verbose_name ="İş Veren Profili" # verbose_name_plural="İş Veren Profilleri" # # Path: adres/models.py # class Adres(models.Model): # kullanici = models.ForeignKey(IsVeren,related_name="adres") # adres_basligi = models.CharField(max_length=50) # adres = models.CharField(max_length=80) # sehir = models.CharField(max_length=40) # ilce = models.CharField(max_length=40,blank=True, null=True) # semt = models.CharField(max_length=40,blank=True, null=True) # mahalle = models.CharField(max_length=40,blank=True, null=True) # sokak = models.CharField(max_length=40,blank=True, null=True) # no = models.CharField(max_length=10,blank=True, null=True) # posta_kodu = models.CharField(max_length=40,blank=True, null=True) # # def __str__(self): # return self.kullanici.kullanici.username + " " + self.adres_basligi # # class Meta: # verbose_name ="İş Veren Adresi" # verbose_name_plural="İş Veren Adresleri" # # def adresSec(adresID): # return Adres.objects.get(pk=adresID) # # Path: hizmet/models.py # class HizmetDescription(models.Model): # hizmetBasligi = models.CharField(max_length=50) # hizmet = models.ForeignKey(Hizmet) # yolMasrafi = models.BooleanField(default=True) # yemekMasrafi = models.BooleanField(default=True) # calismaTipleri = ( # ('U', 'Uzaktan'), # ('A', 'Çalışma Alanında'), # ) # calismaTipi = models.CharField(max_length=1, choices=calismaTipleri,blank=True, null=True) # # def hizmetSec(kategoriID): # return HizmetDescription.objects.get(pk=kategoriID) # # def __str__(self): # return self.hizmetBasligi # # class Meta: # verbose_name ="Hizmet" # verbose_name_plural="Hizmetler" # # class Hizmet(models.Model): # hizmetAdi = models.CharField(max_length=50) # # def __str__(self): # return self.hizmetAdi # # class Meta: # verbose_name ="Hizmet Türü" # verbose_name_plural="Hizmet Türleri" . Output only the next line.
sure = models.IntegerField()
Based on the snippet: <|code_start|> cinsiyetSecenekleri = ( ('E', 'Erkek'), ('K', 'Kadın'), ) cinsiyet = models.CharField(max_length=1, choices=cinsiyetSecenekleri,blank=True, null=True) dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) telefon = models.CharField(max_length=12,blank=True, null=True) fotograf = models.ImageField(blank=True, null=True,upload_to="users") def __str__(self): return self.kullanici.username def getIsveren(kullaniciID): return IsVeren.objects.get(pk=kullaniciID) class Meta: verbose_name ="İş Veren Profili" verbose_name_plural="İş Veren Profilleri" class IsArayan(models.Model): kullanici = models.OneToOneField(User,related_name="is_arayan") hizmetler = models.ManyToManyField(Hizmet,related_name="hizmetler") CinsiyetSecenekleri = ( ('E', 'Erkek'), ('K', 'Kadın'), ) ISARAYANTIPI = ( ('S', 'Şirket'), ('B', 'Bireysel'), ) <|code_end|> , predict the immediate next line with the help of imports: from django.db import models from django.contrib.auth.models import User from hizmet.models import Hizmet import datetime and context (classes, functions, sometimes code) from other files: # Path: hizmet/models.py # class Hizmet(models.Model): # hizmetAdi = models.CharField(max_length=50) # # def __str__(self): # return self.hizmetAdi # # class Meta: # verbose_name ="Hizmet Türü" # verbose_name_plural="Hizmet Türleri" . Output only the next line.
cinsiyet = models.CharField(max_length=1, choices=CinsiyetSecenekleri,blank=True, null=True)
Predict the next line for this snippet: <|code_start|> class Teklif(models.Model): ilan = models.ForeignKey(Ilan,blank=True,null=True,related_name="odeme_ilanı") teklif_veren = models.OneToOneField(IsArayan,related_name="is_arayan") butce = models.IntegerField() sure = models.IntegerField() onay_durumu = models.BooleanField(default=False) teklif_tarihi = models.DateTimeField(auto_now_add=True) duzenlenme_tarihi = models.DateField(auto_now=True) def __str__(self): return self.ilan.ilan_basligi+ " ilanına "+ self.teklif_veren.kullanici.username + " kullanıcısının Teklifi" class Meta: verbose_name ="Teklifler" <|code_end|> with the help of current file imports: from django.db import models from ilan.models import Ilan from kullanici.models import IsArayan from register.models import Register from register.models import Register from odeme.models import Odeme and context from other files: # Path: ilan/models.py # class Ilan(models.Model): # kullanici = models.ForeignKey(IsVeren,related_name="is_veren") # hizmetDescr = models.ForeignKey(HizmetDescription,related_name="hizmet_descr") # hizmet = models.ForeignKey(Hizmet,blank=True,null=True,related_name="hizmet_tipi") # adres = models.ForeignKey(Adres,blank=True,null=True,related_name="is_veren_adresi") # # ilan_basligi = models.CharField(max_length=40) # butceTipleri = ( # ('TL', 'Türk Lirası'), # ('DLR', 'DOLAR'), # ('EUR', 'EURO'), # ) # sureUzunluklari = ( # ('S', 'Saat'), # ('G', 'Gün'), # ('A', 'Ay'), # ('H', 'Hafta'), # ('Y', 'Yıl'), # ) # # sureUzunlugu = models.CharField(max_length=3, choices=sureUzunluklari,default="G") # sure = models.IntegerField() # butceTipi = models.CharField(max_length=3, choices=butceTipleri,default="TL") # butce = models.IntegerField() # yayin_tarihi = models.DateTimeField(auto_now_add=True) # duzenlenme_tarihi = models.DateField(auto_now=True) # # is_active = models.BooleanField(default=True) # # def __str__(self): # return self.ilan_basligi # # class Meta: # verbose_name ="İlan" # verbose_name_plural="İlanlar" # # def adresSec(adresID): # return Adres.objects.get(pk=adresID) # # def save(self, *args, **kwargs): # # from register.models import Register # ilan = Register.ilanVermeBaslat() # ilan = self # ilan.kullanici = Register.getIsveren(self.kullanici.pk) # ilan.hizmetDescr = Register.hizmetKategorisiSec(self.hizmetDescr.pk) # ilan.adres = Ilan.adresSec(self.adres.pk) # # ilan.hizmet = ilan.hizmetDescr.hizmet # ilan.ilan_basligi = self.ilan_basligi # ilan.sureUzunlugu = self.sureUzunlugu # ilan.sure = self.sure # ilan.butceTipi = self.butceTipi # ilan.butce = self.butce # ilan.yayin_tarihi = self.yayin_tarihi # ilan.duzenlenme_tarihi = self.duzenlenme_tarihi # self = ilan # # super(Ilan, self).save(*args, **kwargs) # # Path: kullanici/models.py # class IsArayan(models.Model): # kullanici = models.OneToOneField(User,related_name="is_arayan") # hizmetler = models.ManyToManyField(Hizmet,related_name="hizmetler") # CinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # ISARAYANTIPI = ( # ('S', 'Şirket'), # ('B', 'Bireysel'), # ) # cinsiyet = models.CharField(max_length=1, choices=CinsiyetSecenekleri,blank=True, null=True) # isArayanTipi = models.CharField(max_length=1, choices=ISARAYANTIPI,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="kullanicilar") # # def getIsArayan(kullaniciID): # return IsArayan.objects.get(pk=kullaniciID) # # def __str__(self): # return self.kullanici.username # # class Meta: # verbose_name ="İş Arayan Profili" # verbose_name_plural="İş Arayan Profilleri" # # Path: register/models.py # class Register(models.Model): # def ilanVermeBaslat(): # ilan = Ilan() # return ilan # # def getIsveren(kullaniciID): # return IsVeren.getIsveren(kullaniciID) # # def hizmetKategorisiSec(kategoriID): # return HizmetDescription.hizmetSec(kategoriID) # # def teklifVermeBaslat(ilanID): # return Ilan.objects.get(pk=ilanID) # # def getIsArayan(kullaniciID): # return IsArayan.getIsArayan(kullaniciID) , which may contain function names, class names, or code. Output only the next line.
verbose_name_plural="Teklif"
Predict the next line for this snippet: <|code_start|> class Teklif(models.Model): ilan = models.ForeignKey(Ilan,blank=True,null=True,related_name="odeme_ilanı") teklif_veren = models.OneToOneField(IsArayan,related_name="is_arayan") <|code_end|> with the help of current file imports: from django.db import models from ilan.models import Ilan from kullanici.models import IsArayan from register.models import Register from register.models import Register from odeme.models import Odeme and context from other files: # Path: ilan/models.py # class Ilan(models.Model): # kullanici = models.ForeignKey(IsVeren,related_name="is_veren") # hizmetDescr = models.ForeignKey(HizmetDescription,related_name="hizmet_descr") # hizmet = models.ForeignKey(Hizmet,blank=True,null=True,related_name="hizmet_tipi") # adres = models.ForeignKey(Adres,blank=True,null=True,related_name="is_veren_adresi") # # ilan_basligi = models.CharField(max_length=40) # butceTipleri = ( # ('TL', 'Türk Lirası'), # ('DLR', 'DOLAR'), # ('EUR', 'EURO'), # ) # sureUzunluklari = ( # ('S', 'Saat'), # ('G', 'Gün'), # ('A', 'Ay'), # ('H', 'Hafta'), # ('Y', 'Yıl'), # ) # # sureUzunlugu = models.CharField(max_length=3, choices=sureUzunluklari,default="G") # sure = models.IntegerField() # butceTipi = models.CharField(max_length=3, choices=butceTipleri,default="TL") # butce = models.IntegerField() # yayin_tarihi = models.DateTimeField(auto_now_add=True) # duzenlenme_tarihi = models.DateField(auto_now=True) # # is_active = models.BooleanField(default=True) # # def __str__(self): # return self.ilan_basligi # # class Meta: # verbose_name ="İlan" # verbose_name_plural="İlanlar" # # def adresSec(adresID): # return Adres.objects.get(pk=adresID) # # def save(self, *args, **kwargs): # # from register.models import Register # ilan = Register.ilanVermeBaslat() # ilan = self # ilan.kullanici = Register.getIsveren(self.kullanici.pk) # ilan.hizmetDescr = Register.hizmetKategorisiSec(self.hizmetDescr.pk) # ilan.adres = Ilan.adresSec(self.adres.pk) # # ilan.hizmet = ilan.hizmetDescr.hizmet # ilan.ilan_basligi = self.ilan_basligi # ilan.sureUzunlugu = self.sureUzunlugu # ilan.sure = self.sure # ilan.butceTipi = self.butceTipi # ilan.butce = self.butce # ilan.yayin_tarihi = self.yayin_tarihi # ilan.duzenlenme_tarihi = self.duzenlenme_tarihi # self = ilan # # super(Ilan, self).save(*args, **kwargs) # # Path: kullanici/models.py # class IsArayan(models.Model): # kullanici = models.OneToOneField(User,related_name="is_arayan") # hizmetler = models.ManyToManyField(Hizmet,related_name="hizmetler") # CinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # ISARAYANTIPI = ( # ('S', 'Şirket'), # ('B', 'Bireysel'), # ) # cinsiyet = models.CharField(max_length=1, choices=CinsiyetSecenekleri,blank=True, null=True) # isArayanTipi = models.CharField(max_length=1, choices=ISARAYANTIPI,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="kullanicilar") # # def getIsArayan(kullaniciID): # return IsArayan.objects.get(pk=kullaniciID) # # def __str__(self): # return self.kullanici.username # # class Meta: # verbose_name ="İş Arayan Profili" # verbose_name_plural="İş Arayan Profilleri" # # Path: register/models.py # class Register(models.Model): # def ilanVermeBaslat(): # ilan = Ilan() # return ilan # # def getIsveren(kullaniciID): # return IsVeren.getIsveren(kullaniciID) # # def hizmetKategorisiSec(kategoriID): # return HizmetDescription.hizmetSec(kategoriID) # # def teklifVermeBaslat(ilanID): # return Ilan.objects.get(pk=ilanID) # # def getIsArayan(kullaniciID): # return IsArayan.getIsArayan(kullaniciID) , which may contain function names, class names, or code. Output only the next line.
butce = models.IntegerField()
Based on the snippet: <|code_start|> class Teklif(models.Model): ilan = models.ForeignKey(Ilan,blank=True,null=True,related_name="odeme_ilanı") teklif_veren = models.OneToOneField(IsArayan,related_name="is_arayan") butce = models.IntegerField() sure = models.IntegerField() onay_durumu = models.BooleanField(default=False) teklif_tarihi = models.DateTimeField(auto_now_add=True) duzenlenme_tarihi = models.DateField(auto_now=True) def __str__(self): return self.ilan.ilan_basligi+ " ilanına "+ self.teklif_veren.kullanici.username + " kullanıcısının Teklifi" class Meta: verbose_name ="Teklifler" verbose_name_plural="Teklif" <|code_end|> , predict the immediate next line with the help of imports: from django.db import models from ilan.models import Ilan from kullanici.models import IsArayan from register.models import Register from register.models import Register from odeme.models import Odeme and context (classes, functions, sometimes code) from other files: # Path: ilan/models.py # class Ilan(models.Model): # kullanici = models.ForeignKey(IsVeren,related_name="is_veren") # hizmetDescr = models.ForeignKey(HizmetDescription,related_name="hizmet_descr") # hizmet = models.ForeignKey(Hizmet,blank=True,null=True,related_name="hizmet_tipi") # adres = models.ForeignKey(Adres,blank=True,null=True,related_name="is_veren_adresi") # # ilan_basligi = models.CharField(max_length=40) # butceTipleri = ( # ('TL', 'Türk Lirası'), # ('DLR', 'DOLAR'), # ('EUR', 'EURO'), # ) # sureUzunluklari = ( # ('S', 'Saat'), # ('G', 'Gün'), # ('A', 'Ay'), # ('H', 'Hafta'), # ('Y', 'Yıl'), # ) # # sureUzunlugu = models.CharField(max_length=3, choices=sureUzunluklari,default="G") # sure = models.IntegerField() # butceTipi = models.CharField(max_length=3, choices=butceTipleri,default="TL") # butce = models.IntegerField() # yayin_tarihi = models.DateTimeField(auto_now_add=True) # duzenlenme_tarihi = models.DateField(auto_now=True) # # is_active = models.BooleanField(default=True) # # def __str__(self): # return self.ilan_basligi # # class Meta: # verbose_name ="İlan" # verbose_name_plural="İlanlar" # # def adresSec(adresID): # return Adres.objects.get(pk=adresID) # # def save(self, *args, **kwargs): # # from register.models import Register # ilan = Register.ilanVermeBaslat() # ilan = self # ilan.kullanici = Register.getIsveren(self.kullanici.pk) # ilan.hizmetDescr = Register.hizmetKategorisiSec(self.hizmetDescr.pk) # ilan.adres = Ilan.adresSec(self.adres.pk) # # ilan.hizmet = ilan.hizmetDescr.hizmet # ilan.ilan_basligi = self.ilan_basligi # ilan.sureUzunlugu = self.sureUzunlugu # ilan.sure = self.sure # ilan.butceTipi = self.butceTipi # ilan.butce = self.butce # ilan.yayin_tarihi = self.yayin_tarihi # ilan.duzenlenme_tarihi = self.duzenlenme_tarihi # self = ilan # # super(Ilan, self).save(*args, **kwargs) # # Path: kullanici/models.py # class IsArayan(models.Model): # kullanici = models.OneToOneField(User,related_name="is_arayan") # hizmetler = models.ManyToManyField(Hizmet,related_name="hizmetler") # CinsiyetSecenekleri = ( # ('E', 'Erkek'), # ('K', 'Kadın'), # ) # ISARAYANTIPI = ( # ('S', 'Şirket'), # ('B', 'Bireysel'), # ) # cinsiyet = models.CharField(max_length=1, choices=CinsiyetSecenekleri,blank=True, null=True) # isArayanTipi = models.CharField(max_length=1, choices=ISARAYANTIPI,blank=True, null=True) # dogumGunu = models.DateField(blank=True, null=True,default=datetime.date.today) # telefon = models.CharField(max_length=12,blank=True, null=True) # fotograf = models.ImageField(blank=True, null=True,upload_to="kullanicilar") # # def getIsArayan(kullaniciID): # return IsArayan.objects.get(pk=kullaniciID) # # def __str__(self): # return self.kullanici.username # # class Meta: # verbose_name ="İş Arayan Profili" # verbose_name_plural="İş Arayan Profilleri" # # Path: register/models.py # class Register(models.Model): # def ilanVermeBaslat(): # ilan = Ilan() # return ilan # # def getIsveren(kullaniciID): # return IsVeren.getIsveren(kullaniciID) # # def hizmetKategorisiSec(kategoriID): # return HizmetDescription.hizmetSec(kategoriID) # # def teklifVermeBaslat(ilanID): # return Ilan.objects.get(pk=ilanID) # # def getIsArayan(kullaniciID): # return IsArayan.getIsArayan(kullaniciID) . Output only the next line.
def save(self, *args, **kwargs):
Predict the next line for this snippet: <|code_start|> class DateTimeParserTest(unittest.TestCase): @defer.inlineCallbacks def test_parsing_and_getting_date(self): processor = datetime_processors.DateTimeParser(format_string='%Y-%m-%dT%H:%M:%S', as_date=True) result = yield processor.process('2011-02-03T15:14:12') self.assertEquals(result, datetime.date(2011, 2, 3)) @defer.inlineCallbacks def test_parse_with_different_formats(self): simple_tests = dict() simple_tests[('2011-02-03', '%Y-%m-%d')] = datetime.datetime(2011, 2, 3) simple_tests[('2011-2-3', '%Y-%m-%d')] = datetime.datetime(2011, 2, 3) simple_tests[('2011-2-3-15-14-12', '%Y-%m-%d-%H-%M-%S')] = datetime.datetime(2011, 2, 3, 15, 14, 12) for (datetime_string, format_string), expected_datetime in simple_tests.items(): processor = datetime_processors.DateTimeParser(format_string=format_string) result = yield processor.process(datetime_string) self.assertEquals(expected_datetime, result) processor = datetime_processors.DateTimeParser(format_string='%Y') self.assertRaises(ValueError, processor.process_input, 'this string does not match the format', baton=None) class DateFormatterTest(unittest.TestCase): @defer.inlineCallbacks <|code_end|> with the help of current file imports: import datetime from twisted.trial import unittest from twisted.internet import defer from piped.processors import datetime_processors and context from other files: # Path: piped/processors/datetime_processors.py # class DateTimeParser(base.InputOutputProcessor): # class DateFormatter(base.InputOutputProcessor): # def __init__(self, format_string, as_date=False, **kw): # def process_input(self, input, baton): # def __init__(self, format_string, **kw): # def process_input(self, input, baton): , which may contain function names, class names, or code. Output only the next line.
def test_parse_simple(self):
Given the code snippet: <|code_start|> def test_replacement_errors(self): self.assertRaises(ValueError, self.graph.replace_edge_from, 'a', 'b', 'd') self.graph.add_edge('a', 'b') self.graph.add_edge('a', 'c') self.assertRaises(ValueError, self.graph.replace_edge_from, 'a', 'b', 'c') def test_deepcopying_graph(self): g1 = graph.DirectedGraphWithOrderedEdges() g1.add_edge('a', 'c') g1.add_edge('a', 'd') g1.add_edge('a', 'b') self.assertEquals(g1.edges(), [('a', 'c'), ('a', 'd'), ('a', 'b')]) g2 = copy.deepcopy(g1) self.assertEquals(g2.edges(), [('a', 'c'), ('a', 'd'), ('a', 'b')]) g2.remove_edge('a', 'd') self.assertEquals(g1.edges(), [('a', 'c'), ('a', 'd'), ('a', 'b')]) self.assertEquals(g2.edges(), [('a', 'c'), ('a', 'b')]) def test_deepcopying_graph_and_nodes(self): class Foo(object): """ Just something deep-copyable that is hashable, mutable and comparable. """ def __init__(self, value): self.value = value <|code_end|> , generate the next line using the imports in this file: import copy from twisted.trial import unittest from piped import graph and context (functions, classes, or occasionally code) from other files: # Path: piped/graph.py # class DirectedGraphWithOrderedEdges(nx.DiGraph): # def __init__(self): # def _ensure_ordered_dicts_for_node(self, node): # def add_node(self, node, *a, **kw): # def add_nodes_from(self, nodes, **kw): # def add_edge(self, u, v, attr_dict=None, **attr): # def add_edges_from(self, ebunch, *a, **kw): # def replace_edge_from(self, from_node, old_to, new_to, **kw): . Output only the next line.
def __cmp__(self, other):
Here is a snippet: <|code_start|># Copyright (c) 2010-2011, Found IT A/S and Piped Project Contributors. # See LICENSE for details. class TestPythonLoggingObserver(unittest.TestCase): def setUp(self): self.observer = log.PythonLoggingObserver() def test_system_logger(self): self.observer.emit(dict(system='-', isError=False, message='test')) <|code_end|> . Write the next line using the current file imports: from twisted.trial import unittest from piped import log and context from other files: # Path: piped/log.py # class PythonLoggingObserver(log.PythonLoggingObserver): # class UTCFormatter(logging.Formatter): # class REPLAwareUTCFormatter(UTCFormatter): # def __init__(self): # def emit(self, eventDict): # def _get_logger(self, eventDict): # def formatTime(self, record, datefmt=None): # def format(self, record): # def configure(args): , which may include functions, classes, or code. Output only the next line.
self.assertIn('twisted', self.observer.loggers)
Predict the next line after this snippet: <|code_start|> return items() # ----------------------------------------------------------- def __init__(self, items=None): super(Dict, self).__init__(self.to_items(items)) # ----------------------------------------------------------- def __iadd__(self, items): for key, value in self.to_items(items): try: self[key] += value except KeyError: self[key] = value return self # ----------------------------------------------------------- def copy(self, key_type=None, value_type=None): other = Dict() for key, value in self.items(): if key_type: key = key_type(key) if value_type: value = value_type(value) <|code_end|> using the current file's imports: from .aql_simple_types import is_string from .aql_list_types import List and any relevant context from other files: # Path: aql/util_types/aql_simple_types.py # def is_string(value, _str_types=(u_str, str), _isinstance=isinstance): # return _isinstance(value, _str_types) # # Path: aql/util_types/aql_list_types.py # class List (list): # # # ----------------------------------------------------------- # # def __init__(self, values=None): # super(List, self).__init__(to_sequence(values)) # # # ----------------------------------------------------------- # # def __iadd__(self, values): # super(List, self).__iadd__(to_sequence(values)) # return self # # # ----------------------------------------------------------- # # def __add__(self, values): # other = List(self) # other += List(self) # # return other # # # ----------------------------------------------------------- # # def __radd__(self, values): # other = List(values) # other += self # # return other # # # ----------------------------------------------------------- # # def __isub__(self, values): # for value in to_sequence(values): # while True: # try: # self.remove(value) # except ValueError: # break # # return self # # # ----------------------------------------------------------- # # @staticmethod # def __to_list(values): # if isinstance(values, List): # return values # # return List(values) # # # ----------------------------------------------------------- # # def __eq__(self, other): # return super(List, self).__eq__(self.__to_list(other)) # # def __ne__(self, other): # return super(List, self).__ne__(self.__to_list(other)) # # def __lt__(self, other): # return super(List, self).__lt__(self.__to_list(other)) # # def __le__(self, other): # return super(List, self).__le__(self.__to_list(other)) # # def __gt__(self, other): # return super(List, self).__gt__(self.__to_list(other)) # # def __ge__(self, other): # return super(List, self).__ge__(self.__to_list(other)) # # # ----------------------------------------------------------- # # def append_front(self, value): # self.insert(0, value) # # # ----------------------------------------------------------- # # def extend(self, values): # super(List, self).extend(to_sequence(values)) # # # ----------------------------------------------------------- # # def extend_front(self, values): # self[:0] = to_sequence(values) # # # ----------------------------------------------------------- # # def pop_front(self): # return self.pop(0) . Output only the next line.
other[key] = value
Next line prediction: <|code_start|> @classmethod def __to_items(cls, items_str): if not is_string(items_str): return items_str sep = cls._separator for s in cls._other_separators: items_str = items_str.replace(s, sep) items = [] for v in filter(None, items_str.split(sep)): key, _, value = v.partition('=') items.append((key, value)) return items # ----------------------------------------------------------- @classmethod def __to_split_dict(cls, items): if isinstance(items, cls): return items return cls(cls.__to_items(items)) # ----------------------------------------------------------- def __init__(self, items=None): <|code_end|> . Use current file imports: (from .aql_simple_types import is_string from .aql_list_types import List) and context including class names, function names, or small code snippets from other files: # Path: aql/util_types/aql_simple_types.py # def is_string(value, _str_types=(u_str, str), _isinstance=isinstance): # return _isinstance(value, _str_types) # # Path: aql/util_types/aql_list_types.py # class List (list): # # # ----------------------------------------------------------- # # def __init__(self, values=None): # super(List, self).__init__(to_sequence(values)) # # # ----------------------------------------------------------- # # def __iadd__(self, values): # super(List, self).__iadd__(to_sequence(values)) # return self # # # ----------------------------------------------------------- # # def __add__(self, values): # other = List(self) # other += List(self) # # return other # # # ----------------------------------------------------------- # # def __radd__(self, values): # other = List(values) # other += self # # return other # # # ----------------------------------------------------------- # # def __isub__(self, values): # for value in to_sequence(values): # while True: # try: # self.remove(value) # except ValueError: # break # # return self # # # ----------------------------------------------------------- # # @staticmethod # def __to_list(values): # if isinstance(values, List): # return values # # return List(values) # # # ----------------------------------------------------------- # # def __eq__(self, other): # return super(List, self).__eq__(self.__to_list(other)) # # def __ne__(self, other): # return super(List, self).__ne__(self.__to_list(other)) # # def __lt__(self, other): # return super(List, self).__lt__(self.__to_list(other)) # # def __le__(self, other): # return super(List, self).__le__(self.__to_list(other)) # # def __gt__(self, other): # return super(List, self).__gt__(self.__to_list(other)) # # def __ge__(self, other): # return super(List, self).__ge__(self.__to_list(other)) # # # ----------------------------------------------------------- # # def append_front(self, value): # self.insert(0, value) # # # ----------------------------------------------------------- # # def extend(self, values): # super(List, self).extend(to_sequence(values)) # # # ----------------------------------------------------------- # # def extend_front(self, values): # self[:0] = to_sequence(values) # # # ----------------------------------------------------------- # # def pop_front(self): # return self.pop(0) . Output only the next line.
super(_SplitDictBase, self).__init__(self.__to_items(items))
Given the code snippet: <|code_start|> return FilePathBase(drive) # ----------------------------------------------------------- def change(self, dirname=None, name=None, ext=None, prefix=None): self_dirname, self_filename = os.path.split(self) self_name, self_ext = os.path.splitext(self_filename) if dirname is None: dirname = self_dirname if name is None: name = self_name if ext is None: ext = self_ext if prefix: name = prefix + name return FilePath(os.path.join(dirname, name + ext)) # ----------------------------------------------------------- def join_path(self, *paths): return FilePath(os.path.join(self, *paths)) # ============================================================================== class AbsFilePath (FilePath): <|code_end|> , generate the next line using the imports in this file: import os.path from .aql_simple_types import String, IgnoreCaseString and context (functions, classes, or occasionally code) from other files: # Path: aql/util_types/aql_simple_types.py # class String (str): # # def __new__(cls, value=None): # # if type(value) is cls: # return value # # if value is None: # value = '' # # return super(String, cls).__new__(cls, value) # # class IgnoreCaseString (String): # # def __hash__(self): # return hash(self.lower()) # # def _cmp(self, other, op): # return op(self.lower(), str(other).lower()) # # def __eq__(self, other): # return self._cmp(other, operator.eq) # # def __ne__(self, other): # return self._cmp(other, operator.ne) # # def __lt__(self, other): # return self._cmp(other, operator.lt) # # def __le__(self, other): # return self._cmp(other, operator.le) # # def __gt__(self, other): # return self._cmp(other, operator.gt) # # def __ge__(self, other): # return self._cmp(other, operator.ge) . Output only the next line.
def __new__(cls, value=None):
Given the code snippet: <|code_start|>__all__ = ( 'FilePath', 'AbsFilePath', ) # ============================================================================== if os.path.normcase('ABC') == os.path.normcase('abc'): FilePathBase = IgnoreCaseString else: FilePathBase = String try: _splitunc = os.path.splitunc except AttributeError: def _splitunc(path): return str(), path # ============================================================================== class FilePath (FilePathBase): # ----------------------------------------------------------- def __getnewargs__(self): return str(self), def __getstate__(self): return {} <|code_end|> , generate the next line using the imports in this file: import os.path from .aql_simple_types import String, IgnoreCaseString and context (functions, classes, or occasionally code) from other files: # Path: aql/util_types/aql_simple_types.py # class String (str): # # def __new__(cls, value=None): # # if type(value) is cls: # return value # # if value is None: # value = '' # # return super(String, cls).__new__(cls, value) # # class IgnoreCaseString (String): # # def __hash__(self): # return hash(self.lower()) # # def _cmp(self, other, op): # return op(self.lower(), str(other).lower()) # # def __eq__(self, other): # return self._cmp(other, operator.eq) # # def __ne__(self, other): # return self._cmp(other, operator.ne) # # def __lt__(self, other): # return self._cmp(other, operator.lt) # # def __le__(self, other): # return self._cmp(other, operator.le) # # def __gt__(self, other): # return self._cmp(other, operator.gt) # # def __ge__(self, other): # return self._cmp(other, operator.ge) . Output only the next line.
def __setstate__(self, state):
Given snippet: <|code_start|> # ----------------------------------------------------------- @staticmethod def _is_aql_db(filename): magic_tag = b".AQL.DB." with open_file(filename, read=True, binary=True) as f: tag = f.read(len(magic_tag)) return tag == magic_tag # ----------------------------------------------------------- @staticmethod def _open_connection(filename): conn = None try: conn = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES) with conn: conn.execute( "CREATE TABLE IF NOT EXISTS items(" "key INTEGER PRIMARY KEY AUTOINCREMENT," "id BLOB UNIQUE," "data BLOB NOT NULL" ")") <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sqlite3 import binascii from .aql_utils import open_file and context: # Path: aql/utils/aql_utils.py # def open_file(filename, read=True, write=False, binary=False, # sync=False, truncate=False, encoding=None): # # if not is_string(filename): # raise ErrorFileName(filename) # # if write: # mode = 'r+' # else: # mode = 'r' # # if binary: # mode += 'b' # # fd = _open_file_handle(filename, read=read, write=write, # sync=sync, truncate=truncate) # try: # if sync and binary: # return io.open(fd, mode, 0, encoding=encoding) # else: # return io.open(fd, mode, encoding=encoding) # except: # os.close(fd) # raise which might include code, classes, or functions. Output only the next line.
except (sqlite3.DataError, sqlite3.IntegrityError):
Next line prediction: <|code_start|> if self.data_begin != data_begin: raise AssertionError("self.data_begin(%s) != data_begin(%s)" % (self.data_begin, data_begin)) # ----------------------------------------------------------- items = sorted(self.id2data.items(), key=lambda item: item[1].offset) last_meta_offset = self._META_TABLE_OFFSET last_data_offset = self.data_begin for data_id, meta in items: if meta.id != data_id: raise AssertionError( "meta.id(%s) != data_id(%s)" % (meta.id, data_id)) if meta.key != 0: if self.key2id[meta.key] != data_id: raise AssertionError( "self.key2id[ meta.key ](%s) != data_id(%s)" % (self.key2id[meta.key], data_id)) if meta.data_capacity < meta.data_size: raise AssertionError( "meta.data_capacity(%s) < meta.data_size (%s)" % (meta.data_capacity, meta.data_size)) if meta.offset >= self.meta_end: raise AssertionError("meta.offset(%s) >= self.meta_end(%s)" % <|code_end|> . Use current file imports: (import os import operator import struct import mmap from .aql_utils import open_file from .aql_logging import log_debug) and context including class names, function names, or small code snippets from other files: # Path: aql/utils/aql_utils.py # def open_file(filename, read=True, write=False, binary=False, # sync=False, truncate=False, encoding=None): # # if not is_string(filename): # raise ErrorFileName(filename) # # if write: # mode = 'r+' # else: # mode = 'r' # # if binary: # mode += 'b' # # fd = _open_file_handle(filename, read=read, write=write, # sync=sync, truncate=truncate) # try: # if sync and binary: # return io.open(fd, mode, 0, encoding=encoding) # else: # return io.open(fd, mode, encoding=encoding) # except: # os.close(fd) # raise # # Path: aql/utils/aql_logging.py # LOG_CRITICAL = logging.CRITICAL # LOG_ERROR = logging.ERROR # LOG_WARNING = logging.WARNING # LOG_INFO = logging.INFO # LOG_DEBUG = logging.DEBUG # class LogFormatter(logging.Formatter): # def __init__(self, *args, **kw): # def format(self, record): # def _make_aql_logger(): . Output only the next line.
(meta.offset, self.meta_end))
Here is a snippet: <|code_start|> # 4 bytes (offset of data area) _META_TABLE_HEADER_STRUCT = struct.Struct(">L") _META_TABLE_HEADER_SIZE = _META_TABLE_HEADER_STRUCT.size _META_TABLE_HEADER_OFFSET = _KEY_OFFSET + _KEY_SIZE _META_TABLE_OFFSET = _META_TABLE_HEADER_OFFSET + _META_TABLE_HEADER_SIZE # ----------------------------------------------------------- def __init__(self, filename, force=False): self.id2data = {} self.key2id = {} self.meta_end = 0 self.data_begin = 0 self.data_end = 0 self.handle = None self.next_key = None self.open(filename, force=force) # ----------------------------------------------------------- def open(self, filename, force=False): self.close() try: self.handle = _MmapFile(filename) except Exception as ex: log_debug("mmap is not supported: %s", ex) <|code_end|> . Write the next line using the current file imports: import os import operator import struct import mmap from .aql_utils import open_file from .aql_logging import log_debug and context from other files: # Path: aql/utils/aql_utils.py # def open_file(filename, read=True, write=False, binary=False, # sync=False, truncate=False, encoding=None): # # if not is_string(filename): # raise ErrorFileName(filename) # # if write: # mode = 'r+' # else: # mode = 'r' # # if binary: # mode += 'b' # # fd = _open_file_handle(filename, read=read, write=write, # sync=sync, truncate=truncate) # try: # if sync and binary: # return io.open(fd, mode, 0, encoding=encoding) # else: # return io.open(fd, mode, encoding=encoding) # except: # os.close(fd) # raise # # Path: aql/utils/aql_logging.py # LOG_CRITICAL = logging.CRITICAL # LOG_ERROR = logging.ERROR # LOG_WARNING = logging.WARNING # LOG_INFO = logging.INFO # LOG_DEBUG = logging.DEBUG # class LogFormatter(logging.Formatter): # def __init__(self, *args, **kw): # def format(self, record): # def _make_aql_logger(): , which may include functions, classes, or code. Output only the next line.
self.handle = _IOFile(filename)
Based on the snippet: <|code_start|> task_id = task.task_id if task_id is not None: task_result = TaskResult(task_id=task_id) else: task_result = None try: result = task(task_lock) if task_result is not None: task_result.result = result except BaseException as ex: self.fail_handler(task_result, ex) finally: if task_result is not None: finished_tasks.put(task_result) tasks.task_done() # ============================================================================== class TaskManager (object): __slots__ = ( 'task_lock', 'num_threads', <|code_end|> , predict the immediate next line with the help of imports: import threading import traceback import queue import Queue as queue # python 2 from .aql_logging import log_warning and context (classes, functions, sometimes code) from other files: # Path: aql/utils/aql_logging.py # LOG_CRITICAL = logging.CRITICAL # LOG_ERROR = logging.ERROR # LOG_WARNING = logging.WARNING # LOG_INFO = logging.INFO # LOG_DEBUG = logging.DEBUG # class LogFormatter(logging.Formatter): # def __init__(self, *args, **kw): # def format(self, record): # def _make_aql_logger(): . Output only the next line.
'threads',
Continue the code snippet: <|code_start|> try: self.remove(value) except ValueError: break return self # ----------------------------------------------------------- @staticmethod def __to_list(values): if isinstance(values, List): return values return List(values) # ----------------------------------------------------------- def __eq__(self, other): return super(List, self).__eq__(self.__to_list(other)) def __ne__(self, other): return super(List, self).__ne__(self.__to_list(other)) def __lt__(self, other): return super(List, self).__lt__(self.__to_list(other)) def __le__(self, other): return super(List, self).__le__(self.__to_list(other)) <|code_end|> . Use current file imports: from .aql_simple_types import u_str, is_string, cast_str and context (classes, functions, or code) from other files: # Path: aql/util_types/aql_simple_types.py # _TRY_ENCODINGS = [] # SIMPLE_TYPES_SET = frozenset( # (u_str, str, int, float, complex, bool, bytes, bytearray)) # SIMPLE_TYPES = tuple(SIMPLE_TYPES_SET) # def encode_str(value, encoding=None, _try_encodings=_TRY_ENCODINGS): # def decode_bytes(obj, encoding=None, _try_encodings=_TRY_ENCODINGS): # def to_unicode(obj, encoding=None): # def is_unicode(value, _ustr=u_str, _isinstance=isinstance): # def is_string(value, _str_types=(u_str, str), _isinstance=isinstance): # def to_string(value, _str_types=(u_str, str), _isinstance=isinstance): # def cast_str(obj, encoding=None, _ustr=u_str): # def __new__(cls, value=None): # def __hash__(self): # def _cmp(self, other, op): # def __eq__(self, other): # def __ne__(self, other): # def __lt__(self, other): # def __le__(self, other): # def __gt__(self, other): # def __ge__(self, other): # def __new__(cls, value=None): # def __new__(cls, value=None): # def __new__(cls, version=None, _ver_re=__ver_re): # def __convert(other): # def _cmp(self, other, cmp_op): # def __hash__(self): # def __eq__(self, other): # def __ne__(self, other): # def __lt__(self, other): # def __le__(self, other): # def __gt__(self, other): # def __ge__(self, other): # def is_simple_value(value, _simple_types=SIMPLE_TYPES): # def is_simple_type(value_type, _simple_types=SIMPLE_TYPES): # class String (str): # class IgnoreCaseString (String): # class LowerCaseString (str): # class UpperCaseString (str): # class Version (str): . Output only the next line.
def __gt__(self, other):
Based on the snippet: <|code_start|> self.__add_values(values) return self # ----------------------------------------------------------- def __add__(self, values): other = UniqueList(self) other.__add_values(values) return other # ----------------------------------------------------------- def __radd__(self, values): other = UniqueList(values) other.__add_values(self) return other # ----------------------------------------------------------- def __isub__(self, values): self.__remove_values(values) return self # ----------------------------------------------------------- def append(self, value): self.__add_value(value) # ----------------------------------------------------------- <|code_end|> , predict the immediate next line with the help of imports: from .aql_simple_types import u_str, is_string, cast_str and context (classes, functions, sometimes code) from other files: # Path: aql/util_types/aql_simple_types.py # _TRY_ENCODINGS = [] # SIMPLE_TYPES_SET = frozenset( # (u_str, str, int, float, complex, bool, bytes, bytearray)) # SIMPLE_TYPES = tuple(SIMPLE_TYPES_SET) # def encode_str(value, encoding=None, _try_encodings=_TRY_ENCODINGS): # def decode_bytes(obj, encoding=None, _try_encodings=_TRY_ENCODINGS): # def to_unicode(obj, encoding=None): # def is_unicode(value, _ustr=u_str, _isinstance=isinstance): # def is_string(value, _str_types=(u_str, str), _isinstance=isinstance): # def to_string(value, _str_types=(u_str, str), _isinstance=isinstance): # def cast_str(obj, encoding=None, _ustr=u_str): # def __new__(cls, value=None): # def __hash__(self): # def _cmp(self, other, op): # def __eq__(self, other): # def __ne__(self, other): # def __lt__(self, other): # def __le__(self, other): # def __gt__(self, other): # def __ge__(self, other): # def __new__(cls, value=None): # def __new__(cls, value=None): # def __new__(cls, version=None, _ver_re=__ver_re): # def __convert(other): # def _cmp(self, other, cmp_op): # def __hash__(self): # def __eq__(self, other): # def __ne__(self, other): # def __lt__(self, other): # def __le__(self, other): # def __gt__(self, other): # def __ge__(self, other): # def is_simple_value(value, _simple_types=SIMPLE_TYPES): # def is_simple_type(value_type, _simple_types=SIMPLE_TYPES): # class String (str): # class IgnoreCaseString (String): # class LowerCaseString (str): # class UpperCaseString (str): # class Version (str): . Output only the next line.
def extend(self, values):
Based on the snippet: <|code_start|> if value in values_set: values_list.remove(value) else: values_set.add(value) values_list.insert(0, value) # ----------------------------------------------------------- def __add_value(self, value): values_set = self.__values_set values_list = self.__values_list if value not in values_set: values_set.add(value) values_list.append(value) # ----------------------------------------------------------- def __add_values(self, values): values_set_add = self.__values_set.add values_list_append = self.__values_list.append values_set_size = self.__values_set.__len__ values_list_size = self.__values_list.__len__ for value in to_sequence(values): values_set_add(value) if values_set_size() > values_list_size(): <|code_end|> , predict the immediate next line with the help of imports: from .aql_simple_types import u_str, is_string, cast_str and context (classes, functions, sometimes code) from other files: # Path: aql/util_types/aql_simple_types.py # _TRY_ENCODINGS = [] # SIMPLE_TYPES_SET = frozenset( # (u_str, str, int, float, complex, bool, bytes, bytearray)) # SIMPLE_TYPES = tuple(SIMPLE_TYPES_SET) # def encode_str(value, encoding=None, _try_encodings=_TRY_ENCODINGS): # def decode_bytes(obj, encoding=None, _try_encodings=_TRY_ENCODINGS): # def to_unicode(obj, encoding=None): # def is_unicode(value, _ustr=u_str, _isinstance=isinstance): # def is_string(value, _str_types=(u_str, str), _isinstance=isinstance): # def to_string(value, _str_types=(u_str, str), _isinstance=isinstance): # def cast_str(obj, encoding=None, _ustr=u_str): # def __new__(cls, value=None): # def __hash__(self): # def _cmp(self, other, op): # def __eq__(self, other): # def __ne__(self, other): # def __lt__(self, other): # def __le__(self, other): # def __gt__(self, other): # def __ge__(self, other): # def __new__(cls, value=None): # def __new__(cls, value=None): # def __new__(cls, version=None, _ver_re=__ver_re): # def __convert(other): # def _cmp(self, other, cmp_op): # def __hash__(self): # def __eq__(self, other): # def __ne__(self, other): # def __lt__(self, other): # def __le__(self, other): # def __gt__(self, other): # def __ge__(self, other): # def is_simple_value(value, _simple_types=SIMPLE_TYPES): # def is_simple_type(value_type, _simple_types=SIMPLE_TYPES): # class String (str): # class IgnoreCaseString (String): # class LowerCaseString (str): # class UpperCaseString (str): # class Version (str): . Output only the next line.
values_list_append(value)
Here is a snippet: <|code_start|> def __init__(self): pass @staticmethod def _fix_paths(job): """Modelled after hadoop_jar.HadoopJarJobRunner._fix_paths. """ tmp_files = [] args = [] for x in job.args(): if isinstance(x, luigi.LocalTarget): # input/output if x.exists(): # input args.append(x.path) else: # output ypath = x.path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) y = luigi.LocalTarget(ypath) logger.info("Using temp path: {0} for path {1}".format(y.path, x.path)) args.append(y.path) if job.add_suffix(): x = luigi.LocalTarget(x.path + job.add_suffix()) y = luigi.LocalTarget(y.path + job.add_suffix()) tmp_files.append((y, x)) else: args.append(str(x)) return (tmp_files, args) @staticmethod def _get_main(job): """Add main program to command. Override this for programs where main is given as a parameter, e.g. for GATK""" <|code_end|> . Write the next line using the current file imports: import random import sys import os import yaml import subprocess import logging import warnings import luigi import ratatosk.shell as shell import ratatosk from datetime import datetime from subprocess import Popen, PIPE from itertools import izip from luigi.task import flatten from ratatosk import backend from ratatosk.handler import RatatoskHandler, register_attr from ratatosk.config import get_config, get_custom_config from ratatosk.utils import rreplace, update, config_to_dict from ratatosk.log import get_logger and context from other files: # Path: ratatosk/backend.py # # Path: ratatosk/handler.py # class RatatoskHandler(IHandler): # """Ratatosk handler class. Ensures we have at least label and mod # functions that uses register to place mod in # backend.__handlers__[label]. # """ # _label = None # _mod = None # _load_type = None # # def __init__(self, label, mod, load_type="function"): # """Initialize handler with label (key in backend.__handlers__) # and mod (string representation of class/function). Load_type # deterimines what load function to use. # """ # setattr(self, "_label", label) # setattr(self, "_mod", mod) # setattr(self, "_load_type", load_type) # # def label(self): # """Handler identifier label""" # return self._label # # def mod(self): # """String representation of class/function""" # return self._mod # # def load_type(self): # """Load type (class or function)""" # return self._load_type # # def register_attr(obj, handler_obj, default_handler=None): # """Register a class represented as string to a task attribute. # # :param obj: the object to which the handler class is registered # :param handler_obj: the handler object to register, with attribute defined by handler_obj.label() # :param default_handler: the default handler to fall back on # # :return: None # """ # attr_list = getattr(obj, handler_obj.label(), []) # if not handler_obj: # logging.warn("No handler object provided; skipping") # return # if not isinstance(handler_obj, IHandler): # raise ValueError, "handler object must implement the IHandler interface" # hdl = _load(handler_obj) # if not hdl: # return # attr_list.append(hdl) # setattr(obj, handler_obj.label(), attr_list) # # Path: ratatosk/config.py # def get_config(): # return RatatoskConfigParser.instance() # # def get_custom_config(): # """Get separate parser for custom config; else custom config # parent_task setting will override config file settings""" # return RatatoskCustomConfigParser.instance() # # Path: ratatosk/utils.py # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # def update(d, u, override=True, expandvars=True): # """Update values of a nested dictionary of varying depth""" # for k, v in u.iteritems(): # if isinstance(v, collections.Mapping): # r = update(d.get(k, {}), v) # d[k] = r # else: # if expandvars and isinstance(v, str): # u[k] = os.path.expandvars(v) # d[k] = u[k] # return d # # def config_to_dict(d): # """Convert config handler or OrderedDict entries to dict for yaml # output. # # :param d: config handler or ordered dict # """ # if d is None: # return {} # if isinstance(d, dict): # pass # else: # raise TypeError("unsupported type <{}>".format(type(d))) # u = {} # for k, v in d.iteritems(): # u[k] = {} # if isinstance(v, collections.Mapping): # for x, y in v.iteritems(): # if isinstance(y, collections.Mapping): # u[k][x] = dict(y) # else: # u[k][x] = y # else: # u[k] = v # return u # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger , which may include functions, classes, or code. Output only the next line.
return job.main()
Next line prediction: <|code_start|> logging.basicConfig(level=logging.DEBUG) def local_target_generator(task): return None def setUpModule(): global cnf, conf cnf = get_custom_config() cnf.clear() conf = get_config() conf.clear() def tearDownModule(): cnf.clear() conf.clear() class TestHandler(unittest.TestCase): <|code_end|> . Use current file imports: (import os import glob import shutil import sys import unittest import luigi import yaml import logging from ratatosk import interface, backend from ratatosk.config import get_config, get_custom_config from ratatosk.lib.tools.picard import MergeSamFiles from ratatosk.utils import fullclassname, rreplace from types import GeneratorType from ratatosk.handler import register, register_task_handler, RatatoskHandler) and context including class names, function names, or small code snippets from other files: # Path: ratatosk/interface.py # class Interface(object): # def __init__(self): # # Path: ratatosk/backend.py # # Path: ratatosk/config.py # def get_config(): # return RatatoskConfigParser.instance() # # def get_custom_config(): # """Get separate parser for custom config; else custom config # parent_task setting will override config file settings""" # return RatatoskCustomConfigParser.instance() # # Path: ratatosk/lib/tools/picard.py # class MergeSamFiles(PicardJobTask): # executable = "MergeSamFiles.jar" # label = luigi.Parameter(default=".merge") # read1_suffix = luigi.Parameter(default="_R1_001") # target_generator_handler = luigi.Parameter(default=None) # # FIXME: TMP_DIR should not be hard-coded # options = luigi.Parameter(default=("SO=coordinate TMP_DIR=./tmp", ), is_list=True) # # def args(self): # return ["OUTPUT=", self.output()] + [item for sublist in [["INPUT=", x] for x in self.input()] for item in sublist] # # def requires(self): # cls = self.parent()[0] # sources = [] # cnf = get_config() # if self.target_generator_handler and "target_generator_handler" not in self._handlers.keys(): # tgf = RatatoskHandler(label="target_generator_handler", mod=self.target_generator_handler) # register_task_handler(self, tgf) # if not "target_generator_handler" in self._handlers.keys(): # logging.warn("MergeSamFiles requires a target generator handler; no defaults are as of yet implemented") # return [] # sources = list(set(self._handlers["target_generator_handler"](self))) # return [cls(target=src) for src in sources] # # Path: ratatosk/utils.py # def fullclassname(o): # return o.__module__ + "." + o.__name__ # # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # Path: ratatosk/handler.py # def register(handler_obj, default_handler=None): # """Register a module function represented as string in # to a backend handler. # # :param handler_obj: the handler object to register # :param default_handler: the default handler to fall back on # # :return: None # """ # if not handler_obj: # logging.warn("No handler object provided; skipping") # return # if not isinstance(handler_obj, IHandler): # raise ValueError, "handler object must implement the IHandler interface" # hdl = _load(handler_obj) # if not hdl: # return # if handler_obj.label() in backend.__handlers__: # old_hdl = backend.__handlers__[handler_obj.label()] # if fullclassname(old_hdl) == fullclassname(hdl): # logging.info("Handler object '{}' already registered; skipping".format(fullclassname(hdl))) # return # else: # logging.warn("Trying to reset already registered '{}' which is not supported".format(handler_obj.label())) # return # else: # backend.__handlers__[handler_obj.label()] = hdl # # def register_task_handler(obj, handler_obj, default_handler=None): # """Register a module function represented as string in # to a task handler. # # :param obj: the object to which the handler is registered # :param handler_obj: the handler object to register # :param default_handler: the default handler to fall back on # # :return: None # """ # if not handler_obj: # logging.warn("No handler object provided; skipping") # return # if not isinstance(handler_obj, IHandler): # raise ValueError, "handler object must implement the IHandler interface" # hdl = _load(handler_obj) # if not hdl: # return # if handler_obj.label() in obj._handlers: # old_hdl = obj._handlers[handler_obj.label()] # if fullclassname(old_hdl) == fullclassname(hdl): # logging.info("Handler object '{}' already registered in {}; skipping".format(fullclassname(hdl), obj)) # return # else: # logging.warn("Trying to reset already registered '{}' which is not supported".format(handler_obj.label())) # return # else: # obj._handlers[handler_obj.label()] = hdl # # class RatatoskHandler(IHandler): # """Ratatosk handler class. Ensures we have at least label and mod # functions that uses register to place mod in # backend.__handlers__[label]. # """ # _label = None # _mod = None # _load_type = None # # def __init__(self, label, mod, load_type="function"): # """Initialize handler with label (key in backend.__handlers__) # and mod (string representation of class/function). Load_type # deterimines what load function to use. # """ # setattr(self, "_label", label) # setattr(self, "_mod", mod) # setattr(self, "_load_type", load_type) # # def label(self): # """Handler identifier label""" # return self._label # # def mod(self): # """String representation of class/function""" # return self._mod # # def load_type(self): # """Load type (class or function)""" # return self._load_type . Output only the next line.
def test_register_handler(self):
Given the following code snippet before the placeholder: <|code_start|> logging.basicConfig(level=logging.DEBUG) def local_target_generator(task): return None def setUpModule(): global cnf, conf cnf = get_custom_config() cnf.clear() conf = get_config() <|code_end|> , predict the next line using imports from the current file: import os import glob import shutil import sys import unittest import luigi import yaml import logging from ratatosk import interface, backend from ratatosk.config import get_config, get_custom_config from ratatosk.lib.tools.picard import MergeSamFiles from ratatosk.utils import fullclassname, rreplace from types import GeneratorType from ratatosk.handler import register, register_task_handler, RatatoskHandler and context including class names, function names, and sometimes code from other files: # Path: ratatosk/interface.py # class Interface(object): # def __init__(self): # # Path: ratatosk/backend.py # # Path: ratatosk/config.py # def get_config(): # return RatatoskConfigParser.instance() # # def get_custom_config(): # """Get separate parser for custom config; else custom config # parent_task setting will override config file settings""" # return RatatoskCustomConfigParser.instance() # # Path: ratatosk/lib/tools/picard.py # class MergeSamFiles(PicardJobTask): # executable = "MergeSamFiles.jar" # label = luigi.Parameter(default=".merge") # read1_suffix = luigi.Parameter(default="_R1_001") # target_generator_handler = luigi.Parameter(default=None) # # FIXME: TMP_DIR should not be hard-coded # options = luigi.Parameter(default=("SO=coordinate TMP_DIR=./tmp", ), is_list=True) # # def args(self): # return ["OUTPUT=", self.output()] + [item for sublist in [["INPUT=", x] for x in self.input()] for item in sublist] # # def requires(self): # cls = self.parent()[0] # sources = [] # cnf = get_config() # if self.target_generator_handler and "target_generator_handler" not in self._handlers.keys(): # tgf = RatatoskHandler(label="target_generator_handler", mod=self.target_generator_handler) # register_task_handler(self, tgf) # if not "target_generator_handler" in self._handlers.keys(): # logging.warn("MergeSamFiles requires a target generator handler; no defaults are as of yet implemented") # return [] # sources = list(set(self._handlers["target_generator_handler"](self))) # return [cls(target=src) for src in sources] # # Path: ratatosk/utils.py # def fullclassname(o): # return o.__module__ + "." + o.__name__ # # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # Path: ratatosk/handler.py # def register(handler_obj, default_handler=None): # """Register a module function represented as string in # to a backend handler. # # :param handler_obj: the handler object to register # :param default_handler: the default handler to fall back on # # :return: None # """ # if not handler_obj: # logging.warn("No handler object provided; skipping") # return # if not isinstance(handler_obj, IHandler): # raise ValueError, "handler object must implement the IHandler interface" # hdl = _load(handler_obj) # if not hdl: # return # if handler_obj.label() in backend.__handlers__: # old_hdl = backend.__handlers__[handler_obj.label()] # if fullclassname(old_hdl) == fullclassname(hdl): # logging.info("Handler object '{}' already registered; skipping".format(fullclassname(hdl))) # return # else: # logging.warn("Trying to reset already registered '{}' which is not supported".format(handler_obj.label())) # return # else: # backend.__handlers__[handler_obj.label()] = hdl # # def register_task_handler(obj, handler_obj, default_handler=None): # """Register a module function represented as string in # to a task handler. # # :param obj: the object to which the handler is registered # :param handler_obj: the handler object to register # :param default_handler: the default handler to fall back on # # :return: None # """ # if not handler_obj: # logging.warn("No handler object provided; skipping") # return # if not isinstance(handler_obj, IHandler): # raise ValueError, "handler object must implement the IHandler interface" # hdl = _load(handler_obj) # if not hdl: # return # if handler_obj.label() in obj._handlers: # old_hdl = obj._handlers[handler_obj.label()] # if fullclassname(old_hdl) == fullclassname(hdl): # logging.info("Handler object '{}' already registered in {}; skipping".format(fullclassname(hdl), obj)) # return # else: # logging.warn("Trying to reset already registered '{}' which is not supported".format(handler_obj.label())) # return # else: # obj._handlers[handler_obj.label()] = hdl # # class RatatoskHandler(IHandler): # """Ratatosk handler class. Ensures we have at least label and mod # functions that uses register to place mod in # backend.__handlers__[label]. # """ # _label = None # _mod = None # _load_type = None # # def __init__(self, label, mod, load_type="function"): # """Initialize handler with label (key in backend.__handlers__) # and mod (string representation of class/function). Load_type # deterimines what load function to use. # """ # setattr(self, "_label", label) # setattr(self, "_mod", mod) # setattr(self, "_load_type", load_type) # # def label(self): # """Handler identifier label""" # return self._label # # def mod(self): # """String representation of class/function""" # return self._mod # # def load_type(self): # """Load type (class or function)""" # return self._load_type . Output only the next line.
conf.clear()
Here is a snippet: <|code_start|> logging.basicConfig(level=logging.DEBUG) def local_target_generator(task): return None def setUpModule(): global cnf, conf cnf = get_custom_config() cnf.clear() conf = get_config() conf.clear() <|code_end|> . Write the next line using the current file imports: import os import glob import shutil import sys import unittest import luigi import yaml import logging from ratatosk import interface, backend from ratatosk.config import get_config, get_custom_config from ratatosk.lib.tools.picard import MergeSamFiles from ratatosk.utils import fullclassname, rreplace from types import GeneratorType from ratatosk.handler import register, register_task_handler, RatatoskHandler and context from other files: # Path: ratatosk/interface.py # class Interface(object): # def __init__(self): # # Path: ratatosk/backend.py # # Path: ratatosk/config.py # def get_config(): # return RatatoskConfigParser.instance() # # def get_custom_config(): # """Get separate parser for custom config; else custom config # parent_task setting will override config file settings""" # return RatatoskCustomConfigParser.instance() # # Path: ratatosk/lib/tools/picard.py # class MergeSamFiles(PicardJobTask): # executable = "MergeSamFiles.jar" # label = luigi.Parameter(default=".merge") # read1_suffix = luigi.Parameter(default="_R1_001") # target_generator_handler = luigi.Parameter(default=None) # # FIXME: TMP_DIR should not be hard-coded # options = luigi.Parameter(default=("SO=coordinate TMP_DIR=./tmp", ), is_list=True) # # def args(self): # return ["OUTPUT=", self.output()] + [item for sublist in [["INPUT=", x] for x in self.input()] for item in sublist] # # def requires(self): # cls = self.parent()[0] # sources = [] # cnf = get_config() # if self.target_generator_handler and "target_generator_handler" not in self._handlers.keys(): # tgf = RatatoskHandler(label="target_generator_handler", mod=self.target_generator_handler) # register_task_handler(self, tgf) # if not "target_generator_handler" in self._handlers.keys(): # logging.warn("MergeSamFiles requires a target generator handler; no defaults are as of yet implemented") # return [] # sources = list(set(self._handlers["target_generator_handler"](self))) # return [cls(target=src) for src in sources] # # Path: ratatosk/utils.py # def fullclassname(o): # return o.__module__ + "." + o.__name__ # # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # Path: ratatosk/handler.py # def register(handler_obj, default_handler=None): # """Register a module function represented as string in # to a backend handler. # # :param handler_obj: the handler object to register # :param default_handler: the default handler to fall back on # # :return: None # """ # if not handler_obj: # logging.warn("No handler object provided; skipping") # return # if not isinstance(handler_obj, IHandler): # raise ValueError, "handler object must implement the IHandler interface" # hdl = _load(handler_obj) # if not hdl: # return # if handler_obj.label() in backend.__handlers__: # old_hdl = backend.__handlers__[handler_obj.label()] # if fullclassname(old_hdl) == fullclassname(hdl): # logging.info("Handler object '{}' already registered; skipping".format(fullclassname(hdl))) # return # else: # logging.warn("Trying to reset already registered '{}' which is not supported".format(handler_obj.label())) # return # else: # backend.__handlers__[handler_obj.label()] = hdl # # def register_task_handler(obj, handler_obj, default_handler=None): # """Register a module function represented as string in # to a task handler. # # :param obj: the object to which the handler is registered # :param handler_obj: the handler object to register # :param default_handler: the default handler to fall back on # # :return: None # """ # if not handler_obj: # logging.warn("No handler object provided; skipping") # return # if not isinstance(handler_obj, IHandler): # raise ValueError, "handler object must implement the IHandler interface" # hdl = _load(handler_obj) # if not hdl: # return # if handler_obj.label() in obj._handlers: # old_hdl = obj._handlers[handler_obj.label()] # if fullclassname(old_hdl) == fullclassname(hdl): # logging.info("Handler object '{}' already registered in {}; skipping".format(fullclassname(hdl), obj)) # return # else: # logging.warn("Trying to reset already registered '{}' which is not supported".format(handler_obj.label())) # return # else: # obj._handlers[handler_obj.label()] = hdl # # class RatatoskHandler(IHandler): # """Ratatosk handler class. Ensures we have at least label and mod # functions that uses register to place mod in # backend.__handlers__[label]. # """ # _label = None # _mod = None # _load_type = None # # def __init__(self, label, mod, load_type="function"): # """Initialize handler with label (key in backend.__handlers__) # and mod (string representation of class/function). Load_type # deterimines what load function to use. # """ # setattr(self, "_label", label) # setattr(self, "_mod", mod) # setattr(self, "_load_type", load_type) # # def label(self): # """Handler identifier label""" # return self._label # # def mod(self): # """String representation of class/function""" # return self._mod # # def load_type(self): # """Load type (class or function)""" # return self._load_type , which may include functions, classes, or code. Output only the next line.
def tearDownModule():
Continue the code snippet: <|code_start|> logging.basicConfig(level=logging.DEBUG) def local_target_generator(task): return None def setUpModule(): global cnf, conf cnf = get_custom_config() cnf.clear() conf = get_config() conf.clear() def tearDownModule(): cnf.clear() <|code_end|> . Use current file imports: import os import glob import shutil import sys import unittest import luigi import yaml import logging from ratatosk import interface, backend from ratatosk.config import get_config, get_custom_config from ratatosk.lib.tools.picard import MergeSamFiles from ratatosk.utils import fullclassname, rreplace from types import GeneratorType from ratatosk.handler import register, register_task_handler, RatatoskHandler and context (classes, functions, or code) from other files: # Path: ratatosk/interface.py # class Interface(object): # def __init__(self): # # Path: ratatosk/backend.py # # Path: ratatosk/config.py # def get_config(): # return RatatoskConfigParser.instance() # # def get_custom_config(): # """Get separate parser for custom config; else custom config # parent_task setting will override config file settings""" # return RatatoskCustomConfigParser.instance() # # Path: ratatosk/lib/tools/picard.py # class MergeSamFiles(PicardJobTask): # executable = "MergeSamFiles.jar" # label = luigi.Parameter(default=".merge") # read1_suffix = luigi.Parameter(default="_R1_001") # target_generator_handler = luigi.Parameter(default=None) # # FIXME: TMP_DIR should not be hard-coded # options = luigi.Parameter(default=("SO=coordinate TMP_DIR=./tmp", ), is_list=True) # # def args(self): # return ["OUTPUT=", self.output()] + [item for sublist in [["INPUT=", x] for x in self.input()] for item in sublist] # # def requires(self): # cls = self.parent()[0] # sources = [] # cnf = get_config() # if self.target_generator_handler and "target_generator_handler" not in self._handlers.keys(): # tgf = RatatoskHandler(label="target_generator_handler", mod=self.target_generator_handler) # register_task_handler(self, tgf) # if not "target_generator_handler" in self._handlers.keys(): # logging.warn("MergeSamFiles requires a target generator handler; no defaults are as of yet implemented") # return [] # sources = list(set(self._handlers["target_generator_handler"](self))) # return [cls(target=src) for src in sources] # # Path: ratatosk/utils.py # def fullclassname(o): # return o.__module__ + "." + o.__name__ # # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # Path: ratatosk/handler.py # def register(handler_obj, default_handler=None): # """Register a module function represented as string in # to a backend handler. # # :param handler_obj: the handler object to register # :param default_handler: the default handler to fall back on # # :return: None # """ # if not handler_obj: # logging.warn("No handler object provided; skipping") # return # if not isinstance(handler_obj, IHandler): # raise ValueError, "handler object must implement the IHandler interface" # hdl = _load(handler_obj) # if not hdl: # return # if handler_obj.label() in backend.__handlers__: # old_hdl = backend.__handlers__[handler_obj.label()] # if fullclassname(old_hdl) == fullclassname(hdl): # logging.info("Handler object '{}' already registered; skipping".format(fullclassname(hdl))) # return # else: # logging.warn("Trying to reset already registered '{}' which is not supported".format(handler_obj.label())) # return # else: # backend.__handlers__[handler_obj.label()] = hdl # # def register_task_handler(obj, handler_obj, default_handler=None): # """Register a module function represented as string in # to a task handler. # # :param obj: the object to which the handler is registered # :param handler_obj: the handler object to register # :param default_handler: the default handler to fall back on # # :return: None # """ # if not handler_obj: # logging.warn("No handler object provided; skipping") # return # if not isinstance(handler_obj, IHandler): # raise ValueError, "handler object must implement the IHandler interface" # hdl = _load(handler_obj) # if not hdl: # return # if handler_obj.label() in obj._handlers: # old_hdl = obj._handlers[handler_obj.label()] # if fullclassname(old_hdl) == fullclassname(hdl): # logging.info("Handler object '{}' already registered in {}; skipping".format(fullclassname(hdl), obj)) # return # else: # logging.warn("Trying to reset already registered '{}' which is not supported".format(handler_obj.label())) # return # else: # obj._handlers[handler_obj.label()] = hdl # # class RatatoskHandler(IHandler): # """Ratatosk handler class. Ensures we have at least label and mod # functions that uses register to place mod in # backend.__handlers__[label]. # """ # _label = None # _mod = None # _load_type = None # # def __init__(self, label, mod, load_type="function"): # """Initialize handler with label (key in backend.__handlers__) # and mod (string representation of class/function). Load_type # deterimines what load function to use. # """ # setattr(self, "_label", label) # setattr(self, "_mod", mod) # setattr(self, "_load_type", load_type) # # def label(self): # """Handler identifier label""" # return self._label # # def mod(self): # """String representation of class/function""" # return self._mod # # def load_type(self): # """Load type (class or function)""" # return self._load_type . Output only the next line.
conf.clear()
Next line prediction: <|code_start|> logging.basicConfig(level=logging.DEBUG) def local_target_generator(task): return None def setUpModule(): global cnf, conf cnf = get_custom_config() cnf.clear() conf = get_config() conf.clear() <|code_end|> . Use current file imports: (import os import glob import shutil import sys import unittest import luigi import yaml import logging from ratatosk import interface, backend from ratatosk.config import get_config, get_custom_config from ratatosk.lib.tools.picard import MergeSamFiles from ratatosk.utils import fullclassname, rreplace from types import GeneratorType from ratatosk.handler import register, register_task_handler, RatatoskHandler) and context including class names, function names, or small code snippets from other files: # Path: ratatosk/interface.py # class Interface(object): # def __init__(self): # # Path: ratatosk/backend.py # # Path: ratatosk/config.py # def get_config(): # return RatatoskConfigParser.instance() # # def get_custom_config(): # """Get separate parser for custom config; else custom config # parent_task setting will override config file settings""" # return RatatoskCustomConfigParser.instance() # # Path: ratatosk/lib/tools/picard.py # class MergeSamFiles(PicardJobTask): # executable = "MergeSamFiles.jar" # label = luigi.Parameter(default=".merge") # read1_suffix = luigi.Parameter(default="_R1_001") # target_generator_handler = luigi.Parameter(default=None) # # FIXME: TMP_DIR should not be hard-coded # options = luigi.Parameter(default=("SO=coordinate TMP_DIR=./tmp", ), is_list=True) # # def args(self): # return ["OUTPUT=", self.output()] + [item for sublist in [["INPUT=", x] for x in self.input()] for item in sublist] # # def requires(self): # cls = self.parent()[0] # sources = [] # cnf = get_config() # if self.target_generator_handler and "target_generator_handler" not in self._handlers.keys(): # tgf = RatatoskHandler(label="target_generator_handler", mod=self.target_generator_handler) # register_task_handler(self, tgf) # if not "target_generator_handler" in self._handlers.keys(): # logging.warn("MergeSamFiles requires a target generator handler; no defaults are as of yet implemented") # return [] # sources = list(set(self._handlers["target_generator_handler"](self))) # return [cls(target=src) for src in sources] # # Path: ratatosk/utils.py # def fullclassname(o): # return o.__module__ + "." + o.__name__ # # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # Path: ratatosk/handler.py # def register(handler_obj, default_handler=None): # """Register a module function represented as string in # to a backend handler. # # :param handler_obj: the handler object to register # :param default_handler: the default handler to fall back on # # :return: None # """ # if not handler_obj: # logging.warn("No handler object provided; skipping") # return # if not isinstance(handler_obj, IHandler): # raise ValueError, "handler object must implement the IHandler interface" # hdl = _load(handler_obj) # if not hdl: # return # if handler_obj.label() in backend.__handlers__: # old_hdl = backend.__handlers__[handler_obj.label()] # if fullclassname(old_hdl) == fullclassname(hdl): # logging.info("Handler object '{}' already registered; skipping".format(fullclassname(hdl))) # return # else: # logging.warn("Trying to reset already registered '{}' which is not supported".format(handler_obj.label())) # return # else: # backend.__handlers__[handler_obj.label()] = hdl # # def register_task_handler(obj, handler_obj, default_handler=None): # """Register a module function represented as string in # to a task handler. # # :param obj: the object to which the handler is registered # :param handler_obj: the handler object to register # :param default_handler: the default handler to fall back on # # :return: None # """ # if not handler_obj: # logging.warn("No handler object provided; skipping") # return # if not isinstance(handler_obj, IHandler): # raise ValueError, "handler object must implement the IHandler interface" # hdl = _load(handler_obj) # if not hdl: # return # if handler_obj.label() in obj._handlers: # old_hdl = obj._handlers[handler_obj.label()] # if fullclassname(old_hdl) == fullclassname(hdl): # logging.info("Handler object '{}' already registered in {}; skipping".format(fullclassname(hdl), obj)) # return # else: # logging.warn("Trying to reset already registered '{}' which is not supported".format(handler_obj.label())) # return # else: # obj._handlers[handler_obj.label()] = hdl # # class RatatoskHandler(IHandler): # """Ratatosk handler class. Ensures we have at least label and mod # functions that uses register to place mod in # backend.__handlers__[label]. # """ # _label = None # _mod = None # _load_type = None # # def __init__(self, label, mod, load_type="function"): # """Initialize handler with label (key in backend.__handlers__) # and mod (string representation of class/function). Load_type # deterimines what load function to use. # """ # setattr(self, "_label", label) # setattr(self, "_mod", mod) # setattr(self, "_load_type", load_type) # # def label(self): # """Handler identifier label""" # return self._label # # def mod(self): # """String representation of class/function""" # return self._mod # # def load_type(self): # """Load type (class or function)""" # return self._load_type . Output only the next line.
def tearDownModule():
Continue the code snippet: <|code_start|>class SamtoolsJobTask(JobTask): """Main samtools job task""" executable = luigi.Parameter(default="samtools") parent_task = luigi.Parameter(default=("ratatosk.lib.tools.samtools.InputSamFile", ), is_list=True) suffix = luigi.Parameter(default=".bam") def job_runner(self): return SamtoolsJobRunner() class SamToBam(SamtoolsJobTask): sub_executable = "view" options = luigi.Parameter(default=("-bSh",), is_list=True) parent_task = luigi.Parameter(default=("ratatosk.lib.tools.samtools.InputSamFile", ), is_list=True) suffix = luigi.Parameter(default=".bam") def args(self): retval = [self.input()[0], ">", self.output()] if self.pipe: return retval + ["-"] return retval class SortBam(SamtoolsJobTask): sub_executable = "sort" suffix = luigi.Parameter(default=".bam") label = luigi.Parameter(default=".sort") parent_task = luigi.Parameter(default=("ratatosk.lib.tools.samtools.SamToBam", ), is_list=True) def add_suffix(self): """samtools sort generates its output based on a prefix, hence we need to add a suffix here""" <|code_end|> . Use current file imports: import os import luigi import ratatosk.lib.files.input from ratatosk.job import InputJobTask, JobTask from ratatosk.utils import rreplace from ratatosk.jobrunner import DefaultShellJobRunner from ratatosk.log import get_logger and context (classes, functions, or code) from other files: # Path: ratatosk/job.py # class InputJobTask(JobTask): # """Input job task. Should have as a parent task one of the tasks # in ratatosk.lib.files.external""" # def requires(self): # cls = self.parent()[0] # return cls(target=self.target) # # def run(self): # """No run should be defined""" # pass # # class JobTask(BaseJobTask): # def job_runner(self): # return DefaultShellJobRunner() # # def args(self): # return [] # # Path: ratatosk/utils.py # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # Path: ratatosk/jobrunner.py # class DefaultShellJobRunner(JobRunner): # """Default job runner to use for shell jobs.""" # def __init__(self): # pass # # @staticmethod # def _fix_paths(job): # """Modelled after hadoop_jar.HadoopJarJobRunner._fix_paths. # """ # tmp_files = [] # args = [] # for x in job.args(): # if isinstance(x, luigi.LocalTarget): # input/output # if x.exists(): # input # args.append(x.path) # else: # output # ypath = x.path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) # y = luigi.LocalTarget(ypath) # logger.info("Using temp path: {0} for path {1}".format(y.path, x.path)) # args.append(y.path) # if job.add_suffix(): # x = luigi.LocalTarget(x.path + job.add_suffix()) # y = luigi.LocalTarget(y.path + job.add_suffix()) # tmp_files.append((y, x)) # else: # args.append(str(x)) # return (tmp_files, args) # # @staticmethod # def _get_main(job): # """Add main program to command. Override this for programs # where main is given as a parameter, e.g. for GATK""" # return job.main() # # def _make_arglist(self, job): # """Make and return the arglist""" # if job.path(): # exe = os.path.join(job.path(), job.exe()) # else: # exe = job.exe() # if not exe:# or not os.path.exists(exe): # logger.error("Can't find executable: {0}, full path {1}".format(exe, # os.path.abspath(exe))) # raise Exception("executable does not exist") # arglist = [exe] # if job.main(): # arglist.append(self._get_main(job)) # if job.opts(): # arglist += job.opts() # # Need to call self.__class__ since fix_paths overridden in # # DefaultGzShellJobRunner # (tmp_files, job_args) = self.__class__._fix_paths(job) # if not job.pipe: # arglist += job_args # return (arglist, tmp_files) # # def run_job(self, job): # (arglist, tmp_files) = self._make_arglist(job) # if job.pipe: # return (arglist, tmp_files) # cmd = ' '.join(arglist) # logger.info("\nJob runner '{0}';\n\trunning command '{1}'\n".format(self.__class__, cmd)) # (stdout, stderr, returncode) = shell.exec_cmd(cmd, shell=True) # if returncode == 0: # logger.info("Shell job completed") # for a, b in tmp_files: # logger.info("renaming {0} to {1}".format(a.path, b.path)) # # This is weird; using the example in luigi # # (a.move(b)) doesn't work, and using just b.path # # fails unless it contains a directory (e.g. './file' # # works, 'file' doesn't) # a.move(os.path.join(os.curdir, b.path)) # else: # raise Exception("Job '{}' failed: \n{}".format(' '.join(arglist), " ".join([stderr]))) # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger . Output only the next line.
return self.suffix
Based on the snippet: <|code_start|> suffix = luigi.Parameter(default=".bam") def job_runner(self): return SamtoolsJobRunner() class SamToBam(SamtoolsJobTask): sub_executable = "view" options = luigi.Parameter(default=("-bSh",), is_list=True) parent_task = luigi.Parameter(default=("ratatosk.lib.tools.samtools.InputSamFile", ), is_list=True) suffix = luigi.Parameter(default=".bam") def args(self): retval = [self.input()[0], ">", self.output()] if self.pipe: return retval + ["-"] return retval class SortBam(SamtoolsJobTask): sub_executable = "sort" suffix = luigi.Parameter(default=".bam") label = luigi.Parameter(default=".sort") parent_task = luigi.Parameter(default=("ratatosk.lib.tools.samtools.SamToBam", ), is_list=True) def add_suffix(self): """samtools sort generates its output based on a prefix, hence we need to add a suffix here""" return self.suffix def args(self): output_prefix = luigi.LocalTarget(rreplace(self.output().path, self.suffix, "", 1)) <|code_end|> , predict the immediate next line with the help of imports: import os import luigi import ratatosk.lib.files.input from ratatosk.job import InputJobTask, JobTask from ratatosk.utils import rreplace from ratatosk.jobrunner import DefaultShellJobRunner from ratatosk.log import get_logger and context (classes, functions, sometimes code) from other files: # Path: ratatosk/job.py # class InputJobTask(JobTask): # """Input job task. Should have as a parent task one of the tasks # in ratatosk.lib.files.external""" # def requires(self): # cls = self.parent()[0] # return cls(target=self.target) # # def run(self): # """No run should be defined""" # pass # # class JobTask(BaseJobTask): # def job_runner(self): # return DefaultShellJobRunner() # # def args(self): # return [] # # Path: ratatosk/utils.py # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # Path: ratatosk/jobrunner.py # class DefaultShellJobRunner(JobRunner): # """Default job runner to use for shell jobs.""" # def __init__(self): # pass # # @staticmethod # def _fix_paths(job): # """Modelled after hadoop_jar.HadoopJarJobRunner._fix_paths. # """ # tmp_files = [] # args = [] # for x in job.args(): # if isinstance(x, luigi.LocalTarget): # input/output # if x.exists(): # input # args.append(x.path) # else: # output # ypath = x.path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) # y = luigi.LocalTarget(ypath) # logger.info("Using temp path: {0} for path {1}".format(y.path, x.path)) # args.append(y.path) # if job.add_suffix(): # x = luigi.LocalTarget(x.path + job.add_suffix()) # y = luigi.LocalTarget(y.path + job.add_suffix()) # tmp_files.append((y, x)) # else: # args.append(str(x)) # return (tmp_files, args) # # @staticmethod # def _get_main(job): # """Add main program to command. Override this for programs # where main is given as a parameter, e.g. for GATK""" # return job.main() # # def _make_arglist(self, job): # """Make and return the arglist""" # if job.path(): # exe = os.path.join(job.path(), job.exe()) # else: # exe = job.exe() # if not exe:# or not os.path.exists(exe): # logger.error("Can't find executable: {0}, full path {1}".format(exe, # os.path.abspath(exe))) # raise Exception("executable does not exist") # arglist = [exe] # if job.main(): # arglist.append(self._get_main(job)) # if job.opts(): # arglist += job.opts() # # Need to call self.__class__ since fix_paths overridden in # # DefaultGzShellJobRunner # (tmp_files, job_args) = self.__class__._fix_paths(job) # if not job.pipe: # arglist += job_args # return (arglist, tmp_files) # # def run_job(self, job): # (arglist, tmp_files) = self._make_arglist(job) # if job.pipe: # return (arglist, tmp_files) # cmd = ' '.join(arglist) # logger.info("\nJob runner '{0}';\n\trunning command '{1}'\n".format(self.__class__, cmd)) # (stdout, stderr, returncode) = shell.exec_cmd(cmd, shell=True) # if returncode == 0: # logger.info("Shell job completed") # for a, b in tmp_files: # logger.info("renaming {0} to {1}".format(a.path, b.path)) # # This is weird; using the example in luigi # # (a.move(b)) doesn't work, and using just b.path # # fails unless it contains a directory (e.g. './file' # # works, 'file' doesn't) # a.move(os.path.join(os.curdir, b.path)) # else: # raise Exception("Job '{}' failed: \n{}".format(' '.join(arglist), " ".join([stderr]))) # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger . Output only the next line.
return [self.input()[0], output_prefix]
Using the snippet: <|code_start|> executable = luigi.Parameter(default="samtools") parent_task = luigi.Parameter(default=("ratatosk.lib.tools.samtools.InputSamFile", ), is_list=True) suffix = luigi.Parameter(default=".bam") def job_runner(self): return SamtoolsJobRunner() class SamToBam(SamtoolsJobTask): sub_executable = "view" options = luigi.Parameter(default=("-bSh",), is_list=True) parent_task = luigi.Parameter(default=("ratatosk.lib.tools.samtools.InputSamFile", ), is_list=True) suffix = luigi.Parameter(default=".bam") def args(self): retval = [self.input()[0], ">", self.output()] if self.pipe: return retval + ["-"] return retval class SortBam(SamtoolsJobTask): sub_executable = "sort" suffix = luigi.Parameter(default=".bam") label = luigi.Parameter(default=".sort") parent_task = luigi.Parameter(default=("ratatosk.lib.tools.samtools.SamToBam", ), is_list=True) def add_suffix(self): """samtools sort generates its output based on a prefix, hence we need to add a suffix here""" return self.suffix <|code_end|> , determine the next line of code. You have imports: import os import luigi import ratatosk.lib.files.input from ratatosk.job import InputJobTask, JobTask from ratatosk.utils import rreplace from ratatosk.jobrunner import DefaultShellJobRunner from ratatosk.log import get_logger and context (class names, function names, or code) available: # Path: ratatosk/job.py # class InputJobTask(JobTask): # """Input job task. Should have as a parent task one of the tasks # in ratatosk.lib.files.external""" # def requires(self): # cls = self.parent()[0] # return cls(target=self.target) # # def run(self): # """No run should be defined""" # pass # # class JobTask(BaseJobTask): # def job_runner(self): # return DefaultShellJobRunner() # # def args(self): # return [] # # Path: ratatosk/utils.py # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # Path: ratatosk/jobrunner.py # class DefaultShellJobRunner(JobRunner): # """Default job runner to use for shell jobs.""" # def __init__(self): # pass # # @staticmethod # def _fix_paths(job): # """Modelled after hadoop_jar.HadoopJarJobRunner._fix_paths. # """ # tmp_files = [] # args = [] # for x in job.args(): # if isinstance(x, luigi.LocalTarget): # input/output # if x.exists(): # input # args.append(x.path) # else: # output # ypath = x.path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) # y = luigi.LocalTarget(ypath) # logger.info("Using temp path: {0} for path {1}".format(y.path, x.path)) # args.append(y.path) # if job.add_suffix(): # x = luigi.LocalTarget(x.path + job.add_suffix()) # y = luigi.LocalTarget(y.path + job.add_suffix()) # tmp_files.append((y, x)) # else: # args.append(str(x)) # return (tmp_files, args) # # @staticmethod # def _get_main(job): # """Add main program to command. Override this for programs # where main is given as a parameter, e.g. for GATK""" # return job.main() # # def _make_arglist(self, job): # """Make and return the arglist""" # if job.path(): # exe = os.path.join(job.path(), job.exe()) # else: # exe = job.exe() # if not exe:# or not os.path.exists(exe): # logger.error("Can't find executable: {0}, full path {1}".format(exe, # os.path.abspath(exe))) # raise Exception("executable does not exist") # arglist = [exe] # if job.main(): # arglist.append(self._get_main(job)) # if job.opts(): # arglist += job.opts() # # Need to call self.__class__ since fix_paths overridden in # # DefaultGzShellJobRunner # (tmp_files, job_args) = self.__class__._fix_paths(job) # if not job.pipe: # arglist += job_args # return (arglist, tmp_files) # # def run_job(self, job): # (arglist, tmp_files) = self._make_arglist(job) # if job.pipe: # return (arglist, tmp_files) # cmd = ' '.join(arglist) # logger.info("\nJob runner '{0}';\n\trunning command '{1}'\n".format(self.__class__, cmd)) # (stdout, stderr, returncode) = shell.exec_cmd(cmd, shell=True) # if returncode == 0: # logger.info("Shell job completed") # for a, b in tmp_files: # logger.info("renaming {0} to {1}".format(a.path, b.path)) # # This is weird; using the example in luigi # # (a.move(b)) doesn't work, and using just b.path # # fails unless it contains a directory (e.g. './file' # # works, 'file' doesn't) # a.move(os.path.join(os.curdir, b.path)) # else: # raise Exception("Job '{}' failed: \n{}".format(' '.join(arglist), " ".join([stderr]))) # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger . Output only the next line.
def args(self):
Next line prediction: <|code_start|>class SamtoolsJobTask(JobTask): """Main samtools job task""" executable = luigi.Parameter(default="samtools") parent_task = luigi.Parameter(default=("ratatosk.lib.tools.samtools.InputSamFile", ), is_list=True) suffix = luigi.Parameter(default=".bam") def job_runner(self): return SamtoolsJobRunner() class SamToBam(SamtoolsJobTask): sub_executable = "view" options = luigi.Parameter(default=("-bSh",), is_list=True) parent_task = luigi.Parameter(default=("ratatosk.lib.tools.samtools.InputSamFile", ), is_list=True) suffix = luigi.Parameter(default=".bam") def args(self): retval = [self.input()[0], ">", self.output()] if self.pipe: return retval + ["-"] return retval class SortBam(SamtoolsJobTask): sub_executable = "sort" suffix = luigi.Parameter(default=".bam") label = luigi.Parameter(default=".sort") parent_task = luigi.Parameter(default=("ratatosk.lib.tools.samtools.SamToBam", ), is_list=True) def add_suffix(self): """samtools sort generates its output based on a prefix, hence we need to add a suffix here""" <|code_end|> . Use current file imports: (import os import luigi import ratatosk.lib.files.input from ratatosk.job import InputJobTask, JobTask from ratatosk.utils import rreplace from ratatosk.jobrunner import DefaultShellJobRunner from ratatosk.log import get_logger) and context including class names, function names, or small code snippets from other files: # Path: ratatosk/job.py # class InputJobTask(JobTask): # """Input job task. Should have as a parent task one of the tasks # in ratatosk.lib.files.external""" # def requires(self): # cls = self.parent()[0] # return cls(target=self.target) # # def run(self): # """No run should be defined""" # pass # # class JobTask(BaseJobTask): # def job_runner(self): # return DefaultShellJobRunner() # # def args(self): # return [] # # Path: ratatosk/utils.py # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # Path: ratatosk/jobrunner.py # class DefaultShellJobRunner(JobRunner): # """Default job runner to use for shell jobs.""" # def __init__(self): # pass # # @staticmethod # def _fix_paths(job): # """Modelled after hadoop_jar.HadoopJarJobRunner._fix_paths. # """ # tmp_files = [] # args = [] # for x in job.args(): # if isinstance(x, luigi.LocalTarget): # input/output # if x.exists(): # input # args.append(x.path) # else: # output # ypath = x.path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) # y = luigi.LocalTarget(ypath) # logger.info("Using temp path: {0} for path {1}".format(y.path, x.path)) # args.append(y.path) # if job.add_suffix(): # x = luigi.LocalTarget(x.path + job.add_suffix()) # y = luigi.LocalTarget(y.path + job.add_suffix()) # tmp_files.append((y, x)) # else: # args.append(str(x)) # return (tmp_files, args) # # @staticmethod # def _get_main(job): # """Add main program to command. Override this for programs # where main is given as a parameter, e.g. for GATK""" # return job.main() # # def _make_arglist(self, job): # """Make and return the arglist""" # if job.path(): # exe = os.path.join(job.path(), job.exe()) # else: # exe = job.exe() # if not exe:# or not os.path.exists(exe): # logger.error("Can't find executable: {0}, full path {1}".format(exe, # os.path.abspath(exe))) # raise Exception("executable does not exist") # arglist = [exe] # if job.main(): # arglist.append(self._get_main(job)) # if job.opts(): # arglist += job.opts() # # Need to call self.__class__ since fix_paths overridden in # # DefaultGzShellJobRunner # (tmp_files, job_args) = self.__class__._fix_paths(job) # if not job.pipe: # arglist += job_args # return (arglist, tmp_files) # # def run_job(self, job): # (arglist, tmp_files) = self._make_arglist(job) # if job.pipe: # return (arglist, tmp_files) # cmd = ' '.join(arglist) # logger.info("\nJob runner '{0}';\n\trunning command '{1}'\n".format(self.__class__, cmd)) # (stdout, stderr, returncode) = shell.exec_cmd(cmd, shell=True) # if returncode == 0: # logger.info("Shell job completed") # for a, b in tmp_files: # logger.info("renaming {0} to {1}".format(a.path, b.path)) # # This is weird; using the example in luigi # # (a.move(b)) doesn't work, and using just b.path # # fails unless it contains a directory (e.g. './file' # # works, 'file' doesn't) # a.move(os.path.join(os.curdir, b.path)) # else: # raise Exception("Job '{}' failed: \n{}".format(' '.join(arglist), " ".join([stderr]))) # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger . Output only the next line.
return self.suffix
Given the code 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. """ Provide wrappers for `fastqc <http://www.bioinformatics.babraham.ac.uk/projects/fastqc/>`_ Classes ------- """ logger = get_logger() class InputBamFile(ratatosk.lib.files.input.InputBamFile): pass class InputFastqFile(ratatosk.lib.files.input.InputFastqFile): pass # This was a nightmare to get right. Temporary output is a directory, # so would need custom _fix_paths for cases like this class FastQCJobRunner(DefaultShellJobRunner): """This job runner must take into account that there is no default output file but rather an output directory""" def _make_arglist(self, job): arglist = [job.exe()] if job.opts(): <|code_end|> , generate the next line using the imports in this file: import os import luigi import ratatosk.lib.files.input import ratatosk.shell as shell from ratatosk.job import JobTask from ratatosk.jobrunner import DefaultShellJobRunner from ratatosk.log import get_logger and context (functions, classes, or occasionally code) from other files: # Path: ratatosk/job.py # class JobTask(BaseJobTask): # def job_runner(self): # return DefaultShellJobRunner() # # def args(self): # return [] # # Path: ratatosk/jobrunner.py # class DefaultShellJobRunner(JobRunner): # """Default job runner to use for shell jobs.""" # def __init__(self): # pass # # @staticmethod # def _fix_paths(job): # """Modelled after hadoop_jar.HadoopJarJobRunner._fix_paths. # """ # tmp_files = [] # args = [] # for x in job.args(): # if isinstance(x, luigi.LocalTarget): # input/output # if x.exists(): # input # args.append(x.path) # else: # output # ypath = x.path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) # y = luigi.LocalTarget(ypath) # logger.info("Using temp path: {0} for path {1}".format(y.path, x.path)) # args.append(y.path) # if job.add_suffix(): # x = luigi.LocalTarget(x.path + job.add_suffix()) # y = luigi.LocalTarget(y.path + job.add_suffix()) # tmp_files.append((y, x)) # else: # args.append(str(x)) # return (tmp_files, args) # # @staticmethod # def _get_main(job): # """Add main program to command. Override this for programs # where main is given as a parameter, e.g. for GATK""" # return job.main() # # def _make_arglist(self, job): # """Make and return the arglist""" # if job.path(): # exe = os.path.join(job.path(), job.exe()) # else: # exe = job.exe() # if not exe:# or not os.path.exists(exe): # logger.error("Can't find executable: {0}, full path {1}".format(exe, # os.path.abspath(exe))) # raise Exception("executable does not exist") # arglist = [exe] # if job.main(): # arglist.append(self._get_main(job)) # if job.opts(): # arglist += job.opts() # # Need to call self.__class__ since fix_paths overridden in # # DefaultGzShellJobRunner # (tmp_files, job_args) = self.__class__._fix_paths(job) # if not job.pipe: # arglist += job_args # return (arglist, tmp_files) # # def run_job(self, job): # (arglist, tmp_files) = self._make_arglist(job) # if job.pipe: # return (arglist, tmp_files) # cmd = ' '.join(arglist) # logger.info("\nJob runner '{0}';\n\trunning command '{1}'\n".format(self.__class__, cmd)) # (stdout, stderr, returncode) = shell.exec_cmd(cmd, shell=True) # if returncode == 0: # logger.info("Shell job completed") # for a, b in tmp_files: # logger.info("renaming {0} to {1}".format(a.path, b.path)) # # This is weird; using the example in luigi # # (a.move(b)) doesn't work, and using just b.path # # fails unless it contains a directory (e.g. './file' # # works, 'file' doesn't) # a.move(os.path.join(os.curdir, b.path)) # else: # raise Exception("Job '{}' failed: \n{}".format(' '.join(arglist), " ".join([stderr]))) # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger . Output only the next line.
arglist += job.opts()
Continue the code snippet: <|code_start|> output file but rather an output directory""" def _make_arglist(self, job): arglist = [job.exe()] if job.opts(): arglist += job.opts() (tmp_files, job_args) = DefaultShellJobRunner._fix_paths(job) (tmpdir, outdir) = tmp_files[0] arglist += ['-o', tmpdir.path] arglist += [job_args[0]] return (arglist, tmp_files) def run_job(self, job): (arglist, tmp_files) = self._make_arglist(job) (tmpdir, outdir) = tmp_files[0] os.makedirs(os.path.join(os.curdir, tmpdir.path)) # Need to send output to temporary *directory*, not file cmd = ' '.join(arglist) logger.info("Job runner '{0}'; running command '{1}'".format(self.__class__, cmd)) (stdout, stderr, returncode) = shell.exec_cmd(cmd, shell=True) if returncode == 0: logger.info("Shell job completed") for a, b in tmp_files: logger.info("renaming {0} to {1}".format(a.path, b.path)) a.move(os.path.join(os.curdir, b.path)) else: raise Exception("Job '{}' failed: \n{}".format(cmd.replace("= ", "="), " ".join([stderr]))) class FastQC(JobTask): executable = luigi.Parameter(default="fastqc") <|code_end|> . Use current file imports: import os import luigi import ratatosk.lib.files.input import ratatosk.shell as shell from ratatosk.job import JobTask from ratatosk.jobrunner import DefaultShellJobRunner from ratatosk.log import get_logger and context (classes, functions, or code) from other files: # Path: ratatosk/job.py # class JobTask(BaseJobTask): # def job_runner(self): # return DefaultShellJobRunner() # # def args(self): # return [] # # Path: ratatosk/jobrunner.py # class DefaultShellJobRunner(JobRunner): # """Default job runner to use for shell jobs.""" # def __init__(self): # pass # # @staticmethod # def _fix_paths(job): # """Modelled after hadoop_jar.HadoopJarJobRunner._fix_paths. # """ # tmp_files = [] # args = [] # for x in job.args(): # if isinstance(x, luigi.LocalTarget): # input/output # if x.exists(): # input # args.append(x.path) # else: # output # ypath = x.path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) # y = luigi.LocalTarget(ypath) # logger.info("Using temp path: {0} for path {1}".format(y.path, x.path)) # args.append(y.path) # if job.add_suffix(): # x = luigi.LocalTarget(x.path + job.add_suffix()) # y = luigi.LocalTarget(y.path + job.add_suffix()) # tmp_files.append((y, x)) # else: # args.append(str(x)) # return (tmp_files, args) # # @staticmethod # def _get_main(job): # """Add main program to command. Override this for programs # where main is given as a parameter, e.g. for GATK""" # return job.main() # # def _make_arglist(self, job): # """Make and return the arglist""" # if job.path(): # exe = os.path.join(job.path(), job.exe()) # else: # exe = job.exe() # if not exe:# or not os.path.exists(exe): # logger.error("Can't find executable: {0}, full path {1}".format(exe, # os.path.abspath(exe))) # raise Exception("executable does not exist") # arglist = [exe] # if job.main(): # arglist.append(self._get_main(job)) # if job.opts(): # arglist += job.opts() # # Need to call self.__class__ since fix_paths overridden in # # DefaultGzShellJobRunner # (tmp_files, job_args) = self.__class__._fix_paths(job) # if not job.pipe: # arglist += job_args # return (arglist, tmp_files) # # def run_job(self, job): # (arglist, tmp_files) = self._make_arglist(job) # if job.pipe: # return (arglist, tmp_files) # cmd = ' '.join(arglist) # logger.info("\nJob runner '{0}';\n\trunning command '{1}'\n".format(self.__class__, cmd)) # (stdout, stderr, returncode) = shell.exec_cmd(cmd, shell=True) # if returncode == 0: # logger.info("Shell job completed") # for a, b in tmp_files: # logger.info("renaming {0} to {1}".format(a.path, b.path)) # # This is weird; using the example in luigi # # (a.move(b)) doesn't work, and using just b.path # # fails unless it contains a directory (e.g. './file' # # works, 'file' doesn't) # a.move(os.path.join(os.curdir, b.path)) # else: # raise Exception("Job '{}' failed: \n{}".format(' '.join(arglist), " ".join([stderr]))) # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger . Output only the next line.
parent_task = luigi.Parameter(default = "ratatosk.lib.tools.fastqc.InputFastqFile")
Given the following code snippet before the placeholder: <|code_start|>logger = get_logger() class InputBamFile(ratatosk.lib.files.input.InputBamFile): pass class InputFastqFile(ratatosk.lib.files.input.InputFastqFile): pass # This was a nightmare to get right. Temporary output is a directory, # so would need custom _fix_paths for cases like this class FastQCJobRunner(DefaultShellJobRunner): """This job runner must take into account that there is no default output file but rather an output directory""" def _make_arglist(self, job): arglist = [job.exe()] if job.opts(): arglist += job.opts() (tmp_files, job_args) = DefaultShellJobRunner._fix_paths(job) (tmpdir, outdir) = tmp_files[0] arglist += ['-o', tmpdir.path] arglist += [job_args[0]] return (arglist, tmp_files) def run_job(self, job): (arglist, tmp_files) = self._make_arglist(job) (tmpdir, outdir) = tmp_files[0] os.makedirs(os.path.join(os.curdir, tmpdir.path)) # Need to send output to temporary *directory*, not file cmd = ' '.join(arglist) logger.info("Job runner '{0}'; running command '{1}'".format(self.__class__, cmd)) <|code_end|> , predict the next line using imports from the current file: import os import luigi import ratatosk.lib.files.input import ratatosk.shell as shell from ratatosk.job import JobTask from ratatosk.jobrunner import DefaultShellJobRunner from ratatosk.log import get_logger and context including class names, function names, and sometimes code from other files: # Path: ratatosk/job.py # class JobTask(BaseJobTask): # def job_runner(self): # return DefaultShellJobRunner() # # def args(self): # return [] # # Path: ratatosk/jobrunner.py # class DefaultShellJobRunner(JobRunner): # """Default job runner to use for shell jobs.""" # def __init__(self): # pass # # @staticmethod # def _fix_paths(job): # """Modelled after hadoop_jar.HadoopJarJobRunner._fix_paths. # """ # tmp_files = [] # args = [] # for x in job.args(): # if isinstance(x, luigi.LocalTarget): # input/output # if x.exists(): # input # args.append(x.path) # else: # output # ypath = x.path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) # y = luigi.LocalTarget(ypath) # logger.info("Using temp path: {0} for path {1}".format(y.path, x.path)) # args.append(y.path) # if job.add_suffix(): # x = luigi.LocalTarget(x.path + job.add_suffix()) # y = luigi.LocalTarget(y.path + job.add_suffix()) # tmp_files.append((y, x)) # else: # args.append(str(x)) # return (tmp_files, args) # # @staticmethod # def _get_main(job): # """Add main program to command. Override this for programs # where main is given as a parameter, e.g. for GATK""" # return job.main() # # def _make_arglist(self, job): # """Make and return the arglist""" # if job.path(): # exe = os.path.join(job.path(), job.exe()) # else: # exe = job.exe() # if not exe:# or not os.path.exists(exe): # logger.error("Can't find executable: {0}, full path {1}".format(exe, # os.path.abspath(exe))) # raise Exception("executable does not exist") # arglist = [exe] # if job.main(): # arglist.append(self._get_main(job)) # if job.opts(): # arglist += job.opts() # # Need to call self.__class__ since fix_paths overridden in # # DefaultGzShellJobRunner # (tmp_files, job_args) = self.__class__._fix_paths(job) # if not job.pipe: # arglist += job_args # return (arglist, tmp_files) # # def run_job(self, job): # (arglist, tmp_files) = self._make_arglist(job) # if job.pipe: # return (arglist, tmp_files) # cmd = ' '.join(arglist) # logger.info("\nJob runner '{0}';\n\trunning command '{1}'\n".format(self.__class__, cmd)) # (stdout, stderr, returncode) = shell.exec_cmd(cmd, shell=True) # if returncode == 0: # logger.info("Shell job completed") # for a, b in tmp_files: # logger.info("renaming {0} to {1}".format(a.path, b.path)) # # This is weird; using the example in luigi # # (a.move(b)) doesn't work, and using just b.path # # fails unless it contains a directory (e.g. './file' # # works, 'file' doesn't) # a.move(os.path.join(os.curdir, b.path)) # else: # raise Exception("Job '{}' failed: \n{}".format(' '.join(arglist), " ".join([stderr]))) # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger . Output only the next line.
(stdout, stderr, returncode) = shell.exec_cmd(cmd, shell=True)
Given the code snippet: <|code_start|># Copyright (c) 2013 Per Unneberg # # 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. # NOTE: this test suite only verifies that the commands are formatted # correctly. No actual spawning of subprocesses is done. class TestABCSample(unittest.TestCase): def setUp(self): self.sample = Sample(project_id="project", sample_id="sample", sample_prefix="project/sample/sample", project_prefix="project", sample_run_prefix="project/sample/samplerun/samplerun") <|code_end|> , generate the next line using the imports in this file: import os import re import unittest from ratatosk.experiment import Sample and context (functions, classes, or occasionally code) from other files: # Path: ratatosk/experiment.py # class Sample(ISample): # """A class describing a sample. Provides placeholders for # project_id, sample_id, project_prefix, sample_prefix, and # sample_run_prefix. # # """ # _levels = {} # _sample_id = None # _project_id = None # _project_prefix = None # _sample_prefix = None # _sample_run_prefix = None # # def __init__(self, project_id=None, sample_id=None, project_prefix=None, sample_prefix=None, sample_run_prefix=None, **kwargs): # self._project_id = project_id # self._sample_id = sample_id # self._prefix = {'project' : project_prefix, # 'sample' : sample_prefix, # 'sample_run' : sample_run_prefix # } # def __repr__(self): # return "{} (".format(self.__class__) + ",".join([str(self.project_id()), str(self.sample_id()), str(self.prefix("project")), str(self.prefix("sample")), str(self.prefix("sample_run"))]) + ")" # def project_id(self): # return self._project_id # def sample_id(self): # return self._sample_id # def prefix(self, group="sample"): # if not group in ["project", "sample", "sample_run"]: # raise ValueError, "No such prefix level '{}'".format(group) # return self._prefix[group] # def path(self, group="sample"): # if not group in ["project", "sample", "sample_run"]: # raise ValueError, "No such prefix level '{}'".format(group) # d = os.path.dirname(self._prefix[group]) # if not d: # d = os.curdir # return d # def levels(self): # return # def add_level(self, level): # return # def get_level(self, level): # return . Output only the next line.
def test_sample(self):
Continue the code snippet: <|code_start|># Copyright (c) 2013 Per Unneberg # # 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. TEMPLATEPATH = os.path.join(os.path.dirname(__file__), os.pardir, "data", "templates", "doc") templates = { 'make' : (Template(filename=os.path.join(TEMPLATEPATH, "Makefile.mako")),''), 'sample' : (Template(filename=os.path.join(TEMPLATEPATH, "source", "samples", "sample.mako")), '.rst'), 'index' : (Template(filename=os.path.join(TEMPLATEPATH, "source", "index.mako")), '.rst'), 'sampleindex' : (Template(filename=os.path.join(TEMPLATEPATH, "source", "samples", "index.mako")), '.rst'), 'conf' : (Template(filename=os.path.join(TEMPLATEPATH, "source", "conf.mako")), '.py') <|code_end|> . Use current file imports: import os import luigi import re import texttable as tt import cPickle as pickle from mako.template import Template from ratatosk.job import JobTask from ratatosk.log import get_logger from ratatosk.report.utils import group_samples and context (classes, functions, or code) from other files: # Path: ratatosk/job.py # class JobTask(BaseJobTask): # def job_runner(self): # return DefaultShellJobRunner() # # def args(self): # return [] # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger # # Path: ratatosk/report/utils.py # def group_samples(samples, grouping="sample"): # """Group samples by sample or sample run. # # :param samples: list of :class:`ISample <ratatosk.experiment.ISample>` objects # :param grouping: what to group by # # :returns: dictionary of grouped items # """ # groups = OrderedDict() # if grouping == "sample": # for k,g in itertools.groupby(samples, key=lambda x:x.sample_id()): # groups[k] = list(g) # elif grouping == "samplerun": # for k,g in itertools.groupby(samples, key=lambda x:x.prefix("samplerun")): # groups[k] = list(g) # return groups . Output only the next line.
}
Given snippet: <|code_start|># Copyright (c) 2013 Per Unneberg # # 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. TEMPLATEPATH = os.path.join(os.path.dirname(__file__), os.pardir, "data", "templates", "doc") templates = { 'make' : (Template(filename=os.path.join(TEMPLATEPATH, "Makefile.mako")),''), 'sample' : (Template(filename=os.path.join(TEMPLATEPATH, "source", "samples", "sample.mako")), '.rst'), 'index' : (Template(filename=os.path.join(TEMPLATEPATH, "source", "index.mako")), '.rst'), <|code_end|> , continue by predicting the next line. Consider current file imports: import os import luigi import re import texttable as tt import cPickle as pickle from mako.template import Template from ratatosk.job import JobTask from ratatosk.log import get_logger from ratatosk.report.utils import group_samples and context: # Path: ratatosk/job.py # class JobTask(BaseJobTask): # def job_runner(self): # return DefaultShellJobRunner() # # def args(self): # return [] # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger # # Path: ratatosk/report/utils.py # def group_samples(samples, grouping="sample"): # """Group samples by sample or sample run. # # :param samples: list of :class:`ISample <ratatosk.experiment.ISample>` objects # :param grouping: what to group by # # :returns: dictionary of grouped items # """ # groups = OrderedDict() # if grouping == "sample": # for k,g in itertools.groupby(samples, key=lambda x:x.sample_id()): # groups[k] = list(g) # elif grouping == "samplerun": # for k,g in itertools.groupby(samples, key=lambda x:x.prefix("samplerun")): # groups[k] = list(g) # return groups which might include code, classes, or functions. Output only the next line.
'sampleindex' : (Template(filename=os.path.join(TEMPLATEPATH, "source", "samples", "index.mako")), '.rst'),
Using the snippet: <|code_start|># Copyright (c) 2013 Per Unneberg # # 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. TEMPLATEPATH = os.path.join(os.path.dirname(__file__), os.pardir, "data", "templates", "doc") templates = { 'make' : (Template(filename=os.path.join(TEMPLATEPATH, "Makefile.mako")),''), 'sample' : (Template(filename=os.path.join(TEMPLATEPATH, "source", "samples", "sample.mako")), '.rst'), 'index' : (Template(filename=os.path.join(TEMPLATEPATH, "source", "index.mako")), '.rst'), 'sampleindex' : (Template(filename=os.path.join(TEMPLATEPATH, "source", "samples", "index.mako")), '.rst'), 'conf' : (Template(filename=os.path.join(TEMPLATEPATH, "source", "conf.mako")), '.py') } docdirs = ["build", "source", os.path.join("source", "_static"), os.path.join("source", "_templates"), os.path.join("source", "samples")] logger = get_logger() <|code_end|> , determine the next line of code. You have imports: import os import luigi import re import texttable as tt import cPickle as pickle from mako.template import Template from ratatosk.job import JobTask from ratatosk.log import get_logger from ratatosk.report.utils import group_samples and context (class names, function names, or code) available: # Path: ratatosk/job.py # class JobTask(BaseJobTask): # def job_runner(self): # return DefaultShellJobRunner() # # def args(self): # return [] # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger # # Path: ratatosk/report/utils.py # def group_samples(samples, grouping="sample"): # """Group samples by sample or sample run. # # :param samples: list of :class:`ISample <ratatosk.experiment.ISample>` objects # :param grouping: what to group by # # :returns: dictionary of grouped items # """ # groups = OrderedDict() # if grouping == "sample": # for k,g in itertools.groupby(samples, key=lambda x:x.sample_id()): # groups[k] = list(g) # elif grouping == "samplerun": # for k,g in itertools.groupby(samples, key=lambda x:x.prefix("samplerun")): # groups[k] = list(g) # return groups . Output only the next line.
def _setup_directories(root):
Given the code snippet: <|code_start|> logging.basicConfig(level=logging.DEBUG) sample = "P001_101_index3_TGACCA_L001" bam = os.path.join(sample + ".bam") localconf = "mock.yaml" ratatosk_conf = os.path.join(os.path.dirname(__file__), os.pardir, "config", "ratatosk.yaml") def setUpModule(): global cnf cnf = get_config() with open(localconf, "w") as fp: fp.write(yaml.safe_dump({ 'picard' : { <|code_end|> , generate the next line using the imports in this file: import os import shutil import unittest import luigi import logging import yaml import ratatosk.lib.align.bwa as BWA import ratatosk.lib.tools.samtools as SAM import ratatosk.lib.files.fastq as FASTQ import ratatosk.lib.tools.picard as PICARD import ratatosk.lib.tools.gatk as GATK import ratatosk.lib.utils.cutadapt as CUTADAPT import ratatosk.lib.tools.fastqc as FASTQC import ratatosk.lib.files.external from itertools import izip from ratatosk.config import get_config from ratatosk.utils import make_fastq_links, rreplace, determine_read_type and context (functions, classes, or occasionally code) from other files: # Path: ratatosk/config.py # def get_config(): # return RatatoskConfigParser.instance() # # Path: ratatosk/utils.py # def make_fastq_links(targets, indir, outdir, fastq_suffix="001.fastq.gz", ssheet="SampleSheet.csv"): # """Given a set of targets and an output directory, create links # from targets (source raw data) to an output directory. # # :param targets: list of :class:`ratatosk.experiment.ISample` objects # :param outdir: (top) output directory # :param fastq_suffix: fastq suffix # :param ssheet: sample sheet name # # :returns: new targets list with updated output directory # """ # newtargets = [] # for tgt in targets: # fastq = glob.glob("{}*{}".format(tgt.prefix("sample_run"), fastq_suffix)) # if len(fastq) == 0: # logger.warn("No fastq files for prefix {} in {}".format(tgt.prefix("sample_run"), "make_fastq_links")) # for f in fastq: # newpath = os.path.join(outdir, os.path.relpath(f, indir)) # if not os.path.exists(os.path.dirname(newpath)): # logger.info("Making directories to {}".format(os.path.dirname(newpath))) # os.makedirs(os.path.dirname(newpath)) # if not os.path.exists(os.path.join(os.path.dirname(newpath), ssheet)): # try: # os.symlink(os.path.abspath(os.path.join(os.path.dirname(f), ssheet)), # os.path.join(os.path.dirname(newpath), ssheet)) # except: # logger.warn("No sample sheet found for {}".format()) # # if not os.path.exists(newpath): # logger.info("Linking {} -> {}".format(newpath, os.path.abspath(f))) # os.symlink(os.path.abspath(f), newpath) # if not os.path.lexists(os.path.join(os.path.dirname(newpath), ssheet)) and os.path.exists(os.path.abspath(os.path.join(os.path.dirname(f), ssheet))): # os.symlink(os.path.abspath(os.path.join(os.path.dirname(f), ssheet)), os.path.join(os.path.dirname(newpath), ssheet)) # newsample = Sample(project_id=tgt.project_id(), sample_id=tgt.sample_id(), # project_prefix=outdir, sample_prefix=os.path.join(outdir, os.path.relpath(tgt.prefix("sample"), indir)), # sample_run_prefix=os.path.join(outdir, os.path.relpath(tgt.prefix("sample_run"), indir))) # newtargets.append(newsample) # # newtargets.append((tgt.sample_id(), # # os.path.join(outdir, os.path.relpath(tgt.prefix("sample"), indir)), # # os.path.join(outdir, os.path.relpath(tgt.prefix("sample_run"), indir)))) # return newtargets # # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # def determine_read_type(fn, read1_suffix, read2_suffix=None, suffix="(.fastq.gz$|.fastq$|.fq.gz$|.fq$|.sai$)"): # """Deduce if fn is first or second in read pair. # # :param fn: file name # :param read1_suffix: read1 suffix # :param read2_suffix: read2 suffix # :param suffix: suffix to use for paired files # """ # parts = os.path.basename(fn).split(".") # # if parts[0].endswith(read1_suffix): # return 1 # if read2_suffix: # if parts[0].endswith(str(read2_suffix)): # return 2 # raise Exception("file name {} doesn't appear to have any read pair information in it's name".format(fn)) . Output only the next line.
'InsertMetrics' :
Given snippet: <|code_start|> logging.basicConfig(level=logging.DEBUG) sample = "P001_101_index3_TGACCA_L001" bam = os.path.join(sample + ".bam") localconf = "mock.yaml" ratatosk_conf = os.path.join(os.path.dirname(__file__), os.pardir, "config", "ratatosk.yaml") def setUpModule(): global cnf cnf = get_config() with open(localconf, "w") as fp: fp.write(yaml.safe_dump({ 'picard' : { 'InsertMetrics' : {'parent_task' : 'ratatosk.lib.tools.picard.DuplicationMetrics'}, }, 'gatk' : { 'IndelRealigner' : {'parent_task': ['ratatosk.lib.tools.picard.MergeSamFiles', 'ratatosk.lib.tools.gatk.RealignerTargetCreator', 'ratatosk.lib.tools.gatk.UnifiedGenotyper'], 'source_label': [None, None, 'BOTH.raw'], 'source_suffix' : ['.bam', '.intervals', '.vcf'], }, 'RealignerTargetCreator' : {'parent_task' : 'ratatosk.lib.align.bwa.BwaAln'}, } }, <|code_end|> , continue by predicting the next line. Consider current file imports: import os import shutil import unittest import luigi import logging import yaml import ratatosk.lib.align.bwa as BWA import ratatosk.lib.tools.samtools as SAM import ratatosk.lib.files.fastq as FASTQ import ratatosk.lib.tools.picard as PICARD import ratatosk.lib.tools.gatk as GATK import ratatosk.lib.utils.cutadapt as CUTADAPT import ratatosk.lib.tools.fastqc as FASTQC import ratatosk.lib.files.external from itertools import izip from ratatosk.config import get_config from ratatosk.utils import make_fastq_links, rreplace, determine_read_type and context: # Path: ratatosk/config.py # def get_config(): # return RatatoskConfigParser.instance() # # Path: ratatosk/utils.py # def make_fastq_links(targets, indir, outdir, fastq_suffix="001.fastq.gz", ssheet="SampleSheet.csv"): # """Given a set of targets and an output directory, create links # from targets (source raw data) to an output directory. # # :param targets: list of :class:`ratatosk.experiment.ISample` objects # :param outdir: (top) output directory # :param fastq_suffix: fastq suffix # :param ssheet: sample sheet name # # :returns: new targets list with updated output directory # """ # newtargets = [] # for tgt in targets: # fastq = glob.glob("{}*{}".format(tgt.prefix("sample_run"), fastq_suffix)) # if len(fastq) == 0: # logger.warn("No fastq files for prefix {} in {}".format(tgt.prefix("sample_run"), "make_fastq_links")) # for f in fastq: # newpath = os.path.join(outdir, os.path.relpath(f, indir)) # if not os.path.exists(os.path.dirname(newpath)): # logger.info("Making directories to {}".format(os.path.dirname(newpath))) # os.makedirs(os.path.dirname(newpath)) # if not os.path.exists(os.path.join(os.path.dirname(newpath), ssheet)): # try: # os.symlink(os.path.abspath(os.path.join(os.path.dirname(f), ssheet)), # os.path.join(os.path.dirname(newpath), ssheet)) # except: # logger.warn("No sample sheet found for {}".format()) # # if not os.path.exists(newpath): # logger.info("Linking {} -> {}".format(newpath, os.path.abspath(f))) # os.symlink(os.path.abspath(f), newpath) # if not os.path.lexists(os.path.join(os.path.dirname(newpath), ssheet)) and os.path.exists(os.path.abspath(os.path.join(os.path.dirname(f), ssheet))): # os.symlink(os.path.abspath(os.path.join(os.path.dirname(f), ssheet)), os.path.join(os.path.dirname(newpath), ssheet)) # newsample = Sample(project_id=tgt.project_id(), sample_id=tgt.sample_id(), # project_prefix=outdir, sample_prefix=os.path.join(outdir, os.path.relpath(tgt.prefix("sample"), indir)), # sample_run_prefix=os.path.join(outdir, os.path.relpath(tgt.prefix("sample_run"), indir))) # newtargets.append(newsample) # # newtargets.append((tgt.sample_id(), # # os.path.join(outdir, os.path.relpath(tgt.prefix("sample"), indir)), # # os.path.join(outdir, os.path.relpath(tgt.prefix("sample_run"), indir)))) # return newtargets # # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # def determine_read_type(fn, read1_suffix, read2_suffix=None, suffix="(.fastq.gz$|.fastq$|.fq.gz$|.fq$|.sai$)"): # """Deduce if fn is first or second in read pair. # # :param fn: file name # :param read1_suffix: read1 suffix # :param read2_suffix: read2 suffix # :param suffix: suffix to use for paired files # """ # parts = os.path.basename(fn).split(".") # # if parts[0].endswith(read1_suffix): # return 1 # if read2_suffix: # if parts[0].endswith(str(read2_suffix)): # return 2 # raise Exception("file name {} doesn't appear to have any read pair information in it's name".format(fn)) which might include code, classes, or functions. Output only the next line.
default_flow_style=False))
Here is a snippet: <|code_start|> logging.basicConfig(level=logging.DEBUG) sample = "P001_101_index3_TGACCA_L001" bam = os.path.join(sample + ".bam") localconf = "mock.yaml" ratatosk_conf = os.path.join(os.path.dirname(__file__), os.pardir, "config", "ratatosk.yaml") def setUpModule(): global cnf cnf = get_config() with open(localconf, "w") as fp: fp.write(yaml.safe_dump({ 'picard' : { 'InsertMetrics' : {'parent_task' : 'ratatosk.lib.tools.picard.DuplicationMetrics'}, }, 'gatk' : <|code_end|> . Write the next line using the current file imports: import os import shutil import unittest import luigi import logging import yaml import ratatosk.lib.align.bwa as BWA import ratatosk.lib.tools.samtools as SAM import ratatosk.lib.files.fastq as FASTQ import ratatosk.lib.tools.picard as PICARD import ratatosk.lib.tools.gatk as GATK import ratatosk.lib.utils.cutadapt as CUTADAPT import ratatosk.lib.tools.fastqc as FASTQC import ratatosk.lib.files.external from itertools import izip from ratatosk.config import get_config from ratatosk.utils import make_fastq_links, rreplace, determine_read_type and context from other files: # Path: ratatosk/config.py # def get_config(): # return RatatoskConfigParser.instance() # # Path: ratatosk/utils.py # def make_fastq_links(targets, indir, outdir, fastq_suffix="001.fastq.gz", ssheet="SampleSheet.csv"): # """Given a set of targets and an output directory, create links # from targets (source raw data) to an output directory. # # :param targets: list of :class:`ratatosk.experiment.ISample` objects # :param outdir: (top) output directory # :param fastq_suffix: fastq suffix # :param ssheet: sample sheet name # # :returns: new targets list with updated output directory # """ # newtargets = [] # for tgt in targets: # fastq = glob.glob("{}*{}".format(tgt.prefix("sample_run"), fastq_suffix)) # if len(fastq) == 0: # logger.warn("No fastq files for prefix {} in {}".format(tgt.prefix("sample_run"), "make_fastq_links")) # for f in fastq: # newpath = os.path.join(outdir, os.path.relpath(f, indir)) # if not os.path.exists(os.path.dirname(newpath)): # logger.info("Making directories to {}".format(os.path.dirname(newpath))) # os.makedirs(os.path.dirname(newpath)) # if not os.path.exists(os.path.join(os.path.dirname(newpath), ssheet)): # try: # os.symlink(os.path.abspath(os.path.join(os.path.dirname(f), ssheet)), # os.path.join(os.path.dirname(newpath), ssheet)) # except: # logger.warn("No sample sheet found for {}".format()) # # if not os.path.exists(newpath): # logger.info("Linking {} -> {}".format(newpath, os.path.abspath(f))) # os.symlink(os.path.abspath(f), newpath) # if not os.path.lexists(os.path.join(os.path.dirname(newpath), ssheet)) and os.path.exists(os.path.abspath(os.path.join(os.path.dirname(f), ssheet))): # os.symlink(os.path.abspath(os.path.join(os.path.dirname(f), ssheet)), os.path.join(os.path.dirname(newpath), ssheet)) # newsample = Sample(project_id=tgt.project_id(), sample_id=tgt.sample_id(), # project_prefix=outdir, sample_prefix=os.path.join(outdir, os.path.relpath(tgt.prefix("sample"), indir)), # sample_run_prefix=os.path.join(outdir, os.path.relpath(tgt.prefix("sample_run"), indir))) # newtargets.append(newsample) # # newtargets.append((tgt.sample_id(), # # os.path.join(outdir, os.path.relpath(tgt.prefix("sample"), indir)), # # os.path.join(outdir, os.path.relpath(tgt.prefix("sample_run"), indir)))) # return newtargets # # def rreplace(s, old, new, occurrence): # li = s.rsplit(old, occurrence) # return new.join(li) # # def determine_read_type(fn, read1_suffix, read2_suffix=None, suffix="(.fastq.gz$|.fastq$|.fq.gz$|.fq$|.sai$)"): # """Deduce if fn is first or second in read pair. # # :param fn: file name # :param read1_suffix: read1 suffix # :param read2_suffix: read2 suffix # :param suffix: suffix to use for paired files # """ # parts = os.path.basename(fn).split(".") # # if parts[0].endswith(read1_suffix): # return 1 # if read2_suffix: # if parts[0].endswith(str(read2_suffix)): # return 2 # raise Exception("file name {} doesn't appear to have any read pair information in it's name".format(fn)) , which may include functions, classes, or code. Output only the next line.
{
Predict the next line for this snippet: <|code_start|> # target_generator_handler="test.test_wrapper.gatk_vcf_generator") # self.assertEqual(['java', '-Xmx2g', '-jar', self.gatk, '-T CombineVariants', '-V', 'vcf1.vcf', '-V', 'vcf2.vcf', '-o', 'data/sample.sort.merge-variants-combined.vcf', '-R', 'data/chr11.fa'], # _prune_luigi_tmp(task.job_runner()._make_arglist(task)[0])) def test_combine_variants(self): task = ratatosk.lib.tools.gatk.CombineSplitVariants(target=self.mergebam.replace(".bam", "-variants-combined.vcf"), ref='data/chr11.fa') self.assertEqual(['java', '-Xmx2g', '-jar', self.gatk, '-T CombineVariants', '-V', 'data/sample.sort.merge-variants-combined-split/sample.sort.merge-variants-combined-chr11.vcf', '-o', 'data/sample.sort.merge-variants-combined.vcf', '-R', 'data/chr11.fa'], _prune_luigi_tmp(task.job_runner()._make_arglist(task)[0])) def test_select_variants(self): task = ratatosk.lib.tools.gatk.SelectVariants(target=self.mergebam.replace(".bam", "-snp-all.vcf")) self.assertEqual(['java', '-Xmx2g', '-jar', self.gatk, '-T SelectVariants', '--selectTypeToInclude', 'SNP', '--selectTypeToInclude', 'INDEL', '--selectTypeToInclude', 'MIXED', '--selectTypeToInclude', 'MNP', '--selectTypeToInclude', 'SYMBOLIC', '--selectTypeToInclude', 'NO_VARIATION', '--variant', 'data/sample.sort.merge-snp.vcf', '--out', 'data/sample.sort.merge-snp-all.vcf', '-R', 'data/chr11.fa'], _prune_luigi_tmp(task.job_runner()._make_arglist(task)[0])) def test_select_snp_variants(self): task = ratatosk.lib.tools.gatk.SelectSnpVariants(target=self.mergebam.replace(".bam", "-snp.vcf")) self.assertEqual(['java', '-Xmx2g', '-jar', self.gatk, '-T SelectVariants', '--selectTypeToInclude', 'SNP', '--variant', 'data/sample.sort.merge.vcf', '--out', 'data/sample.sort.merge-snp.vcf', '-R', 'data/chr11.fa'], _prune_luigi_tmp(task.job_runner()._make_arglist(task)[0])) def test_select_indel_variants(self): task = ratatosk.lib.tools.gatk.SelectIndelVariants(target=self.mergebam.replace(".bam", "-indel.vcf")) self.assertEqual(['java', '-Xmx2g', '-jar', self.gatk, '-T SelectVariants', '--selectTypeToInclude', 'INDEL', '--selectTypeToInclude', 'MIXED', '--selectTypeToInclude', 'MNP', '--selectTypeToInclude', 'SYMBOLIC', '--selectTypeToInclude', 'NO_VARIATION', '--variant', 'data/sample.sort.merge.vcf', '--out', 'data/sample.sort.merge-indel.vcf', '-R', 'data/chr11.fa'], _prune_luigi_tmp(task.job_runner()._make_arglist(task)[0])) def test_variant_recalibrator(self): """Test variant recalibation. Note that commands that require training data will not work; only JEXL filtering is applicable""" task = ratatosk.lib.tools.gatk.VariantRecalibrator(target=self.mergebam.replace(".bam", ".tranches"), ref="data/chr11.fa", <|code_end|> with the help of current file imports: import os import re import unittest import luigi import logging import ratatosk.lib.files.fastq import ratatosk.lib.tools.samtools import ratatosk.lib.tools.picard import ratatosk.lib.tools.gatk import ratatosk.lib.tools.fastqc import ratatosk.lib.utils.cutadapt import ratatosk.lib.utils.misc import ratatosk.lib.annotation.snpeff import ratatosk.lib.annotation.annovar import ratatosk.lib.align.bwa import ratatosk.lib.variation.htslib import ratatosk.lib.variation.tabix from luigi.mock import MockFile from ratatosk.config import get_config, get_custom_config and context from other files: # Path: ratatosk/config.py # def get_config(): # return RatatoskConfigParser.instance() # # def get_custom_config(): # """Get separate parser for custom config; else custom config # parent_task setting will override config file settings""" # return RatatoskCustomConfigParser.instance() , which may contain function names, class names, or code. Output only the next line.
options=["-an", "QD", "-resource:hapmap,VCF,known=false,training=true,truth=true,prior=15.0", "data/hapmap_3.3.vcf"])
Given snippet: <|code_start|> def test_select_variants(self): task = ratatosk.lib.tools.gatk.SelectVariants(target=self.mergebam.replace(".bam", "-snp-all.vcf")) self.assertEqual(['java', '-Xmx2g', '-jar', self.gatk, '-T SelectVariants', '--selectTypeToInclude', 'SNP', '--selectTypeToInclude', 'INDEL', '--selectTypeToInclude', 'MIXED', '--selectTypeToInclude', 'MNP', '--selectTypeToInclude', 'SYMBOLIC', '--selectTypeToInclude', 'NO_VARIATION', '--variant', 'data/sample.sort.merge-snp.vcf', '--out', 'data/sample.sort.merge-snp-all.vcf', '-R', 'data/chr11.fa'], _prune_luigi_tmp(task.job_runner()._make_arglist(task)[0])) def test_select_snp_variants(self): task = ratatosk.lib.tools.gatk.SelectSnpVariants(target=self.mergebam.replace(".bam", "-snp.vcf")) self.assertEqual(['java', '-Xmx2g', '-jar', self.gatk, '-T SelectVariants', '--selectTypeToInclude', 'SNP', '--variant', 'data/sample.sort.merge.vcf', '--out', 'data/sample.sort.merge-snp.vcf', '-R', 'data/chr11.fa'], _prune_luigi_tmp(task.job_runner()._make_arglist(task)[0])) def test_select_indel_variants(self): task = ratatosk.lib.tools.gatk.SelectIndelVariants(target=self.mergebam.replace(".bam", "-indel.vcf")) self.assertEqual(['java', '-Xmx2g', '-jar', self.gatk, '-T SelectVariants', '--selectTypeToInclude', 'INDEL', '--selectTypeToInclude', 'MIXED', '--selectTypeToInclude', 'MNP', '--selectTypeToInclude', 'SYMBOLIC', '--selectTypeToInclude', 'NO_VARIATION', '--variant', 'data/sample.sort.merge.vcf', '--out', 'data/sample.sort.merge-indel.vcf', '-R', 'data/chr11.fa'], _prune_luigi_tmp(task.job_runner()._make_arglist(task)[0])) def test_variant_recalibrator(self): """Test variant recalibation. Note that commands that require training data will not work; only JEXL filtering is applicable""" task = ratatosk.lib.tools.gatk.VariantRecalibrator(target=self.mergebam.replace(".bam", ".tranches"), ref="data/chr11.fa", options=["-an", "QD", "-resource:hapmap,VCF,known=false,training=true,truth=true,prior=15.0", "data/hapmap_3.3.vcf"]) self.assertEqual(['java', '-Xmx2g', '-jar', self.gatk, '-T VariantRecalibrator', '-an', 'QD', '-resource:hapmap,VCF,known=false,training=true,truth=true,prior=15.0', 'data/hapmap_3.3.vcf', '--input', 'data/sample.sort.merge.vcf', '--tranches_file', 'data/sample.sort.merge.tranches', '--mode', 'BOTH', '--recal_file', 'data/sample.sort.merge.recal', '-R', 'data/chr11.fa'], _prune_luigi_tmp(task.job_runner()._make_arglist(task)[0])) def test_variant_snp_recalibrator(self): task = ratatosk.lib.tools.gatk.VariantSnpRecalibrator(target=self.mergebam.replace(".bam", ".tranches"), train_hapmap="data/hapmap_3.3.vcf", ref="data/chr11.fa", dbsnp="data/dbsnp132_chr11.vcf") self.assertEqual(['java', '-Xmx2g', '-jar', self.gatk, '-T VariantRecalibrator', '-an', 'QD', '-an', 'HaplotypeScore', '-an', 'MQRankSum', '-an', 'ReadPosRankSum', '-an', 'FS', '-an', 'MQ', '-an', 'DP', '-resource:hapmap,VCF,known=false,training=true,truth=true,prior=15.0', 'data/hapmap_3.3.vcf', '-resource:dbsnp,VCF,known=true,training=false,truth=false,prior=8.0', 'data/dbsnp132_chr11.vcf', '--input', 'data/sample.sort.merge.vcf', '--tranches_file', 'data/sample.sort.merge.tranches', '--mode', 'SNP', '--recal_file', 'data/sample.sort.merge.recal', '-R', 'data/chr11.fa'], <|code_end|> , continue by predicting the next line. Consider current file imports: import os import re import unittest import luigi import logging import ratatosk.lib.files.fastq import ratatosk.lib.tools.samtools import ratatosk.lib.tools.picard import ratatosk.lib.tools.gatk import ratatosk.lib.tools.fastqc import ratatosk.lib.utils.cutadapt import ratatosk.lib.utils.misc import ratatosk.lib.annotation.snpeff import ratatosk.lib.annotation.annovar import ratatosk.lib.align.bwa import ratatosk.lib.variation.htslib import ratatosk.lib.variation.tabix from luigi.mock import MockFile from ratatosk.config import get_config, get_custom_config and context: # Path: ratatosk/config.py # def get_config(): # return RatatoskConfigParser.instance() # # def get_custom_config(): # """Get separate parser for custom config; else custom config # parent_task setting will override config file settings""" # return RatatoskCustomConfigParser.instance() which might include code, classes, or functions. Output only the next line.
_prune_luigi_tmp(task.job_runner()._make_arglist(task)[0]))
Given snippet: <|code_start|> if path and path in cls._instance._custom_config_paths: logger.debug("removing config path {}".format(path)) try: i = cls._instance._custom_config_paths.index(path) del cls._instance._custom_config_paths[i] except ValueError: logger.warn("No such path {} in _custom_config_paths".format(path)) else: return # Need to clear sections before reloading cls._instance._sections = cls._cls_dict() cls._instance.reload() @classmethod def clear(cls): cls._instance._custom_config_paths = [] cls._instance._sections = cls._cls_dict() def reload(self): return self._instance.read(self._instance._custom_config_paths) def get_config(): return RatatoskConfigParser.instance() def get_custom_config(): """Get separate parser for custom config; else custom config parent_task setting will override config file settings""" return RatatoskCustomConfigParser.instance() <|code_end|> , continue by predicting the next line. Consider current file imports: import os import yaml import logging import collections from ConfigParser import NoSectionError, NoOptionError, DuplicateSectionError from ratatosk import backend from ratatosk.utils import update, config_to_dict from ratatosk.log import get_logger from collections import OrderedDict as _default_dict and context: # Path: ratatosk/backend.py # # Path: ratatosk/utils.py # def update(d, u, override=True, expandvars=True): # """Update values of a nested dictionary of varying depth""" # for k, v in u.iteritems(): # if isinstance(v, collections.Mapping): # r = update(d.get(k, {}), v) # d[k] = r # else: # if expandvars and isinstance(v, str): # u[k] = os.path.expandvars(v) # d[k] = u[k] # return d # # def config_to_dict(d): # """Convert config handler or OrderedDict entries to dict for yaml # output. # # :param d: config handler or ordered dict # """ # if d is None: # return {} # if isinstance(d, dict): # pass # else: # raise TypeError("unsupported type <{}>".format(type(d))) # u = {} # for k, v in d.iteritems(): # u[k] = {} # if isinstance(v, collections.Mapping): # for x, y in v.iteritems(): # if isinstance(y, collections.Mapping): # u[k][x] = dict(y) # else: # u[k][x] = y # else: # u[k] = v # return u # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger which might include code, classes, or functions. Output only the next line.
def setup_config(config_file=None, custom_config_file=None, **kwargs):
Given snippet: <|code_start|> if path and path in cls._instance._custom_config_paths: logger.debug("removing config path {}".format(path)) try: i = cls._instance._custom_config_paths.index(path) del cls._instance._custom_config_paths[i] except ValueError: logger.warn("No such path {} in _custom_config_paths".format(path)) else: return # Need to clear sections before reloading cls._instance._sections = cls._cls_dict() cls._instance.reload() @classmethod def clear(cls): cls._instance._custom_config_paths = [] cls._instance._sections = cls._cls_dict() def reload(self): return self._instance.read(self._instance._custom_config_paths) def get_config(): return RatatoskConfigParser.instance() def get_custom_config(): """Get separate parser for custom config; else custom config parent_task setting will override config file settings""" return RatatoskCustomConfigParser.instance() <|code_end|> , continue by predicting the next line. Consider current file imports: import os import yaml import logging import collections from ConfigParser import NoSectionError, NoOptionError, DuplicateSectionError from ratatosk import backend from ratatosk.utils import update, config_to_dict from ratatosk.log import get_logger from collections import OrderedDict as _default_dict and context: # Path: ratatosk/backend.py # # Path: ratatosk/utils.py # def update(d, u, override=True, expandvars=True): # """Update values of a nested dictionary of varying depth""" # for k, v in u.iteritems(): # if isinstance(v, collections.Mapping): # r = update(d.get(k, {}), v) # d[k] = r # else: # if expandvars and isinstance(v, str): # u[k] = os.path.expandvars(v) # d[k] = u[k] # return d # # def config_to_dict(d): # """Convert config handler or OrderedDict entries to dict for yaml # output. # # :param d: config handler or ordered dict # """ # if d is None: # return {} # if isinstance(d, dict): # pass # else: # raise TypeError("unsupported type <{}>".format(type(d))) # u = {} # for k, v in d.iteritems(): # u[k] = {} # if isinstance(v, collections.Mapping): # for x, y in v.iteritems(): # if isinstance(y, collections.Mapping): # u[k][x] = dict(y) # else: # u[k][x] = y # else: # u[k] = v # return u # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger which might include code, classes, or functions. Output only the next line.
def setup_config(config_file=None, custom_config_file=None, **kwargs):
Continue the code snippet: <|code_start|># Copyright (c) 2013 Per Unneberg # # 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. logger = get_logger() try: except ImportError: # fallback for setup.py which hasn't yet built _collections _default_dict = dict <|code_end|> . Use current file imports: import os import yaml import logging import collections from ConfigParser import NoSectionError, NoOptionError, DuplicateSectionError from ratatosk import backend from ratatosk.utils import update, config_to_dict from ratatosk.log import get_logger from collections import OrderedDict as _default_dict and context (classes, functions, or code) from other files: # Path: ratatosk/backend.py # # Path: ratatosk/utils.py # def update(d, u, override=True, expandvars=True): # """Update values of a nested dictionary of varying depth""" # for k, v in u.iteritems(): # if isinstance(v, collections.Mapping): # r = update(d.get(k, {}), v) # d[k] = r # else: # if expandvars and isinstance(v, str): # u[k] = os.path.expandvars(v) # d[k] = u[k] # return d # # def config_to_dict(d): # """Convert config handler or OrderedDict entries to dict for yaml # output. # # :param d: config handler or ordered dict # """ # if d is None: # return {} # if isinstance(d, dict): # pass # else: # raise TypeError("unsupported type <{}>".format(type(d))) # u = {} # for k, v in d.iteritems(): # u[k] = {} # if isinstance(v, collections.Mapping): # for x, y in v.iteritems(): # if isinstance(y, collections.Mapping): # u[k][x] = dict(y) # else: # u[k][x] = y # else: # u[k] = v # return u # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger . Output only the next line.
class RatatoskConfigParser(object):
Next line prediction: <|code_start|> @classmethod def del_config_path(cls, path): if path and path in cls._instance._custom_config_paths: logger.debug("removing config path {}".format(path)) try: i = cls._instance._custom_config_paths.index(path) del cls._instance._custom_config_paths[i] except ValueError: logger.warn("No such path {} in _custom_config_paths".format(path)) else: return # Need to clear sections before reloading cls._instance._sections = cls._cls_dict() cls._instance.reload() @classmethod def clear(cls): cls._instance._custom_config_paths = [] cls._instance._sections = cls._cls_dict() def reload(self): return self._instance.read(self._instance._custom_config_paths) def get_config(): return RatatoskConfigParser.instance() def get_custom_config(): """Get separate parser for custom config; else custom config parent_task setting will override config file settings""" <|code_end|> . Use current file imports: (import os import yaml import logging import collections from ConfigParser import NoSectionError, NoOptionError, DuplicateSectionError from ratatosk import backend from ratatosk.utils import update, config_to_dict from ratatosk.log import get_logger from collections import OrderedDict as _default_dict) and context including class names, function names, or small code snippets from other files: # Path: ratatosk/backend.py # # Path: ratatosk/utils.py # def update(d, u, override=True, expandvars=True): # """Update values of a nested dictionary of varying depth""" # for k, v in u.iteritems(): # if isinstance(v, collections.Mapping): # r = update(d.get(k, {}), v) # d[k] = r # else: # if expandvars and isinstance(v, str): # u[k] = os.path.expandvars(v) # d[k] = u[k] # return d # # def config_to_dict(d): # """Convert config handler or OrderedDict entries to dict for yaml # output. # # :param d: config handler or ordered dict # """ # if d is None: # return {} # if isinstance(d, dict): # pass # else: # raise TypeError("unsupported type <{}>".format(type(d))) # u = {} # for k, v in d.iteritems(): # u[k] = {} # if isinstance(v, collections.Mapping): # for x, y in v.iteritems(): # if isinstance(y, collections.Mapping): # u[k][x] = dict(y) # else: # u[k][x] = y # else: # u[k] = v # return u # # Path: ratatosk/log.py # def get_logger(): # logger = logging.getLogger('ratatosk-interface') # if not logger.handlers: # setup_logging() # return logger . Output only the next line.
return RatatoskCustomConfigParser.instance()
Next line prediction: <|code_start|> # decoding can fail with a padding error when # a line of encoded content runs across a read chunk lines = content.split(b'\n') # decode and yield all but the last line of encoded content decoded_content = binascii.a2b_base64(b''.join(lines[:-1])) # store the leftover to be decoded with the next chunk leftover = lines[-1] if decoded_content is not None: if self.verify: md5.update(decoded_content) size += len(decoded_content) yield decoded_content def binarycontent_sections(chunk): '''Split a chunk of data into sections by start and end binary content tags.''' # using string split because it is significantly faster than regex. # use common text of start and end tags to split the text # (i.e. without < or </ tag beginning) binary_content_tag = BINARY_CONTENT_START[1:] if binary_content_tag not in chunk: # if no tags are present, don't do any extra work yield chunk else: # split on common portion of foxml:binaryContent <|code_end|> . Use current file imports: (import binascii import hashlib import io import logging import math import re import six import progressbar from six.moves.urllib.parse import urlparse from eulfedora.util import force_bytes, force_text) and context including class names, function names, or small code snippets from other files: # Path: eulfedora/util.py # def force_bytes(s, encoding='utf-8'): # if isinstance(s, bytes): # if encoding == 'utf-8': # return s # else: # return s.decode('utf-8').encode(encoding) # # if not isinstance(s, six.string_types): # if six.PY3: # return six.text_type(s).encode(encoding) # else: # return bytes(s) # else: # return s.encode(encoding) # # def force_text(s, encoding='utf-8'): # if six.PY3: # if isinstance(s, bytes): # s = six.text_type(s, encoding) # else: # s = six.text_type(s) # else: # s = six.text_type(bytes(s), encoding) # # return s . Output only the next line.
sections = chunk.split(binary_content_tag)
Given the following code snippet before the placeholder: <|code_start|> try: # decode method used by base64.decode decoded_content = binascii.a2b_base64(content) except binascii.Error: # decoding can fail with a padding error when # a line of encoded content runs across a read chunk lines = content.split(b'\n') # decode and yield all but the last line of encoded content decoded_content = binascii.a2b_base64(b''.join(lines[:-1])) # store the leftover to be decoded with the next chunk leftover = lines[-1] if decoded_content is not None: if self.verify: md5.update(decoded_content) size += len(decoded_content) yield decoded_content def binarycontent_sections(chunk): '''Split a chunk of data into sections by start and end binary content tags.''' # using string split because it is significantly faster than regex. # use common text of start and end tags to split the text # (i.e. without < or </ tag beginning) binary_content_tag = BINARY_CONTENT_START[1:] if binary_content_tag not in chunk: # if no tags are present, don't do any extra work <|code_end|> , predict the next line using imports from the current file: import binascii import hashlib import io import logging import math import re import six import progressbar from six.moves.urllib.parse import urlparse from eulfedora.util import force_bytes, force_text and context including class names, function names, and sometimes code from other files: # Path: eulfedora/util.py # def force_bytes(s, encoding='utf-8'): # if isinstance(s, bytes): # if encoding == 'utf-8': # return s # else: # return s.decode('utf-8').encode(encoding) # # if not isinstance(s, six.string_types): # if six.PY3: # return six.text_type(s).encode(encoding) # else: # return bytes(s) # else: # return s.encode(encoding) # # def force_text(s, encoding='utf-8'): # if six.PY3: # if isinstance(s, bytes): # s = six.text_type(s, encoding) # else: # s = six.text_type(s) # else: # s = six.text_type(bytes(s), encoding) # # return s . Output only the next line.
yield chunk
Here is a snippet: <|code_start|># 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. try: except ImportError: try: except ImportError: django = None class MockFedoraObject(object): # not even a close approximation, just something we can force to raise # interesting exceptions def __init__(self): self._value = 'sample text' def value(self): if isinstance(self._value, Exception): raise self._value <|code_end|> . Write the next line using the current file imports: import unittest import django from unittest import skipIf from unittest2 import skipIf from mock import Mock from django.template import Context, Template from eulfedora.util import RequestFailed, PermissionDenied and context from other files: # Path: eulfedora/util.py # class RequestFailed(IOError): # '''An exception representing an arbitrary error while trying to access a # Fedora object or datastream. # ''' # error_regex = re.compile('<pre>(.*\n.*)\n', re.MULTILINE) # # def __init__(self, response, content=None): # # init params: # # response = HttpResponse with the error information # # content = optional content of the response body, if it needed to be read # # to determine what kind of exception to raise # super(RequestFailed, self).__init__('%d %s' % (response.status_code, response.text)) # self.code = response.status_code # self.reason = response.text # if response.status_code == requests.codes.server_error: # # grab the response content if not passed in # if content is None: # content = response.text # content = force_text(content) # # when Fedora gives a 500 error, it includes a stack-trace - pulling first line as detail # # NOTE: this is likely to break if and when Fedora error responses change # if 'content-type' in response.headers and response.headers['content-type'] == 'text/plain': # # for plain text, first line of stack-trace is first line of text # self.detail = content.split('\n')[0] # else: # # for html, stack trace is wrapped with a <pre> tag; using regex to grab first line # match = self.error_regex.findall(content) # if len(match): # self.detail = match[0] # # class PermissionDenied(RequestFailed): # '''An exception representing a permission error while trying to access a # Fedora object or datastream. # ''' , which may include functions, classes, or code. Output only the next line.
return self._value
Given the following code snippet before the placeholder: <|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. try: except ImportError: try: except ImportError: django = None class MockFedoraObject(object): # not even a close approximation, just something we can force to raise # interesting exceptions def __init__(self): self._value = 'sample text' def value(self): if isinstance(self._value, Exception): raise self._value return self._value @skipIf(django is None, 'Requires Django') <|code_end|> , predict the next line using imports from the current file: import unittest import django from unittest import skipIf from unittest2 import skipIf from mock import Mock from django.template import Context, Template from eulfedora.util import RequestFailed, PermissionDenied and context including class names, function names, and sometimes code from other files: # Path: eulfedora/util.py # class RequestFailed(IOError): # '''An exception representing an arbitrary error while trying to access a # Fedora object or datastream. # ''' # error_regex = re.compile('<pre>(.*\n.*)\n', re.MULTILINE) # # def __init__(self, response, content=None): # # init params: # # response = HttpResponse with the error information # # content = optional content of the response body, if it needed to be read # # to determine what kind of exception to raise # super(RequestFailed, self).__init__('%d %s' % (response.status_code, response.text)) # self.code = response.status_code # self.reason = response.text # if response.status_code == requests.codes.server_error: # # grab the response content if not passed in # if content is None: # content = response.text # content = force_text(content) # # when Fedora gives a 500 error, it includes a stack-trace - pulling first line as detail # # NOTE: this is likely to break if and when Fedora error responses change # if 'content-type' in response.headers and response.headers['content-type'] == 'text/plain': # # for plain text, first line of stack-trace is first line of text # self.detail = content.split('\n')[0] # else: # # for html, stack trace is wrapped with a <pre> tag; using regex to grab first line # match = self.error_regex.findall(content) # if len(match): # self.detail = match[0] # # class PermissionDenied(RequestFailed): # '''An exception representing a permission error while trying to access a # Fedora object or datastream. # ''' . Output only the next line.
class TemplateTagTest(unittest.TestCase):
Based on the snippet: <|code_start|># file eulfedora/templatetags/fedora.py # # Copyright 2010,2011 Emory University Libraries # # 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. """Template tags utilities for communicating with a Fedora server This module defines a single template tag, {% fedora_access %} (and matched {% end_fedora_access %}), which further recognizes internal tags {% permission_denied %} and {% fedora_failed %}. See Sphinx docs for sample template code. """ register = template.Library() class CatchFedoraErrorsNode(template.Node): """Template render node for catching fedora access errors and providing fallback content.""" <|code_end|> , predict the immediate next line with the help of imports: from django import template from eulfedora.util import RequestFailed, PermissionDenied and context (classes, functions, sometimes code) from other files: # Path: eulfedora/util.py # class RequestFailed(IOError): # '''An exception representing an arbitrary error while trying to access a # Fedora object or datastream. # ''' # error_regex = re.compile('<pre>(.*\n.*)\n', re.MULTILINE) # # def __init__(self, response, content=None): # # init params: # # response = HttpResponse with the error information # # content = optional content of the response body, if it needed to be read # # to determine what kind of exception to raise # super(RequestFailed, self).__init__('%d %s' % (response.status_code, response.text)) # self.code = response.status_code # self.reason = response.text # if response.status_code == requests.codes.server_error: # # grab the response content if not passed in # if content is None: # content = response.text # content = force_text(content) # # when Fedora gives a 500 error, it includes a stack-trace - pulling first line as detail # # NOTE: this is likely to break if and when Fedora error responses change # if 'content-type' in response.headers and response.headers['content-type'] == 'text/plain': # # for plain text, first line of stack-trace is first line of text # self.detail = content.split('\n')[0] # else: # # for html, stack trace is wrapped with a <pre> tag; using regex to grab first line # match = self.error_regex.findall(content) # if len(match): # self.detail = match[0] # # class PermissionDenied(RequestFailed): # '''An exception representing a permission error while trying to access a # Fedora object or datastream. # ''' . Output only the next line.
def __init__(self, fedora_access, permission_denied=None,
Given snippet: <|code_start|># file eulfedora/templatetags/fedora.py # # Copyright 2010,2011 Emory University Libraries # # 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. """Template tags utilities for communicating with a Fedora server This module defines a single template tag, {% fedora_access %} (and matched {% end_fedora_access %}), which further recognizes internal tags {% permission_denied %} and {% fedora_failed %}. See Sphinx docs for sample template code. """ register = template.Library() class CatchFedoraErrorsNode(template.Node): """Template render node for catching fedora access errors and providing fallback content.""" def __init__(self, fedora_access, permission_denied=None, <|code_end|> , continue by predicting the next line. Consider current file imports: from django import template from eulfedora.util import RequestFailed, PermissionDenied and context: # Path: eulfedora/util.py # class RequestFailed(IOError): # '''An exception representing an arbitrary error while trying to access a # Fedora object or datastream. # ''' # error_regex = re.compile('<pre>(.*\n.*)\n', re.MULTILINE) # # def __init__(self, response, content=None): # # init params: # # response = HttpResponse with the error information # # content = optional content of the response body, if it needed to be read # # to determine what kind of exception to raise # super(RequestFailed, self).__init__('%d %s' % (response.status_code, response.text)) # self.code = response.status_code # self.reason = response.text # if response.status_code == requests.codes.server_error: # # grab the response content if not passed in # if content is None: # content = response.text # content = force_text(content) # # when Fedora gives a 500 error, it includes a stack-trace - pulling first line as detail # # NOTE: this is likely to break if and when Fedora error responses change # if 'content-type' in response.headers and response.headers['content-type'] == 'text/plain': # # for plain text, first line of stack-trace is first line of text # self.detail = content.split('\n')[0] # else: # # for html, stack trace is wrapped with a <pre> tag; using regex to grab first line # match = self.error_regex.findall(content) # if len(match): # self.detail = match[0] # # class PermissionDenied(RequestFailed): # '''An exception representing a permission error while trying to access a # Fedora object or datastream. # ''' which might include code, classes, or functions. Output only the next line.
fedora_failed=None):
Given the code snippet: <|code_start|> """Stream filter class.""" def decode(self, data, **kwargs): """Decode the encoded stream. Keyword arguments are the parameters from the stream dictionary.""" if self.EOD: end = data.find(bytes(self.EOD)) return self.decoder(data[:end if end > 0 else None], **kwargs) else: return self.decoder(data, **kwargs) def encode(self, data, **kwargs): """Encode the stream data. Keyword arguments are the parameters from the stream dictionary.""" if self.encoder: return self.encoder(data, **kwargs) + (self.EOD if self.EOD else b'') else: warn('Encoding for {} not implemented'.format(self.filter_name)) return data + (self.EOD if self.EOD else b'') @six.add_metaclass(MetaGettable) class StreamFilter(object): """PDF stream filter stream dispatcher. Stream filters are registered by calling PdfOperation.register() and passing a subclass of StreamFilterBase. Information on filters at can be found at https://partners.adobe.com/public/developer/en/ps/sdk/TN5603.Filters.pdf""" # Nothing to see here. Pay no attention to that man behind the curtain. _filters = {} _nop_filter = StreamFilterBase('NOPFilter', lambda x: x) @classmethod <|code_end|> , generate the next line using the imports in this file: import six from collections import namedtuple from warnings import warn from ..misc import ensure_str, MetaGettable and context (functions, classes, or occasionally code) from other files: # Path: gymnast/misc.py # def ensure_str(val): # """Converts the argument to a string if it isn't one already""" # if isinstance(val, str): # return val # elif isinstance(val, (bytes, bytearray)): # return val.decode() # else: # raise ValueError('Expected bytes or string') # # class MetaGettable(type): # """Metaclass to allow classes to be treated as dictlikes with MyClass[key]. # Instance classes should implement a classmethod __getitem__(cls, key).""" # def __getitem__(cls, key): # return cls.__getitem__(key) . Output only the next line.
def register(cls, filter_name, decoder, eod=None, encoder=None):
Given snippet: <|code_start|>""" Abstract base class for stream filters """ base = namedtuple('StreamFilter', ('filter_name','decoder', 'EOD', 'encoder')) base.__new__.__defaults__ = (None, None) class StreamFilterBase(base): """Stream filter class.""" def decode(self, data, **kwargs): """Decode the encoded stream. Keyword arguments are the parameters from the stream dictionary.""" if self.EOD: end = data.find(bytes(self.EOD)) <|code_end|> , continue by predicting the next line. Consider current file imports: import six from collections import namedtuple from warnings import warn from ..misc import ensure_str, MetaGettable and context: # Path: gymnast/misc.py # def ensure_str(val): # """Converts the argument to a string if it isn't one already""" # if isinstance(val, str): # return val # elif isinstance(val, (bytes, bytearray)): # return val.decode() # else: # raise ValueError('Expected bytes or string') # # class MetaGettable(type): # """Metaclass to allow classes to be treated as dictlikes with MyClass[key]. # Instance classes should implement a classmethod __getitem__(cls, key).""" # def __getitem__(cls, key): # return cls.__getitem__(key) which might include code, classes, or functions. Output only the next line.
return self.decoder(data[:end if end > 0 else None], **kwargs)
Next line prediction: <|code_start|> class TestSimpleTypes(ParserTestCase): def setUp(self): super(TestSimpleTypes, self).__init__() <|code_end|> . Use current file imports: (from .parser_test import ParserTestCase from ..pdf_parser.exc import PdfParseError) and context including class names, function names, or small code snippets from other files: # Path: tests/parser_test.py # class ParserTestCase(unittest.TestCase): # """Test the parser""" # def setUp(self): # self.parser = PdfParser() . Output only the next line.
self.func = self.parser._parse_literal
Given the following code snippet before the placeholder: <|code_start|> return data.decode('utf_16_be') # If the string isn't UTF-16BE, it follows PDF standard encoding # described in Appendix D of the reference. return data.decode('pdf_doc') ESCAPES = {b'n' : b'\n', b'r' : b'\r', b't' : b'\t', b'b' : b'\b', b'f' : b'\f', b'(' : b'(', b')' : b')', b'\n' : b'', b'\r' : b''} @staticmethod def _parse_escape(data): r"""Handle escape sequences in literal PDF strings. This should be pretty straightforward except that there are line continuations, so \\n, \\r\n, and \\r are ignored. Moreover, actual newline characters are also valid. It's very stupid. See pp. 53-56 in the Reference if you want to be annoyed. Arguments: data - io.BytesIO-like object Returns the unescaped bytes""" e_str = data.read(1) try: val = PdfLiteralString.ESCAPES[e_str] <|code_end|> , predict the next line using imports from the current file: import binascii import codecs import io from .common import PdfType from ..exc import PdfParseError, PdfError from ..pdf_codec import register_codec and context including class names, function names, and sometimes code from other files: # Path: gymnast/pdf_types/common.py # class PdfType(object): # """Abstract base class for PDF objects""" # def pdf_encode(self): # """Translate the object into bytes in PDF format""" # raise NotImplementedError # @property # def value(self): # """Objects, references, and such will override this in clever # ways.""" # return self # @property # def parsed_object(self): # """Objects, references, and such will override this in clever # ways.""" # return self # # Path: gymnast/exc.py # class PdfParseError(PdfError): # """Exception parsing PDF file""" # pass # # class PdfError(Exception): # """Generic PDF exception""" # pass # # Path: gymnast/pdf_codec.py # def register_codec(): # """Register the 'pdf_doc' codec in the codec registry.""" # codecs.register(lambda s: getregentry() if s == ENCODING_NAME else None) . Output only the next line.
except KeyError:
Continue the code snippet: <|code_start|>""" PDF string-like objects """ # Go ahead and register the codec here, I guess. register_codec() class PdfString(PdfType): """Base class from which all of our string-like classes will inherit""" def __lt__(self, other): return self._parsed_bytes.__lt__(other) def __le__(self, other): return self._parsed_bytes.__le__(other) def __eq__(self, other): return self._parsed_bytes.__eq__(other) def __ne__(self, other): return self._parsed_bytes.__ne__(other) def __gt__(self, other): return self._parsed_bytes.__gt__(other) def __ge__(self, other): return self._parsed_bytes.__ge__(other) def __bool__(self): return self._parsed_bytes.__bool__() def __bytes__(self): return self._parsed_bytes <|code_end|> . Use current file imports: import binascii import codecs import io from .common import PdfType from ..exc import PdfParseError, PdfError from ..pdf_codec import register_codec and context (classes, functions, or code) from other files: # Path: gymnast/pdf_types/common.py # class PdfType(object): # """Abstract base class for PDF objects""" # def pdf_encode(self): # """Translate the object into bytes in PDF format""" # raise NotImplementedError # @property # def value(self): # """Objects, references, and such will override this in clever # ways.""" # return self # @property # def parsed_object(self): # """Objects, references, and such will override this in clever # ways.""" # return self # # Path: gymnast/exc.py # class PdfParseError(PdfError): # """Exception parsing PDF file""" # pass # # class PdfError(Exception): # """Generic PDF exception""" # pass # # Path: gymnast/pdf_codec.py # def register_codec(): # """Register the 'pdf_doc' codec in the codec registry.""" # codecs.register(lambda s: getregentry() if s == ENCODING_NAME else None) . Output only the next line.
def __hash__(self): return self._parsed_bytes.__hash__()
Here is a snippet: <|code_start|>""" PDF string-like objects """ # Go ahead and register the codec here, I guess. register_codec() class PdfString(PdfType): """Base class from which all of our string-like classes will inherit""" def __lt__(self, other): return self._parsed_bytes.__lt__(other) def __le__(self, other): return self._parsed_bytes.__le__(other) def __eq__(self, other): return self._parsed_bytes.__eq__(other) def __ne__(self, other): return self._parsed_bytes.__ne__(other) def __gt__(self, other): return self._parsed_bytes.__gt__(other) <|code_end|> . Write the next line using the current file imports: import binascii import codecs import io from .common import PdfType from ..exc import PdfParseError, PdfError from ..pdf_codec import register_codec and context from other files: # Path: gymnast/pdf_types/common.py # class PdfType(object): # """Abstract base class for PDF objects""" # def pdf_encode(self): # """Translate the object into bytes in PDF format""" # raise NotImplementedError # @property # def value(self): # """Objects, references, and such will override this in clever # ways.""" # return self # @property # def parsed_object(self): # """Objects, references, and such will override this in clever # ways.""" # return self # # Path: gymnast/exc.py # class PdfParseError(PdfError): # """Exception parsing PDF file""" # pass # # class PdfError(Exception): # """Generic PDF exception""" # pass # # Path: gymnast/pdf_codec.py # def register_codec(): # """Register the 'pdf_doc' codec in the codec registry.""" # codecs.register(lambda s: getregentry() if s == ENCODING_NAME else None) , which may include functions, classes, or code. Output only the next line.
def __ge__(self, other): return self._parsed_bytes.__ge__(other)
Given the following code snippet before the placeholder: <|code_start|> """Detect the encoding method and return the decoded string""" # Are we UTF-16BE? Good. if data[:2] == '\xFE\xFF': return data.decode('utf_16_be') # If the string isn't UTF-16BE, it follows PDF standard encoding # described in Appendix D of the reference. return data.decode('pdf_doc') ESCAPES = {b'n' : b'\n', b'r' : b'\r', b't' : b'\t', b'b' : b'\b', b'f' : b'\f', b'(' : b'(', b')' : b')', b'\n' : b'', b'\r' : b''} @staticmethod def _parse_escape(data): r"""Handle escape sequences in literal PDF strings. This should be pretty straightforward except that there are line continuations, so \\n, \\r\n, and \\r are ignored. Moreover, actual newline characters are also valid. It's very stupid. See pp. 53-56 in the Reference if you want to be annoyed. Arguments: data - io.BytesIO-like object Returns the unescaped bytes""" <|code_end|> , predict the next line using imports from the current file: import binascii import codecs import io from .common import PdfType from ..exc import PdfParseError, PdfError from ..pdf_codec import register_codec and context including class names, function names, and sometimes code from other files: # Path: gymnast/pdf_types/common.py # class PdfType(object): # """Abstract base class for PDF objects""" # def pdf_encode(self): # """Translate the object into bytes in PDF format""" # raise NotImplementedError # @property # def value(self): # """Objects, references, and such will override this in clever # ways.""" # return self # @property # def parsed_object(self): # """Objects, references, and such will override this in clever # ways.""" # return self # # Path: gymnast/exc.py # class PdfParseError(PdfError): # """Exception parsing PDF file""" # pass # # class PdfError(Exception): # """Generic PDF exception""" # pass # # Path: gymnast/pdf_codec.py # def register_codec(): # """Register the 'pdf_doc' codec in the codec registry.""" # codecs.register(lambda s: getregentry() if s == ENCODING_NAME else None) . Output only the next line.
e_str = data.read(1)
Predict the next line after this snippet: <|code_start|> return self._return() def bytes_to_glyphs(self, string): """Converts a bytestring into a series of glyphs based upon the active font's encoding""" pass @property def active_font(self): """The PdfBaseFont representing the font specified by T_f""" return self._fonts[self.ts.f] @property def text_coords(self): """The current text matrix coordinates""" return self.ts.m.current_coords def push_state(self): """Push the current graphics state onto the stack""" self._state_stack.append(copy.deepcopy(self.gs)) def pop_state(self): """Pop the last graphics state off the stack""" self.gs = self._state_stack.pop() def _compute_T_rm(self, m=None, CTM=None): """Compute the text rendering matrix (T_rm) based either on the current text matrix and CTM, or using the specified overrides""" ts = self.ts if not m: m = ts.m if not CTM: <|code_end|> using the current file's imports: from .renderer_states import TextState, GraphicsState from ..pdf_matrix import PdfMatrix import copy import io and any relevant context from other files: # Path: gymnast/renderer/renderer_states.py # class TextState(object): # """Renderer text state. Has all of the various text rendering parameters # described on pp. 396-404 in the Reference (without the leading T). # # Attributes (all units are in text space units): # m: The current text matrix # lm: Text matrix at the start of the current line # c: Charcter spacing - Amount of extra space between characters before # scaling by T_h. Default 0. # w: Word spacing - Extra space (pre-T_h) added on encountering a space. # Default 0. # h: Horizontal scaling - Scaling factor applied to character width and # horizontal spacing (i.e., T_c and T_w). Default 1. # N.B.: The associated Tz operator sets this to its operand divided by # 100. # l: Leading - Vertical distance between the baselines of adjacent text # lines. Default 0. # f: Text font - The name of the current font in the current resource # dictionary. No default value. # fs: Text font size - Scaling factor applied to the font in all # directions. No default value. # mode: Text rendering mode - Determines text shading, outlining, when # rendering text. Default 0 (solid fill, no stroke). # rise: Text rise - Vertical offset from the baseline at which to draw # the text. Positive values result in superscript, negative in # subsctipt. Default 0. # k: Text knockout - Boolean used in drawing overlappign characters. # Set through graphics state operators. Default True.""" # id_matrix = PdfMatrix(1, 0, 0, 1, 0, 0) # def __init__(self): # """Create a new TextState object with values initialed to their # respective defaults""" # self.c = 0.0 # Char space # self.w = 0.0 # Word space # self.h = 1.0 # Horizontal text scale # self.l = 0.0 # Text leading # self.f = None # Font # self.fs = None # Font scaling # self.mode = 0 # Text render mode # self.rise = 0.0 # Text rise # self.m = self.id_matrix # Text Matrix # self.lm = self.id_matrix # Line Matrix # # def reset_m(self): # """Reset the text matrix to the identity""" # self.m = self.id_matrix # # def reset_lm(self): # """Reset the line matrix to the general text matrix""" # self.lm = copy.copy(self.m) # # class GraphicsState(RendererState): # """Renderer graphics state. Has all of the various graphical state # parameters, including the current transformation matrix.""" # def __init__(self): # self.CTM = self.id_matrix # Current transformation matrix # self.line_width = 1.0 # self.line_cap = 0 # self.line_join = 0 # self.miter_limit = 10.0 # self.dash_array = [] # See p. 217 # self.dash_phase = 0 # self.intent = None # See p. 260 # self.flatness = 0 # See S6.5.1 - p. 508 # # Path: gymnast/pdf_matrix.py # class PdfMatrix(object): # """Very limited matrix class representing PDF transformations""" # def __init__(self, a, b, c, d, e, f): # """Create a new PdfMatrix object. Arguments real numbers and represent # a matrix as described on p. 208 of the Reference: # [ a b 0 ] # PdfMatrix(a, b, c, d, e, f) = [ c d 0 ] # [ e f 1 ] # """ # self.a = float(a) # self.b = float(b) # self.c = float(c) # self.d = float(d) # self.e = float(e) # self.f = float(f) # def transform_coords(self, x, y): # return (self.a*x+self.c*y+self.e, # self.b*x+self.d*y+self.f) # def __mul__(self, other): # """Matrix multiplication. # Given the type constraint below, this will be self*other""" # if not isinstance(other, PdfMatrix): # raise TypeError('Can only multiply PdfMatrices by PdfMatrice') # return PdfMatrix(self.a*other.a+self.b*other.c, # self.a*other.b+self.b*other.d, # self.c*other.a+self.d*other.c, # self.c*other.b+self.d*other.d, # self.e*other.a+self.f*other.c+other.e, # self.e*other.b+self.f*other.d+other.f) # @property # def current_coords(self): # """Current x, y offset in whatever space this matrix represents""" # return self.e, self.f # def copy(self): # """Return a copy of this matrix""" # return PdfMatrix(self.a, self.b, # self.c, self.d, # self.e, self.f) . Output only the next line.
CTM = self.gs.CTM