Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> class AuthorizationTests(testing.TestCase): clean_collections = ('authorization_codes', 'access_codes', 'users') def test_authorization_codes(self): codes = AuthorizationCodes(self.db) url = codes.get_redirect_url('1234', 'http://example.com', 'test') self.assertEqual(url, 'http://example.com?code=1234&state=test') url = codes.get_redirect_url('1234', 'http://example.com') self.assertEqual(url, 'http://example.com?code=1234') self.assertEqual(self.db.authorization_codes.count(), 0) code1 = codes.create('user1', 'client1', 'passwords') self.assertEqual(self.db.authorization_codes.count(), 1) # creating a code with same arguments replace the old one code2 = codes.create('user1', 'client1', 'passwords') self.assertEqual(self.db.authorization_codes.count(), 1) self.assertNotEqual(code1, code2) self.assertNotEqual(None, codes.find(code2)) self.assertEqual(None, codes.find(code1)) codes.remove(codes.find(code1)) self.assertEqual(self.db.authorization_codes.count(), 0) def test_access_codes(self): <|code_end|> , predict the next line using imports from the current file: from yithlibraryserver import testing from yithlibraryserver.oauth2.authorization import AuthorizationCodes from yithlibraryserver.oauth2.authorization import AccessCodes from yithlibraryserver.oauth2.authorization import Authorizator and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # class FakeRequest(DummyRequest): # class TestCase(unittest.TestCase): # def __init__(self, *args, **kwargs): # def setUp(self): # def tearDown(self): # def set_user_cookie(self, user_id): # def add_to_session(self, data): # def get_session(self, response): # # Path: yithlibraryserver/oauth2/authorization.py # class AuthorizationCodes(Codes): # # collection_name = 'authorization_codes' # # def get_redirect_url(self, code, uri, state=None): # parameters = ['code=%s' % code] # if state: # parameters.append('state=%s' % state) # return '%s?%s' % (uri, '&'.join(parameters)) # # def create(self, user_id, client_id, scope): # return super(AuthorizationCodes, self).create(user_id, # scope=scope, # client_id=client_id) # # Path: yithlibraryserver/oauth2/authorization.py # class AccessCodes(Codes): # # collection_name = 'access_codes' # # def create(self, user_id, grant): # return super(AccessCodes, self).create(user_id, # scope=grant['scope'], # client_id=grant['client_id']) # # Path: yithlibraryserver/oauth2/authorization.py # class Authorizator(object): # # def __init__(self, db, app): # self.db = db # self.app = app # self.auth_codes = AuthorizationCodes(db) # self.access_codes = AccessCodes(db) # # def is_app_authorized(self, user): # return self.app['_id'] in user['authorized_apps'] # # def store_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$addToSet': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # def remove_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$pull': {'authorized_apps': self.app['_id']}}, # safe=True, # ) . Output only the next line.
codes = AccessCodes(self.db)
Given the code snippet: <|code_start|> self.assertNotEqual(code1, code2) self.assertNotEqual(None, codes.find(code2)) self.assertEqual(None, codes.find(code1)) codes.remove(codes.find(code1)) self.assertEqual(self.db.authorization_codes.count(), 0) def test_access_codes(self): codes = AccessCodes(self.db) self.assertEqual(self.db.access_codes.count(), 0) grant = {'scope': 'passwords', 'client_id': 'client1'} code1 = codes.create('user1', grant) self.assertEqual(self.db.access_codes.count(), 1) # creating a code with same arguments replace the old one code2 = codes.create('user1', grant) self.assertEqual(self.db.access_codes.count(), 1) self.assertNotEqual(code1, code2) self.assertNotEqual(None, codes.find(code2)) self.assertEqual(None, codes.find(code1)) codes.remove(codes.find(code1)) self.assertEqual(self.db.access_codes.count(), 0) def test_authorizator(self): app = {'_id': 'app1'} <|code_end|> , generate the next line using the imports in this file: from yithlibraryserver import testing from yithlibraryserver.oauth2.authorization import AuthorizationCodes from yithlibraryserver.oauth2.authorization import AccessCodes from yithlibraryserver.oauth2.authorization import Authorizator and context (functions, classes, or occasionally code) from other files: # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # class FakeRequest(DummyRequest): # class TestCase(unittest.TestCase): # def __init__(self, *args, **kwargs): # def setUp(self): # def tearDown(self): # def set_user_cookie(self, user_id): # def add_to_session(self, data): # def get_session(self, response): # # Path: yithlibraryserver/oauth2/authorization.py # class AuthorizationCodes(Codes): # # collection_name = 'authorization_codes' # # def get_redirect_url(self, code, uri, state=None): # parameters = ['code=%s' % code] # if state: # parameters.append('state=%s' % state) # return '%s?%s' % (uri, '&'.join(parameters)) # # def create(self, user_id, client_id, scope): # return super(AuthorizationCodes, self).create(user_id, # scope=scope, # client_id=client_id) # # Path: yithlibraryserver/oauth2/authorization.py # class AccessCodes(Codes): # # collection_name = 'access_codes' # # def create(self, user_id, grant): # return super(AccessCodes, self).create(user_id, # scope=grant['scope'], # client_id=grant['client_id']) # # Path: yithlibraryserver/oauth2/authorization.py # class Authorizator(object): # # def __init__(self, db, app): # self.db = db # self.app = app # self.auth_codes = AuthorizationCodes(db) # self.access_codes = AccessCodes(db) # # def is_app_authorized(self, user): # return self.app['_id'] in user['authorized_apps'] # # def store_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$addToSet': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # def remove_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$pull': {'authorized_apps': self.app['_id']}}, # safe=True, # ) . Output only the next line.
authorizator = Authorizator(self.db, app)
Given the code snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2012-2013 Yaco Sistemas # Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class PasswordsManagerTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() <|code_end|> , generate the next line using the imports in this file: import unittest from pyramid import testing from yithlibraryserver.db import MongoDB from yithlibraryserver.password.models import PasswordsManager from yithlibraryserver.testing import MONGO_URI and context (functions, classes, or occasionally code) from other files: # Path: yithlibraryserver/db.py # class MongoDB(object): # """Simple wrapper to get pymongo real objects from the settings uri""" # # def __init__(self, db_uri=DEFAULT_MONGODB_URI, # connection_factory=pymongo.Connection): # self.db_uri = urlparse.urlparse(db_uri) # self.connection = connection_factory( # host=self.db_uri.hostname or DEFAULT_MONGODB_HOST, # port=self.db_uri.port or DEFAULT_MONGODB_PORT, # tz_aware=True) # # if self.db_uri.path: # self.database_name = self.db_uri.path[1:] # else: # self.database_name = DEFAULT_MONGODB_NAME # # def get_connection(self): # return self.connection # # def get_database(self): # database = self.connection[self.database_name] # if self.db_uri.username and self.db_uri.password: # database.authenticate(self.db_uri.username, self.db_uri.password) # # return database # # Path: yithlibraryserver/password/models.py # class PasswordsManager(object): # # def __init__(self, db): # self.db = db # # def create(self, user, password): # """Creates and returns a new password or a set of passwords. # # Stores the password in the database for this specific user # and returns a new dict with the 'owner' and '_id' fields # filled. # # If password is a list, do the same with each password in # this list. # """ # if isinstance(password, dict): # if password: # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # _id = self.db.passwords.insert(new_password, safe=True) # new_password['_id'] = _id # return new_password # else: # new_passwords = [] # copy since we are changing this object # for p in password: # if p: # p = dict(p) # p['owner'] = user['_id'] # new_passwords.append(p) # # if new_passwords: # # _ids = self.db.passwords.insert(new_passwords, safe=True) # # for i in range(len(new_passwords)): # new_passwords[i]['_id'] = _ids[i] # # return new_passwords # # def retrieve(self, user, _id=None): # """Return the user's passwords or just one. # # If _id is None return the whole set of passwords for this # user. Otherwise, it returns the password with that _id. # """ # if _id is None: # return self.db.passwords.find({'owner': user['_id']}) # else: # return self.db.passwords.find_one({ # '_id': _id, # 'owner': user['_id'], # }) # # def update(self, user, _id, password): # """Update a password in the database. # # Return the updated password on success or None if the original # password does not exist. # """ # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # result = self.db.passwords.update({ # '_id': _id, # 'owner': user['_id'], # }, new_password, safe=True) # new_password['_id'] = _id # # # result['n'] is the number of documents updated # # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue # if result['n'] == 1: # return new_password # else: # return None # # def delete(self, user, _id=None): # """Deletes a password from the database or the whole set for this user. # # Returns True if the delete is succesfull or False otherwise. # """ # query = {'owner': user['_id']} # if _id is not None: # query['_id'] = _id # # result = self.db.passwords.remove(query, safe=True) # return result['n'] > 0 # # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' . Output only the next line.
mdb = MongoDB(MONGO_URI)
Based on the snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2012-2013 Yaco Sistemas # Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class PasswordsManagerTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() mdb = MongoDB(MONGO_URI) self.db = mdb.get_database() <|code_end|> , predict the immediate next line with the help of imports: import unittest from pyramid import testing from yithlibraryserver.db import MongoDB from yithlibraryserver.password.models import PasswordsManager from yithlibraryserver.testing import MONGO_URI and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/db.py # class MongoDB(object): # """Simple wrapper to get pymongo real objects from the settings uri""" # # def __init__(self, db_uri=DEFAULT_MONGODB_URI, # connection_factory=pymongo.Connection): # self.db_uri = urlparse.urlparse(db_uri) # self.connection = connection_factory( # host=self.db_uri.hostname or DEFAULT_MONGODB_HOST, # port=self.db_uri.port or DEFAULT_MONGODB_PORT, # tz_aware=True) # # if self.db_uri.path: # self.database_name = self.db_uri.path[1:] # else: # self.database_name = DEFAULT_MONGODB_NAME # # def get_connection(self): # return self.connection # # def get_database(self): # database = self.connection[self.database_name] # if self.db_uri.username and self.db_uri.password: # database.authenticate(self.db_uri.username, self.db_uri.password) # # return database # # Path: yithlibraryserver/password/models.py # class PasswordsManager(object): # # def __init__(self, db): # self.db = db # # def create(self, user, password): # """Creates and returns a new password or a set of passwords. # # Stores the password in the database for this specific user # and returns a new dict with the 'owner' and '_id' fields # filled. # # If password is a list, do the same with each password in # this list. # """ # if isinstance(password, dict): # if password: # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # _id = self.db.passwords.insert(new_password, safe=True) # new_password['_id'] = _id # return new_password # else: # new_passwords = [] # copy since we are changing this object # for p in password: # if p: # p = dict(p) # p['owner'] = user['_id'] # new_passwords.append(p) # # if new_passwords: # # _ids = self.db.passwords.insert(new_passwords, safe=True) # # for i in range(len(new_passwords)): # new_passwords[i]['_id'] = _ids[i] # # return new_passwords # # def retrieve(self, user, _id=None): # """Return the user's passwords or just one. # # If _id is None return the whole set of passwords for this # user. Otherwise, it returns the password with that _id. # """ # if _id is None: # return self.db.passwords.find({'owner': user['_id']}) # else: # return self.db.passwords.find_one({ # '_id': _id, # 'owner': user['_id'], # }) # # def update(self, user, _id, password): # """Update a password in the database. # # Return the updated password on success or None if the original # password does not exist. # """ # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # result = self.db.passwords.update({ # '_id': _id, # 'owner': user['_id'], # }, new_password, safe=True) # new_password['_id'] = _id # # # result['n'] is the number of documents updated # # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue # if result['n'] == 1: # return new_password # else: # return None # # def delete(self, user, _id=None): # """Deletes a password from the database or the whole set for this user. # # Returns True if the delete is succesfull or False otherwise. # """ # query = {'owner': user['_id']} # if _id is not None: # query['_id'] = _id # # result = self.db.passwords.remove(query, safe=True) # return result['n'] > 0 # # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' . Output only the next line.
self.pm = PasswordsManager(self.db)
Here is a snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2012-2013 Yaco Sistemas # Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class PasswordsManagerTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() <|code_end|> . Write the next line using the current file imports: import unittest from pyramid import testing from yithlibraryserver.db import MongoDB from yithlibraryserver.password.models import PasswordsManager from yithlibraryserver.testing import MONGO_URI and context from other files: # Path: yithlibraryserver/db.py # class MongoDB(object): # """Simple wrapper to get pymongo real objects from the settings uri""" # # def __init__(self, db_uri=DEFAULT_MONGODB_URI, # connection_factory=pymongo.Connection): # self.db_uri = urlparse.urlparse(db_uri) # self.connection = connection_factory( # host=self.db_uri.hostname or DEFAULT_MONGODB_HOST, # port=self.db_uri.port or DEFAULT_MONGODB_PORT, # tz_aware=True) # # if self.db_uri.path: # self.database_name = self.db_uri.path[1:] # else: # self.database_name = DEFAULT_MONGODB_NAME # # def get_connection(self): # return self.connection # # def get_database(self): # database = self.connection[self.database_name] # if self.db_uri.username and self.db_uri.password: # database.authenticate(self.db_uri.username, self.db_uri.password) # # return database # # Path: yithlibraryserver/password/models.py # class PasswordsManager(object): # # def __init__(self, db): # self.db = db # # def create(self, user, password): # """Creates and returns a new password or a set of passwords. # # Stores the password in the database for this specific user # and returns a new dict with the 'owner' and '_id' fields # filled. # # If password is a list, do the same with each password in # this list. # """ # if isinstance(password, dict): # if password: # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # _id = self.db.passwords.insert(new_password, safe=True) # new_password['_id'] = _id # return new_password # else: # new_passwords = [] # copy since we are changing this object # for p in password: # if p: # p = dict(p) # p['owner'] = user['_id'] # new_passwords.append(p) # # if new_passwords: # # _ids = self.db.passwords.insert(new_passwords, safe=True) # # for i in range(len(new_passwords)): # new_passwords[i]['_id'] = _ids[i] # # return new_passwords # # def retrieve(self, user, _id=None): # """Return the user's passwords or just one. # # If _id is None return the whole set of passwords for this # user. Otherwise, it returns the password with that _id. # """ # if _id is None: # return self.db.passwords.find({'owner': user['_id']}) # else: # return self.db.passwords.find_one({ # '_id': _id, # 'owner': user['_id'], # }) # # def update(self, user, _id, password): # """Update a password in the database. # # Return the updated password on success or None if the original # password does not exist. # """ # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # result = self.db.passwords.update({ # '_id': _id, # 'owner': user['_id'], # }, new_password, safe=True) # new_password['_id'] = _id # # # result['n'] is the number of documents updated # # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue # if result['n'] == 1: # return new_password # else: # return None # # def delete(self, user, _id=None): # """Deletes a password from the database or the whole set for this user. # # Returns True if the delete is succesfull or False otherwise. # """ # query = {'owner': user['_id']} # if _id is not None: # query['_id'] = _id # # result = self.db.passwords.remove(query, safe=True) # return result['n'] > 0 # # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' , which may include functions, classes, or code. Output only the next line.
mdb = MongoDB(MONGO_URI)
Given the code snippet: <|code_start|> ) pstruct = field.schema.deserialize(cstruct) email_verified_output = field.renderer( self.email_verified_template, email=pstruct.get('email', ''), email_verified=pstruct.get('email_verified', False), ) return email_output + email_verified_output def deserialize(self, field, pstruct): return { 'email': super(EmailWidget, self).deserialize(field, pstruct), # The email_verified attr is readonly and # thus, not used in the view 'email_verified': None, } class EmailSchema(colander.MappingSchema): email = colander.SchemaNode(colander.String(), missing='') email_verified = colander.SchemaNode(colander.Boolean()) class BaseUserSchema(colander.MappingSchema): first_name = colander.SchemaNode( colander.String(), <|code_end|> , generate the next line using the imports in this file: import colander from deform.widget import CheckboxWidget, TextAreaWidget, TextInputWidget from yithlibraryserver.i18n import TranslationString as _ and context (functions, classes, or occasionally code) from other files: # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): . Output only the next line.
title=_('First name'),
Given snippet: <|code_start|># This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def get_user_passwords(db, user): passwords_manager = PasswordsManager(db) return [remove_attrs(password, 'owner', '_id') for password in passwords_manager.retrieve(user)] def get_backup_filename(date): return 'yith-library-backup-%d-%02d-%02d.yith' % ( date.year, date.month, date.day) def compress(passwords): <|code_end|> , continue by predicting the next line. Consider current file imports: import gzip import json from yithlibraryserver.compat import BytesIO from yithlibraryserver.password.models import PasswordsManager from yithlibraryserver.utils import remove_attrs and context: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/password/models.py # class PasswordsManager(object): # # def __init__(self, db): # self.db = db # # def create(self, user, password): # """Creates and returns a new password or a set of passwords. # # Stores the password in the database for this specific user # and returns a new dict with the 'owner' and '_id' fields # filled. # # If password is a list, do the same with each password in # this list. # """ # if isinstance(password, dict): # if password: # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # _id = self.db.passwords.insert(new_password, safe=True) # new_password['_id'] = _id # return new_password # else: # new_passwords = [] # copy since we are changing this object # for p in password: # if p: # p = dict(p) # p['owner'] = user['_id'] # new_passwords.append(p) # # if new_passwords: # # _ids = self.db.passwords.insert(new_passwords, safe=True) # # for i in range(len(new_passwords)): # new_passwords[i]['_id'] = _ids[i] # # return new_passwords # # def retrieve(self, user, _id=None): # """Return the user's passwords or just one. # # If _id is None return the whole set of passwords for this # user. Otherwise, it returns the password with that _id. # """ # if _id is None: # return self.db.passwords.find({'owner': user['_id']}) # else: # return self.db.passwords.find_one({ # '_id': _id, # 'owner': user['_id'], # }) # # def update(self, user, _id, password): # """Update a password in the database. # # Return the updated password on success or None if the original # password does not exist. # """ # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # result = self.db.passwords.update({ # '_id': _id, # 'owner': user['_id'], # }, new_password, safe=True) # new_password['_id'] = _id # # # result['n'] is the number of documents updated # # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue # if result['n'] == 1: # return new_password # else: # return None # # def delete(self, user, _id=None): # """Deletes a password from the database or the whole set for this user. # # Returns True if the delete is succesfull or False otherwise. # """ # query = {'owner': user['_id']} # if _id is not None: # query['_id'] = _id # # result = self.db.passwords.remove(query, safe=True) # return result['n'] > 0 # # Path: yithlibraryserver/utils.py # def remove_attrs(dictionary, *attrs): # """Returns a copy of dictionary without attrs""" # result = {} # # for key, value in dictionary.items(): # if key not in attrs: # result[key] = value # # return result which might include code, classes, or functions. Output only the next line.
buf = BytesIO()
Based on the snippet: <|code_start|> class RootFactory(object): __acl__ = ( (Allow, Authenticated, 'user-registration'), (Allow, Authenticated, 'view-applications'), (Allow, Authenticated, 'edit-application'), (Allow, Authenticated, 'add-application'), (Allow, Authenticated, 'delete-application'), (Allow, Authenticated, 'add-authorized-app'), (Allow, Authenticated, 'revoke-authorized-app'), (Allow, Authenticated, 'edit-profile'), (Allow, Authenticated, 'destroy-account'), (Allow, Authenticated, 'backups'), ) def __init__(self, request): self.request = request def authorize_user(request): authorization = request.headers.get('Authorization') if authorization is None: raise HTTPUnauthorized() method, credentials = request.authorization if method.lower() != 'bearer': raise HTTPBadRequest('Authorization method not supported') <|code_end|> , predict the immediate next line with the help of imports: from pyramid.httpexceptions import HTTPBadRequest, HTTPUnauthorized from pyramid.security import Allow, Authenticated from yithlibraryserver.oauth2.authorization import AccessCodes and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/oauth2/authorization.py # class AccessCodes(Codes): # # collection_name = 'access_codes' # # def create(self, user_id, grant): # return super(AccessCodes, self).create(user_id, # scope=grant['scope'], # client_id=grant['client_id']) . Output only the next line.
access_code = AccessCodes(request.db).find(credentials)
Using the snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class User(dict): def __unicode__(self): result = self.get('screen_name', '') if result: return result result = ' '.join([self.get('first_name', ''), self.get('last_name', '')]) result = result.strip() if result: return result result = self.get('email', '') if result: return result <|code_end|> , determine the next line of code. You have imports: from yithlibraryserver.compat import text_type and context (class names, function names, or code) available: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover . Output only the next line.
return text_type(self['_id'])
Given snippet: <|code_start|> context, "Yith Library announcement", [user['email']], ) def announce(): usage = "migrate: %prog config_uri migration_name" description = "Add a 'send_email_periodically' preference to every user." parser = optparse.OptionParser( usage=usage, description=textwrap.dedent(description) ) options, args = parser.parse_args(sys.argv[1:]) if len(args) != 2: safe_print('You must provide two arguments. ' 'The first one is the config file and the ' 'second one is the email template.') return 2 config_uri = args[0] email_template = args[1] env = bootstrap(config_uri) settings, closer = env['registry'].settings, env['closer'] try: db = settings['mongodb'].get_database() request = env['request'] public_url_root = settings['public_url_root'] <|code_end|> , continue by predicting the next line. Consider current file imports: import optparse import textwrap import sys import transaction from pyramid.paster import bootstrap from pyramid_mailer import get_mailer from yithlibraryserver.compat import urlparse from yithlibraryserver.email import create_message from yithlibraryserver.scripts.reports import get_passwords_map from yithlibraryserver.scripts.utils import safe_print from yithlibraryserver.scripts.utils import get_user_display_name and context: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/email.py # def create_message(request, template, context, subject, recipients, # attachments=None, extra_headers=None): # text_body = render(template + '.txt', context, request=request) # # chamaleon txt templates are rendered as utf-8 bytestrings # text_body = text_body.decode('utf-8') # # html_body = render(template + '.pt', context, request=request) # # extra_headers = extra_headers or {} # # message = Message( # subject=subject, # recipients=recipients, # body=text_body, # html=html_body, # extra_headers=extra_headers, # ) # # if attachments is not None: # for attachment in attachments: # message.attach(attachment) # # return message # # Path: yithlibraryserver/scripts/reports.py # def get_passwords_map(passwords): # # make a password dict keyed by users_id # passwords_map = {} # for password in passwords: # owner = password['owner'] # if owner in passwords_map: # passwords_map[owner] += 1 # else: # passwords_map[owner] = 1 # # return passwords_map # # Path: yithlibraryserver/scripts/utils.py # def safe_print(value): # if PY3: # pragma: no cover # print(value) # else: # pragma: no cover # print(value.encode('utf-8')) # # Path: yithlibraryserver/scripts/utils.py # def get_user_display_name(user): # return '%s %s <%s>' % (user.get('first_name', ''), # user.get('last_name', ''), # user.get('email', '')) which might include code, classes, or functions. Output only the next line.
preferences_link = urlparse.urljoin(
Here is a snippet: <|code_start|># 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def get_all_users_with_passwords_and_email(db): all_passwords = list(db.passwords.find()) passwords_map = get_passwords_map(all_passwords) for user in db.users.find({ 'email_verified': True, }): if not user['email']: continue if not user['_id'] in passwords_map: continue yield user def send_email(request, email_template, user, preferences_link): safe_print('Sending email to %s' % get_user_display_name(user)) context = {'user': user, 'preferences_link': preferences_link} <|code_end|> . Write the next line using the current file imports: import optparse import textwrap import sys import transaction from pyramid.paster import bootstrap from pyramid_mailer import get_mailer from yithlibraryserver.compat import urlparse from yithlibraryserver.email import create_message from yithlibraryserver.scripts.reports import get_passwords_map from yithlibraryserver.scripts.utils import safe_print from yithlibraryserver.scripts.utils import get_user_display_name and context from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/email.py # def create_message(request, template, context, subject, recipients, # attachments=None, extra_headers=None): # text_body = render(template + '.txt', context, request=request) # # chamaleon txt templates are rendered as utf-8 bytestrings # text_body = text_body.decode('utf-8') # # html_body = render(template + '.pt', context, request=request) # # extra_headers = extra_headers or {} # # message = Message( # subject=subject, # recipients=recipients, # body=text_body, # html=html_body, # extra_headers=extra_headers, # ) # # if attachments is not None: # for attachment in attachments: # message.attach(attachment) # # return message # # Path: yithlibraryserver/scripts/reports.py # def get_passwords_map(passwords): # # make a password dict keyed by users_id # passwords_map = {} # for password in passwords: # owner = password['owner'] # if owner in passwords_map: # passwords_map[owner] += 1 # else: # passwords_map[owner] = 1 # # return passwords_map # # Path: yithlibraryserver/scripts/utils.py # def safe_print(value): # if PY3: # pragma: no cover # print(value) # else: # pragma: no cover # print(value.encode('utf-8')) # # Path: yithlibraryserver/scripts/utils.py # def get_user_display_name(user): # return '%s %s <%s>' % (user.get('first_name', ''), # user.get('last_name', ''), # user.get('email', '')) , which may include functions, classes, or code. Output only the next line.
return create_message(
Predict the next line for this snippet: <|code_start|># Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def get_all_users_with_passwords_and_email(db): all_passwords = list(db.passwords.find()) passwords_map = get_passwords_map(all_passwords) for user in db.users.find({ 'email_verified': True, }): if not user['email']: continue if not user['_id'] in passwords_map: continue yield user def send_email(request, email_template, user, preferences_link): <|code_end|> with the help of current file imports: import optparse import textwrap import sys import transaction from pyramid.paster import bootstrap from pyramid_mailer import get_mailer from yithlibraryserver.compat import urlparse from yithlibraryserver.email import create_message from yithlibraryserver.scripts.reports import get_passwords_map from yithlibraryserver.scripts.utils import safe_print from yithlibraryserver.scripts.utils import get_user_display_name and context from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/email.py # def create_message(request, template, context, subject, recipients, # attachments=None, extra_headers=None): # text_body = render(template + '.txt', context, request=request) # # chamaleon txt templates are rendered as utf-8 bytestrings # text_body = text_body.decode('utf-8') # # html_body = render(template + '.pt', context, request=request) # # extra_headers = extra_headers or {} # # message = Message( # subject=subject, # recipients=recipients, # body=text_body, # html=html_body, # extra_headers=extra_headers, # ) # # if attachments is not None: # for attachment in attachments: # message.attach(attachment) # # return message # # Path: yithlibraryserver/scripts/reports.py # def get_passwords_map(passwords): # # make a password dict keyed by users_id # passwords_map = {} # for password in passwords: # owner = password['owner'] # if owner in passwords_map: # passwords_map[owner] += 1 # else: # passwords_map[owner] = 1 # # return passwords_map # # Path: yithlibraryserver/scripts/utils.py # def safe_print(value): # if PY3: # pragma: no cover # print(value) # else: # pragma: no cover # print(value.encode('utf-8')) # # Path: yithlibraryserver/scripts/utils.py # def get_user_display_name(user): # return '%s %s <%s>' % (user.get('first_name', ''), # user.get('last_name', ''), # user.get('email', '')) , which may contain function names, class names, or code. Output only the next line.
safe_print('Sending email to %s' % get_user_display_name(user))
Using the snippet: <|code_start|># Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def get_all_users_with_passwords_and_email(db): all_passwords = list(db.passwords.find()) passwords_map = get_passwords_map(all_passwords) for user in db.users.find({ 'email_verified': True, }): if not user['email']: continue if not user['_id'] in passwords_map: continue yield user def send_email(request, email_template, user, preferences_link): <|code_end|> , determine the next line of code. You have imports: import optparse import textwrap import sys import transaction from pyramid.paster import bootstrap from pyramid_mailer import get_mailer from yithlibraryserver.compat import urlparse from yithlibraryserver.email import create_message from yithlibraryserver.scripts.reports import get_passwords_map from yithlibraryserver.scripts.utils import safe_print from yithlibraryserver.scripts.utils import get_user_display_name and context (class names, function names, or code) available: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/email.py # def create_message(request, template, context, subject, recipients, # attachments=None, extra_headers=None): # text_body = render(template + '.txt', context, request=request) # # chamaleon txt templates are rendered as utf-8 bytestrings # text_body = text_body.decode('utf-8') # # html_body = render(template + '.pt', context, request=request) # # extra_headers = extra_headers or {} # # message = Message( # subject=subject, # recipients=recipients, # body=text_body, # html=html_body, # extra_headers=extra_headers, # ) # # if attachments is not None: # for attachment in attachments: # message.attach(attachment) # # return message # # Path: yithlibraryserver/scripts/reports.py # def get_passwords_map(passwords): # # make a password dict keyed by users_id # passwords_map = {} # for password in passwords: # owner = password['owner'] # if owner in passwords_map: # passwords_map[owner] += 1 # else: # passwords_map[owner] = 1 # # return passwords_map # # Path: yithlibraryserver/scripts/utils.py # def safe_print(value): # if PY3: # pragma: no cover # print(value) # else: # pragma: no cover # print(value.encode('utf-8')) # # Path: yithlibraryserver/scripts/utils.py # def get_user_display_name(user): # return '%s %s <%s>' % (user.get('first_name', ''), # user.get('last_name', ''), # user.get('email', '')) . Output only the next line.
safe_print('Sending email to %s' % get_user_display_name(user))
Given snippet: <|code_start|> user_id = self.db.users.insert({ 'twitter_id': 'twitter1', 'screen_name': 'John Doe', 'first_name': 'John', 'last_name': 'Doe', 'email': '', 'email_verified': False, 'authorized_apps': [], 'date_joined': date, 'last_login': date, }, safe=True) self.set_user_cookie(str(user_id)) # no file to upload res = self.testapp.post('/backup/import', status=302) self.assertEqual(res.status, '302 Found') self.assertEqual(res.location, 'http://localhost/backup') self.assertEqual(0, self.db.passwords.count()) # not really a file res = self.testapp.post('/backup/import', { 'passwords-file': '', }, status=302) self.assertEqual(res.status, '302 Found') self.assertEqual(res.location, 'http://localhost/backup') self.assertEqual(0, self.db.passwords.count()) # bad file <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import gzip import json import os from yithlibraryserver.compat import text_type, BytesIO from yithlibraryserver.testing import TestCase and context: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) which might include code, classes, or functions. Output only the next line.
content = get_gzip_data(text_type('[{}'))
Predict the next line after this snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def get_gzip_data(text): buf = BytesIO() gzip_data = gzip.GzipFile(fileobj=buf, mode='wb') gzip_data.write(text.encode('utf-8')) gzip_data.close() return buf.getvalue() <|code_end|> using the current file's imports: import datetime import gzip import json import os from yithlibraryserver.compat import text_type, BytesIO from yithlibraryserver.testing import TestCase and any relevant context from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) . Output only the next line.
class ViewTests(TestCase):
Based on the snippet: <|code_start|># # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class IdentityProviderTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() def tearDown(self): testing.tearDown() def test_add_identity_provider(self): self.config.add_directive('add_identity_provider', <|code_end|> , predict the immediate next line with the help of imports: import unittest from pyramid import testing from yithlibraryserver.user.idp import add_identity_provider and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/user/idp.py # def add_identity_provider(config, name): # log.debug('Registering identity provider "%s"' % name) # # if not hasattr(config.registry, 'identity_providers'): # config.registry.identity_providers = [] # # config.registry.identity_providers.append(IdentityProvider(name)) . Output only the next line.
add_identity_provider)
Given the following code snippet before the placeholder: <|code_start|># (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class PayPalPayloadTests(unittest.TestCase): def setUp(self): self.config = testing.setUp(settings={ 'paypal_user': 'paypal_user', 'paypal_password': 'paypal_password', 'paypal_signature': 'paypal_signature', }) def tearDown(self): testing.tearDown() def test_basic_payload(self): request = testing.DummyRequest() <|code_end|> , predict the next line using imports from the current file: import unittest from mock import patch from pyramid import testing from yithlibraryserver.contributions.paypal import PayPalPayload from yithlibraryserver.contributions.paypal import PayPalExpressCheckout and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/contributions/paypal.py # class PayPalPayload(dict): # # def __init__(self, request, method): # self['METHOD'] = method # self['VERSION'] = '72.0' # self['USER'] = request.registry.settings['paypal_user'] # self['PWD'] = request.registry.settings['paypal_password'] # self['SIGNATURE'] = request.registry.settings['paypal_signature'] # # def add_payment_info(self, amount): # self['PAYMENTREQUEST_0_AMT'] = amount # self['PAYMENTREQUEST_0_ITEMAMT'] = amount # self['PAYMENTREQUEST_0_DESC'] = 'Donation' # self['PAYMENTREQUEST_0_CURRENCYCODE'] = 'USD' # self['PAYMENTREQUEST_0_PAYMENTACTION'] = 'Sale' # self['LOCALECODE'] = 'ES' # # def add_callbacks(self, return_url, cancel_url): # self['RETURNURL'] = return_url # self['CANCELURL'] = cancel_url # # def add_token(self, token, payerid): # self['TOKEN'] = token # self['PAYERID'] = payerid # # Path: yithlibraryserver/contributions/paypal.py # class PayPalExpressCheckout(object): # # def __init__(self, request): # self.request = request # self.nvp_url = request.registry.settings['paypal_nvp_url'] # self.express_checkout_url = request.registry.settings['paypal_express_checkout_url'] # # def get_express_checkout_token(self, amount): # return_url = self.request.route_url('contributions_paypal_success_callback') # cancel_url = self.request.route_url('contributions_paypal_cancel_callback') # payload = PayPalPayload(self.request, 'SetExpressCheckout') # payload.add_payment_info(amount) # payload.add_callbacks(return_url, cancel_url) # # response = requests.post(self.nvp_url, data=payload) # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return data['TOKEN'][0] # # def get_express_checkout_url(self, token): # url = self.express_checkout_url + '?cmd=_express-checkout&token=%s' # return url % token # # def get_express_checkout_details(self, token, payerid): # payload = PayPalPayload(self.request, 'GetExpressCheckoutDetails') # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # amount = data['AMT'][0] # amount = int(amount.split('.')[0]) # return { # 'amount': amount, # 'firstname': data['FIRSTNAME'][0], # 'lastname': data['LASTNAME'][0], # 'city': data['SHIPTOCITY'][0], # 'country': data['SHIPTOCOUNTRYNAME'][0], # 'state': data['SHIPTOSTATE'][0], # 'street': data['SHIPTOSTREET'][0], # 'zip': data['SHIPTOZIP'][0], # 'email': data['EMAIL'][0], # } # # def do_express_checkout_payment(self, token, payerid, amount): # payload = PayPalPayload(self.request, 'DoExpressCheckoutPayment') # payload.add_payment_info(amount) # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return True # # return False . Output only the next line.
payload = PayPalPayload(request, 'method1')
Based on the snippet: <|code_start|> request = testing.DummyRequest() payload = PayPalPayload(request, 'method_with_callbacks') payload.add_token('12345', '6789') self.assertEqual(payload, { 'METHOD': 'method_with_callbacks', 'VERSION': '72.0', 'USER': 'paypal_user', 'PWD': 'paypal_password', 'SIGNATURE': 'paypal_signature', 'TOKEN': '12345', 'PAYERID': '6789', }) class PayPalExpressCheckoutTests(unittest.TestCase): def setUp(self): self.config = testing.setUp(settings={ 'paypal_user': 'paypal_user', 'paypal_password': 'paypal_password', 'paypal_signature': 'paypal_signature', 'paypal_nvp_url': 'http://paypal.com/nvp', 'paypal_express_checkout_url': 'http://paypal.com/express_checkout', }) self.config.include('yithlibraryserver') self.config.include('yithlibraryserver.contributions') def test_express_checkout_token(self): request = testing.DummyRequest() <|code_end|> , predict the immediate next line with the help of imports: import unittest from mock import patch from pyramid import testing from yithlibraryserver.contributions.paypal import PayPalPayload from yithlibraryserver.contributions.paypal import PayPalExpressCheckout and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/contributions/paypal.py # class PayPalPayload(dict): # # def __init__(self, request, method): # self['METHOD'] = method # self['VERSION'] = '72.0' # self['USER'] = request.registry.settings['paypal_user'] # self['PWD'] = request.registry.settings['paypal_password'] # self['SIGNATURE'] = request.registry.settings['paypal_signature'] # # def add_payment_info(self, amount): # self['PAYMENTREQUEST_0_AMT'] = amount # self['PAYMENTREQUEST_0_ITEMAMT'] = amount # self['PAYMENTREQUEST_0_DESC'] = 'Donation' # self['PAYMENTREQUEST_0_CURRENCYCODE'] = 'USD' # self['PAYMENTREQUEST_0_PAYMENTACTION'] = 'Sale' # self['LOCALECODE'] = 'ES' # # def add_callbacks(self, return_url, cancel_url): # self['RETURNURL'] = return_url # self['CANCELURL'] = cancel_url # # def add_token(self, token, payerid): # self['TOKEN'] = token # self['PAYERID'] = payerid # # Path: yithlibraryserver/contributions/paypal.py # class PayPalExpressCheckout(object): # # def __init__(self, request): # self.request = request # self.nvp_url = request.registry.settings['paypal_nvp_url'] # self.express_checkout_url = request.registry.settings['paypal_express_checkout_url'] # # def get_express_checkout_token(self, amount): # return_url = self.request.route_url('contributions_paypal_success_callback') # cancel_url = self.request.route_url('contributions_paypal_cancel_callback') # payload = PayPalPayload(self.request, 'SetExpressCheckout') # payload.add_payment_info(amount) # payload.add_callbacks(return_url, cancel_url) # # response = requests.post(self.nvp_url, data=payload) # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return data['TOKEN'][0] # # def get_express_checkout_url(self, token): # url = self.express_checkout_url + '?cmd=_express-checkout&token=%s' # return url % token # # def get_express_checkout_details(self, token, payerid): # payload = PayPalPayload(self.request, 'GetExpressCheckoutDetails') # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # amount = data['AMT'][0] # amount = int(amount.split('.')[0]) # return { # 'amount': amount, # 'firstname': data['FIRSTNAME'][0], # 'lastname': data['LASTNAME'][0], # 'city': data['SHIPTOCITY'][0], # 'country': data['SHIPTOCOUNTRYNAME'][0], # 'state': data['SHIPTOSTATE'][0], # 'street': data['SHIPTOSTREET'][0], # 'zip': data['SHIPTOZIP'][0], # 'email': data['EMAIL'][0], # } # # def do_express_checkout_payment(self, token, payerid, amount): # payload = PayPalPayload(self.request, 'DoExpressCheckoutPayment') # payload.add_payment_info(amount) # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return True # # return False . Output only the next line.
pec = PayPalExpressCheckout(request)
Next line prediction: <|code_start|> token = paypal.get_express_checkout_token(amount) return HTTPFound(paypal.get_express_checkout_url(token)) return HTTPBadRequest('Wrong action or method') @view_config(route_name='contributions_paypal_success_callback', renderer='templates/contributions_confirm.pt') def contributions_paypal_success(request): error_msg = _('There was a problem in the confirmation process. Please start the checkout again') if request.method == 'POST': if 'submit' in request.POST: token = request.POST.get('token', None) payerid = request.POST.get('payerid', None) amount = request.POST.get('amount', None) success = False if token and payerid and amount: try: amount = int(amount) except ValueError: return HTTPBadRequest('Amount must be an integer') paypal = PayPalExpressCheckout(request) success = paypal.do_express_checkout_payment(token, payerid, amount) if success: donation = create_donation(request, request.POST) <|code_end|> . Use current file imports: (import random from pyramid.httpexceptions import HTTPBadRequest, HTTPFound from pyramid.i18n import get_locale_name from pyramid.view import view_config from yithlibraryserver.contributions.email import send_thankyou_email from yithlibraryserver.contributions.email import send_notification_to_admins from yithlibraryserver.contributions.models import create_donation from yithlibraryserver.contributions.models import include_sticker from yithlibraryserver.contributions.paypal import PayPalExpressCheckout from yithlibraryserver.i18n import TranslationString as _) and context including class names, function names, or small code snippets from other files: # Path: yithlibraryserver/contributions/email.py # def send_thankyou_email(request, donation): # return send_email( # request, # 'yithlibraryserver.contributions:templates/email_thankyou', # donation, # 'Thanks for your contribution!', # [donation['email']], # ) # # Path: yithlibraryserver/contributions/email.py # def send_notification_to_admins(request, donation): # context = { # 'home_link': request.route_url('home'), # } # context.update(donation) # return send_email_to_admins( # request, # 'yithlibraryserver.contributions:templates/email_admin_notification', # context, # 'A new donation was received!', # ) # # Path: yithlibraryserver/contributions/models.py # def create_donation(request, data): # amount = int(data['amount']) # donation = { # 'amount': amount, # 'firstname': data['firstname'], # 'lastname': data['lastname'], # 'city': data['city'], # 'country': data['country'], # 'state': data['state'], # 'street': data['street'], # 'zip': data['zip'], # 'email': data['email'], # 'creation': request.datetime_service.utcnow(), # } # if include_sticker(amount): # donation['send_sticker'] = not ('no-sticker' in data) # else: # donation['send_sticker'] = False # # if request.user is not None: # donation['user'] = request.user['_id'] # else: # donation['user'] = None # # _id = request.db.donations.insert(donation, safe=True) # donation['_id'] = _id # return donation # # Path: yithlibraryserver/contributions/models.py # def include_sticker(amount): # return amount > 1 # # Path: yithlibraryserver/contributions/paypal.py # class PayPalExpressCheckout(object): # # def __init__(self, request): # self.request = request # self.nvp_url = request.registry.settings['paypal_nvp_url'] # self.express_checkout_url = request.registry.settings['paypal_express_checkout_url'] # # def get_express_checkout_token(self, amount): # return_url = self.request.route_url('contributions_paypal_success_callback') # cancel_url = self.request.route_url('contributions_paypal_cancel_callback') # payload = PayPalPayload(self.request, 'SetExpressCheckout') # payload.add_payment_info(amount) # payload.add_callbacks(return_url, cancel_url) # # response = requests.post(self.nvp_url, data=payload) # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return data['TOKEN'][0] # # def get_express_checkout_url(self, token): # url = self.express_checkout_url + '?cmd=_express-checkout&token=%s' # return url % token # # def get_express_checkout_details(self, token, payerid): # payload = PayPalPayload(self.request, 'GetExpressCheckoutDetails') # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # amount = data['AMT'][0] # amount = int(amount.split('.')[0]) # return { # 'amount': amount, # 'firstname': data['FIRSTNAME'][0], # 'lastname': data['LASTNAME'][0], # 'city': data['SHIPTOCITY'][0], # 'country': data['SHIPTOCOUNTRYNAME'][0], # 'state': data['SHIPTOSTATE'][0], # 'street': data['SHIPTOSTREET'][0], # 'zip': data['SHIPTOZIP'][0], # 'email': data['EMAIL'][0], # } # # def do_express_checkout_payment(self, token, payerid, amount): # payload = PayPalPayload(self.request, 'DoExpressCheckoutPayment') # payload.add_payment_info(amount) # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return True # # return False # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): . Output only the next line.
send_thankyou_email(request, donation)
Given the following code snippet before the placeholder: <|code_start|> return HTTPFound(paypal.get_express_checkout_url(token)) return HTTPBadRequest('Wrong action or method') @view_config(route_name='contributions_paypal_success_callback', renderer='templates/contributions_confirm.pt') def contributions_paypal_success(request): error_msg = _('There was a problem in the confirmation process. Please start the checkout again') if request.method == 'POST': if 'submit' in request.POST: token = request.POST.get('token', None) payerid = request.POST.get('payerid', None) amount = request.POST.get('amount', None) success = False if token and payerid and amount: try: amount = int(amount) except ValueError: return HTTPBadRequest('Amount must be an integer') paypal = PayPalExpressCheckout(request) success = paypal.do_express_checkout_payment(token, payerid, amount) if success: donation = create_donation(request, request.POST) send_thankyou_email(request, donation) <|code_end|> , predict the next line using imports from the current file: import random from pyramid.httpexceptions import HTTPBadRequest, HTTPFound from pyramid.i18n import get_locale_name from pyramid.view import view_config from yithlibraryserver.contributions.email import send_thankyou_email from yithlibraryserver.contributions.email import send_notification_to_admins from yithlibraryserver.contributions.models import create_donation from yithlibraryserver.contributions.models import include_sticker from yithlibraryserver.contributions.paypal import PayPalExpressCheckout from yithlibraryserver.i18n import TranslationString as _ and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/contributions/email.py # def send_thankyou_email(request, donation): # return send_email( # request, # 'yithlibraryserver.contributions:templates/email_thankyou', # donation, # 'Thanks for your contribution!', # [donation['email']], # ) # # Path: yithlibraryserver/contributions/email.py # def send_notification_to_admins(request, donation): # context = { # 'home_link': request.route_url('home'), # } # context.update(donation) # return send_email_to_admins( # request, # 'yithlibraryserver.contributions:templates/email_admin_notification', # context, # 'A new donation was received!', # ) # # Path: yithlibraryserver/contributions/models.py # def create_donation(request, data): # amount = int(data['amount']) # donation = { # 'amount': amount, # 'firstname': data['firstname'], # 'lastname': data['lastname'], # 'city': data['city'], # 'country': data['country'], # 'state': data['state'], # 'street': data['street'], # 'zip': data['zip'], # 'email': data['email'], # 'creation': request.datetime_service.utcnow(), # } # if include_sticker(amount): # donation['send_sticker'] = not ('no-sticker' in data) # else: # donation['send_sticker'] = False # # if request.user is not None: # donation['user'] = request.user['_id'] # else: # donation['user'] = None # # _id = request.db.donations.insert(donation, safe=True) # donation['_id'] = _id # return donation # # Path: yithlibraryserver/contributions/models.py # def include_sticker(amount): # return amount > 1 # # Path: yithlibraryserver/contributions/paypal.py # class PayPalExpressCheckout(object): # # def __init__(self, request): # self.request = request # self.nvp_url = request.registry.settings['paypal_nvp_url'] # self.express_checkout_url = request.registry.settings['paypal_express_checkout_url'] # # def get_express_checkout_token(self, amount): # return_url = self.request.route_url('contributions_paypal_success_callback') # cancel_url = self.request.route_url('contributions_paypal_cancel_callback') # payload = PayPalPayload(self.request, 'SetExpressCheckout') # payload.add_payment_info(amount) # payload.add_callbacks(return_url, cancel_url) # # response = requests.post(self.nvp_url, data=payload) # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return data['TOKEN'][0] # # def get_express_checkout_url(self, token): # url = self.express_checkout_url + '?cmd=_express-checkout&token=%s' # return url % token # # def get_express_checkout_details(self, token, payerid): # payload = PayPalPayload(self.request, 'GetExpressCheckoutDetails') # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # amount = data['AMT'][0] # amount = int(amount.split('.')[0]) # return { # 'amount': amount, # 'firstname': data['FIRSTNAME'][0], # 'lastname': data['LASTNAME'][0], # 'city': data['SHIPTOCITY'][0], # 'country': data['SHIPTOCOUNTRYNAME'][0], # 'state': data['SHIPTOSTATE'][0], # 'street': data['SHIPTOSTREET'][0], # 'zip': data['SHIPTOZIP'][0], # 'email': data['EMAIL'][0], # } # # def do_express_checkout_payment(self, token, payerid, amount): # payload = PayPalPayload(self.request, 'DoExpressCheckoutPayment') # payload.add_payment_info(amount) # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return True # # return False # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): . Output only the next line.
send_notification_to_admins(request, donation)
Using the snippet: <|code_start|> return HTTPBadRequest('Amount must be an integer') token = paypal.get_express_checkout_token(amount) return HTTPFound(paypal.get_express_checkout_url(token)) return HTTPBadRequest('Wrong action or method') @view_config(route_name='contributions_paypal_success_callback', renderer='templates/contributions_confirm.pt') def contributions_paypal_success(request): error_msg = _('There was a problem in the confirmation process. Please start the checkout again') if request.method == 'POST': if 'submit' in request.POST: token = request.POST.get('token', None) payerid = request.POST.get('payerid', None) amount = request.POST.get('amount', None) success = False if token and payerid and amount: try: amount = int(amount) except ValueError: return HTTPBadRequest('Amount must be an integer') paypal = PayPalExpressCheckout(request) success = paypal.do_express_checkout_payment(token, payerid, amount) if success: <|code_end|> , determine the next line of code. You have imports: import random from pyramid.httpexceptions import HTTPBadRequest, HTTPFound from pyramid.i18n import get_locale_name from pyramid.view import view_config from yithlibraryserver.contributions.email import send_thankyou_email from yithlibraryserver.contributions.email import send_notification_to_admins from yithlibraryserver.contributions.models import create_donation from yithlibraryserver.contributions.models import include_sticker from yithlibraryserver.contributions.paypal import PayPalExpressCheckout from yithlibraryserver.i18n import TranslationString as _ and context (class names, function names, or code) available: # Path: yithlibraryserver/contributions/email.py # def send_thankyou_email(request, donation): # return send_email( # request, # 'yithlibraryserver.contributions:templates/email_thankyou', # donation, # 'Thanks for your contribution!', # [donation['email']], # ) # # Path: yithlibraryserver/contributions/email.py # def send_notification_to_admins(request, donation): # context = { # 'home_link': request.route_url('home'), # } # context.update(donation) # return send_email_to_admins( # request, # 'yithlibraryserver.contributions:templates/email_admin_notification', # context, # 'A new donation was received!', # ) # # Path: yithlibraryserver/contributions/models.py # def create_donation(request, data): # amount = int(data['amount']) # donation = { # 'amount': amount, # 'firstname': data['firstname'], # 'lastname': data['lastname'], # 'city': data['city'], # 'country': data['country'], # 'state': data['state'], # 'street': data['street'], # 'zip': data['zip'], # 'email': data['email'], # 'creation': request.datetime_service.utcnow(), # } # if include_sticker(amount): # donation['send_sticker'] = not ('no-sticker' in data) # else: # donation['send_sticker'] = False # # if request.user is not None: # donation['user'] = request.user['_id'] # else: # donation['user'] = None # # _id = request.db.donations.insert(donation, safe=True) # donation['_id'] = _id # return donation # # Path: yithlibraryserver/contributions/models.py # def include_sticker(amount): # return amount > 1 # # Path: yithlibraryserver/contributions/paypal.py # class PayPalExpressCheckout(object): # # def __init__(self, request): # self.request = request # self.nvp_url = request.registry.settings['paypal_nvp_url'] # self.express_checkout_url = request.registry.settings['paypal_express_checkout_url'] # # def get_express_checkout_token(self, amount): # return_url = self.request.route_url('contributions_paypal_success_callback') # cancel_url = self.request.route_url('contributions_paypal_cancel_callback') # payload = PayPalPayload(self.request, 'SetExpressCheckout') # payload.add_payment_info(amount) # payload.add_callbacks(return_url, cancel_url) # # response = requests.post(self.nvp_url, data=payload) # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return data['TOKEN'][0] # # def get_express_checkout_url(self, token): # url = self.express_checkout_url + '?cmd=_express-checkout&token=%s' # return url % token # # def get_express_checkout_details(self, token, payerid): # payload = PayPalPayload(self.request, 'GetExpressCheckoutDetails') # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # amount = data['AMT'][0] # amount = int(amount.split('.')[0]) # return { # 'amount': amount, # 'firstname': data['FIRSTNAME'][0], # 'lastname': data['LASTNAME'][0], # 'city': data['SHIPTOCITY'][0], # 'country': data['SHIPTOCOUNTRYNAME'][0], # 'state': data['SHIPTOSTATE'][0], # 'street': data['SHIPTOSTREET'][0], # 'zip': data['SHIPTOZIP'][0], # 'email': data['EMAIL'][0], # } # # def do_express_checkout_payment(self, token, payerid, amount): # payload = PayPalPayload(self.request, 'DoExpressCheckoutPayment') # payload.add_payment_info(amount) # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return True # # return False # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): . Output only the next line.
donation = create_donation(request, request.POST)
Based on the snippet: <|code_start|> donation = create_donation(request, request.POST) send_thankyou_email(request, donation) send_notification_to_admins(request, donation) request.session.flash( _('Thank you very much for your great contribution'), 'success', ) else: request.session.flash(error_msg, 'error') return HTTPFound(location=request.route_path('contributions_index')) elif 'cancel' in request.POST: return HTTPFound(location=request.route_path('contributions_paypal_cancel_callback')) else: return HTTPBadRequest('Wrong action') else: token = request.GET.get('token', None) payerid = request.GET.get('PayerID', None) if token and payerid: paypal = PayPalExpressCheckout(request) details = paypal.get_express_checkout_details(token, payerid) details.update({ 'token': token, 'payerid': payerid, }) amount = details['amount'] <|code_end|> , predict the immediate next line with the help of imports: import random from pyramid.httpexceptions import HTTPBadRequest, HTTPFound from pyramid.i18n import get_locale_name from pyramid.view import view_config from yithlibraryserver.contributions.email import send_thankyou_email from yithlibraryserver.contributions.email import send_notification_to_admins from yithlibraryserver.contributions.models import create_donation from yithlibraryserver.contributions.models import include_sticker from yithlibraryserver.contributions.paypal import PayPalExpressCheckout from yithlibraryserver.i18n import TranslationString as _ and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/contributions/email.py # def send_thankyou_email(request, donation): # return send_email( # request, # 'yithlibraryserver.contributions:templates/email_thankyou', # donation, # 'Thanks for your contribution!', # [donation['email']], # ) # # Path: yithlibraryserver/contributions/email.py # def send_notification_to_admins(request, donation): # context = { # 'home_link': request.route_url('home'), # } # context.update(donation) # return send_email_to_admins( # request, # 'yithlibraryserver.contributions:templates/email_admin_notification', # context, # 'A new donation was received!', # ) # # Path: yithlibraryserver/contributions/models.py # def create_donation(request, data): # amount = int(data['amount']) # donation = { # 'amount': amount, # 'firstname': data['firstname'], # 'lastname': data['lastname'], # 'city': data['city'], # 'country': data['country'], # 'state': data['state'], # 'street': data['street'], # 'zip': data['zip'], # 'email': data['email'], # 'creation': request.datetime_service.utcnow(), # } # if include_sticker(amount): # donation['send_sticker'] = not ('no-sticker' in data) # else: # donation['send_sticker'] = False # # if request.user is not None: # donation['user'] = request.user['_id'] # else: # donation['user'] = None # # _id = request.db.donations.insert(donation, safe=True) # donation['_id'] = _id # return donation # # Path: yithlibraryserver/contributions/models.py # def include_sticker(amount): # return amount > 1 # # Path: yithlibraryserver/contributions/paypal.py # class PayPalExpressCheckout(object): # # def __init__(self, request): # self.request = request # self.nvp_url = request.registry.settings['paypal_nvp_url'] # self.express_checkout_url = request.registry.settings['paypal_express_checkout_url'] # # def get_express_checkout_token(self, amount): # return_url = self.request.route_url('contributions_paypal_success_callback') # cancel_url = self.request.route_url('contributions_paypal_cancel_callback') # payload = PayPalPayload(self.request, 'SetExpressCheckout') # payload.add_payment_info(amount) # payload.add_callbacks(return_url, cancel_url) # # response = requests.post(self.nvp_url, data=payload) # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return data['TOKEN'][0] # # def get_express_checkout_url(self, token): # url = self.express_checkout_url + '?cmd=_express-checkout&token=%s' # return url % token # # def get_express_checkout_details(self, token, payerid): # payload = PayPalPayload(self.request, 'GetExpressCheckoutDetails') # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # amount = data['AMT'][0] # amount = int(amount.split('.')[0]) # return { # 'amount': amount, # 'firstname': data['FIRSTNAME'][0], # 'lastname': data['LASTNAME'][0], # 'city': data['SHIPTOCITY'][0], # 'country': data['SHIPTOCOUNTRYNAME'][0], # 'state': data['SHIPTOSTATE'][0], # 'street': data['SHIPTOSTREET'][0], # 'zip': data['SHIPTOZIP'][0], # 'email': data['EMAIL'][0], # } # # def do_express_checkout_payment(self, token, payerid, amount): # payload = PayPalPayload(self.request, 'DoExpressCheckoutPayment') # payload.add_payment_info(amount) # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return True # # return False # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): . Output only the next line.
details['include_sticker'] = include_sticker(amount)
Continue the code snippet: <|code_start|> @view_config(route_name='contributions_index', renderer='templates/contributions_index.pt') def contributions_index(request): locale_name = get_locale_name(request) return {'locale': locale_name, 'random': random} @view_config(route_name='contributions_donate', renderer='string') def contributions_donate(request): if 'submit' in request.POST: paypal = PayPalExpressCheckout(request) amount = request.POST.get('amount', '1') try: amount = int(amount) except ValueError: return HTTPBadRequest('Amount must be an integer') token = paypal.get_express_checkout_token(amount) return HTTPFound(paypal.get_express_checkout_url(token)) return HTTPBadRequest('Wrong action or method') @view_config(route_name='contributions_paypal_success_callback', renderer='templates/contributions_confirm.pt') def contributions_paypal_success(request): <|code_end|> . Use current file imports: import random from pyramid.httpexceptions import HTTPBadRequest, HTTPFound from pyramid.i18n import get_locale_name from pyramid.view import view_config from yithlibraryserver.contributions.email import send_thankyou_email from yithlibraryserver.contributions.email import send_notification_to_admins from yithlibraryserver.contributions.models import create_donation from yithlibraryserver.contributions.models import include_sticker from yithlibraryserver.contributions.paypal import PayPalExpressCheckout from yithlibraryserver.i18n import TranslationString as _ and context (classes, functions, or code) from other files: # Path: yithlibraryserver/contributions/email.py # def send_thankyou_email(request, donation): # return send_email( # request, # 'yithlibraryserver.contributions:templates/email_thankyou', # donation, # 'Thanks for your contribution!', # [donation['email']], # ) # # Path: yithlibraryserver/contributions/email.py # def send_notification_to_admins(request, donation): # context = { # 'home_link': request.route_url('home'), # } # context.update(donation) # return send_email_to_admins( # request, # 'yithlibraryserver.contributions:templates/email_admin_notification', # context, # 'A new donation was received!', # ) # # Path: yithlibraryserver/contributions/models.py # def create_donation(request, data): # amount = int(data['amount']) # donation = { # 'amount': amount, # 'firstname': data['firstname'], # 'lastname': data['lastname'], # 'city': data['city'], # 'country': data['country'], # 'state': data['state'], # 'street': data['street'], # 'zip': data['zip'], # 'email': data['email'], # 'creation': request.datetime_service.utcnow(), # } # if include_sticker(amount): # donation['send_sticker'] = not ('no-sticker' in data) # else: # donation['send_sticker'] = False # # if request.user is not None: # donation['user'] = request.user['_id'] # else: # donation['user'] = None # # _id = request.db.donations.insert(donation, safe=True) # donation['_id'] = _id # return donation # # Path: yithlibraryserver/contributions/models.py # def include_sticker(amount): # return amount > 1 # # Path: yithlibraryserver/contributions/paypal.py # class PayPalExpressCheckout(object): # # def __init__(self, request): # self.request = request # self.nvp_url = request.registry.settings['paypal_nvp_url'] # self.express_checkout_url = request.registry.settings['paypal_express_checkout_url'] # # def get_express_checkout_token(self, amount): # return_url = self.request.route_url('contributions_paypal_success_callback') # cancel_url = self.request.route_url('contributions_paypal_cancel_callback') # payload = PayPalPayload(self.request, 'SetExpressCheckout') # payload.add_payment_info(amount) # payload.add_callbacks(return_url, cancel_url) # # response = requests.post(self.nvp_url, data=payload) # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return data['TOKEN'][0] # # def get_express_checkout_url(self, token): # url = self.express_checkout_url + '?cmd=_express-checkout&token=%s' # return url % token # # def get_express_checkout_details(self, token, payerid): # payload = PayPalPayload(self.request, 'GetExpressCheckoutDetails') # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # amount = data['AMT'][0] # amount = int(amount.split('.')[0]) # return { # 'amount': amount, # 'firstname': data['FIRSTNAME'][0], # 'lastname': data['LASTNAME'][0], # 'city': data['SHIPTOCITY'][0], # 'country': data['SHIPTOCOUNTRYNAME'][0], # 'state': data['SHIPTOSTATE'][0], # 'street': data['SHIPTOSTREET'][0], # 'zip': data['SHIPTOZIP'][0], # 'email': data['EMAIL'][0], # } # # def do_express_checkout_payment(self, token, payerid, amount): # payload = PayPalPayload(self.request, 'DoExpressCheckoutPayment') # payload.add_payment_info(amount) # payload.add_token(token, payerid) # # response = requests.post(self.nvp_url, data=payload) # # if response.ok: # data = urlparse.parse_qs(response.text) # ack = data['ACK'][0] # if ack == 'Success': # return True # # return False # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): . Output only the next line.
error_msg = _('There was a problem in the confirmation process. Please start the checkout again')
Predict the next line for this snippet: <|code_start|># # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def get_user_info(settings, user_id, oauth_token): user_info_url = settings['twitter_user_info_url'] params = ( ('oauth_token', oauth_token), ) auth = auth_header('GET', user_info_url, params, settings, oauth_token) response = requests.get( <|code_end|> with the help of current file imports: import requests from pyramid.httpexceptions import HTTPUnauthorized from yithlibraryserver.compat import url_encode from yithlibraryserver.twitter.authorization import auth_header and context from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/twitter/authorization.py # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header , which may contain function names, class names, or code. Output only the next line.
user_info_url + '?' + url_encode({'user_id': user_id}),
Continue the code snippet: <|code_start|># Copyright (C) 2012-2013 Yaco Sistemas # Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def get_user_info(settings, user_id, oauth_token): user_info_url = settings['twitter_user_info_url'] params = ( ('oauth_token', oauth_token), ) <|code_end|> . Use current file imports: import requests from pyramid.httpexceptions import HTTPUnauthorized from yithlibraryserver.compat import url_encode from yithlibraryserver.twitter.authorization import auth_header and context (classes, functions, or code) from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/twitter/authorization.py # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header . Output only the next line.
auth = auth_header('GET', user_info_url, params, settings, oauth_token)
Given the following code snippet before the placeholder: <|code_start|> self['PAYMENTREQUEST_0_DESC'] = 'Donation' self['PAYMENTREQUEST_0_CURRENCYCODE'] = 'USD' self['PAYMENTREQUEST_0_PAYMENTACTION'] = 'Sale' self['LOCALECODE'] = 'ES' def add_callbacks(self, return_url, cancel_url): self['RETURNURL'] = return_url self['CANCELURL'] = cancel_url def add_token(self, token, payerid): self['TOKEN'] = token self['PAYERID'] = payerid class PayPalExpressCheckout(object): def __init__(self, request): self.request = request self.nvp_url = request.registry.settings['paypal_nvp_url'] self.express_checkout_url = request.registry.settings['paypal_express_checkout_url'] def get_express_checkout_token(self, amount): return_url = self.request.route_url('contributions_paypal_success_callback') cancel_url = self.request.route_url('contributions_paypal_cancel_callback') payload = PayPalPayload(self.request, 'SetExpressCheckout') payload.add_payment_info(amount) payload.add_callbacks(return_url, cancel_url) response = requests.post(self.nvp_url, data=payload) if response.ok: <|code_end|> , predict the next line using imports from the current file: import requests from yithlibraryserver.compat import urlparse and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover . Output only the next line.
data = urlparse.parse_qs(response.text)
Predict the next line after this snippet: <|code_start|># # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class DummyRegistry(object): def __init__(self, **kwargs): self.settings = kwargs class GoogleAnalyticsTests(unittest.TestCase): def test_enabled(self): request = DummyRequest() request.session = {} request.registry = DummyRegistry(google_analytics_code='1234') <|code_end|> using the current file's imports: import unittest from pyramid.testing import DummyRequest from yithlibraryserver.user.analytics import GoogleAnalytics from yithlibraryserver.user.analytics import get_google_analytics from yithlibraryserver.user.analytics import USER_ATTR and any relevant context from other files: # Path: yithlibraryserver/user/analytics.py # class GoogleAnalytics(object): # # def __init__(self, request): # self.request = request # # @property # def enabled(self): # code = self.request.registry.settings['google_analytics_code'] # return code is not None # # @property # def first_time(self): # if self.request.user is None: # return USER_ATTR not in self.request.session # else: # return USER_ATTR not in self.request.user # # def show_in_session(self): # return self.request.session.get(USER_ATTR, False) # # def show_in_user(self, user): # return user.get(USER_ATTR, False) # # def is_in_session(self): # return USER_ATTR in self.request.session # # def is_stored_in_user(self, user): # return USER_ATTR in user # # @property # def show(self): # user = self.request.user # if user is None: # return self.show_in_session() # else: # return self.show_in_user(user) # # def clean_session(self): # if USER_ATTR in self.request.session: # del self.request.session[USER_ATTR] # # def get_user_attr(self, value): # return {USER_ATTR: value} # # Path: yithlibraryserver/user/analytics.py # def get_google_analytics(request): # return GoogleAnalytics(request) # # Path: yithlibraryserver/user/analytics.py # USER_ATTR = 'allow_google_analytics' . Output only the next line.
ga = GoogleAnalytics(request)
Based on the snippet: <|code_start|> request.session = {USER_ATTR: True} request.user = {USER_ATTR: False} ga = GoogleAnalytics(request) self.assertFalse(ga.show) def test_clean_session(self): request = DummyRequest() request.session = {} request.user = None ga = GoogleAnalytics(request) ga.clean_session() self.assertEqual(request.session, {}) request = DummyRequest() request.session = {USER_ATTR: True} request.user = None ga = GoogleAnalytics(request) ga.clean_session() self.assertEqual(request.session, {}) def test_get_user_attr(self): request = DummyRequest() request.session = {} request.user = None ga = GoogleAnalytics(request) self.assertEqual(ga.get_user_attr(True), {USER_ATTR: True}) self.assertEqual(ga.get_user_attr(False), {USER_ATTR: False}) def test_get_google_analytics(self): request = DummyRequest() <|code_end|> , predict the immediate next line with the help of imports: import unittest from pyramid.testing import DummyRequest from yithlibraryserver.user.analytics import GoogleAnalytics from yithlibraryserver.user.analytics import get_google_analytics from yithlibraryserver.user.analytics import USER_ATTR and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/user/analytics.py # class GoogleAnalytics(object): # # def __init__(self, request): # self.request = request # # @property # def enabled(self): # code = self.request.registry.settings['google_analytics_code'] # return code is not None # # @property # def first_time(self): # if self.request.user is None: # return USER_ATTR not in self.request.session # else: # return USER_ATTR not in self.request.user # # def show_in_session(self): # return self.request.session.get(USER_ATTR, False) # # def show_in_user(self, user): # return user.get(USER_ATTR, False) # # def is_in_session(self): # return USER_ATTR in self.request.session # # def is_stored_in_user(self, user): # return USER_ATTR in user # # @property # def show(self): # user = self.request.user # if user is None: # return self.show_in_session() # else: # return self.show_in_user(user) # # def clean_session(self): # if USER_ATTR in self.request.session: # del self.request.session[USER_ATTR] # # def get_user_attr(self, value): # return {USER_ATTR: value} # # Path: yithlibraryserver/user/analytics.py # def get_google_analytics(request): # return GoogleAnalytics(request) # # Path: yithlibraryserver/user/analytics.py # USER_ATTR = 'allow_google_analytics' . Output only the next line.
ga = get_google_analytics(request)
Predict the next line for this snippet: <|code_start|> class DummyRegistry(object): def __init__(self, **kwargs): self.settings = kwargs class GoogleAnalyticsTests(unittest.TestCase): def test_enabled(self): request = DummyRequest() request.session = {} request.registry = DummyRegistry(google_analytics_code='1234') ga = GoogleAnalytics(request) self.assertTrue(ga.enabled) request = DummyRequest() request.session = {} request.registry = DummyRegistry(google_analytics_code=None) ga = GoogleAnalytics(request) self.assertFalse(ga.enabled) def test_first_time(self): request = DummyRequest() request.session = {} request.user = None ga = GoogleAnalytics(request) self.assertTrue(ga.first_time) request = DummyRequest() <|code_end|> with the help of current file imports: import unittest from pyramid.testing import DummyRequest from yithlibraryserver.user.analytics import GoogleAnalytics from yithlibraryserver.user.analytics import get_google_analytics from yithlibraryserver.user.analytics import USER_ATTR and context from other files: # Path: yithlibraryserver/user/analytics.py # class GoogleAnalytics(object): # # def __init__(self, request): # self.request = request # # @property # def enabled(self): # code = self.request.registry.settings['google_analytics_code'] # return code is not None # # @property # def first_time(self): # if self.request.user is None: # return USER_ATTR not in self.request.session # else: # return USER_ATTR not in self.request.user # # def show_in_session(self): # return self.request.session.get(USER_ATTR, False) # # def show_in_user(self, user): # return user.get(USER_ATTR, False) # # def is_in_session(self): # return USER_ATTR in self.request.session # # def is_stored_in_user(self, user): # return USER_ATTR in user # # @property # def show(self): # user = self.request.user # if user is None: # return self.show_in_session() # else: # return self.show_in_user(user) # # def clean_session(self): # if USER_ATTR in self.request.session: # del self.request.session[USER_ATTR] # # def get_user_attr(self, value): # return {USER_ATTR: value} # # Path: yithlibraryserver/user/analytics.py # def get_google_analytics(request): # return GoogleAnalytics(request) # # Path: yithlibraryserver/user/analytics.py # USER_ATTR = 'allow_google_analytics' , which may contain function names, class names, or code. Output only the next line.
request.session = {USER_ATTR: True}
Given snippet: <|code_start|> log = logging.getLogger(__name__) @view_config(route_name='home', renderer='templates/home.pt') def home(request): return {} @view_config(route_name='contact', renderer='templates/contact.pt') def contact(request): button1 = Button('submit', _('Send message')) button1.css_class = 'btn-primary' button2 = Button('cancel', _('Cancel')) button2.css_class = '' form = Form(ContactSchema(), buttons=(button1, button2)) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render()} context = {'link': request.route_url('contact')} context.update(appstruct) subject= ("%s sent a message from Yith's contact form" % appstruct['name']) <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from deform import Button, Form, ValidationFailure from pyramid.i18n import get_locale_name from pyramid.httpexceptions import HTTPFound from pyramid.renderers import render_to_response from pyramid.view import view_config from yithlibraryserver.email import send_email_to_admins from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.schemas import ContactSchema and context: # Path: yithlibraryserver/email.py # def send_email_to_admins(request, template, context, subject, # attachments=None, extra_headers=None): # admin_emails = request.registry.settings['admin_emails'] # if admin_emails: # return send_email(request, template, context, subject, admin_emails, # attachments, extra_headers) # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/schemas.py # class ContactSchema(colander.MappingSchema): # # name = colander.SchemaNode(colander.String(), title=_('Name')) # email = colander.SchemaNode(colander.String(), title=_('Email')) # message = colander.SchemaNode( # colander.String(), # widget=TextAreaWidget(css_class='input-xxlarge', rows=10), # title=_('Message'), # ) which might include code, classes, or functions. Output only the next line.
result = send_email_to_admins(
Using the snippet: <|code_start|># # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. log = logging.getLogger(__name__) @view_config(route_name='home', renderer='templates/home.pt') def home(request): return {} @view_config(route_name='contact', renderer='templates/contact.pt') def contact(request): <|code_end|> , determine the next line of code. You have imports: import logging from deform import Button, Form, ValidationFailure from pyramid.i18n import get_locale_name from pyramid.httpexceptions import HTTPFound from pyramid.renderers import render_to_response from pyramid.view import view_config from yithlibraryserver.email import send_email_to_admins from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.schemas import ContactSchema and context (class names, function names, or code) available: # Path: yithlibraryserver/email.py # def send_email_to_admins(request, template, context, subject, # attachments=None, extra_headers=None): # admin_emails = request.registry.settings['admin_emails'] # if admin_emails: # return send_email(request, template, context, subject, admin_emails, # attachments, extra_headers) # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/schemas.py # class ContactSchema(colander.MappingSchema): # # name = colander.SchemaNode(colander.String(), title=_('Name')) # email = colander.SchemaNode(colander.String(), title=_('Email')) # message = colander.SchemaNode( # colander.String(), # widget=TextAreaWidget(css_class='input-xxlarge', rows=10), # title=_('Message'), # ) . Output only the next line.
button1 = Button('submit', _('Send message'))
Given the following code snippet before the placeholder: <|code_start|># the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. log = logging.getLogger(__name__) @view_config(route_name='home', renderer='templates/home.pt') def home(request): return {} @view_config(route_name='contact', renderer='templates/contact.pt') def contact(request): button1 = Button('submit', _('Send message')) button1.css_class = 'btn-primary' button2 = Button('cancel', _('Cancel')) button2.css_class = '' <|code_end|> , predict the next line using imports from the current file: import logging from deform import Button, Form, ValidationFailure from pyramid.i18n import get_locale_name from pyramid.httpexceptions import HTTPFound from pyramid.renderers import render_to_response from pyramid.view import view_config from yithlibraryserver.email import send_email_to_admins from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.schemas import ContactSchema and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/email.py # def send_email_to_admins(request, template, context, subject, # attachments=None, extra_headers=None): # admin_emails = request.registry.settings['admin_emails'] # if admin_emails: # return send_email(request, template, context, subject, admin_emails, # attachments, extra_headers) # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/schemas.py # class ContactSchema(colander.MappingSchema): # # name = colander.SchemaNode(colander.String(), title=_('Name')) # email = colander.SchemaNode(colander.String(), title=_('Email')) # message = colander.SchemaNode( # colander.String(), # widget=TextAreaWidget(css_class='input-xxlarge', rows=10), # title=_('Message'), # ) . Output only the next line.
form = Form(ContactSchema(), buttons=(button1, button2))
Based on the snippet: <|code_start|> return str(uuid.uuid4()) def store(self, db, user): result = db.users.update({'_id': user['_id']}, { '$set': {'email_verification_code': self.code}, }, safe=True) return result['n'] == 1 def remove(self, db, email, verified): result = db.users.update({ 'email_verification_code': self.code, 'email': email, }, { '$unset': {'email_verification_code': 1}, '$set': {'email_verified': verified}, }, safe=True) return result['n'] == 1 def verify(self, db, email): result = db.users.find_one({ 'email': email, 'email_verification_code': self.code, }) return result is not None def send(self, request, user, url): context = { 'link': '%s?code=%s&email=%s' % (url, self.code, user['email']), 'user': user, } <|code_end|> , predict the immediate next line with the help of imports: import uuid from yithlibraryserver.email import send_email and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/email.py # def send_email(request, template, context, subject, recipients, # attachments=None, extra_headers=None): # message = create_message(request, template, context, subject, recipients, # attachments, extra_headers) # return get_mailer(request).send(message) . Output only the next line.
return send_email(
Predict the next line after this snippet: <|code_start|># # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class DeformTranslatorTests(unittest.TestCase): def setUp(self): request = testing.DummyRequest() testing.setUp(request=request) def tearDown(self): testing.tearDown() def test_deform_translator(self): <|code_end|> using the current file's imports: import unittest from webtest import TestRequest from pyramid import testing from yithlibraryserver.i18n import deform_translator, locale_negotiator from yithlibraryserver.testing import TestCase and any relevant context from other files: # Path: yithlibraryserver/i18n.py # def deform_translator(term): # return get_localizer(get_current_request()).translate(term) # # def locale_negotiator(request): # available_languages = request.registry.settings['available_languages'] # return request.accept_language.best_match(available_languages) # # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) . Output only the next line.
self.assertEqual('foo', deform_translator('foo'))
Given snippet: <|code_start|># Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class DeformTranslatorTests(unittest.TestCase): def setUp(self): request = testing.DummyRequest() testing.setUp(request=request) def tearDown(self): testing.tearDown() def test_deform_translator(self): self.assertEqual('foo', deform_translator('foo')) class LocaleNegotiatorTests(TestCase): def test_locale_negotiator(self): request = TestRequest.blank('', {}, headers={}) request.registry = self.testapp.app.registry <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from webtest import TestRequest from pyramid import testing from yithlibraryserver.i18n import deform_translator, locale_negotiator from yithlibraryserver.testing import TestCase and context: # Path: yithlibraryserver/i18n.py # def deform_translator(term): # return get_localizer(get_current_request()).translate(term) # # def locale_negotiator(request): # available_languages = request.registry.settings['available_languages'] # return request.accept_language.best_match(available_languages) # # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) which might include code, classes, or functions. Output only the next line.
self.assertEqual(locale_negotiator(request), 'en')
Given the following code snippet before the placeholder: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. migration_registry = {} def migration(fnc): migration_registry[fnc.__name__] = fnc return fnc def add_attribute(collection, obj, obj_repr, attribute, value): if attribute not in obj: <|code_end|> , predict the next line using imports from the current file: import optparse import textwrap import sys from pyramid.paster import bootstrap from yithlibraryserver.scripts.utils import safe_print from yithlibraryserver.scripts.utils import get_user_display_name and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/scripts/utils.py # def safe_print(value): # if PY3: # pragma: no cover # print(value) # else: # pragma: no cover # print(value.encode('utf-8')) # # Path: yithlibraryserver/scripts/utils.py # def get_user_display_name(user): # return '%s %s <%s>' % (user.get('first_name', ''), # user.get('last_name', ''), # user.get('email', '')) . Output only the next line.
safe_print('Adding attribute "%s" to %s' % (attribute, obj_repr))
Next line prediction: <|code_start|># 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. migration_registry = {} def migration(fnc): migration_registry[fnc.__name__] = fnc return fnc def add_attribute(collection, obj, obj_repr, attribute, value): if attribute not in obj: safe_print('Adding attribute "%s" to %s' % (attribute, obj_repr)) collection.update( {'_id': obj['_id']}, {'$set': {attribute: value}}, safe=True, ) @migration def add_send_email_preference(db): for user in db.users.find(): <|code_end|> . Use current file imports: (import optparse import textwrap import sys from pyramid.paster import bootstrap from yithlibraryserver.scripts.utils import safe_print from yithlibraryserver.scripts.utils import get_user_display_name) and context including class names, function names, or small code snippets from other files: # Path: yithlibraryserver/scripts/utils.py # def safe_print(value): # if PY3: # pragma: no cover # print(value) # else: # pragma: no cover # print(value.encode('utf-8')) # # Path: yithlibraryserver/scripts/utils.py # def get_user_display_name(user): # return '%s %s <%s>' % (user.get('first_name', ''), # user.get('last_name', ''), # user.get('email', '')) . Output only the next line.
add_attribute(db.users, user, get_user_display_name(user),
Based on the snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class FakeDateServiceTests(unittest.TestCase): def assertDateEqual(self, date1, date2): delta = date2 - date1 self.assertEqual(delta.days, 0) def test_dateservice(self): <|code_end|> , predict the immediate next line with the help of imports: import os import datetime import unittest from yithlibraryserver.datetimeservice.testing import FakeDateService, get_fake_date from yithlibraryserver.datetimeservice.testing import FakeDatetimeService, get_fake_datetime and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/datetimeservice/testing.py # class FakeDateService(object): # # def __init__(self, request): # self.request = request # # def today(self): # fake = os.environ['YITH_FAKE_DATE'] # parts = [int(p) for p in fake.split('-')] # return datetime.date(*parts) # # def get_fake_date(request): # return FakeDateService(request) # # Path: yithlibraryserver/datetimeservice/testing.py # class FakeDatetimeService(object): # # def __init__(self, request): # self.request = request # # def utcnow(self): # fake = os.environ['YITH_FAKE_DATETIME'] # parts = [int(p) for p in fake.split('-')] # return datetime.datetime(*parts) # # def get_fake_datetime(request): # return FakeDatetimeService(request) . Output only the next line.
ds = FakeDateService(None)
Given the following code snippet before the placeholder: <|code_start|># (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class FakeDateServiceTests(unittest.TestCase): def assertDateEqual(self, date1, date2): delta = date2 - date1 self.assertEqual(delta.days, 0) def test_dateservice(self): ds = FakeDateService(None) fake_today = datetime.date(2012, 1, 10) os.environ['YITH_FAKE_DATE'] = '2012-1-10' self.assertTrue(isinstance(ds.today(), datetime.date)) self.assertDateEqual(ds.today(), fake_today) del os.environ['YITH_FAKE_DATE'] def test_get_fake_date(self): request = object() <|code_end|> , predict the next line using imports from the current file: import os import datetime import unittest from yithlibraryserver.datetimeservice.testing import FakeDateService, get_fake_date from yithlibraryserver.datetimeservice.testing import FakeDatetimeService, get_fake_datetime and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/datetimeservice/testing.py # class FakeDateService(object): # # def __init__(self, request): # self.request = request # # def today(self): # fake = os.environ['YITH_FAKE_DATE'] # parts = [int(p) for p in fake.split('-')] # return datetime.date(*parts) # # def get_fake_date(request): # return FakeDateService(request) # # Path: yithlibraryserver/datetimeservice/testing.py # class FakeDatetimeService(object): # # def __init__(self, request): # self.request = request # # def utcnow(self): # fake = os.environ['YITH_FAKE_DATETIME'] # parts = [int(p) for p in fake.split('-')] # return datetime.datetime(*parts) # # def get_fake_datetime(request): # return FakeDatetimeService(request) . Output only the next line.
date = get_fake_date(request)
Here is a snippet: <|code_start|> class FakeDateServiceTests(unittest.TestCase): def assertDateEqual(self, date1, date2): delta = date2 - date1 self.assertEqual(delta.days, 0) def test_dateservice(self): ds = FakeDateService(None) fake_today = datetime.date(2012, 1, 10) os.environ['YITH_FAKE_DATE'] = '2012-1-10' self.assertTrue(isinstance(ds.today(), datetime.date)) self.assertDateEqual(ds.today(), fake_today) del os.environ['YITH_FAKE_DATE'] def test_get_fake_date(self): request = object() date = get_fake_date(request) self.assertTrue(isinstance(date, FakeDateService)) self.assertEqual(date.request, request) class FakeDatetimeServiceTests(unittest.TestCase): def assertDatetimeEqual(self, datetime1, datetime2): delta = datetime2 - datetime1 self.assertEqual(delta.days, 0) self.assertTrue(delta.seconds < 2) def test_fakedatetimeservice(self): <|code_end|> . Write the next line using the current file imports: import os import datetime import unittest from yithlibraryserver.datetimeservice.testing import FakeDateService, get_fake_date from yithlibraryserver.datetimeservice.testing import FakeDatetimeService, get_fake_datetime and context from other files: # Path: yithlibraryserver/datetimeservice/testing.py # class FakeDateService(object): # # def __init__(self, request): # self.request = request # # def today(self): # fake = os.environ['YITH_FAKE_DATE'] # parts = [int(p) for p in fake.split('-')] # return datetime.date(*parts) # # def get_fake_date(request): # return FakeDateService(request) # # Path: yithlibraryserver/datetimeservice/testing.py # class FakeDatetimeService(object): # # def __init__(self, request): # self.request = request # # def utcnow(self): # fake = os.environ['YITH_FAKE_DATETIME'] # parts = [int(p) for p in fake.split('-')] # return datetime.datetime(*parts) # # def get_fake_datetime(request): # return FakeDatetimeService(request) , which may include functions, classes, or code. Output only the next line.
ds = FakeDatetimeService(None)
Here is a snippet: <|code_start|> fake_today = datetime.date(2012, 1, 10) os.environ['YITH_FAKE_DATE'] = '2012-1-10' self.assertTrue(isinstance(ds.today(), datetime.date)) self.assertDateEqual(ds.today(), fake_today) del os.environ['YITH_FAKE_DATE'] def test_get_fake_date(self): request = object() date = get_fake_date(request) self.assertTrue(isinstance(date, FakeDateService)) self.assertEqual(date.request, request) class FakeDatetimeServiceTests(unittest.TestCase): def assertDatetimeEqual(self, datetime1, datetime2): delta = datetime2 - datetime1 self.assertEqual(delta.days, 0) self.assertTrue(delta.seconds < 2) def test_fakedatetimeservice(self): ds = FakeDatetimeService(None) os.environ['YITH_FAKE_DATETIME'] = '2012-1-10-14-23-01' fake_utcnow = datetime.datetime(2012, 1, 10, 14, 23, 1, 0) self.assertTrue(isinstance(ds.utcnow(), datetime.datetime)) self.assertDatetimeEqual(ds.utcnow(), fake_utcnow) del os.environ['YITH_FAKE_DATETIME'] def test_get_fakedatetime(self): request = object() <|code_end|> . Write the next line using the current file imports: import os import datetime import unittest from yithlibraryserver.datetimeservice.testing import FakeDateService, get_fake_date from yithlibraryserver.datetimeservice.testing import FakeDatetimeService, get_fake_datetime and context from other files: # Path: yithlibraryserver/datetimeservice/testing.py # class FakeDateService(object): # # def __init__(self, request): # self.request = request # # def today(self): # fake = os.environ['YITH_FAKE_DATE'] # parts = [int(p) for p in fake.split('-')] # return datetime.date(*parts) # # def get_fake_date(request): # return FakeDateService(request) # # Path: yithlibraryserver/datetimeservice/testing.py # class FakeDatetimeService(object): # # def __init__(self, request): # self.request = request # # def utcnow(self): # fake = os.environ['YITH_FAKE_DATETIME'] # parts = [int(p) for p in fake.split('-')] # return datetime.datetime(*parts) # # def get_fake_datetime(request): # return FakeDatetimeService(request) , which may include functions, classes, or code. Output only the next line.
datetime = get_fake_datetime(request)
Using the snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2012-2013 Yaco Sistemas # Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class AuthorizationTests(unittest.TestCase): def test_quote(self): self.assertEqual(quote('a test'), 'a%20test') self.assertEqual(quote('a/test'), 'a%2Ftest') def test_nonce(self): <|code_end|> , determine the next line of code. You have imports: import time import unittest from yithlibraryserver.twitter.authorization import quote, nonce, timestamp from yithlibraryserver.twitter.authorization import sign, auth_header and context (class names, function names, or code) available: # Path: yithlibraryserver/twitter/authorization.py # def quote(value): # return url_quote(value, safe='') # # def nonce(length=8): # return ''.join([str(random.randint(0, 9)) for i in range(length)]) # # def timestamp(): # return int(time.time()) # # Path: yithlibraryserver/twitter/authorization.py # def sign(method, url, original_params, consumer_secret, oauth_token): # # 1. create the parameter string # param_string = '&'.join(['%s=%s' % (key, value) # for key, value in sorted(original_params)]) # # # 2. create signature base string # signature_base = '%s&%s&%s' % ( # method.upper(), quote(url), quote(param_string), # ) # # # 3. create the signature key # key = '%s&%s' % (quote(consumer_secret), quote(oauth_token)) # # # 4. calculate the signature # hashed = hmac.new(key.encode('ascii'), # signature_base.encode('ascii'), # hashlib.sha1) # return quote(binascii.b2a_base64(hashed.digest())[:-1]) # # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header . Output only the next line.
self.assertEqual(len(nonce()), 8)
Predict the next line after this snippet: <|code_start|># This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class AuthorizationTests(unittest.TestCase): def test_quote(self): self.assertEqual(quote('a test'), 'a%20test') self.assertEqual(quote('a/test'), 'a%2Ftest') def test_nonce(self): self.assertEqual(len(nonce()), 8) self.assertEqual(len(nonce(10)), 10) self.assertNotEqual(nonce(), nonce()) def test_timestamp(self): <|code_end|> using the current file's imports: import time import unittest from yithlibraryserver.twitter.authorization import quote, nonce, timestamp from yithlibraryserver.twitter.authorization import sign, auth_header and any relevant context from other files: # Path: yithlibraryserver/twitter/authorization.py # def quote(value): # return url_quote(value, safe='') # # def nonce(length=8): # return ''.join([str(random.randint(0, 9)) for i in range(length)]) # # def timestamp(): # return int(time.time()) # # Path: yithlibraryserver/twitter/authorization.py # def sign(method, url, original_params, consumer_secret, oauth_token): # # 1. create the parameter string # param_string = '&'.join(['%s=%s' % (key, value) # for key, value in sorted(original_params)]) # # # 2. create signature base string # signature_base = '%s&%s&%s' % ( # method.upper(), quote(url), quote(param_string), # ) # # # 3. create the signature key # key = '%s&%s' % (quote(consumer_secret), quote(oauth_token)) # # # 4. calculate the signature # hashed = hmac.new(key.encode('ascii'), # signature_base.encode('ascii'), # hashlib.sha1) # return quote(binascii.b2a_base64(hashed.digest())[:-1]) # # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header . Output only the next line.
t1 = timestamp()
Given snippet: <|code_start|> def test_nonce(self): self.assertEqual(len(nonce()), 8) self.assertEqual(len(nonce(10)), 10) self.assertNotEqual(nonce(), nonce()) def test_timestamp(self): t1 = timestamp() time.sleep(1) t2 = timestamp() self.assertTrue(t2 > t1) def test_sign(self): # this example is taken from # https://dev.twitter.com/docs/auth/creating-signature method = 'post' url = 'https://api.twitter.com/1/statuses/update.json' params = ( ('status', quote('Hello Ladies + Gentlemen, a signed OAuth request!')), ('include_entities', quote('true')), ('oauth_consumer_key', quote('xvz1evFS4wEEPTGEFPHBog')), ('oauth_nonce', quote('kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg')), ('oauth_signature_method', quote('HMAC-SHA1')), ('oauth_timestamp', quote('1318622958')), ('oauth_token', quote('370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb')), ('oauth_version', quote('1.0')), ) consumer_secret = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw' oauth_token = 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE' <|code_end|> , continue by predicting the next line. Consider current file imports: import time import unittest from yithlibraryserver.twitter.authorization import quote, nonce, timestamp from yithlibraryserver.twitter.authorization import sign, auth_header and context: # Path: yithlibraryserver/twitter/authorization.py # def quote(value): # return url_quote(value, safe='') # # def nonce(length=8): # return ''.join([str(random.randint(0, 9)) for i in range(length)]) # # def timestamp(): # return int(time.time()) # # Path: yithlibraryserver/twitter/authorization.py # def sign(method, url, original_params, consumer_secret, oauth_token): # # 1. create the parameter string # param_string = '&'.join(['%s=%s' % (key, value) # for key, value in sorted(original_params)]) # # # 2. create signature base string # signature_base = '%s&%s&%s' % ( # method.upper(), quote(url), quote(param_string), # ) # # # 3. create the signature key # key = '%s&%s' % (quote(consumer_secret), quote(oauth_token)) # # # 4. calculate the signature # hashed = hmac.new(key.encode('ascii'), # signature_base.encode('ascii'), # hashlib.sha1) # return quote(binascii.b2a_base64(hashed.digest())[:-1]) # # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header which might include code, classes, or functions. Output only the next line.
self.assertEqual(sign(method, url, params,
Using the snippet: <|code_start|> params = ( ('status', quote('Hello Ladies + Gentlemen, a signed OAuth request!')), ('include_entities', quote('true')), ('oauth_consumer_key', quote('xvz1evFS4wEEPTGEFPHBog')), ('oauth_nonce', quote('kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg')), ('oauth_signature_method', quote('HMAC-SHA1')), ('oauth_timestamp', quote('1318622958')), ('oauth_token', quote('370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb')), ('oauth_version', quote('1.0')), ) consumer_secret = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw' oauth_token = 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE' self.assertEqual(sign(method, url, params, consumer_secret, oauth_token), quote('tnnArxj06cWHq44gCs1OSKk/jLY=')) def test_auth_header(self): # this example is taken from # https://dev.twitter.com/docs/auth/implementing-sign-twitter settings = { 'twitter_consumer_key': 'cChZNFj6T5R0TigYB9yd1w', 'twitter_consumer_secret': 'L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg', } params = ( ('oauth_callback', 'http://localhost/sign-in-with-twitter/'), ) token = '' nc = 'ea9ec8429b68d6b77cd5600adbbb0456' ts = 1318467427 <|code_end|> , determine the next line of code. You have imports: import time import unittest from yithlibraryserver.twitter.authorization import quote, nonce, timestamp from yithlibraryserver.twitter.authorization import sign, auth_header and context (class names, function names, or code) available: # Path: yithlibraryserver/twitter/authorization.py # def quote(value): # return url_quote(value, safe='') # # def nonce(length=8): # return ''.join([str(random.randint(0, 9)) for i in range(length)]) # # def timestamp(): # return int(time.time()) # # Path: yithlibraryserver/twitter/authorization.py # def sign(method, url, original_params, consumer_secret, oauth_token): # # 1. create the parameter string # param_string = '&'.join(['%s=%s' % (key, value) # for key, value in sorted(original_params)]) # # # 2. create signature base string # signature_base = '%s&%s&%s' % ( # method.upper(), quote(url), quote(param_string), # ) # # # 3. create the signature key # key = '%s&%s' % (quote(consumer_secret), quote(oauth_token)) # # # 4. calculate the signature # hashed = hmac.new(key.encode('ascii'), # signature_base.encode('ascii'), # hashlib.sha1) # return quote(binascii.b2a_base64(hashed.digest())[:-1]) # # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header . Output only the next line.
res = auth_header('post', 'https://api.twitter.com/oauth/request_token',
Predict the next line after this snippet: <|code_start|> def test_send_passwords(self): preferences_link = 'http://localhost/preferences' backups_link = 'http://localhost/backups' user_id = self.db.users.insert({ 'first_name': 'John', 'last_name': 'Doe', 'email': 'john@example.com', }, safe=True) user = self.db.users.find_one({'_id': user_id}) request = DummyRequest() request.db = self.db mailer = get_mailer(request) self.assertFalse(send_passwords(request, user, preferences_link, backups_link)) self.assertEqual(len(mailer.outbox), 0) # add some passwords self.db.passwords.insert({ 'owner': user_id, 'password': 'secret1', }) self.db.passwords.insert({ 'owner': user_id, 'password': 'secret2', }) request = DummyRequest() request.db = self.db <|code_end|> using the current file's imports: import os import unittest import bson from pyramid import testing from pyramid.testing import DummyRequest from pyramid_mailer import get_mailer from yithlibraryserver.datetimeservice.testing import FakeDateService from yithlibraryserver.backups.email import get_day_to_send, send_passwords from yithlibraryserver.testing import TestCase and any relevant context from other files: # Path: yithlibraryserver/datetimeservice/testing.py # class FakeDateService(object): # # def __init__(self, request): # self.request = request # # def today(self): # fake = os.environ['YITH_FAKE_DATE'] # parts = [int(p) for p in fake.split('-')] # return datetime.date(*parts) # # Path: yithlibraryserver/backups/email.py # def get_day_to_send(user, days_of_month): # """Sum the ordinal of each character in user._id % days_of_month""" # return sum([ord(chr) for chr in str(user['_id'])]) % days_of_month # # def send_passwords(request, user, preferences_link, backups_link): # passwords = get_user_passwords(request.db, user) # if not passwords: # return False # # context = { # 'user': user, # 'preferences_link': preferences_link, # 'backups_link': backups_link, # } # # today = request.date_service.today() # attachment = Attachment(get_backup_filename(today), # "application/yith", # compress(passwords)) # # send_email( # request, # 'yithlibraryserver.backups:templates/email_passwords', # context, # "Your Yith Library's passwords", # [user['email']], # attachments=[attachment], # ) # # return True # # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) . Output only the next line.
request.date_service = FakeDateService(request)
Given snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class GetDayToSendTests(unittest.TestCase): def test_get_day_to_send(self): user = {} user['_id'] = bson.objectid.ObjectId('000000000000000000000001') <|code_end|> , continue by predicting the next line. Consider current file imports: import os import unittest import bson from pyramid import testing from pyramid.testing import DummyRequest from pyramid_mailer import get_mailer from yithlibraryserver.datetimeservice.testing import FakeDateService from yithlibraryserver.backups.email import get_day_to_send, send_passwords from yithlibraryserver.testing import TestCase and context: # Path: yithlibraryserver/datetimeservice/testing.py # class FakeDateService(object): # # def __init__(self, request): # self.request = request # # def today(self): # fake = os.environ['YITH_FAKE_DATE'] # parts = [int(p) for p in fake.split('-')] # return datetime.date(*parts) # # Path: yithlibraryserver/backups/email.py # def get_day_to_send(user, days_of_month): # """Sum the ordinal of each character in user._id % days_of_month""" # return sum([ord(chr) for chr in str(user['_id'])]) % days_of_month # # def send_passwords(request, user, preferences_link, backups_link): # passwords = get_user_passwords(request.db, user) # if not passwords: # return False # # context = { # 'user': user, # 'preferences_link': preferences_link, # 'backups_link': backups_link, # } # # today = request.date_service.today() # attachment = Attachment(get_backup_filename(today), # "application/yith", # compress(passwords)) # # send_email( # request, # 'yithlibraryserver.backups:templates/email_passwords', # context, # "Your Yith Library's passwords", # [user['email']], # attachments=[attachment], # ) # # return True # # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) which might include code, classes, or functions. Output only the next line.
self.assertEqual(5, get_day_to_send(user, 28))
Given snippet: <|code_start|> return month month = fill_month(30, 1000) empty_days = [i for i, d in enumerate(month) if d == 0] self.assertEqual(empty_days, []) class SendPasswordsTests(TestCase): clean_collections = ('users', 'passwords', ) def setUp(self): self.config = testing.setUp() self.config.include('pyramid_mailer.testing') super(SendPasswordsTests, self).setUp() def test_send_passwords(self): preferences_link = 'http://localhost/preferences' backups_link = 'http://localhost/backups' user_id = self.db.users.insert({ 'first_name': 'John', 'last_name': 'Doe', 'email': 'john@example.com', }, safe=True) user = self.db.users.find_one({'_id': user_id}) request = DummyRequest() request.db = self.db mailer = get_mailer(request) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import unittest import bson from pyramid import testing from pyramid.testing import DummyRequest from pyramid_mailer import get_mailer from yithlibraryserver.datetimeservice.testing import FakeDateService from yithlibraryserver.backups.email import get_day_to_send, send_passwords from yithlibraryserver.testing import TestCase and context: # Path: yithlibraryserver/datetimeservice/testing.py # class FakeDateService(object): # # def __init__(self, request): # self.request = request # # def today(self): # fake = os.environ['YITH_FAKE_DATE'] # parts = [int(p) for p in fake.split('-')] # return datetime.date(*parts) # # Path: yithlibraryserver/backups/email.py # def get_day_to_send(user, days_of_month): # """Sum the ordinal of each character in user._id % days_of_month""" # return sum([ord(chr) for chr in str(user['_id'])]) % days_of_month # # def send_passwords(request, user, preferences_link, backups_link): # passwords = get_user_passwords(request.db, user) # if not passwords: # return False # # context = { # 'user': user, # 'preferences_link': preferences_link, # 'backups_link': backups_link, # } # # today = request.date_service.today() # attachment = Attachment(get_backup_filename(today), # "application/yith", # compress(passwords)) # # send_email( # request, # 'yithlibraryserver.backups:templates/email_passwords', # context, # "Your Yith Library's passwords", # [user['email']], # attachments=[attachment], # ) # # return True # # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) which might include code, classes, or functions. Output only the next line.
self.assertFalse(send_passwords(request, user,
Here is a snippet: <|code_start|># This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. DEFAULT_MONGODB_HOST = 'localhost' DEFAULT_MONGODB_PORT = 27017 DEFAULT_MONGODB_NAME = 'yith-library' DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST, DEFAULT_MONGODB_PORT, DEFAULT_MONGODB_NAME) class MongoDB(object): """Simple wrapper to get pymongo real objects from the settings uri""" def __init__(self, db_uri=DEFAULT_MONGODB_URI, connection_factory=pymongo.Connection): <|code_end|> . Write the next line using the current file imports: import pymongo from yithlibraryserver.compat import urlparse and context from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover , which may include functions, classes, or code. Output only the next line.
self.db_uri = urlparse.urlparse(db_uri)
Next line prediction: <|code_start|># Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. @view_config(route_name='backups_index', renderer='templates/backups_index.pt', permission='backups') def backups_index(request): return {} @view_config(route_name='backups_export', permission='backups') def backups_export(request): passwords = get_user_passwords(request.db, request.user) data = compress(passwords) response = Response(body=data, content_type='application/yith-library') today = request.date_service.today() <|code_end|> . Use current file imports: (from pyramid.i18n import get_localizer from pyramid.httpexceptions import HTTPFound from pyramid.response import Response from pyramid.view import view_config from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import get_user_passwords from yithlibraryserver.backups.utils import compress, uncompress from yithlibraryserver.i18n import translation_domain from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.password.models import PasswordsManager) and context including class names, function names, or small code snippets from other files: # Path: yithlibraryserver/backups/utils.py # def get_backup_filename(date): # return 'yith-library-backup-%d-%02d-%02d.yith' % ( # date.year, date.month, date.day) # # Path: yithlibraryserver/backups/utils.py # def get_user_passwords(db, user): # passwords_manager = PasswordsManager(db) # return [remove_attrs(password, 'owner', '_id') # for password in passwords_manager.retrieve(user)] # # Path: yithlibraryserver/backups/utils.py # def compress(passwords): # buf = BytesIO() # gzip_data = gzip.GzipFile(fileobj=buf, mode='wb') # data = json.dumps(passwords) # gzip_data.write(data.encode('utf-8')) # gzip_data.close() # return buf.getvalue() # # def uncompress(compressed_data): # buf = BytesIO(compressed_data) # gzip_data = gzip.GzipFile(fileobj=buf, mode='rb') # raw_data = gzip_data.read() # return json.loads(raw_data.decode('utf-8')) # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/password/models.py # class PasswordsManager(object): # # def __init__(self, db): # self.db = db # # def create(self, user, password): # """Creates and returns a new password or a set of passwords. # # Stores the password in the database for this specific user # and returns a new dict with the 'owner' and '_id' fields # filled. # # If password is a list, do the same with each password in # this list. # """ # if isinstance(password, dict): # if password: # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # _id = self.db.passwords.insert(new_password, safe=True) # new_password['_id'] = _id # return new_password # else: # new_passwords = [] # copy since we are changing this object # for p in password: # if p: # p = dict(p) # p['owner'] = user['_id'] # new_passwords.append(p) # # if new_passwords: # # _ids = self.db.passwords.insert(new_passwords, safe=True) # # for i in range(len(new_passwords)): # new_passwords[i]['_id'] = _ids[i] # # return new_passwords # # def retrieve(self, user, _id=None): # """Return the user's passwords or just one. # # If _id is None return the whole set of passwords for this # user. Otherwise, it returns the password with that _id. # """ # if _id is None: # return self.db.passwords.find({'owner': user['_id']}) # else: # return self.db.passwords.find_one({ # '_id': _id, # 'owner': user['_id'], # }) # # def update(self, user, _id, password): # """Update a password in the database. # # Return the updated password on success or None if the original # password does not exist. # """ # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # result = self.db.passwords.update({ # '_id': _id, # 'owner': user['_id'], # }, new_password, safe=True) # new_password['_id'] = _id # # # result['n'] is the number of documents updated # # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue # if result['n'] == 1: # return new_password # else: # return None # # def delete(self, user, _id=None): # """Deletes a password from the database or the whole set for this user. # # Returns True if the delete is succesfull or False otherwise. # """ # query = {'owner': user['_id']} # if _id is not None: # query['_id'] = _id # # result = self.db.passwords.remove(query, safe=True) # return result['n'] > 0 . Output only the next line.
filename = get_backup_filename(today)
Based on the snippet: <|code_start|># Copyright (C) 2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. @view_config(route_name='backups_index', renderer='templates/backups_index.pt', permission='backups') def backups_index(request): return {} @view_config(route_name='backups_export', permission='backups') def backups_export(request): <|code_end|> , predict the immediate next line with the help of imports: from pyramid.i18n import get_localizer from pyramid.httpexceptions import HTTPFound from pyramid.response import Response from pyramid.view import view_config from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import get_user_passwords from yithlibraryserver.backups.utils import compress, uncompress from yithlibraryserver.i18n import translation_domain from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.password.models import PasswordsManager and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/backups/utils.py # def get_backup_filename(date): # return 'yith-library-backup-%d-%02d-%02d.yith' % ( # date.year, date.month, date.day) # # Path: yithlibraryserver/backups/utils.py # def get_user_passwords(db, user): # passwords_manager = PasswordsManager(db) # return [remove_attrs(password, 'owner', '_id') # for password in passwords_manager.retrieve(user)] # # Path: yithlibraryserver/backups/utils.py # def compress(passwords): # buf = BytesIO() # gzip_data = gzip.GzipFile(fileobj=buf, mode='wb') # data = json.dumps(passwords) # gzip_data.write(data.encode('utf-8')) # gzip_data.close() # return buf.getvalue() # # def uncompress(compressed_data): # buf = BytesIO(compressed_data) # gzip_data = gzip.GzipFile(fileobj=buf, mode='rb') # raw_data = gzip_data.read() # return json.loads(raw_data.decode('utf-8')) # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/password/models.py # class PasswordsManager(object): # # def __init__(self, db): # self.db = db # # def create(self, user, password): # """Creates and returns a new password or a set of passwords. # # Stores the password in the database for this specific user # and returns a new dict with the 'owner' and '_id' fields # filled. # # If password is a list, do the same with each password in # this list. # """ # if isinstance(password, dict): # if password: # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # _id = self.db.passwords.insert(new_password, safe=True) # new_password['_id'] = _id # return new_password # else: # new_passwords = [] # copy since we are changing this object # for p in password: # if p: # p = dict(p) # p['owner'] = user['_id'] # new_passwords.append(p) # # if new_passwords: # # _ids = self.db.passwords.insert(new_passwords, safe=True) # # for i in range(len(new_passwords)): # new_passwords[i]['_id'] = _ids[i] # # return new_passwords # # def retrieve(self, user, _id=None): # """Return the user's passwords or just one. # # If _id is None return the whole set of passwords for this # user. Otherwise, it returns the password with that _id. # """ # if _id is None: # return self.db.passwords.find({'owner': user['_id']}) # else: # return self.db.passwords.find_one({ # '_id': _id, # 'owner': user['_id'], # }) # # def update(self, user, _id, password): # """Update a password in the database. # # Return the updated password on success or None if the original # password does not exist. # """ # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # result = self.db.passwords.update({ # '_id': _id, # 'owner': user['_id'], # }, new_password, safe=True) # new_password['_id'] = _id # # # result['n'] is the number of documents updated # # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue # if result['n'] == 1: # return new_password # else: # return None # # def delete(self, user, _id=None): # """Deletes a password from the database or the whole set for this user. # # Returns True if the delete is succesfull or False otherwise. # """ # query = {'owner': user['_id']} # if _id is not None: # query['_id'] = _id # # result = self.db.passwords.remove(query, safe=True) # return result['n'] > 0 . Output only the next line.
passwords = get_user_passwords(request.db, request.user)
Next line prediction: <|code_start|># # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. @view_config(route_name='backups_index', renderer='templates/backups_index.pt', permission='backups') def backups_index(request): return {} @view_config(route_name='backups_export', permission='backups') def backups_export(request): passwords = get_user_passwords(request.db, request.user) <|code_end|> . Use current file imports: (from pyramid.i18n import get_localizer from pyramid.httpexceptions import HTTPFound from pyramid.response import Response from pyramid.view import view_config from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import get_user_passwords from yithlibraryserver.backups.utils import compress, uncompress from yithlibraryserver.i18n import translation_domain from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.password.models import PasswordsManager) and context including class names, function names, or small code snippets from other files: # Path: yithlibraryserver/backups/utils.py # def get_backup_filename(date): # return 'yith-library-backup-%d-%02d-%02d.yith' % ( # date.year, date.month, date.day) # # Path: yithlibraryserver/backups/utils.py # def get_user_passwords(db, user): # passwords_manager = PasswordsManager(db) # return [remove_attrs(password, 'owner', '_id') # for password in passwords_manager.retrieve(user)] # # Path: yithlibraryserver/backups/utils.py # def compress(passwords): # buf = BytesIO() # gzip_data = gzip.GzipFile(fileobj=buf, mode='wb') # data = json.dumps(passwords) # gzip_data.write(data.encode('utf-8')) # gzip_data.close() # return buf.getvalue() # # def uncompress(compressed_data): # buf = BytesIO(compressed_data) # gzip_data = gzip.GzipFile(fileobj=buf, mode='rb') # raw_data = gzip_data.read() # return json.loads(raw_data.decode('utf-8')) # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/password/models.py # class PasswordsManager(object): # # def __init__(self, db): # self.db = db # # def create(self, user, password): # """Creates and returns a new password or a set of passwords. # # Stores the password in the database for this specific user # and returns a new dict with the 'owner' and '_id' fields # filled. # # If password is a list, do the same with each password in # this list. # """ # if isinstance(password, dict): # if password: # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # _id = self.db.passwords.insert(new_password, safe=True) # new_password['_id'] = _id # return new_password # else: # new_passwords = [] # copy since we are changing this object # for p in password: # if p: # p = dict(p) # p['owner'] = user['_id'] # new_passwords.append(p) # # if new_passwords: # # _ids = self.db.passwords.insert(new_passwords, safe=True) # # for i in range(len(new_passwords)): # new_passwords[i]['_id'] = _ids[i] # # return new_passwords # # def retrieve(self, user, _id=None): # """Return the user's passwords or just one. # # If _id is None return the whole set of passwords for this # user. Otherwise, it returns the password with that _id. # """ # if _id is None: # return self.db.passwords.find({'owner': user['_id']}) # else: # return self.db.passwords.find_one({ # '_id': _id, # 'owner': user['_id'], # }) # # def update(self, user, _id, password): # """Update a password in the database. # # Return the updated password on success or None if the original # password does not exist. # """ # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # result = self.db.passwords.update({ # '_id': _id, # 'owner': user['_id'], # }, new_password, safe=True) # new_password['_id'] = _id # # # result['n'] is the number of documents updated # # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue # if result['n'] == 1: # return new_password # else: # return None # # def delete(self, user, _id=None): # """Deletes a password from the database or the whole set for this user. # # Returns True if the delete is succesfull or False otherwise. # """ # query = {'owner': user['_id']} # if _id is not None: # query['_id'] = _id # # result = self.db.passwords.remove(query, safe=True) # return result['n'] > 0 . Output only the next line.
data = compress(passwords)
Given the following code snippet before the placeholder: <|code_start|> @view_config(route_name='backups_index', renderer='templates/backups_index.pt', permission='backups') def backups_index(request): return {} @view_config(route_name='backups_export', permission='backups') def backups_export(request): passwords = get_user_passwords(request.db, request.user) data = compress(passwords) response = Response(body=data, content_type='application/yith-library') today = request.date_service.today() filename = get_backup_filename(today) response.content_disposition = 'attachment; filename=%s' % filename return response @view_config(route_name='backups_import', renderer='string', permission='backups') def backups_import(request): response = HTTPFound(location=request.route_path('backups_index')) if 'passwords-file' in request.POST: passwords_field = request.POST['passwords-file'] if passwords_field != '': try: <|code_end|> , predict the next line using imports from the current file: from pyramid.i18n import get_localizer from pyramid.httpexceptions import HTTPFound from pyramid.response import Response from pyramid.view import view_config from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import get_user_passwords from yithlibraryserver.backups.utils import compress, uncompress from yithlibraryserver.i18n import translation_domain from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.password.models import PasswordsManager and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/backups/utils.py # def get_backup_filename(date): # return 'yith-library-backup-%d-%02d-%02d.yith' % ( # date.year, date.month, date.day) # # Path: yithlibraryserver/backups/utils.py # def get_user_passwords(db, user): # passwords_manager = PasswordsManager(db) # return [remove_attrs(password, 'owner', '_id') # for password in passwords_manager.retrieve(user)] # # Path: yithlibraryserver/backups/utils.py # def compress(passwords): # buf = BytesIO() # gzip_data = gzip.GzipFile(fileobj=buf, mode='wb') # data = json.dumps(passwords) # gzip_data.write(data.encode('utf-8')) # gzip_data.close() # return buf.getvalue() # # def uncompress(compressed_data): # buf = BytesIO(compressed_data) # gzip_data = gzip.GzipFile(fileobj=buf, mode='rb') # raw_data = gzip_data.read() # return json.loads(raw_data.decode('utf-8')) # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/password/models.py # class PasswordsManager(object): # # def __init__(self, db): # self.db = db # # def create(self, user, password): # """Creates and returns a new password or a set of passwords. # # Stores the password in the database for this specific user # and returns a new dict with the 'owner' and '_id' fields # filled. # # If password is a list, do the same with each password in # this list. # """ # if isinstance(password, dict): # if password: # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # _id = self.db.passwords.insert(new_password, safe=True) # new_password['_id'] = _id # return new_password # else: # new_passwords = [] # copy since we are changing this object # for p in password: # if p: # p = dict(p) # p['owner'] = user['_id'] # new_passwords.append(p) # # if new_passwords: # # _ids = self.db.passwords.insert(new_passwords, safe=True) # # for i in range(len(new_passwords)): # new_passwords[i]['_id'] = _ids[i] # # return new_passwords # # def retrieve(self, user, _id=None): # """Return the user's passwords or just one. # # If _id is None return the whole set of passwords for this # user. Otherwise, it returns the password with that _id. # """ # if _id is None: # return self.db.passwords.find({'owner': user['_id']}) # else: # return self.db.passwords.find_one({ # '_id': _id, # 'owner': user['_id'], # }) # # def update(self, user, _id, password): # """Update a password in the database. # # Return the updated password on success or None if the original # password does not exist. # """ # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # result = self.db.passwords.update({ # '_id': _id, # 'owner': user['_id'], # }, new_password, safe=True) # new_password['_id'] = _id # # # result['n'] is the number of documents updated # # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue # if result['n'] == 1: # return new_password # else: # return None # # def delete(self, user, _id=None): # """Deletes a password from the database or the whole set for this user. # # Returns True if the delete is succesfull or False otherwise. # """ # query = {'owner': user['_id']} # if _id is not None: # query['_id'] = _id # # result = self.db.passwords.remove(query, safe=True) # return result['n'] > 0 . Output only the next line.
json_data = uncompress(passwords_field.file.read())
Given the following code snippet before the placeholder: <|code_start|> response.content_disposition = 'attachment; filename=%s' % filename return response @view_config(route_name='backups_import', renderer='string', permission='backups') def backups_import(request): response = HTTPFound(location=request.route_path('backups_index')) if 'passwords-file' in request.POST: passwords_field = request.POST['passwords-file'] if passwords_field != '': try: json_data = uncompress(passwords_field.file.read()) passwords_manager = PasswordsManager(request.db) passwords_manager.delete(request.user) passwords_manager.create(request.user, json_data) except (IOError, ValueError): request.session.flash( _('There was a problem reading your passwords file'), 'error') return response n_passwords = len(json_data) localizer = get_localizer(request) msg = localizer.pluralize( _('Congratulations, ${n_passwords} password has been imported'), _('Congratulations, ${n_passwords} passwords have been imported'), n_passwords, <|code_end|> , predict the next line using imports from the current file: from pyramid.i18n import get_localizer from pyramid.httpexceptions import HTTPFound from pyramid.response import Response from pyramid.view import view_config from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import get_user_passwords from yithlibraryserver.backups.utils import compress, uncompress from yithlibraryserver.i18n import translation_domain from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.password.models import PasswordsManager and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/backups/utils.py # def get_backup_filename(date): # return 'yith-library-backup-%d-%02d-%02d.yith' % ( # date.year, date.month, date.day) # # Path: yithlibraryserver/backups/utils.py # def get_user_passwords(db, user): # passwords_manager = PasswordsManager(db) # return [remove_attrs(password, 'owner', '_id') # for password in passwords_manager.retrieve(user)] # # Path: yithlibraryserver/backups/utils.py # def compress(passwords): # buf = BytesIO() # gzip_data = gzip.GzipFile(fileobj=buf, mode='wb') # data = json.dumps(passwords) # gzip_data.write(data.encode('utf-8')) # gzip_data.close() # return buf.getvalue() # # def uncompress(compressed_data): # buf = BytesIO(compressed_data) # gzip_data = gzip.GzipFile(fileobj=buf, mode='rb') # raw_data = gzip_data.read() # return json.loads(raw_data.decode('utf-8')) # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/password/models.py # class PasswordsManager(object): # # def __init__(self, db): # self.db = db # # def create(self, user, password): # """Creates and returns a new password or a set of passwords. # # Stores the password in the database for this specific user # and returns a new dict with the 'owner' and '_id' fields # filled. # # If password is a list, do the same with each password in # this list. # """ # if isinstance(password, dict): # if password: # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # _id = self.db.passwords.insert(new_password, safe=True) # new_password['_id'] = _id # return new_password # else: # new_passwords = [] # copy since we are changing this object # for p in password: # if p: # p = dict(p) # p['owner'] = user['_id'] # new_passwords.append(p) # # if new_passwords: # # _ids = self.db.passwords.insert(new_passwords, safe=True) # # for i in range(len(new_passwords)): # new_passwords[i]['_id'] = _ids[i] # # return new_passwords # # def retrieve(self, user, _id=None): # """Return the user's passwords or just one. # # If _id is None return the whole set of passwords for this # user. Otherwise, it returns the password with that _id. # """ # if _id is None: # return self.db.passwords.find({'owner': user['_id']}) # else: # return self.db.passwords.find_one({ # '_id': _id, # 'owner': user['_id'], # }) # # def update(self, user, _id, password): # """Update a password in the database. # # Return the updated password on success or None if the original # password does not exist. # """ # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # result = self.db.passwords.update({ # '_id': _id, # 'owner': user['_id'], # }, new_password, safe=True) # new_password['_id'] = _id # # # result['n'] is the number of documents updated # # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue # if result['n'] == 1: # return new_password # else: # return None # # def delete(self, user, _id=None): # """Deletes a password from the database or the whole set for this user. # # Returns True if the delete is succesfull or False otherwise. # """ # query = {'owner': user['_id']} # if _id is not None: # query['_id'] = _id # # result = self.db.passwords.remove(query, safe=True) # return result['n'] > 0 . Output only the next line.
domain=translation_domain,
Predict the next line after this snippet: <|code_start|> @view_config(route_name='backups_export', permission='backups') def backups_export(request): passwords = get_user_passwords(request.db, request.user) data = compress(passwords) response = Response(body=data, content_type='application/yith-library') today = request.date_service.today() filename = get_backup_filename(today) response.content_disposition = 'attachment; filename=%s' % filename return response @view_config(route_name='backups_import', renderer='string', permission='backups') def backups_import(request): response = HTTPFound(location=request.route_path('backups_index')) if 'passwords-file' in request.POST: passwords_field = request.POST['passwords-file'] if passwords_field != '': try: json_data = uncompress(passwords_field.file.read()) passwords_manager = PasswordsManager(request.db) passwords_manager.delete(request.user) passwords_manager.create(request.user, json_data) except (IOError, ValueError): request.session.flash( <|code_end|> using the current file's imports: from pyramid.i18n import get_localizer from pyramid.httpexceptions import HTTPFound from pyramid.response import Response from pyramid.view import view_config from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import get_user_passwords from yithlibraryserver.backups.utils import compress, uncompress from yithlibraryserver.i18n import translation_domain from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.password.models import PasswordsManager and any relevant context from other files: # Path: yithlibraryserver/backups/utils.py # def get_backup_filename(date): # return 'yith-library-backup-%d-%02d-%02d.yith' % ( # date.year, date.month, date.day) # # Path: yithlibraryserver/backups/utils.py # def get_user_passwords(db, user): # passwords_manager = PasswordsManager(db) # return [remove_attrs(password, 'owner', '_id') # for password in passwords_manager.retrieve(user)] # # Path: yithlibraryserver/backups/utils.py # def compress(passwords): # buf = BytesIO() # gzip_data = gzip.GzipFile(fileobj=buf, mode='wb') # data = json.dumps(passwords) # gzip_data.write(data.encode('utf-8')) # gzip_data.close() # return buf.getvalue() # # def uncompress(compressed_data): # buf = BytesIO(compressed_data) # gzip_data = gzip.GzipFile(fileobj=buf, mode='rb') # raw_data = gzip_data.read() # return json.loads(raw_data.decode('utf-8')) # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/password/models.py # class PasswordsManager(object): # # def __init__(self, db): # self.db = db # # def create(self, user, password): # """Creates and returns a new password or a set of passwords. # # Stores the password in the database for this specific user # and returns a new dict with the 'owner' and '_id' fields # filled. # # If password is a list, do the same with each password in # this list. # """ # if isinstance(password, dict): # if password: # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # _id = self.db.passwords.insert(new_password, safe=True) # new_password['_id'] = _id # return new_password # else: # new_passwords = [] # copy since we are changing this object # for p in password: # if p: # p = dict(p) # p['owner'] = user['_id'] # new_passwords.append(p) # # if new_passwords: # # _ids = self.db.passwords.insert(new_passwords, safe=True) # # for i in range(len(new_passwords)): # new_passwords[i]['_id'] = _ids[i] # # return new_passwords # # def retrieve(self, user, _id=None): # """Return the user's passwords or just one. # # If _id is None return the whole set of passwords for this # user. Otherwise, it returns the password with that _id. # """ # if _id is None: # return self.db.passwords.find({'owner': user['_id']}) # else: # return self.db.passwords.find_one({ # '_id': _id, # 'owner': user['_id'], # }) # # def update(self, user, _id, password): # """Update a password in the database. # # Return the updated password on success or None if the original # password does not exist. # """ # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # result = self.db.passwords.update({ # '_id': _id, # 'owner': user['_id'], # }, new_password, safe=True) # new_password['_id'] = _id # # # result['n'] is the number of documents updated # # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue # if result['n'] == 1: # return new_password # else: # return None # # def delete(self, user, _id=None): # """Deletes a password from the database or the whole set for this user. # # Returns True if the delete is succesfull or False otherwise. # """ # query = {'owner': user['_id']} # if _id is not None: # query['_id'] = _id # # result = self.db.passwords.remove(query, safe=True) # return result['n'] > 0 . Output only the next line.
_('There was a problem reading your passwords file'),
Given snippet: <|code_start|>@view_config(route_name='backups_index', renderer='templates/backups_index.pt', permission='backups') def backups_index(request): return {} @view_config(route_name='backups_export', permission='backups') def backups_export(request): passwords = get_user_passwords(request.db, request.user) data = compress(passwords) response = Response(body=data, content_type='application/yith-library') today = request.date_service.today() filename = get_backup_filename(today) response.content_disposition = 'attachment; filename=%s' % filename return response @view_config(route_name='backups_import', renderer='string', permission='backups') def backups_import(request): response = HTTPFound(location=request.route_path('backups_index')) if 'passwords-file' in request.POST: passwords_field = request.POST['passwords-file'] if passwords_field != '': try: json_data = uncompress(passwords_field.file.read()) <|code_end|> , continue by predicting the next line. Consider current file imports: from pyramid.i18n import get_localizer from pyramid.httpexceptions import HTTPFound from pyramid.response import Response from pyramid.view import view_config from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import get_user_passwords from yithlibraryserver.backups.utils import compress, uncompress from yithlibraryserver.i18n import translation_domain from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.password.models import PasswordsManager and context: # Path: yithlibraryserver/backups/utils.py # def get_backup_filename(date): # return 'yith-library-backup-%d-%02d-%02d.yith' % ( # date.year, date.month, date.day) # # Path: yithlibraryserver/backups/utils.py # def get_user_passwords(db, user): # passwords_manager = PasswordsManager(db) # return [remove_attrs(password, 'owner', '_id') # for password in passwords_manager.retrieve(user)] # # Path: yithlibraryserver/backups/utils.py # def compress(passwords): # buf = BytesIO() # gzip_data = gzip.GzipFile(fileobj=buf, mode='wb') # data = json.dumps(passwords) # gzip_data.write(data.encode('utf-8')) # gzip_data.close() # return buf.getvalue() # # def uncompress(compressed_data): # buf = BytesIO(compressed_data) # gzip_data = gzip.GzipFile(fileobj=buf, mode='rb') # raw_data = gzip_data.read() # return json.loads(raw_data.decode('utf-8')) # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/password/models.py # class PasswordsManager(object): # # def __init__(self, db): # self.db = db # # def create(self, user, password): # """Creates and returns a new password or a set of passwords. # # Stores the password in the database for this specific user # and returns a new dict with the 'owner' and '_id' fields # filled. # # If password is a list, do the same with each password in # this list. # """ # if isinstance(password, dict): # if password: # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # _id = self.db.passwords.insert(new_password, safe=True) # new_password['_id'] = _id # return new_password # else: # new_passwords = [] # copy since we are changing this object # for p in password: # if p: # p = dict(p) # p['owner'] = user['_id'] # new_passwords.append(p) # # if new_passwords: # # _ids = self.db.passwords.insert(new_passwords, safe=True) # # for i in range(len(new_passwords)): # new_passwords[i]['_id'] = _ids[i] # # return new_passwords # # def retrieve(self, user, _id=None): # """Return the user's passwords or just one. # # If _id is None return the whole set of passwords for this # user. Otherwise, it returns the password with that _id. # """ # if _id is None: # return self.db.passwords.find({'owner': user['_id']}) # else: # return self.db.passwords.find_one({ # '_id': _id, # 'owner': user['_id'], # }) # # def update(self, user, _id, password): # """Update a password in the database. # # Return the updated password on success or None if the original # password does not exist. # """ # new_password = dict(password) # copy since we are changing this object # new_password['owner'] = user['_id'] # result = self.db.passwords.update({ # '_id': _id, # 'owner': user['_id'], # }, new_password, safe=True) # new_password['_id'] = _id # # # result['n'] is the number of documents updated # # See <http://www.mongodb.org/display/DOCS/getLastError+Command#getLastErrorCommand-ReturnValue # if result['n'] == 1: # return new_password # else: # return None # # def delete(self, user, _id=None): # """Deletes a password from the database or the whole set for this user. # # Returns True if the delete is succesfull or False otherwise. # """ # query = {'owner': user['_id']} # if _id is not None: # query['_id'] = _id # # result = self.db.passwords.remove(query, safe=True) # return result['n'] > 0 which might include code, classes, or functions. Output only the next line.
passwords_manager = PasswordsManager(request.db)
Continue the code snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2012-2013 Yaco Sistemas # Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class AuthenticationTests(testing.TestCase): clean_collections = ('applications', ) def test_authenticate_client(self): request = testing.FakeRequest(headers={}) # The authorization header is required <|code_end|> . Use current file imports: from pyramid.httpexceptions import HTTPUnauthorized from yithlibraryserver import testing from yithlibraryserver.oauth2.authentication import authenticate_client from yithlibraryserver.oauth2.authentication import auth_basic_encode and context (classes, functions, or code) from other files: # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # class FakeRequest(DummyRequest): # class TestCase(unittest.TestCase): # def __init__(self, *args, **kwargs): # def setUp(self): # def tearDown(self): # def set_user_cookie(self, user_id): # def add_to_session(self, data): # def get_session(self, response): # # Path: yithlibraryserver/oauth2/authentication.py # def authenticate_client(request): # """Returns the client application representing this request. # # Uses the Authorization header in Basic format to identify # the client of this request against the set of registered # applications on the server. # """ # authorization = request.headers.get('Authorization') # if authorization is None: # raise HTTPUnauthorized() # # method, credentials = request.authorization # if method.lower() != 'basic': # raise HTTPUnauthorized() # # credentials = decodebytes(credentials.encode('utf-8')) # credentials = credentials.decode('utf-8') # client_id, client_secret = credentials.split(':') # # application = request.db.applications.find_one({ # 'client_id': client_id, # 'client_secret': client_secret # }) # # if application is None: # raise HTTPUnauthorized() # # return application # # Path: yithlibraryserver/oauth2/authentication.py # def auth_basic_encode(user, password): # value = '%s:%s' % (user, password) # value = 'Basic ' + encodebytes(value.encode('utf-8')).decode('utf-8') # return encode_header(value) . Output only the next line.
self.assertRaises(HTTPUnauthorized, authenticate_client, request)
Predict the next line after this snippet: <|code_start|># it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class AuthenticationTests(testing.TestCase): clean_collections = ('applications', ) def test_authenticate_client(self): request = testing.FakeRequest(headers={}) # The authorization header is required self.assertRaises(HTTPUnauthorized, authenticate_client, request) request = testing.FakeRequest( headers={'Authorization': 'Advanced foobar'}) # Only the basic method is allowed self.assertRaises(HTTPUnauthorized, authenticate_client, request) request = testing.FakeRequest(headers={ <|code_end|> using the current file's imports: from pyramid.httpexceptions import HTTPUnauthorized from yithlibraryserver import testing from yithlibraryserver.oauth2.authentication import authenticate_client from yithlibraryserver.oauth2.authentication import auth_basic_encode and any relevant context from other files: # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # class FakeRequest(DummyRequest): # class TestCase(unittest.TestCase): # def __init__(self, *args, **kwargs): # def setUp(self): # def tearDown(self): # def set_user_cookie(self, user_id): # def add_to_session(self, data): # def get_session(self, response): # # Path: yithlibraryserver/oauth2/authentication.py # def authenticate_client(request): # """Returns the client application representing this request. # # Uses the Authorization header in Basic format to identify # the client of this request against the set of registered # applications on the server. # """ # authorization = request.headers.get('Authorization') # if authorization is None: # raise HTTPUnauthorized() # # method, credentials = request.authorization # if method.lower() != 'basic': # raise HTTPUnauthorized() # # credentials = decodebytes(credentials.encode('utf-8')) # credentials = credentials.decode('utf-8') # client_id, client_secret = credentials.split(':') # # application = request.db.applications.find_one({ # 'client_id': client_id, # 'client_secret': client_secret # }) # # if application is None: # raise HTTPUnauthorized() # # return application # # Path: yithlibraryserver/oauth2/authentication.py # def auth_basic_encode(user, password): # value = '%s:%s' % (user, password) # value = 'Basic ' + encodebytes(value.encode('utf-8')).decode('utf-8') # return encode_header(value) . Output only the next line.
'Authorization': auth_basic_encode('foo', 'bar'),
Next line prediction: <|code_start|>@view_config(route_name='oauth2_developer_application_new', renderer='templates/developer_application_new.pt', permission='add-application') def developer_application_new(request): assert_authenticated_user_is_registered(request) schema = ApplicationSchema() button1 = Button('submit', _('Save application')) button1.css_class = 'btn-primary' button2 = Button('cancel', _('Cancel')) button2.css_class = '' form = Form(schema, buttons=(button1, button2)) if 'submit' in request.POST: controls = request.POST.items() try: appstruct = form.validate(controls) except ValidationFailure as e: return {'form': e.render()} # the data is fine, save into the db application = { 'owner': request.user['_id'], 'name': appstruct['name'], 'main_url': appstruct['main_url'], 'callback_url': appstruct['callback_url'], 'authorized_origins': appstruct['authorized_origins'], 'production_ready': appstruct['production_ready'], 'image_url': appstruct['image_url'], 'description': appstruct['description'], } <|code_end|> . Use current file imports: (import bson from deform import Button, Form, ValidationFailure from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPNotFound from pyramid.httpexceptions import HTTPNotImplemented, HTTPUnauthorized from pyramid.view import view_config from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.oauth2.application import create_client_id_and_secret from yithlibraryserver.oauth2.authentication import authenticate_client from yithlibraryserver.oauth2.authorization import Authorizator from yithlibraryserver.oauth2.schemas import ApplicationSchema from yithlibraryserver.oauth2.schemas import FullApplicationSchema from yithlibraryserver.user.security import assert_authenticated_user_is_registered) and context including class names, function names, or small code snippets from other files: # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/oauth2/application.py # def create_client_id_and_secret(application): # application['client_id'] = str(uuid.uuid4()) # application['client_secret'] = str(uuid.uuid4()) # # Path: yithlibraryserver/oauth2/authentication.py # def authenticate_client(request): # """Returns the client application representing this request. # # Uses the Authorization header in Basic format to identify # the client of this request against the set of registered # applications on the server. # """ # authorization = request.headers.get('Authorization') # if authorization is None: # raise HTTPUnauthorized() # # method, credentials = request.authorization # if method.lower() != 'basic': # raise HTTPUnauthorized() # # credentials = decodebytes(credentials.encode('utf-8')) # credentials = credentials.decode('utf-8') # client_id, client_secret = credentials.split(':') # # application = request.db.applications.find_one({ # 'client_id': client_id, # 'client_secret': client_secret # }) # # if application is None: # raise HTTPUnauthorized() # # return application # # Path: yithlibraryserver/oauth2/authorization.py # class Authorizator(object): # # def __init__(self, db, app): # self.db = db # self.app = app # self.auth_codes = AuthorizationCodes(db) # self.access_codes = AccessCodes(db) # # def is_app_authorized(self, user): # return self.app['_id'] in user['authorized_apps'] # # def store_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$addToSet': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # def remove_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$pull': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # Path: yithlibraryserver/oauth2/schemas.py # class ApplicationSchema(colander.MappingSchema): # # name = colander.SchemaNode(colander.String(), title=_('Name')) # main_url = colander.SchemaNode( # colander.String(), # title=_('Main URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # callback_url = colander.SchemaNode( # colander.String(), # title=_('Callback URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # authorized_origins = AuthorizedOriginsNode( # colander.String(), # title=_('Authorized Origins'), # description=_('One per line. For example https://example.com'), # missing=[], # widget=TextAreaWidget(css_class='input-xlarge'), # ) # production_ready = colander.SchemaNode( # colander.Boolean(), # title=_('Production ready'), # missing=False, # ) # image_url = colander.SchemaNode( # colander.String(), # title=_('Image URL'), # missing='', # widget=TextInputWidget(css_class='input-xlarge'), # ) # description = colander.SchemaNode( # colander.String(), # title=_('Description'), # missing='', # widget=TextAreaWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/oauth2/schemas.py # class FullApplicationSchema(ApplicationSchema): # # client_id = colander.SchemaNode( # colander.String(), # title=_('Client Id'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # client_secret = colander.SchemaNode( # colander.String(), # title=_('Client secret'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/user/security.py # def assert_authenticated_user_is_registered(request): # user_id = authenticated_userid(request) # try: # user = request.db.users.find_one(bson.ObjectId(user_id)) # except bson.errors.InvalidId: # raise HTTPFound(location=request.route_path('register_new_user')) # else: # return User(user) . Output only the next line.
create_client_id_and_secret(application)
Given the code snippet: <|code_start|> return HTTPFound(location=url) else: authorship_information = '' owner_id = app.get('owner', None) if owner_id is not None: owner = request.db.users.find_one({'_id': owner_id}) if owner: email = owner.get('email', None) if email: authorship_information = _('By ${owner}', mapping={'owner': email}) scopes = [SCOPE_NAMES.get(scope, scope) for scope in scope.split(' ')] return { 'response_type': response_type, 'client_id': client_id, 'redirect_uri': redirect_uri, 'scope': scope, 'state': state, 'app': app, 'scopes': scopes, 'authorship_information': authorship_information, } @view_config(route_name='oauth2_token_endpoint', renderer='json') def token_endpoint(request): <|code_end|> , generate the next line using the imports in this file: import bson from deform import Button, Form, ValidationFailure from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPNotFound from pyramid.httpexceptions import HTTPNotImplemented, HTTPUnauthorized from pyramid.view import view_config from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.oauth2.application import create_client_id_and_secret from yithlibraryserver.oauth2.authentication import authenticate_client from yithlibraryserver.oauth2.authorization import Authorizator from yithlibraryserver.oauth2.schemas import ApplicationSchema from yithlibraryserver.oauth2.schemas import FullApplicationSchema from yithlibraryserver.user.security import assert_authenticated_user_is_registered and context (functions, classes, or occasionally code) from other files: # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/oauth2/application.py # def create_client_id_and_secret(application): # application['client_id'] = str(uuid.uuid4()) # application['client_secret'] = str(uuid.uuid4()) # # Path: yithlibraryserver/oauth2/authentication.py # def authenticate_client(request): # """Returns the client application representing this request. # # Uses the Authorization header in Basic format to identify # the client of this request against the set of registered # applications on the server. # """ # authorization = request.headers.get('Authorization') # if authorization is None: # raise HTTPUnauthorized() # # method, credentials = request.authorization # if method.lower() != 'basic': # raise HTTPUnauthorized() # # credentials = decodebytes(credentials.encode('utf-8')) # credentials = credentials.decode('utf-8') # client_id, client_secret = credentials.split(':') # # application = request.db.applications.find_one({ # 'client_id': client_id, # 'client_secret': client_secret # }) # # if application is None: # raise HTTPUnauthorized() # # return application # # Path: yithlibraryserver/oauth2/authorization.py # class Authorizator(object): # # def __init__(self, db, app): # self.db = db # self.app = app # self.auth_codes = AuthorizationCodes(db) # self.access_codes = AccessCodes(db) # # def is_app_authorized(self, user): # return self.app['_id'] in user['authorized_apps'] # # def store_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$addToSet': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # def remove_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$pull': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # Path: yithlibraryserver/oauth2/schemas.py # class ApplicationSchema(colander.MappingSchema): # # name = colander.SchemaNode(colander.String(), title=_('Name')) # main_url = colander.SchemaNode( # colander.String(), # title=_('Main URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # callback_url = colander.SchemaNode( # colander.String(), # title=_('Callback URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # authorized_origins = AuthorizedOriginsNode( # colander.String(), # title=_('Authorized Origins'), # description=_('One per line. For example https://example.com'), # missing=[], # widget=TextAreaWidget(css_class='input-xlarge'), # ) # production_ready = colander.SchemaNode( # colander.Boolean(), # title=_('Production ready'), # missing=False, # ) # image_url = colander.SchemaNode( # colander.String(), # title=_('Image URL'), # missing='', # widget=TextInputWidget(css_class='input-xlarge'), # ) # description = colander.SchemaNode( # colander.String(), # title=_('Description'), # missing='', # widget=TextAreaWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/oauth2/schemas.py # class FullApplicationSchema(ApplicationSchema): # # client_id = colander.SchemaNode( # colander.String(), # title=_('Client Id'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # client_secret = colander.SchemaNode( # colander.String(), # title=_('Client secret'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/user/security.py # def assert_authenticated_user_is_registered(request): # user_id = authenticated_userid(request) # try: # user = request.db.users.find_one(bson.ObjectId(user_id)) # except bson.errors.InvalidId: # raise HTTPFound(location=request.route_path('register_new_user')) # else: # return User(user) . Output only the next line.
app = authenticate_client(request)
Here is a snippet: <|code_start|>def authorization_endpoint(request): response_type = request.params.get('response_type') if response_type is None: return HTTPBadRequest('Missing required response_type') if response_type != 'code': return HTTPNotImplemented('Only code is supported') client_id = request.params.get('client_id') if client_id is None: return HTTPBadRequest('Missing required client_type') app = request.db.applications.find_one({'client_id': client_id}) if app is None: return HTTPNotFound() redirect_uri = request.params.get('redirect_uri') if redirect_uri is None: redirect_uri = app['callback_url'] else: if redirect_uri != app['callback_url']: return HTTPBadRequest( 'Redirect URI does not match registered callback URL') scope = request.params.get('scope', DEFAULT_SCOPE) state = request.params.get('state') user = assert_authenticated_user_is_registered(request) <|code_end|> . Write the next line using the current file imports: import bson from deform import Button, Form, ValidationFailure from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPNotFound from pyramid.httpexceptions import HTTPNotImplemented, HTTPUnauthorized from pyramid.view import view_config from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.oauth2.application import create_client_id_and_secret from yithlibraryserver.oauth2.authentication import authenticate_client from yithlibraryserver.oauth2.authorization import Authorizator from yithlibraryserver.oauth2.schemas import ApplicationSchema from yithlibraryserver.oauth2.schemas import FullApplicationSchema from yithlibraryserver.user.security import assert_authenticated_user_is_registered and context from other files: # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/oauth2/application.py # def create_client_id_and_secret(application): # application['client_id'] = str(uuid.uuid4()) # application['client_secret'] = str(uuid.uuid4()) # # Path: yithlibraryserver/oauth2/authentication.py # def authenticate_client(request): # """Returns the client application representing this request. # # Uses the Authorization header in Basic format to identify # the client of this request against the set of registered # applications on the server. # """ # authorization = request.headers.get('Authorization') # if authorization is None: # raise HTTPUnauthorized() # # method, credentials = request.authorization # if method.lower() != 'basic': # raise HTTPUnauthorized() # # credentials = decodebytes(credentials.encode('utf-8')) # credentials = credentials.decode('utf-8') # client_id, client_secret = credentials.split(':') # # application = request.db.applications.find_one({ # 'client_id': client_id, # 'client_secret': client_secret # }) # # if application is None: # raise HTTPUnauthorized() # # return application # # Path: yithlibraryserver/oauth2/authorization.py # class Authorizator(object): # # def __init__(self, db, app): # self.db = db # self.app = app # self.auth_codes = AuthorizationCodes(db) # self.access_codes = AccessCodes(db) # # def is_app_authorized(self, user): # return self.app['_id'] in user['authorized_apps'] # # def store_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$addToSet': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # def remove_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$pull': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # Path: yithlibraryserver/oauth2/schemas.py # class ApplicationSchema(colander.MappingSchema): # # name = colander.SchemaNode(colander.String(), title=_('Name')) # main_url = colander.SchemaNode( # colander.String(), # title=_('Main URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # callback_url = colander.SchemaNode( # colander.String(), # title=_('Callback URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # authorized_origins = AuthorizedOriginsNode( # colander.String(), # title=_('Authorized Origins'), # description=_('One per line. For example https://example.com'), # missing=[], # widget=TextAreaWidget(css_class='input-xlarge'), # ) # production_ready = colander.SchemaNode( # colander.Boolean(), # title=_('Production ready'), # missing=False, # ) # image_url = colander.SchemaNode( # colander.String(), # title=_('Image URL'), # missing='', # widget=TextInputWidget(css_class='input-xlarge'), # ) # description = colander.SchemaNode( # colander.String(), # title=_('Description'), # missing='', # widget=TextAreaWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/oauth2/schemas.py # class FullApplicationSchema(ApplicationSchema): # # client_id = colander.SchemaNode( # colander.String(), # title=_('Client Id'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # client_secret = colander.SchemaNode( # colander.String(), # title=_('Client secret'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/user/security.py # def assert_authenticated_user_is_registered(request): # user_id = authenticated_userid(request) # try: # user = request.db.users.find_one(bson.ObjectId(user_id)) # except bson.errors.InvalidId: # raise HTTPFound(location=request.route_path('register_new_user')) # else: # return User(user) , which may include functions, classes, or code. Output only the next line.
authorizator = Authorizator(request.db, app)
Given snippet: <|code_start|># You should have received a copy of the GNU Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. DEFAULT_SCOPE = 'passwords' SCOPE_NAMES = { 'passwords': _('Access your passwords'), } @view_config(route_name='oauth2_developer_applications', renderer='templates/developer_applications.pt', permission='view-applications') def developer_applications(request): assert_authenticated_user_is_registered(request) owned_apps_filter = {'owner': request.user['_id']} return { 'applications': request.db.applications.find(owned_apps_filter) } @view_config(route_name='oauth2_developer_application_new', renderer='templates/developer_application_new.pt', permission='add-application') def developer_application_new(request): assert_authenticated_user_is_registered(request) <|code_end|> , continue by predicting the next line. Consider current file imports: import bson from deform import Button, Form, ValidationFailure from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPNotFound from pyramid.httpexceptions import HTTPNotImplemented, HTTPUnauthorized from pyramid.view import view_config from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.oauth2.application import create_client_id_and_secret from yithlibraryserver.oauth2.authentication import authenticate_client from yithlibraryserver.oauth2.authorization import Authorizator from yithlibraryserver.oauth2.schemas import ApplicationSchema from yithlibraryserver.oauth2.schemas import FullApplicationSchema from yithlibraryserver.user.security import assert_authenticated_user_is_registered and context: # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/oauth2/application.py # def create_client_id_and_secret(application): # application['client_id'] = str(uuid.uuid4()) # application['client_secret'] = str(uuid.uuid4()) # # Path: yithlibraryserver/oauth2/authentication.py # def authenticate_client(request): # """Returns the client application representing this request. # # Uses the Authorization header in Basic format to identify # the client of this request against the set of registered # applications on the server. # """ # authorization = request.headers.get('Authorization') # if authorization is None: # raise HTTPUnauthorized() # # method, credentials = request.authorization # if method.lower() != 'basic': # raise HTTPUnauthorized() # # credentials = decodebytes(credentials.encode('utf-8')) # credentials = credentials.decode('utf-8') # client_id, client_secret = credentials.split(':') # # application = request.db.applications.find_one({ # 'client_id': client_id, # 'client_secret': client_secret # }) # # if application is None: # raise HTTPUnauthorized() # # return application # # Path: yithlibraryserver/oauth2/authorization.py # class Authorizator(object): # # def __init__(self, db, app): # self.db = db # self.app = app # self.auth_codes = AuthorizationCodes(db) # self.access_codes = AccessCodes(db) # # def is_app_authorized(self, user): # return self.app['_id'] in user['authorized_apps'] # # def store_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$addToSet': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # def remove_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$pull': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # Path: yithlibraryserver/oauth2/schemas.py # class ApplicationSchema(colander.MappingSchema): # # name = colander.SchemaNode(colander.String(), title=_('Name')) # main_url = colander.SchemaNode( # colander.String(), # title=_('Main URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # callback_url = colander.SchemaNode( # colander.String(), # title=_('Callback URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # authorized_origins = AuthorizedOriginsNode( # colander.String(), # title=_('Authorized Origins'), # description=_('One per line. For example https://example.com'), # missing=[], # widget=TextAreaWidget(css_class='input-xlarge'), # ) # production_ready = colander.SchemaNode( # colander.Boolean(), # title=_('Production ready'), # missing=False, # ) # image_url = colander.SchemaNode( # colander.String(), # title=_('Image URL'), # missing='', # widget=TextInputWidget(css_class='input-xlarge'), # ) # description = colander.SchemaNode( # colander.String(), # title=_('Description'), # missing='', # widget=TextAreaWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/oauth2/schemas.py # class FullApplicationSchema(ApplicationSchema): # # client_id = colander.SchemaNode( # colander.String(), # title=_('Client Id'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # client_secret = colander.SchemaNode( # colander.String(), # title=_('Client secret'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/user/security.py # def assert_authenticated_user_is_registered(request): # user_id = authenticated_userid(request) # try: # user = request.db.users.find_one(bson.ObjectId(user_id)) # except bson.errors.InvalidId: # raise HTTPFound(location=request.route_path('register_new_user')) # else: # return User(user) which might include code, classes, or functions. Output only the next line.
schema = ApplicationSchema()
Continue the code snippet: <|code_start|> request.db.applications.insert(application, safe=True) return HTTPFound( location=request.route_path('oauth2_developer_applications')) elif 'cancel' in request.POST: return HTTPFound( location=request.route_path('oauth2_developer_applications')) # this is a GET return {'form': form.render()} @view_config(route_name='oauth2_developer_application_edit', renderer='templates/developer_application_edit.pt', permission='edit-application') def developer_application_edit(request): try: app_id = bson.ObjectId(request.matchdict['app']) except bson.errors.InvalidId: return HTTPBadRequest(body='Invalid application id') assert_authenticated_user_is_registered(request) app = request.db.applications.find_one(app_id) if app is None: return HTTPNotFound() if app['owner'] != request.user['_id']: return HTTPUnauthorized() <|code_end|> . Use current file imports: import bson from deform import Button, Form, ValidationFailure from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPNotFound from pyramid.httpexceptions import HTTPNotImplemented, HTTPUnauthorized from pyramid.view import view_config from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.oauth2.application import create_client_id_and_secret from yithlibraryserver.oauth2.authentication import authenticate_client from yithlibraryserver.oauth2.authorization import Authorizator from yithlibraryserver.oauth2.schemas import ApplicationSchema from yithlibraryserver.oauth2.schemas import FullApplicationSchema from yithlibraryserver.user.security import assert_authenticated_user_is_registered and context (classes, functions, or code) from other files: # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/oauth2/application.py # def create_client_id_and_secret(application): # application['client_id'] = str(uuid.uuid4()) # application['client_secret'] = str(uuid.uuid4()) # # Path: yithlibraryserver/oauth2/authentication.py # def authenticate_client(request): # """Returns the client application representing this request. # # Uses the Authorization header in Basic format to identify # the client of this request against the set of registered # applications on the server. # """ # authorization = request.headers.get('Authorization') # if authorization is None: # raise HTTPUnauthorized() # # method, credentials = request.authorization # if method.lower() != 'basic': # raise HTTPUnauthorized() # # credentials = decodebytes(credentials.encode('utf-8')) # credentials = credentials.decode('utf-8') # client_id, client_secret = credentials.split(':') # # application = request.db.applications.find_one({ # 'client_id': client_id, # 'client_secret': client_secret # }) # # if application is None: # raise HTTPUnauthorized() # # return application # # Path: yithlibraryserver/oauth2/authorization.py # class Authorizator(object): # # def __init__(self, db, app): # self.db = db # self.app = app # self.auth_codes = AuthorizationCodes(db) # self.access_codes = AccessCodes(db) # # def is_app_authorized(self, user): # return self.app['_id'] in user['authorized_apps'] # # def store_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$addToSet': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # def remove_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$pull': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # Path: yithlibraryserver/oauth2/schemas.py # class ApplicationSchema(colander.MappingSchema): # # name = colander.SchemaNode(colander.String(), title=_('Name')) # main_url = colander.SchemaNode( # colander.String(), # title=_('Main URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # callback_url = colander.SchemaNode( # colander.String(), # title=_('Callback URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # authorized_origins = AuthorizedOriginsNode( # colander.String(), # title=_('Authorized Origins'), # description=_('One per line. For example https://example.com'), # missing=[], # widget=TextAreaWidget(css_class='input-xlarge'), # ) # production_ready = colander.SchemaNode( # colander.Boolean(), # title=_('Production ready'), # missing=False, # ) # image_url = colander.SchemaNode( # colander.String(), # title=_('Image URL'), # missing='', # widget=TextInputWidget(css_class='input-xlarge'), # ) # description = colander.SchemaNode( # colander.String(), # title=_('Description'), # missing='', # widget=TextAreaWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/oauth2/schemas.py # class FullApplicationSchema(ApplicationSchema): # # client_id = colander.SchemaNode( # colander.String(), # title=_('Client Id'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # client_secret = colander.SchemaNode( # colander.String(), # title=_('Client secret'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/user/security.py # def assert_authenticated_user_is_registered(request): # user_id = authenticated_userid(request) # try: # user = request.db.users.find_one(bson.ObjectId(user_id)) # except bson.errors.InvalidId: # raise HTTPFound(location=request.route_path('register_new_user')) # else: # return User(user) . Output only the next line.
schema = FullApplicationSchema()
Predict the next line for this snippet: <|code_start|># This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. DEFAULT_SCOPE = 'passwords' SCOPE_NAMES = { 'passwords': _('Access your passwords'), } @view_config(route_name='oauth2_developer_applications', renderer='templates/developer_applications.pt', permission='view-applications') def developer_applications(request): <|code_end|> with the help of current file imports: import bson from deform import Button, Form, ValidationFailure from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPNotFound from pyramid.httpexceptions import HTTPNotImplemented, HTTPUnauthorized from pyramid.view import view_config from yithlibraryserver.i18n import TranslationString as _ from yithlibraryserver.oauth2.application import create_client_id_and_secret from yithlibraryserver.oauth2.authentication import authenticate_client from yithlibraryserver.oauth2.authorization import Authorizator from yithlibraryserver.oauth2.schemas import ApplicationSchema from yithlibraryserver.oauth2.schemas import FullApplicationSchema from yithlibraryserver.user.security import assert_authenticated_user_is_registered and context from other files: # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): # # Path: yithlibraryserver/oauth2/application.py # def create_client_id_and_secret(application): # application['client_id'] = str(uuid.uuid4()) # application['client_secret'] = str(uuid.uuid4()) # # Path: yithlibraryserver/oauth2/authentication.py # def authenticate_client(request): # """Returns the client application representing this request. # # Uses the Authorization header in Basic format to identify # the client of this request against the set of registered # applications on the server. # """ # authorization = request.headers.get('Authorization') # if authorization is None: # raise HTTPUnauthorized() # # method, credentials = request.authorization # if method.lower() != 'basic': # raise HTTPUnauthorized() # # credentials = decodebytes(credentials.encode('utf-8')) # credentials = credentials.decode('utf-8') # client_id, client_secret = credentials.split(':') # # application = request.db.applications.find_one({ # 'client_id': client_id, # 'client_secret': client_secret # }) # # if application is None: # raise HTTPUnauthorized() # # return application # # Path: yithlibraryserver/oauth2/authorization.py # class Authorizator(object): # # def __init__(self, db, app): # self.db = db # self.app = app # self.auth_codes = AuthorizationCodes(db) # self.access_codes = AccessCodes(db) # # def is_app_authorized(self, user): # return self.app['_id'] in user['authorized_apps'] # # def store_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$addToSet': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # def remove_user_authorization(self, user): # self.db.users.update( # {'_id': user['_id']}, # {'$pull': {'authorized_apps': self.app['_id']}}, # safe=True, # ) # # Path: yithlibraryserver/oauth2/schemas.py # class ApplicationSchema(colander.MappingSchema): # # name = colander.SchemaNode(colander.String(), title=_('Name')) # main_url = colander.SchemaNode( # colander.String(), # title=_('Main URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # callback_url = colander.SchemaNode( # colander.String(), # title=_('Callback URL'), # widget=TextInputWidget(css_class='input-xlarge'), # ) # authorized_origins = AuthorizedOriginsNode( # colander.String(), # title=_('Authorized Origins'), # description=_('One per line. For example https://example.com'), # missing=[], # widget=TextAreaWidget(css_class='input-xlarge'), # ) # production_ready = colander.SchemaNode( # colander.Boolean(), # title=_('Production ready'), # missing=False, # ) # image_url = colander.SchemaNode( # colander.String(), # title=_('Image URL'), # missing='', # widget=TextInputWidget(css_class='input-xlarge'), # ) # description = colander.SchemaNode( # colander.String(), # title=_('Description'), # missing='', # widget=TextAreaWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/oauth2/schemas.py # class FullApplicationSchema(ApplicationSchema): # # client_id = colander.SchemaNode( # colander.String(), # title=_('Client Id'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # client_secret = colander.SchemaNode( # colander.String(), # title=_('Client secret'), # widget=ReadOnlyTextInputWidget(css_class='input-xlarge'), # ) # # Path: yithlibraryserver/user/security.py # def assert_authenticated_user_is_registered(request): # user_id = authenticated_userid(request) # try: # user = request.db.users.find_one(bson.ObjectId(user_id)) # except bson.errors.InvalidId: # raise HTTPFound(location=request.route_path('register_new_user')) # else: # return User(user) , which may contain function names, class names, or code. Output only the next line.
assert_authenticated_user_is_registered(request)
Using the snippet: <|code_start|># Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class AuthorizedOriginsNode(colander.SchemaNode): """Converts a node of type string into and from a list of strings""" def serialize(self, appstruct=colander.null): if not appstruct is colander.null and isinstance(appstruct, list): appstruct = '\n'.join(appstruct) return super(AuthorizedOriginsNode, self).serialize(appstruct) def deserialize(self, cstruct=colander.null): result = super(AuthorizedOriginsNode, self).deserialize(cstruct) <|code_end|> , determine the next line of code. You have imports: import colander from deform.widget import TextAreaWidget, TextInputWidget from yithlibraryserver.compat import string_types from yithlibraryserver.i18n import TranslationString as _ and context (class names, function names, or code) available: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): . Output only the next line.
if not result is colander.null and isinstance(result, string_types):
Based on the snippet: <|code_start|># Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class AuthorizedOriginsNode(colander.SchemaNode): """Converts a node of type string into and from a list of strings""" def serialize(self, appstruct=colander.null): if not appstruct is colander.null and isinstance(appstruct, list): appstruct = '\n'.join(appstruct) return super(AuthorizedOriginsNode, self).serialize(appstruct) def deserialize(self, cstruct=colander.null): result = super(AuthorizedOriginsNode, self).deserialize(cstruct) if not result is colander.null and isinstance(result, string_types): result = [item.strip() for item in result.split('\n') if item.strip()] return result class ApplicationSchema(colander.MappingSchema): <|code_end|> , predict the immediate next line with the help of imports: import colander from deform.widget import TextAreaWidget, TextInputWidget from yithlibraryserver.compat import string_types from yithlibraryserver.i18n import TranslationString as _ and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): . Output only the next line.
name = colander.SchemaNode(colander.String(), title=_('Name'))
Continue the code snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class UserTests(unittest.TestCase): def test_unicode(self): data = {'_id': '1234'} <|code_end|> . Use current file imports: import unittest from yithlibraryserver.compat import text_type from yithlibraryserver.user.models import User and context (classes, functions, or code) from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/user/models.py # class User(dict): # # def __unicode__(self): # result = self.get('screen_name', '') # if result: # return result # # result = ' '.join([self.get('first_name', ''), # self.get('last_name', '')]) # result = result.strip() # if result: # return result # # result = self.get('email', '') # if result: # return result # # return text_type(self['_id']) # # # py3 compatibility # def __str__(self): # return self.__unicode__() . Output only the next line.
self.assertEqual(text_type(User(data)), '1234')
Predict the next line after this snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class UserTests(unittest.TestCase): def test_unicode(self): data = {'_id': '1234'} <|code_end|> using the current file's imports: import unittest from yithlibraryserver.compat import text_type from yithlibraryserver.user.models import User and any relevant context from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/user/models.py # class User(dict): # # def __unicode__(self): # result = self.get('screen_name', '') # if result: # return result # # result = ' '.join([self.get('first_name', ''), # self.get('last_name', '')]) # result = result.strip() # if result: # return result # # result = self.get('email', '') # if result: # return result # # return text_type(self['_id']) # # # py3 compatibility # def __str__(self): # return self.__unicode__() . Output only the next line.
self.assertEqual(text_type(User(data)), '1234')
Predict the next line for this snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class SNACallbackTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() self.config.include('yithlibraryserver') self.config.include('yithlibraryserver.user') self.request = testing.DummyRequest() self.request.session = {} <|code_end|> with the help of current file imports: import unittest from pyramid import testing from yithlibraryserver.db import MongoDB from yithlibraryserver.sna_callbacks import facebook_callback, google_callback from yithlibraryserver.testing import MONGO_URI and context from other files: # Path: yithlibraryserver/db.py # class MongoDB(object): # """Simple wrapper to get pymongo real objects from the settings uri""" # # def __init__(self, db_uri=DEFAULT_MONGODB_URI, # connection_factory=pymongo.Connection): # self.db_uri = urlparse.urlparse(db_uri) # self.connection = connection_factory( # host=self.db_uri.hostname or DEFAULT_MONGODB_HOST, # port=self.db_uri.port or DEFAULT_MONGODB_PORT, # tz_aware=True) # # if self.db_uri.path: # self.database_name = self.db_uri.path[1:] # else: # self.database_name = DEFAULT_MONGODB_NAME # # def get_connection(self): # return self.connection # # def get_database(self): # database = self.connection[self.database_name] # if self.db_uri.username and self.db_uri.password: # database.authenticate(self.db_uri.username, self.db_uri.password) # # return database # # Path: yithlibraryserver/sna_callbacks.py # def facebook_callback(request, user_id, info): # return register_or_update(request, 'facebook', user_id, info, # request.route_path('home')) # # def google_callback(request, user_id, new_info): # return register_or_update(request, 'google', user_id, new_info, # request.route_path('home')) # # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' , which may contain function names, class names, or code. Output only the next line.
mdb = MongoDB(MONGO_URI)
Based on the snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class SNACallbackTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() self.config.include('yithlibraryserver') self.config.include('yithlibraryserver.user') self.request = testing.DummyRequest() self.request.session = {} mdb = MongoDB(MONGO_URI) self.request.db = mdb.get_database() def tearDown(self): testing.tearDown() def test_facebook_callback(self): <|code_end|> , predict the immediate next line with the help of imports: import unittest from pyramid import testing from yithlibraryserver.db import MongoDB from yithlibraryserver.sna_callbacks import facebook_callback, google_callback from yithlibraryserver.testing import MONGO_URI and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/db.py # class MongoDB(object): # """Simple wrapper to get pymongo real objects from the settings uri""" # # def __init__(self, db_uri=DEFAULT_MONGODB_URI, # connection_factory=pymongo.Connection): # self.db_uri = urlparse.urlparse(db_uri) # self.connection = connection_factory( # host=self.db_uri.hostname or DEFAULT_MONGODB_HOST, # port=self.db_uri.port or DEFAULT_MONGODB_PORT, # tz_aware=True) # # if self.db_uri.path: # self.database_name = self.db_uri.path[1:] # else: # self.database_name = DEFAULT_MONGODB_NAME # # def get_connection(self): # return self.connection # # def get_database(self): # database = self.connection[self.database_name] # if self.db_uri.username and self.db_uri.password: # database.authenticate(self.db_uri.username, self.db_uri.password) # # return database # # Path: yithlibraryserver/sna_callbacks.py # def facebook_callback(request, user_id, info): # return register_or_update(request, 'facebook', user_id, info, # request.route_path('home')) # # def google_callback(request, user_id, new_info): # return register_or_update(request, 'google', user_id, new_info, # request.route_path('home')) # # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' . Output only the next line.
result = facebook_callback(self.request, '123', {
Given the code snippet: <|code_start|> class SNACallbackTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() self.config.include('yithlibraryserver') self.config.include('yithlibraryserver.user') self.request = testing.DummyRequest() self.request.session = {} mdb = MongoDB(MONGO_URI) self.request.db = mdb.get_database() def tearDown(self): testing.tearDown() def test_facebook_callback(self): result = facebook_callback(self.request, '123', { 'screen_name': 'John Doe', 'name': 'John Doe', 'email': 'john@example.com', 'username': 'john.doe', 'first_name': 'John', 'last_name': 'Doe', }) self.assertEqual(result.status, '302 Found') self.assertEqual(result.location, '/register') def test_google_callback(self): <|code_end|> , generate the next line using the imports in this file: import unittest from pyramid import testing from yithlibraryserver.db import MongoDB from yithlibraryserver.sna_callbacks import facebook_callback, google_callback from yithlibraryserver.testing import MONGO_URI and context (functions, classes, or occasionally code) from other files: # Path: yithlibraryserver/db.py # class MongoDB(object): # """Simple wrapper to get pymongo real objects from the settings uri""" # # def __init__(self, db_uri=DEFAULT_MONGODB_URI, # connection_factory=pymongo.Connection): # self.db_uri = urlparse.urlparse(db_uri) # self.connection = connection_factory( # host=self.db_uri.hostname or DEFAULT_MONGODB_HOST, # port=self.db_uri.port or DEFAULT_MONGODB_PORT, # tz_aware=True) # # if self.db_uri.path: # self.database_name = self.db_uri.path[1:] # else: # self.database_name = DEFAULT_MONGODB_NAME # # def get_connection(self): # return self.connection # # def get_database(self): # database = self.connection[self.database_name] # if self.db_uri.username and self.db_uri.password: # database.authenticate(self.db_uri.username, self.db_uri.password) # # return database # # Path: yithlibraryserver/sna_callbacks.py # def facebook_callback(request, user_id, info): # return register_or_update(request, 'facebook', user_id, info, # request.route_path('home')) # # def google_callback(request, user_id, new_info): # return register_or_update(request, 'google', user_id, new_info, # request.route_path('home')) # # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' . Output only the next line.
result = google_callback(self.request, '123', {
Predict the next line after this snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class SNACallbackTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() self.config.include('yithlibraryserver') self.config.include('yithlibraryserver.user') self.request = testing.DummyRequest() self.request.session = {} <|code_end|> using the current file's imports: import unittest from pyramid import testing from yithlibraryserver.db import MongoDB from yithlibraryserver.sna_callbacks import facebook_callback, google_callback from yithlibraryserver.testing import MONGO_URI and any relevant context from other files: # Path: yithlibraryserver/db.py # class MongoDB(object): # """Simple wrapper to get pymongo real objects from the settings uri""" # # def __init__(self, db_uri=DEFAULT_MONGODB_URI, # connection_factory=pymongo.Connection): # self.db_uri = urlparse.urlparse(db_uri) # self.connection = connection_factory( # host=self.db_uri.hostname or DEFAULT_MONGODB_HOST, # port=self.db_uri.port or DEFAULT_MONGODB_PORT, # tz_aware=True) # # if self.db_uri.path: # self.database_name = self.db_uri.path[1:] # else: # self.database_name = DEFAULT_MONGODB_NAME # # def get_connection(self): # return self.connection # # def get_database(self): # database = self.connection[self.database_name] # if self.db_uri.username and self.db_uri.password: # database.authenticate(self.db_uri.username, self.db_uri.password) # # return database # # Path: yithlibraryserver/sna_callbacks.py # def facebook_callback(request, user_id, info): # return register_or_update(request, 'facebook', user_id, info, # request.route_path('home')) # # def google_callback(request, user_id, new_info): # return register_or_update(request, 'google', user_id, new_info, # request.route_path('home')) # # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' . Output only the next line.
mdb = MongoDB(MONGO_URI)
Here is a snippet: <|code_start|># # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class MigrationsTests(ScriptTests): clean_collections = ('users', 'passwords', 'applications') def test_migrate_add_send_email_preference(self): # Save sys values old_args = sys.argv[:] old_stdout = sys.stdout # Replace sys argv and stdout sys.argv = [] <|code_end|> . Write the next line using the current file imports: import sys from yithlibraryserver.compat import StringIO from yithlibraryserver.scripts.migrations import migrate from yithlibraryserver.scripts.testing import ScriptTests and context from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/scripts/migrations.py # def migrate(): # usage = "migrate: %prog config_uri migration_name" # description = "Add a 'send_email_periodically' preference to every user." # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if len(args) != 2: # safe_print('You must provide two arguments. ' # 'The first one is the config file and the ' # 'second one is the migration name.') # return 2 # config_uri = args[0] # migration_name = args[1] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # try: # db = settings['mongodb'].get_database() # # if migration_name in migration_registry: # migration = migration_registry[migration_name] # migration(db) # else: # safe_print('The migration "%s" does not exist.' % migration_name) # return 3 # finally: # closer() # # Path: yithlibraryserver/scripts/testing.py # class ScriptTests(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # super(ScriptTests, self).setUp() # # fd, self.conf_file_path = tempfile.mkstemp() # os.write(fd, CONFIG.encode('ascii')) # mdb = MongoDB(MONGO_URI) # self.db = mdb.get_database() # # def tearDown(self): # super(ScriptTests, self).tearDown() # os.unlink(self.conf_file_path) # for col in self.clean_collections: # self.db.drop_collection(col) # # def add_passwords(self, user, n): # for i in range(n): # self.db.passwords.insert({ # 'service': 'service-%d' % (i + 1), # 'secret': 's3cr3t', # 'owner': user, # }) # return user , which may include functions, classes, or code. Output only the next line.
sys.stdout = StringIO()
Continue the code snippet: <|code_start|># Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class MigrationsTests(ScriptTests): clean_collections = ('users', 'passwords', 'applications') def test_migrate_add_send_email_preference(self): # Save sys values old_args = sys.argv[:] old_stdout = sys.stdout # Replace sys argv and stdout sys.argv = [] sys.stdout = StringIO() # Call migrate with no arguments <|code_end|> . Use current file imports: import sys from yithlibraryserver.compat import StringIO from yithlibraryserver.scripts.migrations import migrate from yithlibraryserver.scripts.testing import ScriptTests and context (classes, functions, or code) from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/scripts/migrations.py # def migrate(): # usage = "migrate: %prog config_uri migration_name" # description = "Add a 'send_email_periodically' preference to every user." # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if len(args) != 2: # safe_print('You must provide two arguments. ' # 'The first one is the config file and the ' # 'second one is the migration name.') # return 2 # config_uri = args[0] # migration_name = args[1] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # try: # db = settings['mongodb'].get_database() # # if migration_name in migration_registry: # migration = migration_registry[migration_name] # migration(db) # else: # safe_print('The migration "%s" does not exist.' % migration_name) # return 3 # finally: # closer() # # Path: yithlibraryserver/scripts/testing.py # class ScriptTests(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # super(ScriptTests, self).setUp() # # fd, self.conf_file_path = tempfile.mkstemp() # os.write(fd, CONFIG.encode('ascii')) # mdb = MongoDB(MONGO_URI) # self.db = mdb.get_database() # # def tearDown(self): # super(ScriptTests, self).tearDown() # os.unlink(self.conf_file_path) # for col in self.clean_collections: # self.db.drop_collection(col) # # def add_passwords(self, user, n): # for i in range(n): # self.db.passwords.insert({ # 'service': 'service-%d' % (i + 1), # 'secret': 's3cr3t', # 'owner': user, # }) # return user . Output only the next line.
result = migrate()
Given snippet: <|code_start|> res = self.testapp.post('/profile', { 'submit': 'Save changes', 'first_name': 'John', 'last_name': 'Doe', 'email': 'john@example.com', }) self.assertEqual(res.status, '200 OK') res.mustcontain('There were an error while saving your changes') def test_user_preferences(self): # this view required authentication res = self.testapp.get('/preferences') self.assertEqual(res.status, '200 OK') res.mustcontain('Log in') # Log in date = datetime.datetime(2012, 12, 12, 12, 12) while True: user_id = self.db.users.insert({ 'twitter_id': 'twitter1', 'screen_name': 'John Doe', 'first_name': 'John', 'last_name': 'Doe', 'email': '', 'email_verified': False, 'authorized_apps': [], 'date_joined': date, 'last_login': date, 'allow_google_analytics': False, }, safe=True) <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import os from deform import ValidationFailure from mock import patch from pyramid_mailer import get_mailer from yithlibraryserver.backups.email import get_day_to_send from yithlibraryserver.compat import url_quote from yithlibraryserver.testing import TestCase from yithlibraryserver.user.analytics import USER_ATTR and context: # Path: yithlibraryserver/backups/email.py # def get_day_to_send(user, days_of_month): # """Sum the ordinal of each character in user._id % days_of_month""" # return sum([ord(chr) for chr in str(user['_id'])]) % days_of_month # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) # # Path: yithlibraryserver/user/analytics.py # USER_ATTR = 'allow_google_analytics' which might include code, classes, or functions. Output only the next line.
day = get_day_to_send({'_id': user_id}, 28)
Given the code snippet: <|code_start|> class BadCollection(object): def __init__(self, user=None): self.user = user def find_one(self, *args, **kwargs): return self.user def update(self, *args, **kwargs): return {'n': 0} class BadDB(object): def __init__(self, user): self.users = BadCollection(user) self.passwords = BadCollection() class ViewTests(TestCase): clean_collections = ('users', 'passwords', ) def test_login(self): res = self.testapp.get('/login?param1=value1&param2=value2') self.assertEqual(res.status, '200 OK') res.mustcontain('Log in with Twitter') res.mustcontain('/twitter/login') <|code_end|> , generate the next line using the imports in this file: import datetime import os from deform import ValidationFailure from mock import patch from pyramid_mailer import get_mailer from yithlibraryserver.backups.email import get_day_to_send from yithlibraryserver.compat import url_quote from yithlibraryserver.testing import TestCase from yithlibraryserver.user.analytics import USER_ATTR and context (functions, classes, or occasionally code) from other files: # Path: yithlibraryserver/backups/email.py # def get_day_to_send(user, days_of_month): # """Sum the ordinal of each character in user._id % days_of_month""" # return sum([ord(chr) for chr in str(user['_id'])]) % days_of_month # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) # # Path: yithlibraryserver/user/analytics.py # USER_ATTR = 'allow_google_analytics' . Output only the next line.
res.mustcontain(url_quote('param1=value1&param2=value2'))
Given the following code snippet before the placeholder: <|code_start|> class DummyValidationFailure(ValidationFailure): def render(self): return 'dummy error' class BadCollection(object): def __init__(self, user=None): self.user = user def find_one(self, *args, **kwargs): return self.user def update(self, *args, **kwargs): return {'n': 0} class BadDB(object): def __init__(self, user): self.users = BadCollection(user) self.passwords = BadCollection() <|code_end|> , predict the next line using imports from the current file: import datetime import os from deform import ValidationFailure from mock import patch from pyramid_mailer import get_mailer from yithlibraryserver.backups.email import get_day_to_send from yithlibraryserver.compat import url_quote from yithlibraryserver.testing import TestCase from yithlibraryserver.user.analytics import USER_ATTR and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/backups/email.py # def get_day_to_send(user, days_of_month): # """Sum the ordinal of each character in user._id % days_of_month""" # return sum([ord(chr) for chr in str(user['_id'])]) % days_of_month # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) # # Path: yithlibraryserver/user/analytics.py # USER_ATTR = 'allow_google_analytics' . Output only the next line.
class ViewTests(TestCase):
Continue the code snippet: <|code_start|> user = self.db.users.find_one({'first_name': 'John2'}) self.assertFalse(user is None) self.assertEqual(user['first_name'], 'John2') self.assertEqual(user['last_name'], 'Doe2') self.assertEqual(user['email'], '') self.assertEqual(user['email_verified'], False) self.assertEqual(user['authorized_apps'], []) self.assertEqual(user['send_passwords_periodically'], False) # check that the email was sent res.request.registry = self.testapp.app.registry mailer = get_mailer(res.request) self.assertEqual(len(mailer.outbox), 1) self.assertEqual(mailer.outbox[0].subject, 'Please verify your email address') self.assertEqual(mailer.outbox[0].recipients, ['john@example.com']) # the next_url and user_info keys are cleared at this point self.add_to_session({ 'next_url': 'http://localhost/foo/bar', 'user_info': { 'provider': 'myprovider', 'myprovider_id': '1234', 'screen_name': 'John Doe', 'first_name': 'John', 'last_name': 'Doe', 'email': '', }, <|code_end|> . Use current file imports: import datetime import os from deform import ValidationFailure from mock import patch from pyramid_mailer import get_mailer from yithlibraryserver.backups.email import get_day_to_send from yithlibraryserver.compat import url_quote from yithlibraryserver.testing import TestCase from yithlibraryserver.user.analytics import USER_ATTR and context (classes, functions, or code) from other files: # Path: yithlibraryserver/backups/email.py # def get_day_to_send(user, days_of_month): # """Sum the ordinal of each character in user._id % days_of_month""" # return sum([ord(chr) for chr in str(user['_id'])]) % days_of_month # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) # # Path: yithlibraryserver/user/analytics.py # USER_ATTR = 'allow_google_analytics' . Output only the next line.
USER_ATTR: True,
Continue the code snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class ErrorsTests(unittest.TestCase): def test_password_not_found(self): result = password_not_found() self.assertTrue(isinstance(result, HTTPNotFound)) self.assertTrue(result.content_type, 'application/json') self.assertTrue(result.body, '{"message": "Password not found"}') # try a different message result = password_not_found('test') self.assertTrue(result.body, '{"message": "test"}') def test_invalid_password_id(self): <|code_end|> . Use current file imports: import unittest from pyramid.httpexceptions import HTTPBadRequest, HTTPNotFound from yithlibraryserver.errors import password_not_found, invalid_password_id and context (classes, functions, or code) from other files: # Path: yithlibraryserver/errors.py # def password_not_found(msg='Password not found'): # return HTTPNotFound(body=json.dumps({'message': msg}), # content_type='application/json') # # def invalid_password_id(msg='Invalid password id'): # return HTTPBadRequest(body=json.dumps({'message': msg}), # content_type='application/json') . Output only the next line.
result = invalid_password_id()
Predict the next line for this snippet: <|code_start|># it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class InformationTests(unittest.TestCase): def test_get_user_info(self): settings = { 'twitter_consumer_key': 'key', 'twitter_consumer_secret': 'secret', 'twitter_user_info_url': 'https://api.twitter.com/1/users/show.json' } with patch('requests.get') as fake: response = fake.return_value response.status_code = 200 response.json = lambda: {'screen_name': 'John Doe'} <|code_end|> with the help of current file imports: import unittest from mock import patch from pyramid.httpexceptions import HTTPUnauthorized from yithlibraryserver.twitter.information import get_user_info and context from other files: # Path: yithlibraryserver/twitter/information.py # def get_user_info(settings, user_id, oauth_token): # user_info_url = settings['twitter_user_info_url'] # # params = ( # ('oauth_token', oauth_token), # ) # # auth = auth_header('GET', user_info_url, params, settings, oauth_token) # # response = requests.get( # user_info_url + '?' + url_encode({'user_id': user_id}), # headers={'Authorization': auth}, # ) # # if response.status_code != 200: # raise HTTPUnauthorized(response.text) # # return response.json() , which may contain function names, class names, or code. Output only the next line.
info = get_user_info(settings, '1234', 'token')
Here is a snippet: <|code_start|># # You should have received a copy of the GNU Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class FakeDatabase(object): def __init__(self, name): self.name = name self.is_authenticated = False def authenticate(self, user, password): self.is_authenticated = True class FakeConnection(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __getitem__(self, key): return FakeDatabase(key) class MongoDBTests(unittest.TestCase): def test_uri(self): <|code_end|> . Write the next line using the current file imports: import unittest from yithlibraryserver import db and context from other files: # Path: yithlibraryserver/db.py # DEFAULT_MONGODB_HOST = 'localhost' # DEFAULT_MONGODB_PORT = 27017 # DEFAULT_MONGODB_NAME = 'yith-library' # DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST, # DEFAULT_MONGODB_PORT, # DEFAULT_MONGODB_NAME) # class MongoDB(object): # def __init__(self, db_uri=DEFAULT_MONGODB_URI, # connection_factory=pymongo.Connection): # def get_connection(self): # def get_database(self): # def get_db(request): , which may include functions, classes, or code. Output only the next line.
mdb = db.MongoDB(connection_factory=FakeConnection)
Here is a snippet: <|code_start|> res = self.testapp.post('/oauth2/endpoints/authorization', { 'cancel': 'No thanks', 'response_type': 'code', 'client_id': '123456', 'redirect_uri': 'https://example.com/callback', }) self.assertEqual(res.status, '302 Found') self.assertEqual(res.location, 'https://example.com') # authenticated user who hasn't authorized the app res = self.testapp.get('/oauth2/endpoints/authorization', { 'response_type': 'code', 'client_id': '123456', 'redirect_uri': 'https://example.com/callback', }) self.assertEqual(res.status, '200 OK') res.mustcontain('is asking your permission for') res.mustcontain('Allow access') res.mustcontain('No, thanks') res = self.testapp.post('/oauth2/endpoints/authorization', { 'submit': 'Authorize', 'response_type': 'code', 'client_id': '123456', 'redirect_uri': 'https://example.com/callback', }) self.assertEqual(res.status, '302 Found') user = self.db.users.find_one({'_id': user_id}) self.assertEqual(user['authorized_apps'], [app_id]) grant = self.db.authorization_codes.find_one({ <|code_end|> . Write the next line using the current file imports: import bson from yithlibraryserver import testing from yithlibraryserver.oauth2.views import DEFAULT_SCOPE from yithlibraryserver.oauth2.authentication import auth_basic_encode and context from other files: # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # class FakeRequest(DummyRequest): # class TestCase(unittest.TestCase): # def __init__(self, *args, **kwargs): # def setUp(self): # def tearDown(self): # def set_user_cookie(self, user_id): # def add_to_session(self, data): # def get_session(self, response): # # Path: yithlibraryserver/oauth2/views.py # DEFAULT_SCOPE = 'passwords' # # Path: yithlibraryserver/oauth2/authentication.py # def auth_basic_encode(user, password): # value = '%s:%s' % (user, password) # value = 'Basic ' + encodebytes(value.encode('utf-8')).decode('utf-8') # return encode_header(value) , which may include functions, classes, or code. Output only the next line.
'scope': DEFAULT_SCOPE,
Given the following code snippet before the placeholder: <|code_start|> self.assertNotEqual(grant, None) code = grant['code'] location = 'https://example.com/callback?code=%s' % code self.assertEqual(res.location, location) # authenticate user who has already authorize the app res = self.testapp.get('/oauth2/endpoints/authorization', { 'response_type': 'code', 'client_id': '123456', 'redirect_uri': 'https://example.com/callback', }) self.assertEqual(res.status, '302 Found') new_grant = self.db.authorization_codes.find_one({ 'scope': DEFAULT_SCOPE, 'client_id': '123456', 'user': user_id, }) self.assertNotEqual(new_grant, None) self.assertNotEqual(new_grant['_id'], grant['_id']) self.assertNotEqual(new_grant['code'], grant['code']) code = new_grant['code'] location = 'https://example.com/callback?code=%s' % code self.assertEqual(res.location, location) def test_token_endpoint(self): # 1. test incorrect requests res = self.testapp.post('/oauth2/endpoints/token', {}, status=401) self.assertEqual(res.status, '401 Unauthorized') headers = { <|code_end|> , predict the next line using imports from the current file: import bson from yithlibraryserver import testing from yithlibraryserver.oauth2.views import DEFAULT_SCOPE from yithlibraryserver.oauth2.authentication import auth_basic_encode and context including class names, function names, and sometimes code from other files: # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # class FakeRequest(DummyRequest): # class TestCase(unittest.TestCase): # def __init__(self, *args, **kwargs): # def setUp(self): # def tearDown(self): # def set_user_cookie(self, user_id): # def add_to_session(self, data): # def get_session(self, response): # # Path: yithlibraryserver/oauth2/views.py # DEFAULT_SCOPE = 'passwords' # # Path: yithlibraryserver/oauth2/authentication.py # def auth_basic_encode(user, password): # value = '%s:%s' % (user, password) # value = 'Basic ' + encodebytes(value.encode('utf-8')).decode('utf-8') # return encode_header(value) . Output only the next line.
'Authorization': auth_basic_encode('123456', 'secret'),
Given the code snippet: <|code_start|># along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def persona_login(request): if request.method != 'POST': return HTTPMethodNotAllowed('Only POST is allowed') assertion = request.POST.get('assertion', None) if assertion is None: return HTTPBadRequest('The assertion parameter is required') if 'next_url' in request.params and request.params['next_url']: request.session['next_url'] = request.params['next_url'] settings = request.registry.settings data = {'assertion': assertion, 'audience': get_audience(settings['public_url_root'])} response = requests.post(settings['persona_verifier_url'], data=data, verify=True) if response.ok: verification_data = response.json() if verification_data['status'] == 'okay': email = verification_data['email'] info = {'email': email} user_id = hashlib.sha1(email.encode('utf-8')).hexdigest() <|code_end|> , generate the next line using the imports in this file: import hashlib import requests from pyramid.httpexceptions import HTTPBadRequest, HTTPForbidden from pyramid.httpexceptions import HTTPMethodNotAllowed, HTTPServerError from yithlibraryserver.user.utils import register_or_update from yithlibraryserver.persona.audience import get_audience and context (functions, classes, or occasionally code) from other files: # Path: yithlibraryserver/user/utils.py # def register_or_update(request, provider, user_id, info, default_url='/'): # provider_key = get_provider_key(provider) # user = user_from_provider_id(request.db, provider, user_id) # if user is None: # # new_info = {'provider': provider, provider_key: user_id} # for attribute in ('screen_name', 'first_name', 'last_name', 'email'): # if attribute in info: # new_info[attribute] = info[attribute] # else: # new_info[attribute] = '' # # request.session['user_info'] = new_info # if 'next_url' not in request.session: # request.session['next_url'] = default_url # return HTTPFound(location=request.route_path('register_new_user')) # else: # changes = {'last_login': request.datetime_service.utcnow()} # # ga = request.google_analytics # if ga.is_in_session(): # if not ga.is_stored_in_user(user): # changes.update(ga.get_user_attr(ga.show_in_session())) # ga.clean_session() # # update_user(request.db, user, info, changes) # # if 'next_url' in request.session: # next_url = request.session['next_url'] # del request.session['next_url'] # else: # next_url = default_url # # request.session['current_provider'] = provider # remember_headers = remember(request, str(user['_id'])) # return HTTPFound(location=next_url, headers=remember_headers) # # Path: yithlibraryserver/persona/audience.py # def get_audience(public_url_root): # parts = urlparse.urlparse(public_url_root) # if parts.port is None: # if parts.scheme == 'http': # port = 80 # elif parts.scheme == 'https': # port = 443 # else: # raise ValueError('Error geting the port from %s' % public_url_root) # else: # port = parts.port # # return '%s://%s:%d' % (parts.scheme, parts.hostname, port) . Output only the next line.
return register_or_update(request, 'persona', user_id,
Next line prediction: <|code_start|># it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def persona_login(request): if request.method != 'POST': return HTTPMethodNotAllowed('Only POST is allowed') assertion = request.POST.get('assertion', None) if assertion is None: return HTTPBadRequest('The assertion parameter is required') if 'next_url' in request.params and request.params['next_url']: request.session['next_url'] = request.params['next_url'] settings = request.registry.settings data = {'assertion': assertion, <|code_end|> . Use current file imports: (import hashlib import requests from pyramid.httpexceptions import HTTPBadRequest, HTTPForbidden from pyramid.httpexceptions import HTTPMethodNotAllowed, HTTPServerError from yithlibraryserver.user.utils import register_or_update from yithlibraryserver.persona.audience import get_audience) and context including class names, function names, or small code snippets from other files: # Path: yithlibraryserver/user/utils.py # def register_or_update(request, provider, user_id, info, default_url='/'): # provider_key = get_provider_key(provider) # user = user_from_provider_id(request.db, provider, user_id) # if user is None: # # new_info = {'provider': provider, provider_key: user_id} # for attribute in ('screen_name', 'first_name', 'last_name', 'email'): # if attribute in info: # new_info[attribute] = info[attribute] # else: # new_info[attribute] = '' # # request.session['user_info'] = new_info # if 'next_url' not in request.session: # request.session['next_url'] = default_url # return HTTPFound(location=request.route_path('register_new_user')) # else: # changes = {'last_login': request.datetime_service.utcnow()} # # ga = request.google_analytics # if ga.is_in_session(): # if not ga.is_stored_in_user(user): # changes.update(ga.get_user_attr(ga.show_in_session())) # ga.clean_session() # # update_user(request.db, user, info, changes) # # if 'next_url' in request.session: # next_url = request.session['next_url'] # del request.session['next_url'] # else: # next_url = default_url # # request.session['current_provider'] = provider # remember_headers = remember(request, str(user['_id'])) # return HTTPFound(location=next_url, headers=remember_headers) # # Path: yithlibraryserver/persona/audience.py # def get_audience(public_url_root): # parts = urlparse.urlparse(public_url_root) # if parts.port is None: # if parts.scheme == 'http': # port = 80 # elif parts.scheme == 'https': # port = 443 # else: # raise ValueError('Error geting the port from %s' % public_url_root) # else: # port = parts.port # # return '%s://%s:%d' % (parts.scheme, parts.hostname, port) . Output only the next line.
'audience': get_audience(settings['public_url_root'])}
Predict the next line for this snippet: <|code_start|># Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class EmailVerificationCodeTests(TestCase): clean_collections = ('users', ) def setUp(self): self.config = testing.setUp() self.config.include('pyramid_mailer.testing') super(EmailVerificationCodeTests, self).setUp() def test_email_verification_code(self): <|code_end|> with the help of current file imports: from pyramid import testing from pyramid.testing import DummyRequest from pyramid_mailer import get_mailer from yithlibraryserver.testing import TestCase from yithlibraryserver.user.email_verification import EmailVerificationCode and context from other files: # Path: yithlibraryserver/testing.py # class TestCase(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # settings = { # 'mongo_uri': MONGO_URI, # 'auth_tk_secret': '123456', # 'twitter_consumer_key': 'key', # 'twitter_consumer_secret': 'secret', # 'facebook_app_id': 'id', # 'facebook_app_secret': 'secret', # 'google_client_id': 'id', # 'google_client_secret': 'secret', # 'paypal_user': 'sdk-three_api1.sdk.com', # 'paypal_password': 'QFZCWN5HZM8VBG7Q', # 'paypal_signature': 'A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU', # 'testing': 'True', # 'pyramid_mailer.prefix': 'mail_', # 'mail_default_sender': 'no-reply@yithlibrary.com', # 'admin_emails': 'admin1@example.com admin2@example.com', # 'public_url_root': 'http://localhost:6543/', # } # app = main({}, **settings) # self.testapp = TestApp(app) # self.db = app.registry.settings['db_conn']['test-yith-library'] # # def tearDown(self): # for col in self.clean_collections: # self.db.drop_collection(col) # # self.testapp.reset() # # def set_user_cookie(self, user_id): # request = TestRequest.blank('', {}) # request.registry = self.testapp.app.registry # remember_headers = remember(request, user_id) # cookie_value = remember_headers[0][1].split('"')[1] # self.testapp.cookies['auth_tkt'] = cookie_value # # def add_to_session(self, data): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = DummyRequest() # session = session_factory(request) # for key, value in data.items(): # session[key] = value # session.persist() # self.testapp.cookies['beaker.session.id'] = session._sess.id # # def get_session(self, response): # queryUtility = self.testapp.app.registry.queryUtility # session_factory = queryUtility(ISessionFactory) # request = response.request # # if not hasattr(request, 'add_response_callback'): # request.add_response_callback = lambda r: r # # if 'Set-Cookie' in response.headers: # request.environ['HTTP_COOKIE'] = response.headers['Set-Cookie'] # # return session_factory(request) # # Path: yithlibraryserver/user/email_verification.py # class EmailVerificationCode(object): # # def __init__(self, code=None): # if code is None: # self.code = self._generate_code() # else: # self.code = code # # def _generate_code(self): # return str(uuid.uuid4()) # # def store(self, db, user): # result = db.users.update({'_id': user['_id']}, { # '$set': {'email_verification_code': self.code}, # }, safe=True) # return result['n'] == 1 # # def remove(self, db, email, verified): # result = db.users.update({ # 'email_verification_code': self.code, # 'email': email, # }, { # '$unset': {'email_verification_code': 1}, # '$set': {'email_verified': verified}, # }, safe=True) # return result['n'] == 1 # # def verify(self, db, email): # result = db.users.find_one({ # 'email': email, # 'email_verification_code': self.code, # }) # return result is not None # # def send(self, request, user, url): # context = { # 'link': '%s?code=%s&email=%s' % (url, self.code, user['email']), # 'user': user, # } # return send_email( # request, # 'yithlibraryserver.user:templates/email_verification_code', # context, # 'Please verify your email address', # [user['email']], # ) , which may contain function names, class names, or code. Output only the next line.
evc = EmailVerificationCode()
Given the code snippet: <|code_start|># Yith Library Server is a password storage server. # Copyright (C) 2012-2013 Yaco Sistemas # Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class CORSManagerTests(testing.TestCase): clean_collections = ('applications', ) def test_cors_headers_global_origins_access_denied(self): <|code_end|> , generate the next line using the imports in this file: from pyramid.testing import DummyRequest from yithlibraryserver import testing from yithlibraryserver.cors import CORSManager and context (functions, classes, or occasionally code) from other files: # Path: yithlibraryserver/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # class FakeRequest(DummyRequest): # class TestCase(unittest.TestCase): # def __init__(self, *args, **kwargs): # def setUp(self): # def tearDown(self): # def set_user_cookie(self, user_id): # def add_to_session(self, data): # def get_session(self, response): # # Path: yithlibraryserver/cors.py # class CORSManager(object): # # def __init__(self, global_allowed_origins): # self.global_allowed_origins = global_allowed_origins.split(' ') # # def add_cors_header(self, request, response): # if 'Origin' in request.headers: # origin = request.headers['Origin'] # # client_id = request.GET.get('client_id') # if client_id is None: # allowed_origins = self.global_allowed_origins # else: # allowed_origins = self._get_allowed_origins_for_client( # request, client_id) # # if origin in allowed_origins: # log.debug('Origin %s is allowed: %s' % # (origin, ' '.join(allowed_origins))) # response.headers['Access-Control-Allow-Origin'] = origin # else: # log.debug('Origin %s is not allowed: %s' % # (origin, ' '.join(allowed_origins))) # # def _get_allowed_origins_for_client(self, request, client_id): # app = request.db.applications.find_one({'client_id': client_id}) # if app is None: # return [] # else: # return app['authorized_origins'] . Output only the next line.
cm = CORSManager('')
Based on the snippet: <|code_start|> sys.stdout = StringIO() result = send_backups_via_email() self.assertEqual(result, None) stdout = sys.stdout.getvalue() expected_output = """Passwords sent to John3 Doe <john3@example.com> """ self.assertEqual(stdout, expected_output) def test_several_users(self): date_joined = datetime.datetime(2012, 12, 12, 12, 12) # Add some users self.add_passwords(self.db.users.insert({ 'first_name': 'John1', 'last_name': 'Doe', 'date_joined': date_joined, 'email': '', 'email_verified': False, 'send_passwords_periodically': False, }), 10) i = 1 while True: user_id = self.add_passwords(self.db.users.insert({ 'first_name': 'John%d' % i, 'last_name': 'Doe', 'date_joined': date_joined, 'email': 'john%d@example.com' % i, 'email_verified': True, 'send_passwords_periodically': True, }), 10) <|code_end|> , predict the immediate next line with the help of imports: import datetime import os import sys from yithlibraryserver.backups.email import get_day_to_send from yithlibraryserver.compat import StringIO from yithlibraryserver.scripts.backups import send_backups_via_email from yithlibraryserver.scripts.testing import ScriptTests and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/backups/email.py # def get_day_to_send(user, days_of_month): # """Sum the ordinal of each character in user._id % days_of_month""" # return sum([ord(chr) for chr in str(user['_id'])]) % days_of_month # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/scripts/backups.py # def send_backups_via_email(): # result = setup_simple_command( # "send_backups_via_email", # "Report information about users and their passwords.", # ) # if isinstance(result, int): # return result # else: # settings, closer, env, args = result # # try: # request = env['request'] # # if len(args) == 0: # user_iterator = get_all_users(request) # else: # user_iterator = get_selected_users(request, *args) # # tx = transaction.begin() # # public_url_root = settings['public_url_root'] # preferences_link = urlparse.urljoin( # public_url_root, # request.route_path('user_preferences')) # backups_link = urlparse.urljoin( # public_url_root, # request.route_path('backups_index')) # # for user in user_iterator: # if user['email']: # sent = send_passwords(request, user, # preferences_link, backups_link) # if sent: # safe_print('Passwords sent to %s' % # get_user_display_name(user)) # # tx.commit() # # finally: # closer() # # Path: yithlibraryserver/scripts/testing.py # class ScriptTests(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # super(ScriptTests, self).setUp() # # fd, self.conf_file_path = tempfile.mkstemp() # os.write(fd, CONFIG.encode('ascii')) # mdb = MongoDB(MONGO_URI) # self.db = mdb.get_database() # # def tearDown(self): # super(ScriptTests, self).tearDown() # os.unlink(self.conf_file_path) # for col in self.clean_collections: # self.db.drop_collection(col) # # def add_passwords(self, user, n): # for i in range(n): # self.db.passwords.insert({ # 'service': 'service-%d' % (i + 1), # 'secret': 's3cr3t', # 'owner': user, # }) # return user . Output only the next line.
day = get_day_to_send({'_id': user_id}, 28)
Using the snippet: <|code_start|># along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. class BackupsTests(ScriptTests): clean_collections = ('users', 'passwords', ) def setUp(self): super(BackupsTests, self).setUp() # Save sys values self.old_args = sys.argv[:] self.old_stdout = sys.stdout os.environ['YITH_FAKE_DATE'] = '2012-1-10' def tearDown(self): # Restore sys.values sys.argv = self.old_args sys.stdout = self.old_stdout del os.environ['YITH_FAKE_DATE'] super(BackupsTests, self).tearDown() def test_no_arguments(self): # Replace sys argv and stdout sys.argv = [] <|code_end|> , determine the next line of code. You have imports: import datetime import os import sys from yithlibraryserver.backups.email import get_day_to_send from yithlibraryserver.compat import StringIO from yithlibraryserver.scripts.backups import send_backups_via_email from yithlibraryserver.scripts.testing import ScriptTests and context (class names, function names, or code) available: # Path: yithlibraryserver/backups/email.py # def get_day_to_send(user, days_of_month): # """Sum the ordinal of each character in user._id % days_of_month""" # return sum([ord(chr) for chr in str(user['_id'])]) % days_of_month # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/scripts/backups.py # def send_backups_via_email(): # result = setup_simple_command( # "send_backups_via_email", # "Report information about users and their passwords.", # ) # if isinstance(result, int): # return result # else: # settings, closer, env, args = result # # try: # request = env['request'] # # if len(args) == 0: # user_iterator = get_all_users(request) # else: # user_iterator = get_selected_users(request, *args) # # tx = transaction.begin() # # public_url_root = settings['public_url_root'] # preferences_link = urlparse.urljoin( # public_url_root, # request.route_path('user_preferences')) # backups_link = urlparse.urljoin( # public_url_root, # request.route_path('backups_index')) # # for user in user_iterator: # if user['email']: # sent = send_passwords(request, user, # preferences_link, backups_link) # if sent: # safe_print('Passwords sent to %s' % # get_user_display_name(user)) # # tx.commit() # # finally: # closer() # # Path: yithlibraryserver/scripts/testing.py # class ScriptTests(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # super(ScriptTests, self).setUp() # # fd, self.conf_file_path = tempfile.mkstemp() # os.write(fd, CONFIG.encode('ascii')) # mdb = MongoDB(MONGO_URI) # self.db = mdb.get_database() # # def tearDown(self): # super(ScriptTests, self).tearDown() # os.unlink(self.conf_file_path) # for col in self.clean_collections: # self.db.drop_collection(col) # # def add_passwords(self, user, n): # for i in range(n): # self.db.passwords.insert({ # 'service': 'service-%d' % (i + 1), # 'secret': 's3cr3t', # 'owner': user, # }) # return user . Output only the next line.
sys.stdout = StringIO()
Based on the snippet: <|code_start|> class BackupsTests(ScriptTests): clean_collections = ('users', 'passwords', ) def setUp(self): super(BackupsTests, self).setUp() # Save sys values self.old_args = sys.argv[:] self.old_stdout = sys.stdout os.environ['YITH_FAKE_DATE'] = '2012-1-10' def tearDown(self): # Restore sys.values sys.argv = self.old_args sys.stdout = self.old_stdout del os.environ['YITH_FAKE_DATE'] super(BackupsTests, self).tearDown() def test_no_arguments(self): # Replace sys argv and stdout sys.argv = [] sys.stdout = StringIO() # Call send backups with no arguments <|code_end|> , predict the immediate next line with the help of imports: import datetime import os import sys from yithlibraryserver.backups.email import get_day_to_send from yithlibraryserver.compat import StringIO from yithlibraryserver.scripts.backups import send_backups_via_email from yithlibraryserver.scripts.testing import ScriptTests and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/backups/email.py # def get_day_to_send(user, days_of_month): # """Sum the ordinal of each character in user._id % days_of_month""" # return sum([ord(chr) for chr in str(user['_id'])]) % days_of_month # # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/scripts/backups.py # def send_backups_via_email(): # result = setup_simple_command( # "send_backups_via_email", # "Report information about users and their passwords.", # ) # if isinstance(result, int): # return result # else: # settings, closer, env, args = result # # try: # request = env['request'] # # if len(args) == 0: # user_iterator = get_all_users(request) # else: # user_iterator = get_selected_users(request, *args) # # tx = transaction.begin() # # public_url_root = settings['public_url_root'] # preferences_link = urlparse.urljoin( # public_url_root, # request.route_path('user_preferences')) # backups_link = urlparse.urljoin( # public_url_root, # request.route_path('backups_index')) # # for user in user_iterator: # if user['email']: # sent = send_passwords(request, user, # preferences_link, backups_link) # if sent: # safe_print('Passwords sent to %s' % # get_user_display_name(user)) # # tx.commit() # # finally: # closer() # # Path: yithlibraryserver/scripts/testing.py # class ScriptTests(unittest.TestCase): # # clean_collections = tuple() # # def setUp(self): # super(ScriptTests, self).setUp() # # fd, self.conf_file_path = tempfile.mkstemp() # os.write(fd, CONFIG.encode('ascii')) # mdb = MongoDB(MONGO_URI) # self.db = mdb.get_database() # # def tearDown(self): # super(ScriptTests, self).tearDown() # os.unlink(self.conf_file_path) # for col in self.clean_collections: # self.db.drop_collection(col) # # def add_passwords(self, user, n): # for i in range(n): # self.db.passwords.insert({ # 'service': 'service-%d' % (i + 1), # 'secret': 's3cr3t', # 'owner': user, # }) # return user . Output only the next line.
result = send_backups_via_email()
Predict the next line after this snippet: <|code_start|># it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def authenticate_client(request): """Returns the client application representing this request. Uses the Authorization header in Basic format to identify the client of this request against the set of registered applications on the server. """ authorization = request.headers.get('Authorization') if authorization is None: raise HTTPUnauthorized() method, credentials = request.authorization if method.lower() != 'basic': raise HTTPUnauthorized() <|code_end|> using the current file's imports: from pyramid.httpexceptions import HTTPUnauthorized from yithlibraryserver.compat import decodebytes, encodebytes, encode_header and any relevant context from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover . Output only the next line.
credentials = decodebytes(credentials.encode('utf-8'))
Next line prediction: <|code_start|> Uses the Authorization header in Basic format to identify the client of this request against the set of registered applications on the server. """ authorization = request.headers.get('Authorization') if authorization is None: raise HTTPUnauthorized() method, credentials = request.authorization if method.lower() != 'basic': raise HTTPUnauthorized() credentials = decodebytes(credentials.encode('utf-8')) credentials = credentials.decode('utf-8') client_id, client_secret = credentials.split(':') application = request.db.applications.find_one({ 'client_id': client_id, 'client_secret': client_secret }) if application is None: raise HTTPUnauthorized() return application def auth_basic_encode(user, password): value = '%s:%s' % (user, password) <|code_end|> . Use current file imports: (from pyramid.httpexceptions import HTTPUnauthorized from yithlibraryserver.compat import decodebytes, encodebytes, encode_header) and context including class names, function names, or small code snippets from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover . Output only the next line.
value = 'Basic ' + encodebytes(value.encode('utf-8')).decode('utf-8')
Given snippet: <|code_start|> Uses the Authorization header in Basic format to identify the client of this request against the set of registered applications on the server. """ authorization = request.headers.get('Authorization') if authorization is None: raise HTTPUnauthorized() method, credentials = request.authorization if method.lower() != 'basic': raise HTTPUnauthorized() credentials = decodebytes(credentials.encode('utf-8')) credentials = credentials.decode('utf-8') client_id, client_secret = credentials.split(':') application = request.db.applications.find_one({ 'client_id': client_id, 'client_secret': client_secret }) if application is None: raise HTTPUnauthorized() return application def auth_basic_encode(user, password): value = '%s:%s' % (user, password) value = 'Basic ' + encodebytes(value.encode('utf-8')).decode('utf-8') <|code_end|> , continue by predicting the next line. Consider current file imports: from pyramid.httpexceptions import HTTPUnauthorized from yithlibraryserver.compat import decodebytes, encodebytes, encode_header and context: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover which might include code, classes, or functions. Output only the next line.
return encode_header(value)
Next line prediction: <|code_start|># # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def twitter_login(request): settings = request.registry.settings request_token_url = settings['twitter_request_token_url'] oauth_callback_url = request.route_url('twitter_callback') params = ( ('oauth_callback', oauth_callback_url), ) auth = auth_header('POST', request_token_url, params, settings) response = requests.post(request_token_url, data='', headers={'Authorization': auth}) if response.status_code != 200: return HTTPUnauthorized(response.text) <|code_end|> . Use current file imports: (from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPUnauthorized from yithlibraryserver.compat import urlparse from yithlibraryserver.twitter.authorization import auth_header from yithlibraryserver.twitter.information import get_user_info from yithlibraryserver.user.utils import split_name, register_or_update from yithlibraryserver.user.utils import user_from_provider_id import requests) and context including class names, function names, or small code snippets from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/twitter/authorization.py # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header # # Path: yithlibraryserver/twitter/information.py # def get_user_info(settings, user_id, oauth_token): # user_info_url = settings['twitter_user_info_url'] # # params = ( # ('oauth_token', oauth_token), # ) # # auth = auth_header('GET', user_info_url, params, settings, oauth_token) # # response = requests.get( # user_info_url + '?' + url_encode({'user_id': user_id}), # headers={'Authorization': auth}, # ) # # if response.status_code != 200: # raise HTTPUnauthorized(response.text) # # return response.json() # # Path: yithlibraryserver/user/utils.py # def split_name(name): # parts = name.split(' ') # if len(parts) > 1: # first_name = parts[0] # last_name = ' '.join(parts[1:]) # else: # first_name = parts[0] # last_name = '' # # return first_name, last_name # # def register_or_update(request, provider, user_id, info, default_url='/'): # provider_key = get_provider_key(provider) # user = user_from_provider_id(request.db, provider, user_id) # if user is None: # # new_info = {'provider': provider, provider_key: user_id} # for attribute in ('screen_name', 'first_name', 'last_name', 'email'): # if attribute in info: # new_info[attribute] = info[attribute] # else: # new_info[attribute] = '' # # request.session['user_info'] = new_info # if 'next_url' not in request.session: # request.session['next_url'] = default_url # return HTTPFound(location=request.route_path('register_new_user')) # else: # changes = {'last_login': request.datetime_service.utcnow()} # # ga = request.google_analytics # if ga.is_in_session(): # if not ga.is_stored_in_user(user): # changes.update(ga.get_user_attr(ga.show_in_session())) # ga.clean_session() # # update_user(request.db, user, info, changes) # # if 'next_url' in request.session: # next_url = request.session['next_url'] # del request.session['next_url'] # else: # next_url = default_url # # request.session['current_provider'] = provider # remember_headers = remember(request, str(user['_id'])) # return HTTPFound(location=next_url, headers=remember_headers) # # Path: yithlibraryserver/user/utils.py # def user_from_provider_id(db, provider, user_id): # provider_key = get_provider_key(provider) # return db.users.find_one({provider_key: user_id}) . Output only the next line.
response_args = dict(urlparse.parse_qsl(response.text))
Predict the next line for this snippet: <|code_start|># Copyright (C) 2012-2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def twitter_login(request): settings = request.registry.settings request_token_url = settings['twitter_request_token_url'] oauth_callback_url = request.route_url('twitter_callback') params = ( ('oauth_callback', oauth_callback_url), ) <|code_end|> with the help of current file imports: from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPUnauthorized from yithlibraryserver.compat import urlparse from yithlibraryserver.twitter.authorization import auth_header from yithlibraryserver.twitter.information import get_user_info from yithlibraryserver.user.utils import split_name, register_or_update from yithlibraryserver.user.utils import user_from_provider_id import requests and context from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/twitter/authorization.py # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header # # Path: yithlibraryserver/twitter/information.py # def get_user_info(settings, user_id, oauth_token): # user_info_url = settings['twitter_user_info_url'] # # params = ( # ('oauth_token', oauth_token), # ) # # auth = auth_header('GET', user_info_url, params, settings, oauth_token) # # response = requests.get( # user_info_url + '?' + url_encode({'user_id': user_id}), # headers={'Authorization': auth}, # ) # # if response.status_code != 200: # raise HTTPUnauthorized(response.text) # # return response.json() # # Path: yithlibraryserver/user/utils.py # def split_name(name): # parts = name.split(' ') # if len(parts) > 1: # first_name = parts[0] # last_name = ' '.join(parts[1:]) # else: # first_name = parts[0] # last_name = '' # # return first_name, last_name # # def register_or_update(request, provider, user_id, info, default_url='/'): # provider_key = get_provider_key(provider) # user = user_from_provider_id(request.db, provider, user_id) # if user is None: # # new_info = {'provider': provider, provider_key: user_id} # for attribute in ('screen_name', 'first_name', 'last_name', 'email'): # if attribute in info: # new_info[attribute] = info[attribute] # else: # new_info[attribute] = '' # # request.session['user_info'] = new_info # if 'next_url' not in request.session: # request.session['next_url'] = default_url # return HTTPFound(location=request.route_path('register_new_user')) # else: # changes = {'last_login': request.datetime_service.utcnow()} # # ga = request.google_analytics # if ga.is_in_session(): # if not ga.is_stored_in_user(user): # changes.update(ga.get_user_attr(ga.show_in_session())) # ga.clean_session() # # update_user(request.db, user, info, changes) # # if 'next_url' in request.session: # next_url = request.session['next_url'] # del request.session['next_url'] # else: # next_url = default_url # # request.session['current_provider'] = provider # remember_headers = remember(request, str(user['_id'])) # return HTTPFound(location=next_url, headers=remember_headers) # # Path: yithlibraryserver/user/utils.py # def user_from_provider_id(db, provider, user_id): # provider_key = get_provider_key(provider) # return db.users.find_one({provider_key: user_id}) , which may contain function names, class names, or code. Output only the next line.
auth = auth_header('POST', request_token_url, params, settings)
Here is a snippet: <|code_start|> return HTTPUnauthorized("OAuth tokens don't match") else: del request.session['oauth_token'] access_token_url = settings['twitter_access_token_url'] params = ( ('oauth_token', oauth_token), ) auth = auth_header('POST', access_token_url, params, settings, oauth_token) response = requests.post(access_token_url, data='oauth_verifier=%s' % oauth_verifier, headers={'Authorization': auth}) if response.status_code != 200: return HTTPUnauthorized(response.text) response_args = dict(urlparse.parse_qsl(response.text)) #oauth_token_secret = response_args['oauth_token_secret'] oauth_token = response_args['oauth_token'] user_id = response_args['user_id'] screen_name = response_args['screen_name'] existing_user = user_from_provider_id(request.db, 'twitter', user_id) if existing_user is None: # fetch Twitter info only if this is the first time for # the user sice Twitter has very strong limits for using # its APIs <|code_end|> . Write the next line using the current file imports: from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPUnauthorized from yithlibraryserver.compat import urlparse from yithlibraryserver.twitter.authorization import auth_header from yithlibraryserver.twitter.information import get_user_info from yithlibraryserver.user.utils import split_name, register_or_update from yithlibraryserver.user.utils import user_from_provider_id import requests and context from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/twitter/authorization.py # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header # # Path: yithlibraryserver/twitter/information.py # def get_user_info(settings, user_id, oauth_token): # user_info_url = settings['twitter_user_info_url'] # # params = ( # ('oauth_token', oauth_token), # ) # # auth = auth_header('GET', user_info_url, params, settings, oauth_token) # # response = requests.get( # user_info_url + '?' + url_encode({'user_id': user_id}), # headers={'Authorization': auth}, # ) # # if response.status_code != 200: # raise HTTPUnauthorized(response.text) # # return response.json() # # Path: yithlibraryserver/user/utils.py # def split_name(name): # parts = name.split(' ') # if len(parts) > 1: # first_name = parts[0] # last_name = ' '.join(parts[1:]) # else: # first_name = parts[0] # last_name = '' # # return first_name, last_name # # def register_or_update(request, provider, user_id, info, default_url='/'): # provider_key = get_provider_key(provider) # user = user_from_provider_id(request.db, provider, user_id) # if user is None: # # new_info = {'provider': provider, provider_key: user_id} # for attribute in ('screen_name', 'first_name', 'last_name', 'email'): # if attribute in info: # new_info[attribute] = info[attribute] # else: # new_info[attribute] = '' # # request.session['user_info'] = new_info # if 'next_url' not in request.session: # request.session['next_url'] = default_url # return HTTPFound(location=request.route_path('register_new_user')) # else: # changes = {'last_login': request.datetime_service.utcnow()} # # ga = request.google_analytics # if ga.is_in_session(): # if not ga.is_stored_in_user(user): # changes.update(ga.get_user_attr(ga.show_in_session())) # ga.clean_session() # # update_user(request.db, user, info, changes) # # if 'next_url' in request.session: # next_url = request.session['next_url'] # del request.session['next_url'] # else: # next_url = default_url # # request.session['current_provider'] = provider # remember_headers = remember(request, str(user['_id'])) # return HTTPFound(location=next_url, headers=remember_headers) # # Path: yithlibraryserver/user/utils.py # def user_from_provider_id(db, provider, user_id): # provider_key = get_provider_key(provider) # return db.users.find_one({provider_key: user_id}) , which may include functions, classes, or code. Output only the next line.
twitter_info = get_user_info(settings, user_id, oauth_token)
Given snippet: <|code_start|> else: del request.session['oauth_token'] access_token_url = settings['twitter_access_token_url'] params = ( ('oauth_token', oauth_token), ) auth = auth_header('POST', access_token_url, params, settings, oauth_token) response = requests.post(access_token_url, data='oauth_verifier=%s' % oauth_verifier, headers={'Authorization': auth}) if response.status_code != 200: return HTTPUnauthorized(response.text) response_args = dict(urlparse.parse_qsl(response.text)) #oauth_token_secret = response_args['oauth_token_secret'] oauth_token = response_args['oauth_token'] user_id = response_args['user_id'] screen_name = response_args['screen_name'] existing_user = user_from_provider_id(request.db, 'twitter', user_id) if existing_user is None: # fetch Twitter info only if this is the first time for # the user sice Twitter has very strong limits for using # its APIs twitter_info = get_user_info(settings, user_id, oauth_token) <|code_end|> , continue by predicting the next line. Consider current file imports: from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPUnauthorized from yithlibraryserver.compat import urlparse from yithlibraryserver.twitter.authorization import auth_header from yithlibraryserver.twitter.information import get_user_info from yithlibraryserver.user.utils import split_name, register_or_update from yithlibraryserver.user.utils import user_from_provider_id import requests and context: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/twitter/authorization.py # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header # # Path: yithlibraryserver/twitter/information.py # def get_user_info(settings, user_id, oauth_token): # user_info_url = settings['twitter_user_info_url'] # # params = ( # ('oauth_token', oauth_token), # ) # # auth = auth_header('GET', user_info_url, params, settings, oauth_token) # # response = requests.get( # user_info_url + '?' + url_encode({'user_id': user_id}), # headers={'Authorization': auth}, # ) # # if response.status_code != 200: # raise HTTPUnauthorized(response.text) # # return response.json() # # Path: yithlibraryserver/user/utils.py # def split_name(name): # parts = name.split(' ') # if len(parts) > 1: # first_name = parts[0] # last_name = ' '.join(parts[1:]) # else: # first_name = parts[0] # last_name = '' # # return first_name, last_name # # def register_or_update(request, provider, user_id, info, default_url='/'): # provider_key = get_provider_key(provider) # user = user_from_provider_id(request.db, provider, user_id) # if user is None: # # new_info = {'provider': provider, provider_key: user_id} # for attribute in ('screen_name', 'first_name', 'last_name', 'email'): # if attribute in info: # new_info[attribute] = info[attribute] # else: # new_info[attribute] = '' # # request.session['user_info'] = new_info # if 'next_url' not in request.session: # request.session['next_url'] = default_url # return HTTPFound(location=request.route_path('register_new_user')) # else: # changes = {'last_login': request.datetime_service.utcnow()} # # ga = request.google_analytics # if ga.is_in_session(): # if not ga.is_stored_in_user(user): # changes.update(ga.get_user_attr(ga.show_in_session())) # ga.clean_session() # # update_user(request.db, user, info, changes) # # if 'next_url' in request.session: # next_url = request.session['next_url'] # del request.session['next_url'] # else: # next_url = default_url # # request.session['current_provider'] = provider # remember_headers = remember(request, str(user['_id'])) # return HTTPFound(location=next_url, headers=remember_headers) # # Path: yithlibraryserver/user/utils.py # def user_from_provider_id(db, provider, user_id): # provider_key = get_provider_key(provider) # return db.users.find_one({provider_key: user_id}) which might include code, classes, or functions. Output only the next line.
first_name, last_name = split_name(twitter_info['name'])
Given snippet: <|code_start|> auth = auth_header('POST', access_token_url, params, settings, oauth_token) response = requests.post(access_token_url, data='oauth_verifier=%s' % oauth_verifier, headers={'Authorization': auth}) if response.status_code != 200: return HTTPUnauthorized(response.text) response_args = dict(urlparse.parse_qsl(response.text)) #oauth_token_secret = response_args['oauth_token_secret'] oauth_token = response_args['oauth_token'] user_id = response_args['user_id'] screen_name = response_args['screen_name'] existing_user = user_from_provider_id(request.db, 'twitter', user_id) if existing_user is None: # fetch Twitter info only if this is the first time for # the user sice Twitter has very strong limits for using # its APIs twitter_info = get_user_info(settings, user_id, oauth_token) first_name, last_name = split_name(twitter_info['name']) info = { 'screen_name': screen_name, 'first_name': first_name, 'last_name': last_name, } else: info = {} <|code_end|> , continue by predicting the next line. Consider current file imports: from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPUnauthorized from yithlibraryserver.compat import urlparse from yithlibraryserver.twitter.authorization import auth_header from yithlibraryserver.twitter.information import get_user_info from yithlibraryserver.user.utils import split_name, register_or_update from yithlibraryserver.user.utils import user_from_provider_id import requests and context: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/twitter/authorization.py # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header # # Path: yithlibraryserver/twitter/information.py # def get_user_info(settings, user_id, oauth_token): # user_info_url = settings['twitter_user_info_url'] # # params = ( # ('oauth_token', oauth_token), # ) # # auth = auth_header('GET', user_info_url, params, settings, oauth_token) # # response = requests.get( # user_info_url + '?' + url_encode({'user_id': user_id}), # headers={'Authorization': auth}, # ) # # if response.status_code != 200: # raise HTTPUnauthorized(response.text) # # return response.json() # # Path: yithlibraryserver/user/utils.py # def split_name(name): # parts = name.split(' ') # if len(parts) > 1: # first_name = parts[0] # last_name = ' '.join(parts[1:]) # else: # first_name = parts[0] # last_name = '' # # return first_name, last_name # # def register_or_update(request, provider, user_id, info, default_url='/'): # provider_key = get_provider_key(provider) # user = user_from_provider_id(request.db, provider, user_id) # if user is None: # # new_info = {'provider': provider, provider_key: user_id} # for attribute in ('screen_name', 'first_name', 'last_name', 'email'): # if attribute in info: # new_info[attribute] = info[attribute] # else: # new_info[attribute] = '' # # request.session['user_info'] = new_info # if 'next_url' not in request.session: # request.session['next_url'] = default_url # return HTTPFound(location=request.route_path('register_new_user')) # else: # changes = {'last_login': request.datetime_service.utcnow()} # # ga = request.google_analytics # if ga.is_in_session(): # if not ga.is_stored_in_user(user): # changes.update(ga.get_user_attr(ga.show_in_session())) # ga.clean_session() # # update_user(request.db, user, info, changes) # # if 'next_url' in request.session: # next_url = request.session['next_url'] # del request.session['next_url'] # else: # next_url = default_url # # request.session['current_provider'] = provider # remember_headers = remember(request, str(user['_id'])) # return HTTPFound(location=next_url, headers=remember_headers) # # Path: yithlibraryserver/user/utils.py # def user_from_provider_id(db, provider, user_id): # provider_key = get_provider_key(provider) # return db.users.find_one({provider_key: user_id}) which might include code, classes, or functions. Output only the next line.
return register_or_update(request, 'twitter', user_id, info,
Next line prediction: <|code_start|> saved_oauth_token = request.session['oauth_token'] except KeyError: return HTTPBadRequest('No oauth_token was found in the session') if saved_oauth_token != oauth_token: return HTTPUnauthorized("OAuth tokens don't match") else: del request.session['oauth_token'] access_token_url = settings['twitter_access_token_url'] params = ( ('oauth_token', oauth_token), ) auth = auth_header('POST', access_token_url, params, settings, oauth_token) response = requests.post(access_token_url, data='oauth_verifier=%s' % oauth_verifier, headers={'Authorization': auth}) if response.status_code != 200: return HTTPUnauthorized(response.text) response_args = dict(urlparse.parse_qsl(response.text)) #oauth_token_secret = response_args['oauth_token_secret'] oauth_token = response_args['oauth_token'] user_id = response_args['user_id'] screen_name = response_args['screen_name'] <|code_end|> . Use current file imports: (from pyramid.httpexceptions import HTTPBadRequest, HTTPFound, HTTPUnauthorized from yithlibraryserver.compat import urlparse from yithlibraryserver.twitter.authorization import auth_header from yithlibraryserver.twitter.information import get_user_info from yithlibraryserver.user.utils import split_name, register_or_update from yithlibraryserver.user.utils import user_from_provider_id import requests) and context including class names, function names, or small code snippets from other files: # Path: yithlibraryserver/compat.py # PY3 = sys.version_info[0] == 3 # def encode_header(obj): # pragma: no cover # def encode_header(obj): # pragma: no cover # # Path: yithlibraryserver/twitter/authorization.py # def auth_header(method, url, original_params, settings, oauth_token='', # nonce_=None, timestamp_=None): # params = list(original_params) + [ # ('oauth_consumer_key', settings['twitter_consumer_key']), # ('oauth_nonce', nonce_ or nonce()), # ('oauth_signature_method', 'HMAC-SHA1'), # ('oauth_timestamp', str(timestamp_ or timestamp())), # ('oauth_version', '1.0'), # ] # params = [(quote(key), quote(value)) for key, value in params] # # signature = sign(method, url, params, # settings['twitter_consumer_secret'], oauth_token) # params.append(('oauth_signature', signature)) # # header = ", ".join(['%s="%s"' % (key, value) for key, value in params]) # # return 'OAuth %s' % header # # Path: yithlibraryserver/twitter/information.py # def get_user_info(settings, user_id, oauth_token): # user_info_url = settings['twitter_user_info_url'] # # params = ( # ('oauth_token', oauth_token), # ) # # auth = auth_header('GET', user_info_url, params, settings, oauth_token) # # response = requests.get( # user_info_url + '?' + url_encode({'user_id': user_id}), # headers={'Authorization': auth}, # ) # # if response.status_code != 200: # raise HTTPUnauthorized(response.text) # # return response.json() # # Path: yithlibraryserver/user/utils.py # def split_name(name): # parts = name.split(' ') # if len(parts) > 1: # first_name = parts[0] # last_name = ' '.join(parts[1:]) # else: # first_name = parts[0] # last_name = '' # # return first_name, last_name # # def register_or_update(request, provider, user_id, info, default_url='/'): # provider_key = get_provider_key(provider) # user = user_from_provider_id(request.db, provider, user_id) # if user is None: # # new_info = {'provider': provider, provider_key: user_id} # for attribute in ('screen_name', 'first_name', 'last_name', 'email'): # if attribute in info: # new_info[attribute] = info[attribute] # else: # new_info[attribute] = '' # # request.session['user_info'] = new_info # if 'next_url' not in request.session: # request.session['next_url'] = default_url # return HTTPFound(location=request.route_path('register_new_user')) # else: # changes = {'last_login': request.datetime_service.utcnow()} # # ga = request.google_analytics # if ga.is_in_session(): # if not ga.is_stored_in_user(user): # changes.update(ga.get_user_attr(ga.show_in_session())) # ga.clean_session() # # update_user(request.db, user, info, changes) # # if 'next_url' in request.session: # next_url = request.session['next_url'] # del request.session['next_url'] # else: # next_url = default_url # # request.session['current_provider'] = provider # remember_headers = remember(request, str(user['_id'])) # return HTTPFound(location=next_url, headers=remember_headers) # # Path: yithlibraryserver/user/utils.py # def user_from_provider_id(db, provider, user_id): # provider_key = get_provider_key(provider) # return db.users.find_one({provider_key: user_id}) . Output only the next line.
existing_user = user_from_provider_id(request.db, 'twitter', user_id)
Based on the snippet: <|code_start|># Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server 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 Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. def send_thankyou_email(request, donation): return send_email( request, 'yithlibraryserver.contributions:templates/email_thankyou', donation, 'Thanks for your contribution!', [donation['email']], ) def send_notification_to_admins(request, donation): context = { 'home_link': request.route_url('home'), } context.update(donation) <|code_end|> , predict the immediate next line with the help of imports: from yithlibraryserver.email import send_email, send_email_to_admins and context (classes, functions, sometimes code) from other files: # Path: yithlibraryserver/email.py # def send_email(request, template, context, subject, recipients, # attachments=None, extra_headers=None): # message = create_message(request, template, context, subject, recipients, # attachments, extra_headers) # return get_mailer(request).send(message) # # def send_email_to_admins(request, template, context, subject, # attachments=None, extra_headers=None): # admin_emails = request.registry.settings['admin_emails'] # if admin_emails: # return send_email(request, template, context, subject, admin_emails, # attachments, extra_headers) . Output only the next line.
return send_email_to_admins(