Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line for 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/>. def _get_user_info(db, user): return { 'display_name': get_user_display_name(user), 'passwords': get_n_passwords(db, user), <|code_end|> with the help of current file imports: import operator from yithlibraryserver.user.accounts import get_available_providers from yithlibraryserver.user.accounts import get_provider_key, get_n_passwords from yithlibraryserver.scripts.utils import safe_print, setup_simple_command from yithlibraryserver.scripts.utils import get_user_display_name and context from other files: # Path: yithlibraryserver/user/accounts.py # def get_available_providers(): # return ('facebook', 'google', 'twitter', 'persona') # # Path: yithlibraryserver/user/accounts.py # def get_provider_key(provider): # return '%s_id' % provider # # def get_n_passwords(db, user): # return db.passwords.find({ # 'owner': user.get('_id', None), # }, safe=True).count() # # 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')) # # def setup_simple_command(name, description): # usage = name + ": %prog config_uri" # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if not len(args) >= 1: # safe_print('You must provide at least one argument') # return 2 # config_uri = args[0] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # return settings, closer, env, args[1:] # # 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.
'providers': ', '.join([prov for prov in get_available_providers()
Predict the next line for this snippet: <|code_start|> "Report information about oauth2 client applications.", ) if isinstance(result, int): return result else: settings, closer, env, args = result try: db = settings['mongodb'].get_database() for app in db.applications.find(): info = _get_app_info(db, app) text = ('%s\n' '\tOwner: %s\n' '\tMain URL: %s\n' '\tCallback URL: %s\n' '\tUsers: %d\n' % ( info['name'], info['owner'], info['main_url'], info['callback_url'], info['users'], )) safe_print(text) finally: closer() def group_by_identity_provider(users): providers = {} for user in users: for provider in get_available_providers(): <|code_end|> with the help of current file imports: import operator from yithlibraryserver.user.accounts import get_available_providers from yithlibraryserver.user.accounts import get_provider_key, get_n_passwords from yithlibraryserver.scripts.utils import safe_print, setup_simple_command from yithlibraryserver.scripts.utils import get_user_display_name and context from other files: # Path: yithlibraryserver/user/accounts.py # def get_available_providers(): # return ('facebook', 'google', 'twitter', 'persona') # # Path: yithlibraryserver/user/accounts.py # def get_provider_key(provider): # return '%s_id' % provider # # def get_n_passwords(db, user): # return db.passwords.find({ # 'owner': user.get('_id', None), # }, safe=True).count() # # 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')) # # def setup_simple_command(name, description): # usage = name + ": %prog config_uri" # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if not len(args) >= 1: # safe_print('You must provide at least one argument') # return 2 # config_uri = args[0] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # return settings, closer, env, args[1:] # # 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.
key = get_provider_key(provider)
Here is a 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/>. def _get_user_info(db, user): return { 'display_name': get_user_display_name(user), <|code_end|> . Write the next line using the current file imports: import operator from yithlibraryserver.user.accounts import get_available_providers from yithlibraryserver.user.accounts import get_provider_key, get_n_passwords from yithlibraryserver.scripts.utils import safe_print, setup_simple_command from yithlibraryserver.scripts.utils import get_user_display_name and context from other files: # Path: yithlibraryserver/user/accounts.py # def get_available_providers(): # return ('facebook', 'google', 'twitter', 'persona') # # Path: yithlibraryserver/user/accounts.py # def get_provider_key(provider): # return '%s_id' % provider # # def get_n_passwords(db, user): # return db.passwords.find({ # 'owner': user.get('_id', None), # }, safe=True).count() # # 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')) # # def setup_simple_command(name, description): # usage = name + ": %prog config_uri" # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if not len(args) >= 1: # safe_print('You must provide at least one argument') # return 2 # config_uri = args[0] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # return settings, closer, env, args[1:] # # 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.
'passwords': get_n_passwords(db, user),
Next line prediction: <|code_start|> 'verified': user.get('email_verified', False), 'date_joined': user.get('date_joined', 'Unknown'), 'last_login': user.get('last_login', 'Unknown'), } def users(): result = setup_simple_command( "users", "Report information about users and their passwords.", ) if isinstance(result, int): return result else: settings, closer, env, args = result try: db = settings['mongodb'].get_database() for user in db.users.find().sort('date_joined'): info = _get_user_info(db, user) text = ('%s (%s)\n' '\tPasswords: %d\n' '\tProviders: %s\n' '\tVerified: %s\n' '\tDate joined: %s\n' '\tLast login: %s\n' % ( info['display_name'], user['_id'], info['passwords'], info['providers'], info['verified'], info['date_joined'], info['last_login'], )) <|code_end|> . Use current file imports: (import operator from yithlibraryserver.user.accounts import get_available_providers from yithlibraryserver.user.accounts import get_provider_key, get_n_passwords from yithlibraryserver.scripts.utils import safe_print, setup_simple_command 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/user/accounts.py # def get_available_providers(): # return ('facebook', 'google', 'twitter', 'persona') # # Path: yithlibraryserver/user/accounts.py # def get_provider_key(provider): # return '%s_id' % provider # # def get_n_passwords(db, user): # return db.passwords.find({ # 'owner': user.get('_id', None), # }, safe=True).count() # # 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')) # # def setup_simple_command(name, description): # usage = name + ": %prog config_uri" # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if not len(args) >= 1: # safe_print('You must provide at least one argument') # return 2 # config_uri = args[0] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # return settings, closer, env, args[1:] # # 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(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/>. def _get_user_info(db, user): return { 'display_name': get_user_display_name(user), 'passwords': get_n_passwords(db, user), 'providers': ', '.join([prov for prov in get_available_providers() if ('%s_id' % prov) in user]), 'verified': user.get('email_verified', False), 'date_joined': user.get('date_joined', 'Unknown'), 'last_login': user.get('last_login', 'Unknown'), } def users(): <|code_end|> using the current file's imports: import operator from yithlibraryserver.user.accounts import get_available_providers from yithlibraryserver.user.accounts import get_provider_key, get_n_passwords from yithlibraryserver.scripts.utils import safe_print, setup_simple_command from yithlibraryserver.scripts.utils import get_user_display_name and any relevant context from other files: # Path: yithlibraryserver/user/accounts.py # def get_available_providers(): # return ('facebook', 'google', 'twitter', 'persona') # # Path: yithlibraryserver/user/accounts.py # def get_provider_key(provider): # return '%s_id' % provider # # def get_n_passwords(db, user): # return db.passwords.find({ # 'owner': user.get('_id', None), # }, safe=True).count() # # 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')) # # def setup_simple_command(name, description): # usage = name + ": %prog config_uri" # parser = optparse.OptionParser( # usage=usage, # description=textwrap.dedent(description) # ) # options, args = parser.parse_args(sys.argv[1:]) # if not len(args) >= 1: # safe_print('You must provide at least one argument') # return 2 # config_uri = args[0] # env = bootstrap(config_uri) # settings, closer = env['registry'].settings, env['closer'] # # return settings, closer, env, args[1:] # # 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.
result = setup_simple_command(
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/>. class Oauth2ClientTests(unittest.TestCase): def test_oauth2_step1(self): with patch('uuid.uuid4') as fake: fake.return_value = 'random-string' request = DummyRequest() request.params = {'next_url': 'http://localhost/'} request.session = {} response = oauth2_step1( request=request, auth_uri='http://example.com/oauth2/auth', client_id='1234', redirect_url='http://localhost/oauth2/callback', scope='scope1 scope2' ) self.assertEqual(response.status, '302 Found') <|code_end|> , determine the next line of code. You have imports: import unittest from mock import patch from pyramid.testing import DummyRequest from yithlibraryserver.compat import urlparse from yithlibraryserver.oauth2.client import get_user_info from yithlibraryserver.oauth2.client import oauth2_step1, oauth2_step2 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.
url = urlparse.urlparse(response.location)
Next line prediction: <|code_start|># 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 Gravatar(object): def __init__(self, request, default_image_url): self.request = request self.default_image_url = default_image_url def get_email_hash(self, email): return hashlib.md5(email.lower().encode('utf-8')).hexdigest() def get_image_url(self, size=32): default_image_url = self.default_image_url email = self.get_email() if not email: return default_image_url email_hash = self.get_email_hash(email) parameters = { 'd': default_image_url, 's': size, } gravatar_url = 'https://www.gravatar.com/avatar/%s?%s' % ( <|code_end|> . Use current file imports: (import hashlib from yithlibraryserver.compat import url_encode) 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.
email_hash, url_encode(parameters))
Predict the next line after this snippet: <|code_start|> last_name = ' '.join(parts[1:]) else: first_name = parts[0] last_name = '' return first_name, last_name def delete_user(db, user): result = db.users.remove(user['_id'], safe=True) return result['n'] == 1 def update_user(db, user, user_info, other_changes): changes = {} for attribute in ('screen_name', 'first_name', 'last_name', 'email'): if attribute in user_info and user_info[attribute]: if attribute in user: if user_info[attribute] != user[attribute]: changes[attribute] = user_info[attribute] else: changes[attribute] = user_info[attribute] changes.update(other_changes) db.users.update({'_id': user['_id']}, {'$set': changes}, safe=True) def user_from_provider_id(db, provider, user_id): <|code_end|> using the current file's imports: from pyramid.httpexceptions import HTTPFound from pyramid.security import remember from yithlibraryserver.user.accounts import get_provider_key and any relevant context from other files: # Path: yithlibraryserver/user/accounts.py # def get_provider_key(provider): # return '%s_id' % provider . Output only the next line.
provider_key = get_provider_key(provider)
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 CreateMessageTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() def test_create_message(self): request = testing.DummyRequest() <|code_end|> , predict the immediate next line with the help of imports: import unittest from pyramid import testing from pyramid_mailer import get_mailer from pyramid_mailer.message import Attachment from yithlibraryserver.email import create_message, send_email from yithlibraryserver.email import send_email_to_admins from yithlibraryserver.testing import TestCase and context (classes, functions, sometimes code) from other files: # 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 # # 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) # # 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/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.
message = create_message(
Based on the snippet: <|code_start|> message = create_message( request, 'yithlibraryserver.tests:templates/email_test', {'name': 'John', 'email': 'john@example.com'}, 'Testing message', ['john@example.com'], extra_headers={'foo': 'bar'}, ) self.assertEqual(message.subject, 'Testing message') self.assertEqual(message.html, '<p>Hello John,</p>\n\n<p>this is your email address: john@example.com</p>') self.assertEqual(message.body, 'Hello John,\n\nthis is your email address: john@example.com\n') self.assertEqual(message.recipients, ['john@example.com']) self.assertEqual(message.attachments, []) self.assertEqual(message.extra_headers, {'foo': 'bar'}) class SendEmailTests(TestCase): def setUp(self): self.admin_emails = ['admin1@example.com', 'admin2@example.com'] self.config = testing.setUp(settings={ 'admin_emails': self.admin_emails, }) self.config.include('pyramid_mailer.testing') self.config.include('yithlibraryserver') super(SendEmailTests, self).setUp() def test_send_email(self): request = testing.DummyRequest() mailer = get_mailer(request) <|code_end|> , predict the immediate next line with the help of imports: import unittest from pyramid import testing from pyramid_mailer import get_mailer from pyramid_mailer.message import Attachment from yithlibraryserver.email import create_message, send_email from yithlibraryserver.email import send_email_to_admins from yithlibraryserver.testing import TestCase and context (classes, functions, sometimes code) from other files: # 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 # # 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) # # 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/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.
send_email(
Given snippet: <|code_start|> 'admin_emails': self.admin_emails, }) self.config.include('pyramid_mailer.testing') self.config.include('yithlibraryserver') super(SendEmailTests, self).setUp() def test_send_email(self): request = testing.DummyRequest() mailer = get_mailer(request) send_email( request, 'yithlibraryserver.tests:templates/email_test', {'name': 'John', 'email': 'john@example.com'}, 'Testing message', ['john@example.com'], ) self.assertEqual(len(mailer.outbox), 1) message = mailer.outbox[0] self.assertEqual(message.subject, 'Testing message') self.assertEqual(message.html, '<p>Hello John,</p>\n\n<p>this is your email address: john@example.com</p>') self.assertEqual(message.body, 'Hello John,\n\nthis is your email address: john@example.com\n') self.assertEqual(message.recipients, ['john@example.com']) self.assertEqual(message.attachments, []) self.assertEqual(message.extra_headers, {}) def test_send_email_to_admins(self): request = testing.DummyRequest() mailer = get_mailer(request) <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from pyramid import testing from pyramid_mailer import get_mailer from pyramid_mailer.message import Attachment from yithlibraryserver.email import create_message, send_email from yithlibraryserver.email import send_email_to_admins from yithlibraryserver.testing import TestCase and context: # 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 # # 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) # # 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/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.
send_email_to_admins(
Given the code 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 GravatarTests(unittest.TestCase): def assertURLEqual(self, url1, url2): parts1 = urlparse.urlparse(url1) parts2 = urlparse.urlparse(url2) self.assertEqual(parts1.scheme, parts2.scheme) self.assertEqual(parts1.hostname, parts2.hostname) self.assertEqual(parts1.netloc, parts2.netloc) self.assertEqual(parts1.params, parts2.params) self.assertEqual(parts1.path, parts2.path) self.assertEqual(parts1.port, parts2.port) self.assertEqual(urlparse.parse_qs(parts1.query), urlparse.parse_qs(parts2.query)) def test_get_email(self): request = DummyRequest() request.user = None <|code_end|> , generate the next line using the imports in this file: import unittest from pyramid.testing import DummyRequest from yithlibraryserver.compat import urlparse from yithlibraryserver.user.gravatar import Gravatar and context (functions, classes, or occasionally 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/gravatar.py # class Gravatar(object): # # def __init__(self, request, default_image_url): # self.request = request # self.default_image_url = default_image_url # # def get_email_hash(self, email): # return hashlib.md5(email.lower().encode('utf-8')).hexdigest() # # def get_image_url(self, size=32): # default_image_url = self.default_image_url # # email = self.get_email() # if not email: # return default_image_url # # email_hash = self.get_email_hash(email) # parameters = { # 'd': default_image_url, # 's': size, # } # gravatar_url = 'https://www.gravatar.com/avatar/%s?%s' % ( # email_hash, url_encode(parameters)) # # return gravatar_url # # def has_avatar(self): # return self.get_email() is not None # # def get_email(self): # user = self.request.user # if user is None: # return None # # email = user.get('email', '') # if not email: # return None # # return email . Output only the next line.
gravatar = Gravatar(request, 'http://localhost/default_gravatar.png')
Given the code snippet: <|code_start|> response.encode_content('gzip') return response accepted = event.request.accept_encoding.best_match(('identity', 'gzip')) if 'gzip' == accepted: event.request.add_response_callback(gzip_response) def add_base_templates(event): def get_template(name): renderer = get_renderer('yithlibraryserver:templates/%s.pt' % name) return renderer.implementation() event.update({ 'base': get_template('base'), 'profile': get_template('profile'), }) def add_custom_functions(event): locale_name = get_locale_name(event['request']) event.update({ 'dates_formatter': DatesFormatter(locale_name), }) def includeme(config): <|code_end|> , generate the next line using the imports in this file: from pyramid.events import BeforeRender, NewRequest from pyramid.i18n import get_locale_name from pyramid.renderers import get_renderer from yithlibraryserver.db import get_db from yithlibraryserver.locale import DatesFormatter and context (functions, classes, or occasionally code) from other files: # Path: yithlibraryserver/db.py # def get_db(request): # return request.registry.settings['mongodb'].get_database() # # Path: yithlibraryserver/locale.py # class DatesFormatter(object): # # def __init__(self, locale_name): # self.locale_name = locale_name # # def date(self, date_value): # if HAS_BABEL: # return format_date(date_value, locale=self.locale_name) # else: # return date_value.strftime('%c') # # def datetime(self, datetime_value): # if HAS_BABEL: # return format_datetime(datetime_value, locale=self.locale_name) # else: # return datetime_value.strftime('%c') . Output only the next line.
config.set_request_property(get_db, 'db', reify=True)
Given snippet: <|code_start|> def add_compress_response_callback(event): def gzip_response(request, response): response.encode_content('gzip') return response accepted = event.request.accept_encoding.best_match(('identity', 'gzip')) if 'gzip' == accepted: event.request.add_response_callback(gzip_response) def add_base_templates(event): def get_template(name): renderer = get_renderer('yithlibraryserver:templates/%s.pt' % name) return renderer.implementation() event.update({ 'base': get_template('base'), 'profile': get_template('profile'), }) def add_custom_functions(event): locale_name = get_locale_name(event['request']) event.update({ <|code_end|> , continue by predicting the next line. Consider current file imports: from pyramid.events import BeforeRender, NewRequest from pyramid.i18n import get_locale_name from pyramid.renderers import get_renderer from yithlibraryserver.db import get_db from yithlibraryserver.locale import DatesFormatter and context: # Path: yithlibraryserver/db.py # def get_db(request): # return request.registry.settings['mongodb'].get_database() # # Path: yithlibraryserver/locale.py # class DatesFormatter(object): # # def __init__(self, locale_name): # self.locale_name = locale_name # # def date(self, date_value): # if HAS_BABEL: # return format_date(date_value, locale=self.locale_name) # else: # return date_value.strftime('%c') # # def datetime(self, datetime_value): # if HAS_BABEL: # return format_datetime(datetime_value, locale=self.locale_name) # else: # return datetime_value.strftime('%c') which might include code, classes, or functions. Output only the next line.
'dates_formatter': DatesFormatter(locale_name),
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 SecurityTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() self.config.include('yithlibraryserver.user') <|code_end|> . Use current file imports: import unittest from pyramid import testing from pyramid.httpexceptions import HTTPFound from yithlibraryserver.db import MongoDB from yithlibraryserver.testing import MONGO_URI from yithlibraryserver.user.security import ( get_user, assert_authenticated_user_is_registered, ) and context (classes, functions, or 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/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # # Path: yithlibraryserver/user/security.py # def get_user(request): # user_id = unauthenticated_userid(request) # if user_id is None: # return user_id # # try: # user = request.db.users.find_one(bson.ObjectId(user_id)) # except bson.errors.InvalidId: # return None # # return User(user) # # 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.
mdb = MongoDB(MONGO_URI)
Next line prediction: <|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 SecurityTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() self.config.include('yithlibraryserver.user') <|code_end|> . Use current file imports: (import unittest from pyramid import testing from pyramid.httpexceptions import HTTPFound from yithlibraryserver.db import MongoDB from yithlibraryserver.testing import MONGO_URI from yithlibraryserver.user.security import ( get_user, assert_authenticated_user_is_registered, )) and context including class names, function names, or small code snippets 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/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # # Path: yithlibraryserver/user/security.py # def get_user(request): # user_id = unauthenticated_userid(request) # if user_id is None: # return user_id # # try: # user = request.db.users.find_one(bson.ObjectId(user_id)) # except bson.errors.InvalidId: # return None # # return User(user) # # 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.
mdb = MongoDB(MONGO_URI)
Predict the next line after this snippet: <|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 SecurityTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() self.config.include('yithlibraryserver.user') mdb = MongoDB(MONGO_URI) self.db = mdb.get_database() def tearDown(self): testing.tearDown() self.db.drop_collection('users') def test_get_user(self): request = testing.DummyRequest() request.db = self.db <|code_end|> using the current file's imports: import unittest from pyramid import testing from pyramid.httpexceptions import HTTPFound from yithlibraryserver.db import MongoDB from yithlibraryserver.testing import MONGO_URI from yithlibraryserver.user.security import ( get_user, assert_authenticated_user_is_registered, ) 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/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # # Path: yithlibraryserver/user/security.py # def get_user(request): # user_id = unauthenticated_userid(request) # if user_id is None: # return user_id # # try: # user = request.db.users.find_one(bson.ObjectId(user_id)) # except bson.errors.InvalidId: # return None # # return User(user) # # 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.
self.assertEqual(None, get_user(request))
Given the code snippet: <|code_start|> self.config.include('yithlibraryserver.user') mdb = MongoDB(MONGO_URI) self.db = mdb.get_database() def tearDown(self): testing.tearDown() self.db.drop_collection('users') def test_get_user(self): request = testing.DummyRequest() request.db = self.db self.assertEqual(None, get_user(request)) self.config.testing_securitypolicy(userid='john') self.assertEqual(None, get_user(request)) user_id = self.db.users.insert({'screen_name': 'John Doe'}, safe=True) self.config.testing_securitypolicy(userid=str(user_id)) self.assertEqual(get_user(request), { '_id': user_id, 'screen_name': 'John Doe', }) def test_assert_authenticated_user_is_registered(self): self.config.testing_securitypolicy(userid='john') request = testing.DummyRequest() request.db = self.db <|code_end|> , generate the next line using the imports in this file: import unittest from pyramid import testing from pyramid.httpexceptions import HTTPFound from yithlibraryserver.db import MongoDB from yithlibraryserver.testing import MONGO_URI from yithlibraryserver.user.security import ( get_user, assert_authenticated_user_is_registered, ) 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/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # # Path: yithlibraryserver/user/security.py # def get_user(request): # user_id = unauthenticated_userid(request) # if user_id is None: # return user_id # # try: # user = request.db.users.find_one(bson.ObjectId(user_id)) # except bson.errors.InvalidId: # return None # # return User(user) # # 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.
self.assertRaises(HTTPFound, assert_authenticated_user_is_registered, request)
Given the code 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/>. CONFIG = """[app:main] use = egg:yith-library-server mongo_uri = %s auth_tk_secret = 123456 testing = True pyramid_mailer.prefix = mail_ mail_default_sender = no-reply@yithlibrary.com admin_emails = admin1@example.com admin2@example.com [server:main] use = egg:waitress#main host = 0.0.0.0 port = 65432 """ % MONGO_URI 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')) <|code_end|> , generate the next line using the imports in this file: import os import unittest import tempfile from yithlibraryserver.db import MongoDB 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/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' . Output only the next line.
mdb = MongoDB(MONGO_URI)
Given the code 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/>. CONFIG = """[app:main] use = egg:yith-library-server mongo_uri = %s auth_tk_secret = 123456 testing = True pyramid_mailer.prefix = mail_ mail_default_sender = no-reply@yithlibrary.com admin_emails = admin1@example.com admin2@example.com [server:main] use = egg:waitress#main host = 0.0.0.0 port = 65432 <|code_end|> , generate the next line using the imports in this file: import os import unittest import tempfile from yithlibraryserver.db import MongoDB 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/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' . Output only the next line.
""" % MONGO_URI
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/>. class ModelTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() mdb = MongoDB(MONGO_URI) self.db = mdb.get_database() os.environ['YITH_FAKE_DATETIME'] = '2013-1-2-10-11-02' self.request = testing.DummyRequest() <|code_end|> , determine the next line of code. You have imports: import datetime import os import unittest from pyramid import testing from yithlibraryserver.datetimeservice.testing import FakeDatetimeService from yithlibraryserver.db import MongoDB from yithlibraryserver.testing import MONGO_URI from yithlibraryserver.contributions.models import include_sticker from yithlibraryserver.contributions.models import create_donation and context (class names, function names, or code) available: # 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) # # 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/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # # Path: yithlibraryserver/contributions/models.py # def include_sticker(amount): # return amount > 1 # # 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 . Output only the next line.
self.request.datetime_service = FakeDatetimeService(self.request)
Given the code 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 ModelTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() <|code_end|> , generate the next line using the imports in this file: import datetime import os import unittest from pyramid import testing from yithlibraryserver.datetimeservice.testing import FakeDatetimeService from yithlibraryserver.db import MongoDB from yithlibraryserver.testing import MONGO_URI from yithlibraryserver.contributions.models import include_sticker from yithlibraryserver.contributions.models import create_donation and context (functions, classes, or occasionally code) from other files: # 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) # # 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/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # # Path: yithlibraryserver/contributions/models.py # def include_sticker(amount): # return amount > 1 # # 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 . Output only the next line.
mdb = MongoDB(MONGO_URI)
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/>. class ModelTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() <|code_end|> , predict the next line using imports from the current file: import datetime import os import unittest from pyramid import testing from yithlibraryserver.datetimeservice.testing import FakeDatetimeService from yithlibraryserver.db import MongoDB from yithlibraryserver.testing import MONGO_URI from yithlibraryserver.contributions.models import include_sticker from yithlibraryserver.contributions.models import create_donation and context including class names, function names, and sometimes code from other files: # 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) # # 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/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # # Path: yithlibraryserver/contributions/models.py # def include_sticker(amount): # return amount > 1 # # 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 . Output only the next line.
mdb = MongoDB(MONGO_URI)
Using the snippet: <|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/>. class ModelTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() mdb = MongoDB(MONGO_URI) self.db = mdb.get_database() os.environ['YITH_FAKE_DATETIME'] = '2013-1-2-10-11-02' self.request = testing.DummyRequest() self.request.datetime_service = FakeDatetimeService(self.request) self.request.db = self.db def tearDown(self): testing.tearDown() self.db.drop_collection('donations') del os.environ['YITH_FAKE_DATETIME'] def test_include_sticker(self): <|code_end|> , determine the next line of code. You have imports: import datetime import os import unittest from pyramid import testing from yithlibraryserver.datetimeservice.testing import FakeDatetimeService from yithlibraryserver.db import MongoDB from yithlibraryserver.testing import MONGO_URI from yithlibraryserver.contributions.models import include_sticker from yithlibraryserver.contributions.models import create_donation and context (class names, function names, or code) available: # 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) # # 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/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # # Path: yithlibraryserver/contributions/models.py # def include_sticker(amount): # return amount > 1 # # 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 . Output only the next line.
self.assertFalse(include_sticker(1))
Continue the code snippet: <|code_start|> class ModelTests(unittest.TestCase): def setUp(self): self.config = testing.setUp() mdb = MongoDB(MONGO_URI) self.db = mdb.get_database() os.environ['YITH_FAKE_DATETIME'] = '2013-1-2-10-11-02' self.request = testing.DummyRequest() self.request.datetime_service = FakeDatetimeService(self.request) self.request.db = self.db def tearDown(self): testing.tearDown() self.db.drop_collection('donations') del os.environ['YITH_FAKE_DATETIME'] def test_include_sticker(self): self.assertFalse(include_sticker(1)) self.assertTrue(include_sticker(5)) self.assertTrue(include_sticker(10)) def test_create_donation_no_sticker(self): self.request.user = None <|code_end|> . Use current file imports: import datetime import os import unittest from pyramid import testing from yithlibraryserver.datetimeservice.testing import FakeDatetimeService from yithlibraryserver.db import MongoDB from yithlibraryserver.testing import MONGO_URI from yithlibraryserver.contributions.models import include_sticker from yithlibraryserver.contributions.models import create_donation and context (classes, functions, or code) from other files: # 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) # # 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/testing.py # MONGO_URI = 'mongodb://localhost:27017/test-yith-library' # # Path: yithlibraryserver/contributions/models.py # def include_sticker(amount): # return amount > 1 # # 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 . Output only the next line.
donation = create_donation(self.request, {
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/>. class UtilsTests(TestCase): clean_collections = ('users', 'passwords', ) def test_get_user_passwords(self): user_id = self.db.users.insert({ 'first_name': 'John', 'last_name': 'Doe', }, safe=True) user = self.db.users.find_one({'_id': user_id}) <|code_end|> . Use current file imports: (import datetime from yithlibraryserver.backups.utils import get_user_passwords from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import compress, uncompress from yithlibraryserver.testing import TestCase) and context including class names, function names, or small code snippets from other files: # 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 get_backup_filename(date): # return 'yith-library-backup-%d-%02d-%02d.yith' % ( # date.year, date.month, date.day) # # 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/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(get_user_passwords(self.db, user), [])
Based on the snippet: <|code_start|> class UtilsTests(TestCase): clean_collections = ('users', 'passwords', ) def test_get_user_passwords(self): user_id = self.db.users.insert({ 'first_name': 'John', 'last_name': 'Doe', }, safe=True) user = self.db.users.find_one({'_id': user_id}) self.assertEqual(get_user_passwords(self.db, user), []) self.db.passwords.insert({ 'owner': user_id, 'password': 'secret1', }) self.db.passwords.insert({ 'owner': user_id, 'password': 'secret2', }) self.assertEqual(get_user_passwords(self.db, user), [{ 'password': 'secret1', } ,{ 'password': 'secret2', }]) def test_get_backup_filename(self): <|code_end|> , predict the immediate next line with the help of imports: import datetime from yithlibraryserver.backups.utils import get_user_passwords from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import compress, uncompress from yithlibraryserver.testing import TestCase and context (classes, functions, sometimes code) from other files: # 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 get_backup_filename(date): # return 'yith-library-backup-%d-%02d-%02d.yith' % ( # date.year, date.month, date.day) # # 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/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(get_backup_filename(datetime.date(2012, 10, 28)),
Predict the next line after this snippet: <|code_start|> 'last_name': 'Doe', }, safe=True) user = self.db.users.find_one({'_id': user_id}) self.assertEqual(get_user_passwords(self.db, user), []) self.db.passwords.insert({ 'owner': user_id, 'password': 'secret1', }) self.db.passwords.insert({ 'owner': user_id, 'password': 'secret2', }) self.assertEqual(get_user_passwords(self.db, user), [{ 'password': 'secret1', } ,{ 'password': 'secret2', }]) def test_get_backup_filename(self): self.assertEqual(get_backup_filename(datetime.date(2012, 10, 28)), 'yith-library-backup-2012-10-28.yith') self.assertEqual(get_backup_filename(datetime.date(2013, 1, 8)), 'yith-library-backup-2013-01-08.yith') def test_compress_and_uncompress(self): passwords = [{'password': 'secret1'}, {'password': 'secret2'}] <|code_end|> using the current file's imports: import datetime from yithlibraryserver.backups.utils import get_user_passwords from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import compress, uncompress from yithlibraryserver.testing import TestCase and any relevant context from other files: # 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 get_backup_filename(date): # return 'yith-library-backup-%d-%02d-%02d.yith' % ( # date.year, date.month, date.day) # # 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/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(uncompress(compress(passwords)), passwords)
Predict the next line after this snippet: <|code_start|> 'last_name': 'Doe', }, safe=True) user = self.db.users.find_one({'_id': user_id}) self.assertEqual(get_user_passwords(self.db, user), []) self.db.passwords.insert({ 'owner': user_id, 'password': 'secret1', }) self.db.passwords.insert({ 'owner': user_id, 'password': 'secret2', }) self.assertEqual(get_user_passwords(self.db, user), [{ 'password': 'secret1', } ,{ 'password': 'secret2', }]) def test_get_backup_filename(self): self.assertEqual(get_backup_filename(datetime.date(2012, 10, 28)), 'yith-library-backup-2012-10-28.yith') self.assertEqual(get_backup_filename(datetime.date(2013, 1, 8)), 'yith-library-backup-2013-01-08.yith') def test_compress_and_uncompress(self): passwords = [{'password': 'secret1'}, {'password': 'secret2'}] <|code_end|> using the current file's imports: import datetime from yithlibraryserver.backups.utils import get_user_passwords from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import compress, uncompress from yithlibraryserver.testing import TestCase and any relevant context from other files: # 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 get_backup_filename(date): # return 'yith-library-backup-%d-%02d-%02d.yith' % ( # date.year, date.month, date.day) # # 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/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(uncompress(compress(passwords)), passwords)
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 AnnounceTests(ScriptTests): clean_collections = ('users', 'passwords') def setUp(self): super(AnnounceTests, self).setUp() # Save sys values self.old_args = sys.argv[:] self.old_stdout = sys.stdout def tearDown(self): # Restore sys.values sys.argv = self.old_args sys.stdout = self.old_stdout super(AnnounceTests, self).tearDown() def test_no_arguments(self): sys.argv = [] <|code_end|> , predict the immediate next line with the help of imports: import sys from yithlibraryserver.compat import StringIO from yithlibraryserver.scripts.announce import announce from yithlibraryserver.scripts.testing import ScriptTests 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/scripts/announce.py # 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'] # preferences_link = urlparse.urljoin( # public_url_root, # request.route_path('user_preferences')) # # tx = transaction.begin() # # mailer = get_mailer(request) # # for user in get_all_users_with_passwords_and_email(db): # message = send_email(request, email_template, user, # preferences_link) # mailer.send(message) # # 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()
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/>. class AnnounceTests(ScriptTests): clean_collections = ('users', 'passwords') def setUp(self): super(AnnounceTests, self).setUp() # Save sys values self.old_args = sys.argv[:] self.old_stdout = sys.stdout def tearDown(self): # Restore sys.values sys.argv = self.old_args sys.stdout = self.old_stdout super(AnnounceTests, self).tearDown() def test_no_arguments(self): sys.argv = [] sys.stdout = StringIO() <|code_end|> . Use current file imports: (import sys from yithlibraryserver.compat import StringIO from yithlibraryserver.scripts.announce import announce from yithlibraryserver.scripts.testing import ScriptTests) 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/scripts/announce.py # 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'] # preferences_link = urlparse.urljoin( # public_url_root, # request.route_path('user_preferences')) # # tx = transaction.begin() # # mailer = get_mailer(request) # # for user in get_all_users_with_passwords_and_email(db): # message = send_email(request, email_template, user, # preferences_link) # mailer.send(message) # # 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 = announce()
Next line prediction: <|code_start|>class SendEmailTests(TestCase): def setUp(self): self.admin_emails = ['admin1@example.com', 'admin2@example.com'] self.config = testing.setUp(settings={ 'admin_emails': self.admin_emails, }) self.config.include('pyramid_mailer.testing') self.config.include('yithlibraryserver') super(SendEmailTests, self).setUp() def test_send_thankyou_email(self): request = testing.DummyRequest() mailer = get_mailer(request) self.assertEqual(len(mailer.outbox), 0) donation = { 'amount': 10, 'firstname': 'John', 'lastname': 'Doe', 'city': 'Springfield', 'country': 'Exampleland', 'state': 'Example', 'street': 'Main Street 10', 'zip': '12345678', 'email': 'john@example.com', 'creation': datetime.datetime.utcnow(), 'send_sticker': True, } <|code_end|> . Use current file imports: (import datetime from pyramid import testing from pyramid_mailer import get_mailer from yithlibraryserver.testing import TestCase from yithlibraryserver.contributions.email import send_thankyou_email from yithlibraryserver.contributions.email import send_notification_to_admins) and context including class names, function names, or small code snippets 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/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!', # ) . Output only the next line.
send_thankyou_email(request, donation)
Based on the snippet: <|code_start|> 'creation': datetime.datetime.utcnow(), 'send_sticker': True, } send_thankyou_email(request, donation) self.assertEqual(len(mailer.outbox), 1) message = mailer.outbox[0] self.assertEqual(message.subject, 'Thanks for your contribution!') self.assertEqual(message.recipients, ['john@example.com']) def test_send_notification_to_admins(self): request = testing.DummyRequest() mailer = get_mailer(request) self.assertEqual(len(mailer.outbox), 0) donation = { 'amount': 10, 'firstname': 'John', 'lastname': 'Doe', 'city': 'Springfield', 'country': 'Exampleland', 'state': 'Example', 'street': 'Main Street 10', 'zip': '12345678', 'email': 'john@example.com', 'creation': datetime.datetime.utcnow(), 'send_sticker': True, 'user': None, } <|code_end|> , predict the immediate next line with the help of imports: import datetime from pyramid import testing from pyramid_mailer import get_mailer from yithlibraryserver.testing import TestCase from yithlibraryserver.contributions.email import send_thankyou_email from yithlibraryserver.contributions.email import send_notification_to_admins and context (classes, functions, sometimes code) 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/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!', # ) . Output only the next line.
send_notification_to_admins(request, donation)
Using the snippet: <|code_start|># 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(testing.TestCase): clean_collections = ('access_codes', 'users') def test_authorize_user(self): request = testing.FakeRequest(headers={}) # The authorization header is required <|code_end|> , determine the next line of code. You have imports: from pyramid.httpexceptions import HTTPBadRequest, HTTPUnauthorized from yithlibraryserver import testing from yithlibraryserver.security import authorize_user and context (class names, function names, or code) available: # 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/security.py # 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') # # access_code = AccessCodes(request.db).find(credentials) # if access_code is None: # raise HTTPUnauthorized() # # user_id = access_code['user'] # user = request.db.users.find_one(user_id) # if user is None: # raise HTTPUnauthorized() # # return user . Output only the next line.
self.assertRaises(HTTPUnauthorized, authorize_user, request)
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/>. def get_user(request): user_id = unauthenticated_userid(request) if user_id is None: return user_id try: user = request.db.users.find_one(bson.ObjectId(user_id)) except bson.errors.InvalidId: return None <|code_end|> . Write the next line using the current file imports: import bson from pyramid.security import authenticated_userid, unauthenticated_userid from pyramid.httpexceptions import HTTPFound from yithlibraryserver.user.models import User and context from other files: # 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__() , which may include functions, classes, or code. Output only the next line.
return User(user)
Predict the next line for this snippet: <|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/>. 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() <|code_end|> with the help of current file imports: from pyramid_mailer.message import Attachment from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import get_user_passwords, compress from yithlibraryserver.email import send_email and 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)] # # 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() # # 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) , which may contain function names, class names, or code. Output only the next line.
attachment = Attachment(get_backup_filename(today),
Continue the code 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_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): <|code_end|> . Use current file imports: from pyramid_mailer.message import Attachment from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import get_user_passwords, compress from yithlibraryserver.email import send_email and context (classes, functions, or 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)] # # 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() # # 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.
passwords = get_user_passwords(request.db, user)
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 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", <|code_end|> . Use current file imports: (from pyramid_mailer.message import Attachment from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import get_user_passwords, compress from yithlibraryserver.email import send_email) 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)] # # 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() # # 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.
compress(passwords))
Based on the 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_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)) <|code_end|> , predict the immediate next line with the help of imports: from pyramid_mailer.message import Attachment from yithlibraryserver.backups.utils import get_backup_filename from yithlibraryserver.backups.utils import get_user_passwords, compress from yithlibraryserver.email import send_email 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)] # # 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() # # 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.
send_email(
Predict the next line after this snippet: <|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/>. log = logging.getLogger(__name__) class IdentityProvider(object): def __init__(self, name): self.name = name @property def route_path(self): return '%s_login' % self.name @property def image_path(self): return 'yithlibraryserver:static/img/%s-logo.png' % self.name @property def message(self): <|code_end|> using the current file's imports: import logging from yithlibraryserver.i18n import TranslationString as _ and any relevant context from other files: # Path: yithlibraryserver/i18n.py # def deform_translator(term): # def locale_negotiator(request): . Output only the next line.
return _('Log in with ${idp}', mapping={'idp': self.name.capitalize()})
Here is a snippet: <|code_start|> def memoized(fget): """ Return a property attribute for new-style classes that only calls its getter on the first access. The result is stored and on subsequent accesses is returned, preventing the need to call the getter any more. https://github.com/estebistec/python-memoized-property """ attr_name = '_{0}'.format(fget.__name__) @wraps(fget) def fget_memoized(self): if not hasattr(self, attr_name): setattr(self, attr_name, fget(self)) return getattr(self, attr_name) return property(fget_memoized) def timeit(func): """ Returns the number of seconds that a function took along with the result """ @wraps(func) def timer_wrapper(*args, **kwargs): """ Inner function that uses the Timer context object """ <|code_end|> . Write the next line using the current file imports: import signal from functools import wraps from feet.utils.timez import Timer from feet.exceptions import FeetError, TimeoutError and context from other files: # Path: feet/utils/timez.py # class Timer(object): # """ # A context object timer. Usage: # >>> with Timer() as timer: # ... do_something() # >>> print timer.elapsed # """ # # def __init__(self, wall_clock=True): # """ # If wall_clock is True then use time.time() to get the number of # actually elapsed seconds. If wall_clock is False, use time.clock to # get the process time instead. # """ # self.wall_clock = wall_clock # self.time = time.time if wall_clock else time.clock # # # Stubs for serializing an empty timer. # self.started = None # self.finished = None # self.elapsed = 0.0 # # def __enter__(self): # self.started = self.time() # return self # # def __exit__(self, typ, value, tb): # self.finished = self.time() # self.elapsed = self.finished - self.started # # def __str__(self): # return humanizedelta(seconds=self.elapsed) # # Path: feet/exceptions.py # class FeetError(Exception): # """The root of all errors in Feet library""" # pass # # class TimeoutError(Exception): # """ # An operation timed out # """ # pass , which may include functions, classes, or code. Output only the next line.
with Timer() as timer:
Next line prediction: <|code_start|> return result, timer return timer_wrapper def timeout(seconds): """ Raises a TimeoutError if a function does not terminate within specified seconds. """ def _timeout_error(signal, frame): raise TimeoutError("Operation did not finish within \ {} seconds".format(seconds)) def timeout_decorator(func): @wraps(func) def timeout_wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _timeout_error) signal.alarm(seconds) try: return func(*args, **kwargs) finally: signal.alarm(0) return timeout_wrapper return timeout_decorator <|code_end|> . Use current file imports: (import signal from functools import wraps from feet.utils.timez import Timer from feet.exceptions import FeetError, TimeoutError) and context including class names, function names, or small code snippets from other files: # Path: feet/utils/timez.py # class Timer(object): # """ # A context object timer. Usage: # >>> with Timer() as timer: # ... do_something() # >>> print timer.elapsed # """ # # def __init__(self, wall_clock=True): # """ # If wall_clock is True then use time.time() to get the number of # actually elapsed seconds. If wall_clock is False, use time.clock to # get the process time instead. # """ # self.wall_clock = wall_clock # self.time = time.time if wall_clock else time.clock # # # Stubs for serializing an empty timer. # self.started = None # self.finished = None # self.elapsed = 0.0 # # def __enter__(self): # self.started = self.time() # return self # # def __exit__(self, typ, value, tb): # self.finished = self.time() # self.elapsed = self.finished - self.started # # def __str__(self): # return humanizedelta(seconds=self.elapsed) # # Path: feet/exceptions.py # class FeetError(Exception): # """The root of all errors in Feet library""" # pass # # class TimeoutError(Exception): # """ # An operation timed out # """ # pass . Output only the next line.
def reraise(klass=FeetError, message=None, trap=Exception):
Given the code snippet: <|code_start|> setattr(self, attr_name, fget(self)) return getattr(self, attr_name) return property(fget_memoized) def timeit(func): """ Returns the number of seconds that a function took along with the result """ @wraps(func) def timer_wrapper(*args, **kwargs): """ Inner function that uses the Timer context object """ with Timer() as timer: result = func(*args, **kwargs) return result, timer return timer_wrapper def timeout(seconds): """ Raises a TimeoutError if a function does not terminate within specified seconds. """ def _timeout_error(signal, frame): <|code_end|> , generate the next line using the imports in this file: import signal from functools import wraps from feet.utils.timez import Timer from feet.exceptions import FeetError, TimeoutError and context (functions, classes, or occasionally code) from other files: # Path: feet/utils/timez.py # class Timer(object): # """ # A context object timer. Usage: # >>> with Timer() as timer: # ... do_something() # >>> print timer.elapsed # """ # # def __init__(self, wall_clock=True): # """ # If wall_clock is True then use time.time() to get the number of # actually elapsed seconds. If wall_clock is False, use time.clock to # get the process time instead. # """ # self.wall_clock = wall_clock # self.time = time.time if wall_clock else time.clock # # # Stubs for serializing an empty timer. # self.started = None # self.finished = None # self.elapsed = 0.0 # # def __enter__(self): # self.started = self.time() # return self # # def __exit__(self, typ, value, tb): # self.finished = self.time() # self.elapsed = self.finished - self.started # # def __str__(self): # return humanizedelta(seconds=self.elapsed) # # Path: feet/exceptions.py # class FeetError(Exception): # """The root of all errors in Feet library""" # pass # # class TimeoutError(Exception): # """ # An operation timed out # """ # pass . Output only the next line.
raise TimeoutError("Operation did not finish within \
Given the code snippet: <|code_start|> 'help': 'entity dictionary' }, '--txt': { 'metavar': 'PLAIN_FILE', 'required': False, 'help': 'path to a plain text file that will be loaded' }, '--csv': { 'metavar': 'CSV_FILE', 'required': False, 'help': 'path to a csv file that will be loaded' }, '--lang': { 'metavar': 'LANG', 'default': 'en', 'help': 'language of entities' }, '--prefix': { 'metavar': 'PREFIX', 'default': 'feet', 'help': 'prefix used for all keys of dictionary' } } def handle(self, args): """ CLI to load an entity dictionary. """ file_path = args.txt if args.csv is not None: <|code_end|> , generate the next line using the imports in this file: from commis import Command from commis import color from feet.entities.registry import Registry from feet.entities.dictionary import CSVDictionary and context (functions, classes, or occasionally code) from other files: # Path: feet/entities/registry.py # class Registry(StorageMixin, LoggingMixin): # @staticmethod # def registry_list_key(key_prefix): # return '{}:registries'.format(key_prefix) # # @staticmethod # def registry_key(key_prefix, name): # return '{}:registry:{}'.format(key_prefix, name) # # @classmethod # def list(klass, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Gets the list of registries under a prefix. # """ # if key_prefix is None: # return False # storage = Storage(redis_host, redis_port, redis_db) # return list(storage.smembers(klass.registry_list_key(key_prefix))) # # @classmethod # def flush(klass, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Deletes all registries, dictionaries etc. under a prefix # """ # if key_prefix is None: # return False # storage = Storage(redis_host, redis_port, redis_db) # keys = storage.keys('{}:*'.format(key_prefix)) # for key in keys: # storage.delete(key) # return True # # @classmethod # def find_or_create(klass, # name, # dict_class=Dictionary, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Finds a registry if it already exists otherwise creates it. # """ # if key_prefix is None: # return None # storage = Storage(redis_host, redis_port, redis_db) # storage.sadd(klass.registry_list_key(key_prefix), name) # return Registry(name, dict_class, key_prefix, # redis_host, redis_port, redis_db) # # def __init__(self, # name, # dict_class=Dictionary, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # self._name = name # self._dict_class = dict_class # self._key_prefix = key_prefix # self._redis_host = redis_host # self._redis_port = redis_port # self._redis_db = redis_db # # @memoized # def key(self): # return '{}'.format(self.registry_key(self._key_prefix, # self._name)) # # @memoized # def dict_key(self): # return '{}:dictionaries'.format(self.key) # # def dictionaries(self): # """ # Gest list of dictionaries defined under a specific registry. # """ # registry = self.storage.smembers(self.dict_key) # return list(registry) # # def get_dict(self, name): # """ # Adds or gets a dictionary under a specific registry. # """ # # TODO: make a transaction here # self.storage.sadd(self.dict_key, name) # return self._dict_class(name, self.key, self._redis_host, # self._redis_port, self._redis_db) # # def del_dict(self, name): # """ # Deletes a dictionary under a specific registry. # """ # # TODO: make a transaction here # if name not in self.dictionaries(): # return False # dictionary = self._dict_class(name, self.key, self._redis_host, # self._redis_port, self._redis_db) # dictionary.delete() # if self.storage.srem(self.dict_key, name) == 1: # return True # return False # # def delete(self): # """ # Deletes the registry. # """ # self.logger.info("Deleting registry %s ..." % self._name) # if self.storage.srem(self.registry_list_key(self._key_prefix), # self._name) == 1: # self.reset() # self.logger.info("DONE") # return True # return False # # def reset(self): # """ # Resets the registry. Automatically deletes related dictionaries. # """ # if self.storage.delete(self.dict_key) == 1: # self.logger.info("Deleting registry {} entities..." # .format(self._name)) # keys = self.storage.keys('{}:*'.format(self.key)) # for key in keys: # self.storage.delete(key) # self.logger.info("DONE") # return True # return False # # Path: feet/entities/dictionary.py # class CSVDictionary(Dictionary): # def parse_file(self, file_name): # """ # Easy parsing CSV file # """ # first_line = True # with open(file_name, 'rb') as f: # reader = csv.reader(f, delimiter=',') # for row in reader: # if first_line: # first_line = False # continue # else: # yield row[0] . Output only the next line.
registry = Registry.find_or_create(args.registry,
Based on the snippet: <|code_start|> }, '--txt': { 'metavar': 'PLAIN_FILE', 'required': False, 'help': 'path to a plain text file that will be loaded' }, '--csv': { 'metavar': 'CSV_FILE', 'required': False, 'help': 'path to a csv file that will be loaded' }, '--lang': { 'metavar': 'LANG', 'default': 'en', 'help': 'language of entities' }, '--prefix': { 'metavar': 'PREFIX', 'default': 'feet', 'help': 'prefix used for all keys of dictionary' } } def handle(self, args): """ CLI to load an entity dictionary. """ file_path = args.txt if args.csv is not None: registry = Registry.find_or_create(args.registry, <|code_end|> , predict the immediate next line with the help of imports: from commis import Command from commis import color from feet.entities.registry import Registry from feet.entities.dictionary import CSVDictionary and context (classes, functions, sometimes code) from other files: # Path: feet/entities/registry.py # class Registry(StorageMixin, LoggingMixin): # @staticmethod # def registry_list_key(key_prefix): # return '{}:registries'.format(key_prefix) # # @staticmethod # def registry_key(key_prefix, name): # return '{}:registry:{}'.format(key_prefix, name) # # @classmethod # def list(klass, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Gets the list of registries under a prefix. # """ # if key_prefix is None: # return False # storage = Storage(redis_host, redis_port, redis_db) # return list(storage.smembers(klass.registry_list_key(key_prefix))) # # @classmethod # def flush(klass, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Deletes all registries, dictionaries etc. under a prefix # """ # if key_prefix is None: # return False # storage = Storage(redis_host, redis_port, redis_db) # keys = storage.keys('{}:*'.format(key_prefix)) # for key in keys: # storage.delete(key) # return True # # @classmethod # def find_or_create(klass, # name, # dict_class=Dictionary, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Finds a registry if it already exists otherwise creates it. # """ # if key_prefix is None: # return None # storage = Storage(redis_host, redis_port, redis_db) # storage.sadd(klass.registry_list_key(key_prefix), name) # return Registry(name, dict_class, key_prefix, # redis_host, redis_port, redis_db) # # def __init__(self, # name, # dict_class=Dictionary, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # self._name = name # self._dict_class = dict_class # self._key_prefix = key_prefix # self._redis_host = redis_host # self._redis_port = redis_port # self._redis_db = redis_db # # @memoized # def key(self): # return '{}'.format(self.registry_key(self._key_prefix, # self._name)) # # @memoized # def dict_key(self): # return '{}:dictionaries'.format(self.key) # # def dictionaries(self): # """ # Gest list of dictionaries defined under a specific registry. # """ # registry = self.storage.smembers(self.dict_key) # return list(registry) # # def get_dict(self, name): # """ # Adds or gets a dictionary under a specific registry. # """ # # TODO: make a transaction here # self.storage.sadd(self.dict_key, name) # return self._dict_class(name, self.key, self._redis_host, # self._redis_port, self._redis_db) # # def del_dict(self, name): # """ # Deletes a dictionary under a specific registry. # """ # # TODO: make a transaction here # if name not in self.dictionaries(): # return False # dictionary = self._dict_class(name, self.key, self._redis_host, # self._redis_port, self._redis_db) # dictionary.delete() # if self.storage.srem(self.dict_key, name) == 1: # return True # return False # # def delete(self): # """ # Deletes the registry. # """ # self.logger.info("Deleting registry %s ..." % self._name) # if self.storage.srem(self.registry_list_key(self._key_prefix), # self._name) == 1: # self.reset() # self.logger.info("DONE") # return True # return False # # def reset(self): # """ # Resets the registry. Automatically deletes related dictionaries. # """ # if self.storage.delete(self.dict_key) == 1: # self.logger.info("Deleting registry {} entities..." # .format(self._name)) # keys = self.storage.keys('{}:*'.format(self.key)) # for key in keys: # self.storage.delete(key) # self.logger.info("DONE") # return True # return False # # Path: feet/entities/dictionary.py # class CSVDictionary(Dictionary): # def parse_file(self, file_name): # """ # Easy parsing CSV file # """ # first_line = True # with open(file_name, 'rb') as f: # reader = csv.reader(f, delimiter=',') # for row in reader: # if first_line: # first_line = False # continue # else: # yield row[0] . Output only the next line.
dict_class=CSVDictionary,
Based on the snippet: <|code_start|># Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html class NLPEntitiesTests(unittest.TestCase): def setup(self): pass def test_extract_entities(self): """ Test """ text = 'The United Nations (UN) is an intergovernmental organization '\ 'to promote international co-operation. A replacement for the '\ 'ineffective League of Nations, the organization was established '\ 'on 24 October 1945 after World War II in order to prevent '\ 'another such conflict. At its founding, the UN had 51 member '\ 'states; there are now 193. The headquarters of the United '\ 'Nations is in Manhattan, New York City, and experiences '\ 'extraterritoriality. Further main offices are situated in '\ 'Geneva, Nairobi, and Vienna. The organization is financed by '\ 'assessed and voluntary contributions from its member states. '\ 'Its objectives include maintaining international peace and '\ 'security, promoting human rights, fostering social and economic '\ 'development, protecting the environment, and providing '\ 'humanitarian aid in cases of famine, natural disaster, and armed '\ 'conflict.' # probleme with World War II not concatenated # we may take also NN and NNS with combination of CC and IN grammar = 'NE : {<NNP|NNPS|NN>*?<NNP|NNPS|JJ|NNS|NN>+}' <|code_end|> , predict the immediate next line with the help of imports: from feet.entities.nlp import Parser import unittest and context (classes, functions, sometimes code) from other files: # Path: feet/entities/nlp.py # class Parser(LoggingMixin): # """ # Provides NLP tools such as language detection, tokenizer and POS tagger # for entities # """ # _auto_lang_detect = False # _lang = 'en' # # def __init__(self, lang='english', auto_lang_detect=False): # """ # Parser class initialisation. # Defines a default language attribute and decides if automatic language # detection is turned on/off. # """ # self._auto_lang_detect = auto_lang_detect # self._lang = WORLD_2_NLTK[lang] # # def detect_language(self, text): # """ # Provides language detection of a text. # Fallbacks to default language defined in class initialization or 'en' # """ # try: # if text is None: # return None # languages = detect_langs(text.decode('utf8')) # if len(languages) > 0: # return languages[0].lang # except: # self.logger.warning(traceback.format_exc()) # return self._lang or 'en' # # def word_tokenize(self, text, lang=None): # """ # Tokenizes a sentence. # """ # if lang is not None: # lang = WORLD_2_NLTK[lang] # else: # lang = self._lang # if lang == 'japanese': # return JAParser().word_tokenize(text) # else: # if not isinstance(text, unicode): # text = text.decode('utf8') # return [token.encode('utf8') # for token in word_tokenize(text, lang)] # # return text.split() # # def sent_tokenize(self, text, lang=None): # """ # Splits a text into sentences. Yields each sentence for processing. # """ # if lang is not None: # lang = WORLD_2_NLTK[lang] # else: # lang = self._lang # if lang == 'japanese': # for sentence in JAParser().sent_tokenize(text): # yield sentence # else: # if not isinstance(text, unicode): # text = text.decode('utf8') # for sentence in sent_tokenize(text, lang): # yield sentence # # @timeit # def tokenize(self, text, lang=None): # """ # Tokenizes a text by splitting it into sentences that will be tokenized. # """ # if lang is not None: # lang = WORLD_2_NLTK[lang] # else: # lang = self._lang # output = [] # if text is None: # return output # for sentence in self.sent_tokenize(text, lang): # output.append(self.word_tokenize(sentence, lang)) # return output # # def _select_entities(self, # tree, # extra_classes=['NNP', 'NNPS', 'NN', 'NNS']): # """ # Selects candidates of entities as chunks with specific grammatic tags. # """ # entities = defaultdict(list) # for chunk in tree: # if isinstance(chunk, Tree): # entities[chunk._label].append( # " ".join([token[0] for token in chunk.leaves()])) # else: # if chunk[1] in extra_classes: # entities['noun_phrase_leave'].append(chunk[0]) # return [i for key, value in dict(entities).iteritems() for i in value] # # @timeit # def extract_entities(self, text, grammar=None, lang=None): # """ # Extract entities from text # """ # entities = [] # if lang is None: # lang = WORLD_2_NLTK[self.detect_language(text)] # else: # if lang in WORLD_2_NLTK.keys(): # lang = WORLD_2_NLTK[lang] # else: # lang = self._lang # if lang == 'japanese': # return JAParser().extract_entities(text), lang # pos_sentences = [pos_tag(self.word_tokenize(sentence, lang=lang)) # for sentence in self.sent_tokenize(text, lang=lang)] # # if grammar is not None: # chunker = RegexpParser(grammar) # for pos_sentence in pos_sentences: # tree = chunker.parse(pos_sentence) # self.logger.debug(tree) # entities = entities + self._select_entities(tree) # else: # for pos_sentence in pos_sentences: # tree = ne_chunk(pos_sentence, binary=False) # self.logger.debug(tree) # entities = entities + self._select_entities(tree) # return entities, lang . Output only the next line.
result = Parser().extract_entities(text, grammar)
Predict the next line after this snippet: <|code_start|># -*- coding: utf8 -*- # feet TornadoWeb server application # # Author: Romary Dupuis <romary.dupuis@altarika.com> # # Copyright (C) 2016 Romary Dupuis # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ TornadoWeb application definition in Feet. """ # tornado Web server tornado_settings = { "static_path": os.path.join(os.path.dirname(__file__), "static"), "cookie_secret": "__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__", "login_url": "/login", "xsrf_cookies": True, } def run(host, port, debug): <|code_end|> using the current file's imports: import os import logging import tornado.httpserver import tornado.ioloop import tornado.web import tornado.httpclient from feet.www.urls import make_app from feet.config import settings and any relevant context from other files: # Path: feet/www/urls.py # def make_app(): # return Application(handlers()) # # Path: feet/config.py # class RedisConfiguration(Configuration): # class ServerConfiguration(Configuration): # class MecabConfiguration(Configuration): # class FeetConfiguration(Configuration): # CONF_PATHS = [ # "/etc/feet.yaml", # System configuration # os.path.expanduser("~/.feet.yaml"), # User specific config # os.path.abspath("conf/feet.yaml"), # Local configuration # ] . Output only the next line.
app = make_app()
Here is a snippet: <|code_start|># Copyright (C) 2016 Romary Dupuis # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ TornadoWeb application definition in Feet. """ # tornado Web server tornado_settings = { "static_path": os.path.join(os.path.dirname(__file__), "static"), "cookie_secret": "__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__", "login_url": "/login", "xsrf_cookies": True, } def run(host, port, debug): app = make_app() app.listen(port) logging.info('Feet server listening on port %d' % (port)) try: tornado.ioloop.IOLoop.instance().start() except KeyboardInterrupt: logging.info('Feet server interrupted') if __name__ == "__main__": # if you run this file as a script, it will start the tornado Web server <|code_end|> . Write the next line using the current file imports: import os import logging import tornado.httpserver import tornado.ioloop import tornado.web import tornado.httpclient from feet.www.urls import make_app from feet.config import settings and context from other files: # Path: feet/www/urls.py # def make_app(): # return Application(handlers()) # # Path: feet/config.py # class RedisConfiguration(Configuration): # class ServerConfiguration(Configuration): # class MecabConfiguration(Configuration): # class FeetConfiguration(Configuration): # CONF_PATHS = [ # "/etc/feet.yaml", # System configuration # os.path.expanduser("~/.feet.yaml"), # User specific config # os.path.abspath("conf/feet.yaml"), # Local configuration # ] , which may include functions, classes, or code. Output only the next line.
run(host=settings.server.host, port=settings.server.port)
Given the code snippet: <|code_start|># -*- coding: utf8 -*- # test_jptools.py # Test the Japanese NLP tools # # Author: Romary Dupuis <romary.dupuis@altarika.com> # # Copyright (C) 2016 Romary Dupuis # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html class JAParserTests(unittest.TestCase): def setUp(self): pass def test_singleton(self): <|code_end|> , generate the next line using the imports in this file: from feet.entities.jptools import JAParser import unittest and context (functions, classes, or occasionally code) from other files: # Path: feet/entities/jptools.py # class JAParser(LoggingMixin): # __metaclass__ = SingletonMetaClass # # @memoized # def mecab(self): # self.logger.warning('Initialize Mecab') # return MeCab.Tagger('-d %s' % settings.mecab.mecabdict) # # def word_tokenize(self, content, with_separators=True): # if content is None: # return None # output = [] # node = self.mecab.parseToNode(content) # while node: # features = node.feature.split(',') # self.logger.debug('%s %s %s' % (node.surface, features[0], # features[1])) # if node.surface != '': # if features[0] == F1_SEPARATOR: # if with_separators: # output.append(node.surface) # else: # output.append(node.surface) # node = node.next # return output # # def sent_tokenize(self, content): # if content is None: # return [] # node = self.mecab.parseToNode(content) # separators = [] # while node: # features = node.feature.split(',') # self.logger.debug('%s %s %s' % (node.surface, features[0], # features[1])) # if node.surface == 'BOS/EOS' or (features[0] == F1_SEPARATOR and # features[1] == '句点'): # if node.surface != '': # separators.append(node.surface) # node = node.next # return filter(None, re.split(r"%s" % ('|'.join(separators)), content)) # # def extract_entities(self, content, with_numbers=False): # """ # Extract good candidates for entities in a text. # """ # output = [] # node = self.mecab.parseToNode(content) # sentence = 0 # entity = [] # while node: # features = node.feature.split(',') # f1 = features[0] # f2 = features[1] # f3 = features[2] # if f1 == F1_NOUN and \ # f2 != F2_IND_VERB and f2 != F2_NO_MEANING_NAMES and \ # f2 != F2_ADVERBS and \ # f2 != F2_PRONOUN and f2 != F2_ADJECTIVE and \ # f2 != F2_NUMBER and \ # f2 != F2_SUFFIX and \ # f3 != F3_ADVERBS and \ # node.surface not in STOPLIST: # entity.append(node.surface.lower()) # else: # if len(entity) > 0: # output.append(''.join(entity)) # entity = [] # if f1 == F1_SEPARATOR and \ # (f2 == '句点'): # sentence += 1 # # move to next morphem # node = node.next # if (len(entity) > 0): # output.append(entity) # return output # # def extract_dates(self, content, with_year=None): # """ # Extract dates from text in Japanese. # """ # if with_year is None: # with_year = str(datetime.now().year) # # TODO: use regex module instead of re # re_set = ( # re.compile(ur'\d{1,4}年\d{1,2}月\d{1,2}日', re.UNICODE), # re.compile(ur'\d{1,2}月\d{1,2}日', re.UNICODE), # # TODO: deal with days in text # re.compile(ur'\d{1,4}/\d{1}/\d{1}', re.UNICODE), # re.compile(ur'\d{1,2}/\d{1,2}', re.UNICODE) # ) # res = [] # for re_i in re_set: # res_i = re_i.findall(content.decode('utf8')) # for el in res_i: # parsed_date = parse(el) # if parsed_date is not None: # formated_parsed_date = datetime.strftime(parsed_date, # '%Y-%m-%d') # if formated_parsed_date not in res: # res.append(formated_parsed_date) # return res . Output only the next line.
self.assertEqual(JAParser(), JAParser())
Predict the next line for this snippet: <|code_start|> # parse test data csv files, quick and dirty def parse_csv_file(path): first_line = True with open(path, 'rb') as f: reader = csv.reader(f, delimiter=',') for row in reader: if first_line: first_line = False continue else: yield row[0] class GenericTestCase(LoggingMixin, AsyncHTTPTestCase): def get_app(self): return make_app() class SmokeTest(GenericTestCase): def test_http_fetch(self): """ Smoke test """ response = self.fetch('/') self.assertEqual(response.code, 200) class RegistryAPITest(GenericTestCase): def tearDown(self): <|code_end|> with the help of current file imports: import os import csv import unittest import inspect import json from tornado.testing import AsyncHTTPTestCase from feet.www.urls import make_app from feet.utils.logger import LoggingMixin from feet.entities.registry import Registry and context from other files: # Path: feet/www/urls.py # def make_app(): # return Application(handlers()) # # Path: feet/utils/logger.py # class LoggingMixin(object): # """ # Mix in to classes that need their own logging object! # """ # # @property # def logger(self): # """ # Instantiates and returns a ServiceLogger instance # """ # if not hasattr(self, '_logger') or not self._logger: # self._logger = ServiceLogger() # return self._logger # # Path: feet/entities/registry.py # class Registry(StorageMixin, LoggingMixin): # @staticmethod # def registry_list_key(key_prefix): # return '{}:registries'.format(key_prefix) # # @staticmethod # def registry_key(key_prefix, name): # return '{}:registry:{}'.format(key_prefix, name) # # @classmethod # def list(klass, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Gets the list of registries under a prefix. # """ # if key_prefix is None: # return False # storage = Storage(redis_host, redis_port, redis_db) # return list(storage.smembers(klass.registry_list_key(key_prefix))) # # @classmethod # def flush(klass, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Deletes all registries, dictionaries etc. under a prefix # """ # if key_prefix is None: # return False # storage = Storage(redis_host, redis_port, redis_db) # keys = storage.keys('{}:*'.format(key_prefix)) # for key in keys: # storage.delete(key) # return True # # @classmethod # def find_or_create(klass, # name, # dict_class=Dictionary, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Finds a registry if it already exists otherwise creates it. # """ # if key_prefix is None: # return None # storage = Storage(redis_host, redis_port, redis_db) # storage.sadd(klass.registry_list_key(key_prefix), name) # return Registry(name, dict_class, key_prefix, # redis_host, redis_port, redis_db) # # def __init__(self, # name, # dict_class=Dictionary, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # self._name = name # self._dict_class = dict_class # self._key_prefix = key_prefix # self._redis_host = redis_host # self._redis_port = redis_port # self._redis_db = redis_db # # @memoized # def key(self): # return '{}'.format(self.registry_key(self._key_prefix, # self._name)) # # @memoized # def dict_key(self): # return '{}:dictionaries'.format(self.key) # # def dictionaries(self): # """ # Gest list of dictionaries defined under a specific registry. # """ # registry = self.storage.smembers(self.dict_key) # return list(registry) # # def get_dict(self, name): # """ # Adds or gets a dictionary under a specific registry. # """ # # TODO: make a transaction here # self.storage.sadd(self.dict_key, name) # return self._dict_class(name, self.key, self._redis_host, # self._redis_port, self._redis_db) # # def del_dict(self, name): # """ # Deletes a dictionary under a specific registry. # """ # # TODO: make a transaction here # if name not in self.dictionaries(): # return False # dictionary = self._dict_class(name, self.key, self._redis_host, # self._redis_port, self._redis_db) # dictionary.delete() # if self.storage.srem(self.dict_key, name) == 1: # return True # return False # # def delete(self): # """ # Deletes the registry. # """ # self.logger.info("Deleting registry %s ..." % self._name) # if self.storage.srem(self.registry_list_key(self._key_prefix), # self._name) == 1: # self.reset() # self.logger.info("DONE") # return True # return False # # def reset(self): # """ # Resets the registry. Automatically deletes related dictionaries. # """ # if self.storage.delete(self.dict_key) == 1: # self.logger.info("Deleting registry {} entities..." # .format(self._name)) # keys = self.storage.keys('{}:*'.format(self.key)) # for key in keys: # self.storage.delete(key) # self.logger.info("DONE") # return True # return False , which may contain function names, class names, or code. Output only the next line.
Registry.flush('registry_api_test')
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf8 -*- # test_nlp.py # Test the feet.entities.nlp module # # Author: Romary Dupuis <romary.dupuis@altarika.com> # # Copyright (C) 2016 Romary Dupuis # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html class GetLanguageTests(unittest.TestCase): def setUp(self): pass def test_language_text_is_none(self): <|code_end|> , predict the next line using imports from the current file: from feet.entities.nlp import Parser import unittest and context including class names, function names, and sometimes code from other files: # Path: feet/entities/nlp.py # class Parser(LoggingMixin): # """ # Provides NLP tools such as language detection, tokenizer and POS tagger # for entities # """ # _auto_lang_detect = False # _lang = 'en' # # def __init__(self, lang='english', auto_lang_detect=False): # """ # Parser class initialisation. # Defines a default language attribute and decides if automatic language # detection is turned on/off. # """ # self._auto_lang_detect = auto_lang_detect # self._lang = WORLD_2_NLTK[lang] # # def detect_language(self, text): # """ # Provides language detection of a text. # Fallbacks to default language defined in class initialization or 'en' # """ # try: # if text is None: # return None # languages = detect_langs(text.decode('utf8')) # if len(languages) > 0: # return languages[0].lang # except: # self.logger.warning(traceback.format_exc()) # return self._lang or 'en' # # def word_tokenize(self, text, lang=None): # """ # Tokenizes a sentence. # """ # if lang is not None: # lang = WORLD_2_NLTK[lang] # else: # lang = self._lang # if lang == 'japanese': # return JAParser().word_tokenize(text) # else: # if not isinstance(text, unicode): # text = text.decode('utf8') # return [token.encode('utf8') # for token in word_tokenize(text, lang)] # # return text.split() # # def sent_tokenize(self, text, lang=None): # """ # Splits a text into sentences. Yields each sentence for processing. # """ # if lang is not None: # lang = WORLD_2_NLTK[lang] # else: # lang = self._lang # if lang == 'japanese': # for sentence in JAParser().sent_tokenize(text): # yield sentence # else: # if not isinstance(text, unicode): # text = text.decode('utf8') # for sentence in sent_tokenize(text, lang): # yield sentence # # @timeit # def tokenize(self, text, lang=None): # """ # Tokenizes a text by splitting it into sentences that will be tokenized. # """ # if lang is not None: # lang = WORLD_2_NLTK[lang] # else: # lang = self._lang # output = [] # if text is None: # return output # for sentence in self.sent_tokenize(text, lang): # output.append(self.word_tokenize(sentence, lang)) # return output # # def _select_entities(self, # tree, # extra_classes=['NNP', 'NNPS', 'NN', 'NNS']): # """ # Selects candidates of entities as chunks with specific grammatic tags. # """ # entities = defaultdict(list) # for chunk in tree: # if isinstance(chunk, Tree): # entities[chunk._label].append( # " ".join([token[0] for token in chunk.leaves()])) # else: # if chunk[1] in extra_classes: # entities['noun_phrase_leave'].append(chunk[0]) # return [i for key, value in dict(entities).iteritems() for i in value] # # @timeit # def extract_entities(self, text, grammar=None, lang=None): # """ # Extract entities from text # """ # entities = [] # if lang is None: # lang = WORLD_2_NLTK[self.detect_language(text)] # else: # if lang in WORLD_2_NLTK.keys(): # lang = WORLD_2_NLTK[lang] # else: # lang = self._lang # if lang == 'japanese': # return JAParser().extract_entities(text), lang # pos_sentences = [pos_tag(self.word_tokenize(sentence, lang=lang)) # for sentence in self.sent_tokenize(text, lang=lang)] # # if grammar is not None: # chunker = RegexpParser(grammar) # for pos_sentence in pos_sentences: # tree = chunker.parse(pos_sentence) # self.logger.debug(tree) # entities = entities + self._select_entities(tree) # else: # for pos_sentence in pos_sentences: # tree = ne_chunk(pos_sentence, binary=False) # self.logger.debug(tree) # entities = entities + self._select_entities(tree) # return entities, lang . Output only the next line.
self.assertEqual(Parser().detect_language(None), None)
Predict the next line for this snippet: <|code_start|> class DropCommand(Command): name = 'drop' help = 'Drop an entity dictionary' args = { '--registry': { 'metavar': 'REGISTRY', 'default': 'feet', 'required': False, 'help': 'registry of entities' }, '--entity': { 'metavar': 'ENTITY', 'required': True, 'help': 'entity dictionary' }, '--prefix': { 'metavar': 'PREFIX', 'default': 'feet', 'help': 'prefix used for all keys of dictionary' } } def handle(self, args): """ CLI to drop an entity dictionary. """ <|code_end|> with the help of current file imports: from commis import Command from commis import color from feet.entities.registry import Registry and context from other files: # Path: feet/entities/registry.py # class Registry(StorageMixin, LoggingMixin): # @staticmethod # def registry_list_key(key_prefix): # return '{}:registries'.format(key_prefix) # # @staticmethod # def registry_key(key_prefix, name): # return '{}:registry:{}'.format(key_prefix, name) # # @classmethod # def list(klass, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Gets the list of registries under a prefix. # """ # if key_prefix is None: # return False # storage = Storage(redis_host, redis_port, redis_db) # return list(storage.smembers(klass.registry_list_key(key_prefix))) # # @classmethod # def flush(klass, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Deletes all registries, dictionaries etc. under a prefix # """ # if key_prefix is None: # return False # storage = Storage(redis_host, redis_port, redis_db) # keys = storage.keys('{}:*'.format(key_prefix)) # for key in keys: # storage.delete(key) # return True # # @classmethod # def find_or_create(klass, # name, # dict_class=Dictionary, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # """ # Finds a registry if it already exists otherwise creates it. # """ # if key_prefix is None: # return None # storage = Storage(redis_host, redis_port, redis_db) # storage.sadd(klass.registry_list_key(key_prefix), name) # return Registry(name, dict_class, key_prefix, # redis_host, redis_port, redis_db) # # def __init__(self, # name, # dict_class=Dictionary, # key_prefix=settings.database.prefix, # redis_host=settings.database.host, # redis_port=settings.database.port, # redis_db=0): # self._name = name # self._dict_class = dict_class # self._key_prefix = key_prefix # self._redis_host = redis_host # self._redis_port = redis_port # self._redis_db = redis_db # # @memoized # def key(self): # return '{}'.format(self.registry_key(self._key_prefix, # self._name)) # # @memoized # def dict_key(self): # return '{}:dictionaries'.format(self.key) # # def dictionaries(self): # """ # Gest list of dictionaries defined under a specific registry. # """ # registry = self.storage.smembers(self.dict_key) # return list(registry) # # def get_dict(self, name): # """ # Adds or gets a dictionary under a specific registry. # """ # # TODO: make a transaction here # self.storage.sadd(self.dict_key, name) # return self._dict_class(name, self.key, self._redis_host, # self._redis_port, self._redis_db) # # def del_dict(self, name): # """ # Deletes a dictionary under a specific registry. # """ # # TODO: make a transaction here # if name not in self.dictionaries(): # return False # dictionary = self._dict_class(name, self.key, self._redis_host, # self._redis_port, self._redis_db) # dictionary.delete() # if self.storage.srem(self.dict_key, name) == 1: # return True # return False # # def delete(self): # """ # Deletes the registry. # """ # self.logger.info("Deleting registry %s ..." % self._name) # if self.storage.srem(self.registry_list_key(self._key_prefix), # self._name) == 1: # self.reset() # self.logger.info("DONE") # return True # return False # # def reset(self): # """ # Resets the registry. Automatically deletes related dictionaries. # """ # if self.storage.delete(self.dict_key) == 1: # self.logger.info("Deleting registry {} entities..." # .format(self._name)) # keys = self.storage.keys('{}:*'.format(self.key)) # for key in keys: # self.storage.delete(key) # self.logger.info("DONE") # return True # return False , which may contain function names, class names, or code. Output only the next line.
registry = Registry.find_or_create(args.registry,
Given snippet: <|code_start|># -*- coding: utf8 -*- # Launch feet server # # Author: Romary Dupuis <romary.dupuis@altarika.com> # # Copyright (C) 2016 Romary Dupuis # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html class RunCommand(Command): name = 'run' help = 'run the feet server application' args = { '--host': { 'metavar': 'ADDR', <|code_end|> , continue by predicting the next line. Consider current file imports: from commis import Command from feet.config import settings from feet.www.app import run and context: # Path: feet/config.py # class RedisConfiguration(Configuration): # class ServerConfiguration(Configuration): # class MecabConfiguration(Configuration): # class FeetConfiguration(Configuration): # CONF_PATHS = [ # "/etc/feet.yaml", # System configuration # os.path.expanduser("~/.feet.yaml"), # User specific config # os.path.abspath("conf/feet.yaml"), # Local configuration # ] # # Path: feet/www/app.py # def run(host, port, debug): # app = make_app() # app.listen(port) # logging.info('Feet server listening on port %d' % (port)) # try: # tornado.ioloop.IOLoop.instance().start() # except KeyboardInterrupt: # logging.info('Feet server interrupted') which might include code, classes, or functions. Output only the next line.
'default': settings.server.host,
Predict the next line for this snippet: <|code_start|> help = 'run the feet server application' args = { '--host': { 'metavar': 'ADDR', 'default': settings.server.host, 'help': 'set the host to run the app on' }, '--port': { 'metavar': 'PORT', 'type': int, 'default': settings.server.port, 'help': 'set the port to run the app on' }, '--debug': { 'action': 'store_true', 'required': False, 'help': 'force debug mode' } } def handle(self, args): """ CLI to run the Feet HTTP API server application. """ kwargs = { 'host': args.host, 'port': args.port, 'debug': args.debug or settings.debug, } <|code_end|> with the help of current file imports: from commis import Command from feet.config import settings from feet.www.app import run and context from other files: # Path: feet/config.py # class RedisConfiguration(Configuration): # class ServerConfiguration(Configuration): # class MecabConfiguration(Configuration): # class FeetConfiguration(Configuration): # CONF_PATHS = [ # "/etc/feet.yaml", # System configuration # os.path.expanduser("~/.feet.yaml"), # User specific config # os.path.abspath("conf/feet.yaml"), # Local configuration # ] # # Path: feet/www/app.py # def run(host, port, debug): # app = make_app() # app.listen(port) # logging.info('Feet server listening on port %d' % (port)) # try: # tornado.ioloop.IOLoop.instance().start() # except KeyboardInterrupt: # logging.info('Feet server interrupted') , which may contain function names, class names, or code. Output only the next line.
run(**kwargs)
Given snippet: <|code_start|># -*- coding: utf8 -*- # Parser class: provides NLP tools # # Author: Romary Dupuis <romary.dupuis@altarika.com> # # Copyright (C) 2016 Romary Dupuis # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html WORLD_2_NLTK = { 'english': 'english', 'en': 'english', 'fr': 'french', 'french': 'french', 'ja': 'japanese', 'japanese': 'japanese' } <|code_end|> , continue by predicting the next line. Consider current file imports: from nltk import word_tokenize, sent_tokenize, ne_chunk, \ RegexpParser, pos_tag from nltk.tree import Tree from collections import defaultdict from langdetect import detect_langs from jptools import JAParser from feet.utils.logger import LoggingMixin from feet.utils.decorators import timeit import traceback and context: # Path: feet/utils/logger.py # class LoggingMixin(object): # """ # Mix in to classes that need their own logging object! # """ # # @property # def logger(self): # """ # Instantiates and returns a ServiceLogger instance # """ # if not hasattr(self, '_logger') or not self._logger: # self._logger = ServiceLogger() # return self._logger # # Path: feet/utils/decorators.py # def timeit(func): # """ # Returns the number of seconds that a function took along with the result # """ # # @wraps(func) # def timer_wrapper(*args, **kwargs): # """ # Inner function that uses the Timer context object # """ # with Timer() as timer: # result = func(*args, **kwargs) # # return result, timer # # return timer_wrapper which might include code, classes, or functions. Output only the next line.
class Parser(LoggingMixin):
Given the code snippet: <|code_start|> if lang is not None: lang = WORLD_2_NLTK[lang] else: lang = self._lang if lang == 'japanese': return JAParser().word_tokenize(text) else: if not isinstance(text, unicode): text = text.decode('utf8') return [token.encode('utf8') for token in word_tokenize(text, lang)] # return text.split() def sent_tokenize(self, text, lang=None): """ Splits a text into sentences. Yields each sentence for processing. """ if lang is not None: lang = WORLD_2_NLTK[lang] else: lang = self._lang if lang == 'japanese': for sentence in JAParser().sent_tokenize(text): yield sentence else: if not isinstance(text, unicode): text = text.decode('utf8') for sentence in sent_tokenize(text, lang): yield sentence <|code_end|> , generate the next line using the imports in this file: from nltk import word_tokenize, sent_tokenize, ne_chunk, \ RegexpParser, pos_tag from nltk.tree import Tree from collections import defaultdict from langdetect import detect_langs from jptools import JAParser from feet.utils.logger import LoggingMixin from feet.utils.decorators import timeit import traceback and context (functions, classes, or occasionally code) from other files: # Path: feet/utils/logger.py # class LoggingMixin(object): # """ # Mix in to classes that need their own logging object! # """ # # @property # def logger(self): # """ # Instantiates and returns a ServiceLogger instance # """ # if not hasattr(self, '_logger') or not self._logger: # self._logger = ServiceLogger() # return self._logger # # Path: feet/utils/decorators.py # def timeit(func): # """ # Returns the number of seconds that a function took along with the result # """ # # @wraps(func) # def timer_wrapper(*args, **kwargs): # """ # Inner function that uses the Timer context object # """ # with Timer() as timer: # result = func(*args, **kwargs) # # return result, timer # # return timer_wrapper . Output only the next line.
@timeit
Using the snippet: <|code_start|> F1_NOUN = '名詞' F1_PARTICLE = '助詞' F1_CONJONCTION = '接続詞' F1_INTERJECTION = '感動詞' F1_VERB = '動詞' F1_AUXILIARY_VERB = '助動詞' F1_ADJECTIVE = '形容詞' F1_SEPARATOR = '記号' F2_NUMBER = '数' F2_SUFFIX = '接尾' F2_SUFFIX_COUNTER = '接尾' F2_IND_VERB = '自立' F2_NO_MEANING_NAMES = '非自立' F2_PRONOUN = '代名詞' F2_ADVERBS = '副詞可能' F2_ADJECTIVE = '形容動詞語幹' F2_PROPER_NOUN = '固有名詞' F3_ADVERBS = '副詞可能' F3_SUFFIX_COUNTER = '助数詞' SENTENCE_SEPARATORS = ('句点', '') STOPLIST = set('http https for a of the and to in co com jp'.split()) class JAParser(LoggingMixin): __metaclass__ = SingletonMetaClass @memoized def mecab(self): self.logger.warning('Initialize Mecab') <|code_end|> , determine the next line of code. You have imports: import MeCab import re from datetime import datetime from feet.config import settings from dateparser import parse from feet.utils.decorators import memoized from feet.utils.singleton import SingletonMetaClass from feet.utils.logger import LoggingMixin and context (class names, function names, or code) available: # Path: feet/config.py # class RedisConfiguration(Configuration): # class ServerConfiguration(Configuration): # class MecabConfiguration(Configuration): # class FeetConfiguration(Configuration): # CONF_PATHS = [ # "/etc/feet.yaml", # System configuration # os.path.expanduser("~/.feet.yaml"), # User specific config # os.path.abspath("conf/feet.yaml"), # Local configuration # ] # # Path: feet/utils/decorators.py # def memoized(fget): # """ # Return a property attribute for new-style classes that only calls its # getter on the first access. The result is stored and on subsequent # accesses is returned, preventing the need to call the getter any more. # https://github.com/estebistec/python-memoized-property # """ # attr_name = '_{0}'.format(fget.__name__) # # @wraps(fget) # def fget_memoized(self): # if not hasattr(self, attr_name): # setattr(self, attr_name, fget(self)) # return getattr(self, attr_name) # # return property(fget_memoized) # # Path: feet/utils/singleton.py # class SingletonMetaClass(type): # """ # Usage: # class bar(object): # __metaclass__ = SingletonMetaClass # """ # def __init__(cls, name, bases, dict): # super(SingletonMetaClass, cls)\ # .__init__(name, bases, dict) # original_new = cls.__new__ # # def my_new(cls, *args, **kwds): # if cls.instance is None: # cls.instance = original_new(cls, *args, **kwds) # return cls.instance # cls.instance = None # cls.__new__ = staticmethod(my_new) # # Path: feet/utils/logger.py # class LoggingMixin(object): # """ # Mix in to classes that need their own logging object! # """ # # @property # def logger(self): # """ # Instantiates and returns a ServiceLogger instance # """ # if not hasattr(self, '_logger') or not self._logger: # self._logger = ServiceLogger() # return self._logger . Output only the next line.
return MeCab.Tagger('-d %s' % settings.mecab.mecabdict)
Continue the code snippet: <|code_start|> 'with_year': False } ] F1_NOUN = '名詞' F1_PARTICLE = '助詞' F1_CONJONCTION = '接続詞' F1_INTERJECTION = '感動詞' F1_VERB = '動詞' F1_AUXILIARY_VERB = '助動詞' F1_ADJECTIVE = '形容詞' F1_SEPARATOR = '記号' F2_NUMBER = '数' F2_SUFFIX = '接尾' F2_SUFFIX_COUNTER = '接尾' F2_IND_VERB = '自立' F2_NO_MEANING_NAMES = '非自立' F2_PRONOUN = '代名詞' F2_ADVERBS = '副詞可能' F2_ADJECTIVE = '形容動詞語幹' F2_PROPER_NOUN = '固有名詞' F3_ADVERBS = '副詞可能' F3_SUFFIX_COUNTER = '助数詞' SENTENCE_SEPARATORS = ('句点', '') STOPLIST = set('http https for a of the and to in co com jp'.split()) class JAParser(LoggingMixin): __metaclass__ = SingletonMetaClass <|code_end|> . Use current file imports: import MeCab import re from datetime import datetime from feet.config import settings from dateparser import parse from feet.utils.decorators import memoized from feet.utils.singleton import SingletonMetaClass from feet.utils.logger import LoggingMixin and context (classes, functions, or code) from other files: # Path: feet/config.py # class RedisConfiguration(Configuration): # class ServerConfiguration(Configuration): # class MecabConfiguration(Configuration): # class FeetConfiguration(Configuration): # CONF_PATHS = [ # "/etc/feet.yaml", # System configuration # os.path.expanduser("~/.feet.yaml"), # User specific config # os.path.abspath("conf/feet.yaml"), # Local configuration # ] # # Path: feet/utils/decorators.py # def memoized(fget): # """ # Return a property attribute for new-style classes that only calls its # getter on the first access. The result is stored and on subsequent # accesses is returned, preventing the need to call the getter any more. # https://github.com/estebistec/python-memoized-property # """ # attr_name = '_{0}'.format(fget.__name__) # # @wraps(fget) # def fget_memoized(self): # if not hasattr(self, attr_name): # setattr(self, attr_name, fget(self)) # return getattr(self, attr_name) # # return property(fget_memoized) # # Path: feet/utils/singleton.py # class SingletonMetaClass(type): # """ # Usage: # class bar(object): # __metaclass__ = SingletonMetaClass # """ # def __init__(cls, name, bases, dict): # super(SingletonMetaClass, cls)\ # .__init__(name, bases, dict) # original_new = cls.__new__ # # def my_new(cls, *args, **kwds): # if cls.instance is None: # cls.instance = original_new(cls, *args, **kwds) # return cls.instance # cls.instance = None # cls.__new__ = staticmethod(my_new) # # Path: feet/utils/logger.py # class LoggingMixin(object): # """ # Mix in to classes that need their own logging object! # """ # # @property # def logger(self): # """ # Instantiates and returns a ServiceLogger instance # """ # if not hasattr(self, '_logger') or not self._logger: # self._logger = ServiceLogger() # return self._logger . Output only the next line.
@memoized
Predict the next line for this snippet: <|code_start|> 'regex': ur'\d{1}/\d{1}', 'format': '', 'with_year': False } ] F1_NOUN = '名詞' F1_PARTICLE = '助詞' F1_CONJONCTION = '接続詞' F1_INTERJECTION = '感動詞' F1_VERB = '動詞' F1_AUXILIARY_VERB = '助動詞' F1_ADJECTIVE = '形容詞' F1_SEPARATOR = '記号' F2_NUMBER = '数' F2_SUFFIX = '接尾' F2_SUFFIX_COUNTER = '接尾' F2_IND_VERB = '自立' F2_NO_MEANING_NAMES = '非自立' F2_PRONOUN = '代名詞' F2_ADVERBS = '副詞可能' F2_ADJECTIVE = '形容動詞語幹' F2_PROPER_NOUN = '固有名詞' F3_ADVERBS = '副詞可能' F3_SUFFIX_COUNTER = '助数詞' SENTENCE_SEPARATORS = ('句点', '') STOPLIST = set('http https for a of the and to in co com jp'.split()) class JAParser(LoggingMixin): <|code_end|> with the help of current file imports: import MeCab import re from datetime import datetime from feet.config import settings from dateparser import parse from feet.utils.decorators import memoized from feet.utils.singleton import SingletonMetaClass from feet.utils.logger import LoggingMixin and context from other files: # Path: feet/config.py # class RedisConfiguration(Configuration): # class ServerConfiguration(Configuration): # class MecabConfiguration(Configuration): # class FeetConfiguration(Configuration): # CONF_PATHS = [ # "/etc/feet.yaml", # System configuration # os.path.expanduser("~/.feet.yaml"), # User specific config # os.path.abspath("conf/feet.yaml"), # Local configuration # ] # # Path: feet/utils/decorators.py # def memoized(fget): # """ # Return a property attribute for new-style classes that only calls its # getter on the first access. The result is stored and on subsequent # accesses is returned, preventing the need to call the getter any more. # https://github.com/estebistec/python-memoized-property # """ # attr_name = '_{0}'.format(fget.__name__) # # @wraps(fget) # def fget_memoized(self): # if not hasattr(self, attr_name): # setattr(self, attr_name, fget(self)) # return getattr(self, attr_name) # # return property(fget_memoized) # # Path: feet/utils/singleton.py # class SingletonMetaClass(type): # """ # Usage: # class bar(object): # __metaclass__ = SingletonMetaClass # """ # def __init__(cls, name, bases, dict): # super(SingletonMetaClass, cls)\ # .__init__(name, bases, dict) # original_new = cls.__new__ # # def my_new(cls, *args, **kwds): # if cls.instance is None: # cls.instance = original_new(cls, *args, **kwds) # return cls.instance # cls.instance = None # cls.__new__ = staticmethod(my_new) # # Path: feet/utils/logger.py # class LoggingMixin(object): # """ # Mix in to classes that need their own logging object! # """ # # @property # def logger(self): # """ # Instantiates and returns a ServiceLogger instance # """ # if not hasattr(self, '_logger') or not self._logger: # self._logger = ServiceLogger() # return self._logger , which may contain function names, class names, or code. Output only the next line.
__metaclass__ = SingletonMetaClass
Based on the snippet: <|code_start|> { 'regex': ur'\d{1}/\d{1}', 'format': '', 'with_year': False } ] F1_NOUN = '名詞' F1_PARTICLE = '助詞' F1_CONJONCTION = '接続詞' F1_INTERJECTION = '感動詞' F1_VERB = '動詞' F1_AUXILIARY_VERB = '助動詞' F1_ADJECTIVE = '形容詞' F1_SEPARATOR = '記号' F2_NUMBER = '数' F2_SUFFIX = '接尾' F2_SUFFIX_COUNTER = '接尾' F2_IND_VERB = '自立' F2_NO_MEANING_NAMES = '非自立' F2_PRONOUN = '代名詞' F2_ADVERBS = '副詞可能' F2_ADJECTIVE = '形容動詞語幹' F2_PROPER_NOUN = '固有名詞' F3_ADVERBS = '副詞可能' F3_SUFFIX_COUNTER = '助数詞' SENTENCE_SEPARATORS = ('句点', '') STOPLIST = set('http https for a of the and to in co com jp'.split()) <|code_end|> , predict the immediate next line with the help of imports: import MeCab import re from datetime import datetime from feet.config import settings from dateparser import parse from feet.utils.decorators import memoized from feet.utils.singleton import SingletonMetaClass from feet.utils.logger import LoggingMixin and context (classes, functions, sometimes code) from other files: # Path: feet/config.py # class RedisConfiguration(Configuration): # class ServerConfiguration(Configuration): # class MecabConfiguration(Configuration): # class FeetConfiguration(Configuration): # CONF_PATHS = [ # "/etc/feet.yaml", # System configuration # os.path.expanduser("~/.feet.yaml"), # User specific config # os.path.abspath("conf/feet.yaml"), # Local configuration # ] # # Path: feet/utils/decorators.py # def memoized(fget): # """ # Return a property attribute for new-style classes that only calls its # getter on the first access. The result is stored and on subsequent # accesses is returned, preventing the need to call the getter any more. # https://github.com/estebistec/python-memoized-property # """ # attr_name = '_{0}'.format(fget.__name__) # # @wraps(fget) # def fget_memoized(self): # if not hasattr(self, attr_name): # setattr(self, attr_name, fget(self)) # return getattr(self, attr_name) # # return property(fget_memoized) # # Path: feet/utils/singleton.py # class SingletonMetaClass(type): # """ # Usage: # class bar(object): # __metaclass__ = SingletonMetaClass # """ # def __init__(cls, name, bases, dict): # super(SingletonMetaClass, cls)\ # .__init__(name, bases, dict) # original_new = cls.__new__ # # def my_new(cls, *args, **kwds): # if cls.instance is None: # cls.instance = original_new(cls, *args, **kwds) # return cls.instance # cls.instance = None # cls.__new__ = staticmethod(my_new) # # Path: feet/utils/logger.py # class LoggingMixin(object): # """ # Mix in to classes that need their own logging object! # """ # # @property # def logger(self): # """ # Instantiates and returns a ServiceLogger instance # """ # if not hasattr(self, '_logger') or not self._logger: # self._logger = ServiceLogger() # return self._logger . Output only the next line.
class JAParser(LoggingMixin):
Here is a snippet: <|code_start|>""" configuration = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '%(name)s %(levelname)s [%(asctime)s] -- %(message)s', 'datefmt': ISO8601_DATETIME, } }, 'handlers': { 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple', }, 'logfile': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', <|code_end|> . Write the next line using the current file imports: import logging import getpass import warnings import logging.config from feet.config import settings from feet.utils.timez import ISO8601_DATETIME and context from other files: # Path: feet/config.py # class RedisConfiguration(Configuration): # class ServerConfiguration(Configuration): # class MecabConfiguration(Configuration): # class FeetConfiguration(Configuration): # CONF_PATHS = [ # "/etc/feet.yaml", # System configuration # os.path.expanduser("~/.feet.yaml"), # User specific config # os.path.abspath("conf/feet.yaml"), # Local configuration # ] # # Path: feet/utils/timez.py # ISO8601_DATETIME = "%Y-%m-%dT%H:%M:%S%z" , which may include functions, classes, or code. Output only the next line.
'filename': settings.logfile,
Predict the next line for this snippet: <|code_start|># -*- coding: utf8 -*- # load_dictionary # Logging Utility for Feet # # Author: Romary Dupuis <romary.dupuis@altarika.com> # Credits: Benjamin Bengfort <benjamin@bengfort.com> """ Logging utility for Feet """ configuration = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '%(name)s %(levelname)s [%(asctime)s] -- %(message)s', <|code_end|> with the help of current file imports: import logging import getpass import warnings import logging.config from feet.config import settings from feet.utils.timez import ISO8601_DATETIME and context from other files: # Path: feet/config.py # class RedisConfiguration(Configuration): # class ServerConfiguration(Configuration): # class MecabConfiguration(Configuration): # class FeetConfiguration(Configuration): # CONF_PATHS = [ # "/etc/feet.yaml", # System configuration # os.path.expanduser("~/.feet.yaml"), # User specific config # os.path.abspath("conf/feet.yaml"), # Local configuration # ] # # Path: feet/utils/timez.py # ISO8601_DATETIME = "%Y-%m-%dT%H:%M:%S%z" , which may contain function names, class names, or code. Output only the next line.
'datefmt': ISO8601_DATETIME,
Continue the code snippet: <|code_start|># encoding: utf-8 from __future__ import absolute_import, division, print_function # Copyright (C) 2005-2007 Carabos Coop. V. All rights reserved # Copyright (C) 2008-2013 Vicent Mas. All rights reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Author: Vicent Mas - vmas@vitables.org try: except ImportError as e: msg = "the 'view' command is not available because 'vitables' does not seem to be installed correctly (%s)." % e print("Warning:", msg) <|code_end|> . Use current file imports: import locale import warnings import sys from liam2 import config from liam2.compat import PY2 from liam2.utils import ExceptionOnGetAttr from qtpy import QtWidgets from vitables.vtapp import VTApp from vitables.vtapp import VTApp from vitables.preferences import vtconfig and context (classes, functions, or code) from other files: # Path: liam2/config.py # # Path: liam2/compat.py # PY2 = sys.version_info[0] == 2 # # Path: liam2/utils.py # class ExceptionOnGetAttr(object): # """ # ExceptionOnGetAttr can be used when an optional part is missing # so that an exception is only raised if the object is actually used. # """ # def __init__(self, exception): # self.exception = exception # # def __getattr__(self, key): # raise self.exception . Output only the next line.
if not config.debug and not PY2:
Given the code snippet: <|code_start|># encoding: utf-8 from __future__ import absolute_import, division, print_function # Copyright (C) 2005-2007 Carabos Coop. V. All rights reserved # Copyright (C) 2008-2013 Vicent Mas. All rights reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Author: Vicent Mas - vmas@vitables.org try: except ImportError as e: msg = "the 'view' command is not available because 'vitables' does not seem to be installed correctly (%s)." % e print("Warning:", msg) <|code_end|> , generate the next line using the imports in this file: import locale import warnings import sys from liam2 import config from liam2.compat import PY2 from liam2.utils import ExceptionOnGetAttr from qtpy import QtWidgets from vitables.vtapp import VTApp from vitables.vtapp import VTApp from vitables.preferences import vtconfig and context (functions, classes, or occasionally code) from other files: # Path: liam2/config.py # # Path: liam2/compat.py # PY2 = sys.version_info[0] == 2 # # Path: liam2/utils.py # class ExceptionOnGetAttr(object): # """ # ExceptionOnGetAttr can be used when an optional part is missing # so that an exception is only raised if the object is actually used. # """ # def __init__(self, exception): # self.exception = exception # # def __getattr__(self, key): # raise self.exception . Output only the next line.
if not config.debug and not PY2:
Here is a snippet: <|code_start|># encoding: utf-8 from __future__ import absolute_import, division, print_function # Copyright (C) 2005-2007 Carabos Coop. V. All rights reserved # Copyright (C) 2008-2013 Vicent Mas. All rights reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Author: Vicent Mas - vmas@vitables.org try: except ImportError as e: msg = "the 'view' command is not available because 'vitables' does not seem to be installed correctly (%s)." % e print("Warning:", msg) if not config.debug and not PY2: e = ImportError(msg).with_traceback(sys.exc_info()[2]) <|code_end|> . Write the next line using the current file imports: import locale import warnings import sys from liam2 import config from liam2.compat import PY2 from liam2.utils import ExceptionOnGetAttr from qtpy import QtWidgets from vitables.vtapp import VTApp from vitables.vtapp import VTApp from vitables.preferences import vtconfig and context from other files: # Path: liam2/config.py # # Path: liam2/compat.py # PY2 = sys.version_info[0] == 2 # # Path: liam2/utils.py # class ExceptionOnGetAttr(object): # """ # ExceptionOnGetAttr can be used when an optional part is missing # so that an exception is only raised if the object is actually used. # """ # def __init__(self, exception): # self.exception = exception # # def __getattr__(self, key): # raise self.exception , which may include functions, classes, or code. Output only the next line.
VTApp = ExceptionOnGetAttr(e)
Predict the next line after this snippet: <|code_start|># encoding: utf-8 from __future__ import absolute_import, division, print_function __version__ = "0.4" def filter_h5(input_path, output_path, condition, copy_globals=True): print("filtering for '%s'" % condition) input_file = tables.open_file(input_path) output_file = tables.open_file(output_path, mode="w") # copy globals if copy_globals: # noinspection PyProtectedMember input_file.root.globals._f_copy(output_file.root, recursive=True) output_entities = output_file.create_group("/", "entities", "Entities") for table in input_file.iterNodes(input_file.root.entities): # noinspection PyProtectedMember print(table._v_name, "...") <|code_end|> using the current file's imports: import tables import sys import platform from liam2.data import copy_table from liam2.utils import timed and any relevant context from other files: # Path: liam2/data.py # def copy_table(input_table, output_node, output_dtype=None, # chunksize=10000, condition=None, stop=None, show_progress=False, # default_values=None, **kwargs): # complete_kwargs = {'title': input_table._v_title} # # 'filters': input_table.filters} # output_file = output_node._v_file # complete_kwargs.update(kwargs) # if output_dtype is None: # output_dtype = input_table.dtype # output_table = output_file.create_table(output_node, input_table.name, # output_dtype, **complete_kwargs) # return append_table(input_table, output_table, chunksize, condition, # stop=stop, show_progress=show_progress, # default_values=default_values) # # Path: liam2/utils.py # def timed(func, *args, **kwargs): # elapsed, res = gettime(func, *args, **kwargs) # if config.show_timings: # print("done (%s elapsed)." % time2str(elapsed)) # else: # print("done.") # return res . Output only the next line.
copy_table(table, output_entities, condition=condition)
Predict the next line after this snippet: <|code_start|> input_file = tables.open_file(input_path) output_file = tables.open_file(output_path, mode="w") # copy globals if copy_globals: # noinspection PyProtectedMember input_file.root.globals._f_copy(output_file.root, recursive=True) output_entities = output_file.create_group("/", "entities", "Entities") for table in input_file.iterNodes(input_file.root.entities): # noinspection PyProtectedMember print(table._v_name, "...") copy_table(table, output_entities, condition=condition) input_file.close() output_file.close() if __name__ == '__main__': print("LIAM HDF5 filter %s using Python %s (%s)\n" % (__version__, platform.python_version(), platform.architecture()[0])) args = dict(enumerate(sys.argv)) if len(args) < 4: print("""Usage: {} inputpath outputpath condition [copy_globals] where condition is an expression copy_globals is True (default)|False""".format(args[0])) sys.exit() <|code_end|> using the current file's imports: import tables import sys import platform from liam2.data import copy_table from liam2.utils import timed and any relevant context from other files: # Path: liam2/data.py # def copy_table(input_table, output_node, output_dtype=None, # chunksize=10000, condition=None, stop=None, show_progress=False, # default_values=None, **kwargs): # complete_kwargs = {'title': input_table._v_title} # # 'filters': input_table.filters} # output_file = output_node._v_file # complete_kwargs.update(kwargs) # if output_dtype is None: # output_dtype = input_table.dtype # output_table = output_file.create_table(output_node, input_table.name, # output_dtype, **complete_kwargs) # return append_table(input_table, output_table, chunksize, condition, # stop=stop, show_progress=show_progress, # default_values=default_values) # # Path: liam2/utils.py # def timed(func, *args, **kwargs): # elapsed, res = gettime(func, *args, **kwargs) # if config.show_timings: # print("done (%s elapsed)." % time2str(elapsed)) # else: # print("done.") # return res . Output only the next line.
timed(filter_h5, args[1], args[2], args[3], eval(args.get(4, 'True')))
Predict the next line after this snippet: <|code_start|> def longest_word(s): return max(len(w) for w in s.split()) if s else 0 def get_min_width(table, index): return max(longest_word(row[index]) for row in table) def table2str(table, missing): """table is a list of lists""" if not table: return '' numcols = max(len(row) for row in table) # pad rows that have too few columns for row in table: if len(row) < numcols: row.extend([''] * (numcols - len(row))) formatted = [[format_value(value, missing) for value in row] for row in table] colwidths = [get_col_width(formatted, i) for i in range(numcols)] total_width = sum(colwidths) sep_width = (len(colwidths) - 1) * 3 if total_width + sep_width > 80: minwidths = [get_min_width(formatted, i) for i in range(numcols)] available_width = 80.0 - sep_width - sum(minwidths) ratio = available_width / total_width colwidths = [minw + max(int(width * ratio), 0) <|code_end|> using the current file's imports: import ast import itertools import math import re import sys import time import warnings import numpy as np import numexpr as ne import larray as la from collections import defaultdict, deque, namedtuple from textwrap import wrap from liam2.compat import zip, basestring from liam2 import config from liam2.data import ColumnArray from cutils import fromiter and any relevant context from other files: # Path: liam2/compat.py # PY2 = sys.version_info[0] == 2 # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def csv_open(filename, mode='r'): # class metaclass(meta): # # Path: liam2/config.py . Output only the next line.
for minw, width in zip(minwidths, colwidths)]
Using the snippet: <|code_start|> if self.varargs: l.append('*' + self.varargs) if self.varkw: l.append('**' + self.varkw) if self.kwonlyargs: l.extend([k + '=' + repr(self.kwonlydefaults[k]) for k in self.kwonlyargs]) return ', '.join(l) def _argspec(*args, **kwonlyargs): """ args = argument names. Arguments with a default value must be given as a ('name', value) tuple. varargs and varkw argument names, if any, should be prefixed with '*' and '**' respectively and must be the last positional arguments. >>> _argspec('a', 'b', ('c', 1), '*d', '**e', f=None) ... # doctest: +NORMALIZE_WHITESPACE FullArgSpec(args=['a', 'b', 'c'], varargs='d', varkw='e', defaults=(1,), kwonlyargs=['f'], kwonlydefaults={'f': None}, annotations={}) >>> _argspec('a', '*', '**b', c=None) ... # doctest: +NORMALIZE_WHITESPACE FullArgSpec(args=['a'], varargs=None, varkw='b', defaults=None, kwonlyargs=['c'], kwonlydefaults={'c': None}, annotations={}) >>> _argspec('a', 'b', ('c', 1), d=None) ... # doctest: +NORMALIZE_WHITESPACE FullArgSpec(args=['a', 'b', 'c'], varargs=None, varkw=None, defaults=(1,), kwonlyargs=['d'], kwonlydefaults={'d': None}, annotations={}) """ def lastitem_startswith(l, s): <|code_end|> , determine the next line of code. You have imports: import ast import itertools import math import re import sys import time import warnings import numpy as np import numexpr as ne import larray as la from collections import defaultdict, deque, namedtuple from textwrap import wrap from liam2.compat import zip, basestring from liam2 import config from liam2.data import ColumnArray from cutils import fromiter and context (class names, function names, or code) available: # Path: liam2/compat.py # PY2 = sys.version_info[0] == 2 # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def csv_open(filename, mode='r'): # class metaclass(meta): # # Path: liam2/config.py . Output only the next line.
return l and isinstance(l[-1], basestring) and l[-1].startswith(s)
Given the following code snippet before the placeholder: <|code_start|> '1.95 Kb' >>> size2str(10000000) '9.54 Mb' >>> size2str(1.27 * 1024 ** 3) '1.27 Gb' """ units = ["bytes", "Kb", "Mb", "Gb", "Tb", "Pb"] scale = int(math.log(value, 1024)) if value else 0 fmt = "%.2f %s" if scale else "%d %s" return fmt % (value / 1024.0 ** scale, units[scale]) # def mem_usage(): # pid = os.getpid() # proc = psutil.Process(pid) # return proc.get_memory_info()[0] # def mem_usage_str(): # return size2str(mem_usage()) def gettime(func, *args, **kwargs): start = time.time() res = func(*args, **kwargs) return time.time() - start, res def timed(func, *args, **kwargs): elapsed, res = gettime(func, *args, **kwargs) <|code_end|> , predict the next line using imports from the current file: import ast import itertools import math import re import sys import time import warnings import numpy as np import numexpr as ne import larray as la from collections import defaultdict, deque, namedtuple from textwrap import wrap from liam2.compat import zip, basestring from liam2 import config from liam2.data import ColumnArray from cutils import fromiter and context including class names, function names, and sometimes code from other files: # Path: liam2/compat.py # PY2 = sys.version_info[0] == 2 # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def csv_open(filename, mode='r'): # class metaclass(meta): # # Path: liam2/config.py . Output only the next line.
if config.show_timings:
Predict the next line for this snippet: <|code_start|># encoding: utf-8 from __future__ import absolute_import, division, print_function __version__ = "0.1" def dropfields(input_path, output_path, todrop): input_file = tables.open_file(input_path, mode="r") input_root = input_file.root output_file = tables.open_file(output_path, mode="w") output_globals = output_file.create_group("/", "globals", "Globals") print(" * copying globals ...", end=' ') <|code_end|> with the help of current file imports: import tables import numpy as np import sys import platform from liam2.data import copy_table, get_fields from liam2.utils import timed and context from other files: # Path: liam2/data.py # def copy_table(input_table, output_node, output_dtype=None, # chunksize=10000, condition=None, stop=None, show_progress=False, # default_values=None, **kwargs): # complete_kwargs = {'title': input_table._v_title} # # 'filters': input_table.filters} # output_file = output_node._v_file # complete_kwargs.update(kwargs) # if output_dtype is None: # output_dtype = input_table.dtype # output_table = output_file.create_table(output_node, input_table.name, # output_dtype, **complete_kwargs) # return append_table(input_table, output_table, chunksize, condition, # stop=stop, show_progress=show_progress, # default_values=default_values) # # def get_fields(array): # dtype = array.dtype # return [(name, normalize_type(dtype[name].type)) for name in dtype.names] # # Path: liam2/utils.py # def timed(func, *args, **kwargs): # elapsed, res = gettime(func, *args, **kwargs) # if config.show_timings: # print("done (%s elapsed)." % time2str(elapsed)) # else: # print("done.") # return res , which may contain function names, class names, or code. Output only the next line.
copy_table(input_root.globals.periodic, output_globals)
Here is a snippet: <|code_start|># encoding: utf-8 from __future__ import absolute_import, division, print_function __version__ = "0.1" def dropfields(input_path, output_path, todrop): input_file = tables.open_file(input_path, mode="r") input_root = input_file.root output_file = tables.open_file(output_path, mode="w") output_globals = output_file.create_group("/", "globals", "Globals") print(" * copying globals ...", end=' ') copy_table(input_root.globals.periodic, output_globals) print("done.") output_entities = output_file.create_group("/", "entities", "Entities") for table in input_file.iterNodes(input_root.entities): <|code_end|> . Write the next line using the current file imports: import tables import numpy as np import sys import platform from liam2.data import copy_table, get_fields from liam2.utils import timed and context from other files: # Path: liam2/data.py # def copy_table(input_table, output_node, output_dtype=None, # chunksize=10000, condition=None, stop=None, show_progress=False, # default_values=None, **kwargs): # complete_kwargs = {'title': input_table._v_title} # # 'filters': input_table.filters} # output_file = output_node._v_file # complete_kwargs.update(kwargs) # if output_dtype is None: # output_dtype = input_table.dtype # output_table = output_file.create_table(output_node, input_table.name, # output_dtype, **complete_kwargs) # return append_table(input_table, output_table, chunksize, condition, # stop=stop, show_progress=show_progress, # default_values=default_values) # # def get_fields(array): # dtype = array.dtype # return [(name, normalize_type(dtype[name].type)) for name in dtype.names] # # Path: liam2/utils.py # def timed(func, *args, **kwargs): # elapsed, res = gettime(func, *args, **kwargs) # if config.show_timings: # print("done (%s elapsed)." % time2str(elapsed)) # else: # print("done.") # return res , which may include functions, classes, or code. Output only the next line.
table_fields = get_fields(table)
Predict the next line after this snippet: <|code_start|> print(" * copying globals ...", end=' ') copy_table(input_root.globals.periodic, output_globals) print("done.") output_entities = output_file.create_group("/", "entities", "Entities") for table in input_file.iterNodes(input_root.entities): table_fields = get_fields(table) output_dtype = np.dtype([(fname, ftype) for fname, ftype in table_fields if fname not in todrop]) size = (len(table) * table.dtype.itemsize) / 1024.0 / 1024.0 # noinspection PyProtectedMember print(" * copying table %s (%.2f Mb) ..." % (table._v_name, size), end=' ') copy_table(table, output_entities, output_dtype) print("done.") input_file.close() output_file.close() if __name__ == '__main__': print("LIAM HDF5 drop fields %s using Python %s (%s)\n" % \ (__version__, platform.python_version(), platform.architecture()[0])) args = sys.argv if len(args) < 4: print("Usage: %s inputpath outputpath field1 [field2 ...]" % args[0]) sys.exit() <|code_end|> using the current file's imports: import tables import numpy as np import sys import platform from liam2.data import copy_table, get_fields from liam2.utils import timed and any relevant context from other files: # Path: liam2/data.py # def copy_table(input_table, output_node, output_dtype=None, # chunksize=10000, condition=None, stop=None, show_progress=False, # default_values=None, **kwargs): # complete_kwargs = {'title': input_table._v_title} # # 'filters': input_table.filters} # output_file = output_node._v_file # complete_kwargs.update(kwargs) # if output_dtype is None: # output_dtype = input_table.dtype # output_table = output_file.create_table(output_node, input_table.name, # output_dtype, **complete_kwargs) # return append_table(input_table, output_table, chunksize, condition, # stop=stop, show_progress=show_progress, # default_values=default_values) # # def get_fields(array): # dtype = array.dtype # return [(name, normalize_type(dtype[name].type)) for name in dtype.names] # # Path: liam2/utils.py # def timed(func, *args, **kwargs): # elapsed, res = gettime(func, *args, **kwargs) # if config.show_timings: # print("done (%s elapsed)." % time2str(elapsed)) # else: # print("done.") # return res . Output only the next line.
timed(dropfields, args[1], args[2], args[3:])
Here is a snippet: <|code_start|> fname + ' (file1)', fname + ' (file2)']] + [[ids[idx], col1[idx], col2[idx]] for idx in diff])) if raiseondiff: raise Exception('different') def diff_h5(input1_path, input2_path, numdiff=10): input1_file = tables.open_file(input1_path, mode="r") input2_file = tables.open_file(input2_path, mode="r") input1_entities = input1_file.root.entities input2_entities = input2_file.root.entities # noinspection PyProtectedMember ent_names1 = set(table._v_name for table in input1_entities) # noinspection PyProtectedMember ent_names2 = set(table._v_name for table in input2_entities) for ent_name in sorted(ent_names1 | ent_names2): print() print(ent_name) if ent_name not in ent_names1: print("missing in file 1") continue elif ent_name not in ent_names2: print("missing in file 2") continue table1 = getattr(input1_entities, ent_name) <|code_end|> . Write the next line using the current file imports: import numpy as np import tables import sys import platform from liam2.data import index_table_light, get_fields from liam2.utils import PrettyTable, merge_items and context from other files: # Path: liam2/data.py # def index_table_light(table, index='period'): # """ # table is an iterable of rows, each row is a mapping (name -> value) # Rows must contain the index column and must be sorted by that column. # Returns a dict: {index_value: start_row, stop_row} # """ # rows_per_period = {} # current_value = None # start_row = None # # I don't know why but my attempts to only retrieve one column # # made the function slower, not faster (this is only used in diff_h5 & # # merge_h5 though). # for idx, row in enumerate(table): # value = row[index] # if value != current_value: # # 0 > None is True # if value < current_value: # msg = "data is not ordered by {} ({} at data line {} is < {})" # raise Exception(msg.format(index, value, idx + 1, current_value)) # if start_row is not None: # rows_per_period[current_value] = (start_row, idx) # start_row = idx # current_value = value # if current_value is not None: # rows_per_period[current_value] = (start_row, len(table)) # return rows_per_period # # def get_fields(array): # dtype = array.dtype # return [(name, normalize_type(dtype[name].type)) for name in dtype.names] # # Path: liam2/utils.py # class PrettyTable(object): # def __init__(self, data, missing=None): # assert isinstance(data, (tuple, list)) # self.data = data # self.missing = missing # # def __iter__(self): # if self.missing is not None: # return iter(self.convert_nans()) # else: # return iter(self.data) # # def __len__(self): # return len(self.data) # # def convert_nans(self): # missing = self.missing # for row in self.data: # formatted = [missing if value != value else value # for value in row] # yield formatted # # def __repr__(self): # missing = self.missing # if missing is None: # missing = 'nan' # else: # missing = str(missing) # return '\n' + table2str(self.data, missing) + '\n' # # def merge_items(item_sequences, merge_order='first_to_last', value_priority='first'): # """ # Returns a list of (key, value) pairs which is the result of merging all sequences of (key, value) pairs passed as # arguments. # Order of keys is preserved on a "first" merged basis. # If merge_order is 'first_to_last', items will be merged from first to last, appending if not present, otherwise the # merge happens from last to first. # # value_priority determines which sequence items will have priority over the others. 'first' means the value of # a key will be from the earliest sequence (relative to the order given in item_sequences, independently of the # merge order). # """ # assert merge_order in {'first_to_last', 'last_to_first'} # assert value_priority in {'first', 'last'} # # keep_first = value_priority == 'first' # if merge_order == 'last_to_first': # item_sequences = item_sequences[::-1] # keep_first = not keep_first # # result_keys = [] # values = {} # for items in item_sequences: # if keep_first: # for k, v in items: # if k not in values: # result_keys.append(k) # values[k] = v # else: # for k, v in items: # if k not in values: # result_keys.append(k) # values[k] = v # # return [(k, values[k]) for k in result_keys] , which may include functions, classes, or code. Output only the next line.
input1_rows = index_table_light(table1)
Based on the snippet: <|code_start|> def diff_array(array1, array2, showdiffs=10, raiseondiff=False): if len(array1) != len(array2): print("length is different: %d vs %d" % (len(array1), len(array2))) ids1 = array1['id'] ids2 = array2['id'] all_ids = np.union1d(ids1, ids2) notin1 = np.setdiff1d(ids1, all_ids) notin2 = np.setdiff1d(ids2, all_ids) if notin1: print("the following ids are not present in file 1:", notin1) elif notin2: print("the following ids are not present in file 2:", notin2) else: # some ids must be duplicated if len(ids1) > len(all_ids): print("file 1 contain duplicate ids:", end=' ') uniques, dupes = unique_dupes(ids1) print(dupes) array1 = array1[uniques] if len(ids2) > len(all_ids): print("file 2 contain duplicate ids:", end=' ') uniques, dupes = unique_dupes(ids2) print(dupes) array2 = array2[uniques] <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import tables import sys import platform from liam2.data import index_table_light, get_fields from liam2.utils import PrettyTable, merge_items and context (classes, functions, sometimes code) from other files: # Path: liam2/data.py # def index_table_light(table, index='period'): # """ # table is an iterable of rows, each row is a mapping (name -> value) # Rows must contain the index column and must be sorted by that column. # Returns a dict: {index_value: start_row, stop_row} # """ # rows_per_period = {} # current_value = None # start_row = None # # I don't know why but my attempts to only retrieve one column # # made the function slower, not faster (this is only used in diff_h5 & # # merge_h5 though). # for idx, row in enumerate(table): # value = row[index] # if value != current_value: # # 0 > None is True # if value < current_value: # msg = "data is not ordered by {} ({} at data line {} is < {})" # raise Exception(msg.format(index, value, idx + 1, current_value)) # if start_row is not None: # rows_per_period[current_value] = (start_row, idx) # start_row = idx # current_value = value # if current_value is not None: # rows_per_period[current_value] = (start_row, len(table)) # return rows_per_period # # def get_fields(array): # dtype = array.dtype # return [(name, normalize_type(dtype[name].type)) for name in dtype.names] # # Path: liam2/utils.py # class PrettyTable(object): # def __init__(self, data, missing=None): # assert isinstance(data, (tuple, list)) # self.data = data # self.missing = missing # # def __iter__(self): # if self.missing is not None: # return iter(self.convert_nans()) # else: # return iter(self.data) # # def __len__(self): # return len(self.data) # # def convert_nans(self): # missing = self.missing # for row in self.data: # formatted = [missing if value != value else value # for value in row] # yield formatted # # def __repr__(self): # missing = self.missing # if missing is None: # missing = 'nan' # else: # missing = str(missing) # return '\n' + table2str(self.data, missing) + '\n' # # def merge_items(item_sequences, merge_order='first_to_last', value_priority='first'): # """ # Returns a list of (key, value) pairs which is the result of merging all sequences of (key, value) pairs passed as # arguments. # Order of keys is preserved on a "first" merged basis. # If merge_order is 'first_to_last', items will be merged from first to last, appending if not present, otherwise the # merge happens from last to first. # # value_priority determines which sequence items will have priority over the others. 'first' means the value of # a key will be from the earliest sequence (relative to the order given in item_sequences, independently of the # merge order). # """ # assert merge_order in {'first_to_last', 'last_to_first'} # assert value_priority in {'first', 'last'} # # keep_first = value_priority == 'first' # if merge_order == 'last_to_first': # item_sequences = item_sequences[::-1] # keep_first = not keep_first # # result_keys = [] # values = {} # for items in item_sequences: # if keep_first: # for k, v in items: # if k not in values: # result_keys.append(k) # values[k] = v # else: # for k, v in items: # if k not in values: # result_keys.append(k) # values[k] = v # # return [(k, values[k]) for k in result_keys] . Output only the next line.
fields1 = get_fields(array1)
Predict the next line after this snippet: <|code_start|> for fname, _ in merge_items((fields1, fields2)): print(" - %s:" % fname, end=' ') if fname not in fnames1: print("missing in file 1") continue elif fname not in fnames2: print("missing in file 2") continue col1, col2 = array1[fname], array2[fname] if np.issubdtype(col1.dtype, np.inexact): if len(col1) == len(col2): both_nan = np.isnan(col1) & np.isnan(col2) eq = np.all(both_nan | (col1 == col2)) else: eq = False else: eq = np.array_equal(col1, col2) if eq: print("ok") else: print("different", end=' ') if len(col1) != len(col2): print("(length)") else: diff = (col1 != col2).nonzero()[0] print("(%d differences)" % len(diff)) ids = array1['id'] if len(diff) > showdiffs: diff = diff[:showdiffs] <|code_end|> using the current file's imports: import numpy as np import tables import sys import platform from liam2.data import index_table_light, get_fields from liam2.utils import PrettyTable, merge_items and any relevant context from other files: # Path: liam2/data.py # def index_table_light(table, index='period'): # """ # table is an iterable of rows, each row is a mapping (name -> value) # Rows must contain the index column and must be sorted by that column. # Returns a dict: {index_value: start_row, stop_row} # """ # rows_per_period = {} # current_value = None # start_row = None # # I don't know why but my attempts to only retrieve one column # # made the function slower, not faster (this is only used in diff_h5 & # # merge_h5 though). # for idx, row in enumerate(table): # value = row[index] # if value != current_value: # # 0 > None is True # if value < current_value: # msg = "data is not ordered by {} ({} at data line {} is < {})" # raise Exception(msg.format(index, value, idx + 1, current_value)) # if start_row is not None: # rows_per_period[current_value] = (start_row, idx) # start_row = idx # current_value = value # if current_value is not None: # rows_per_period[current_value] = (start_row, len(table)) # return rows_per_period # # def get_fields(array): # dtype = array.dtype # return [(name, normalize_type(dtype[name].type)) for name in dtype.names] # # Path: liam2/utils.py # class PrettyTable(object): # def __init__(self, data, missing=None): # assert isinstance(data, (tuple, list)) # self.data = data # self.missing = missing # # def __iter__(self): # if self.missing is not None: # return iter(self.convert_nans()) # else: # return iter(self.data) # # def __len__(self): # return len(self.data) # # def convert_nans(self): # missing = self.missing # for row in self.data: # formatted = [missing if value != value else value # for value in row] # yield formatted # # def __repr__(self): # missing = self.missing # if missing is None: # missing = 'nan' # else: # missing = str(missing) # return '\n' + table2str(self.data, missing) + '\n' # # def merge_items(item_sequences, merge_order='first_to_last', value_priority='first'): # """ # Returns a list of (key, value) pairs which is the result of merging all sequences of (key, value) pairs passed as # arguments. # Order of keys is preserved on a "first" merged basis. # If merge_order is 'first_to_last', items will be merged from first to last, appending if not present, otherwise the # merge happens from last to first. # # value_priority determines which sequence items will have priority over the others. 'first' means the value of # a key will be from the earliest sequence (relative to the order given in item_sequences, independently of the # merge order). # """ # assert merge_order in {'first_to_last', 'last_to_first'} # assert value_priority in {'first', 'last'} # # keep_first = value_priority == 'first' # if merge_order == 'last_to_first': # item_sequences = item_sequences[::-1] # keep_first = not keep_first # # result_keys = [] # values = {} # for items in item_sequences: # if keep_first: # for k, v in items: # if k not in values: # result_keys.append(k) # values[k] = v # else: # for k, v in items: # if k not in values: # result_keys.append(k) # values[k] = v # # return [(k, values[k]) for k in result_keys] . Output only the next line.
print(PrettyTable([['id',
Continue the code snippet: <|code_start|> len(array2))) ids1 = array1['id'] ids2 = array2['id'] all_ids = np.union1d(ids1, ids2) notin1 = np.setdiff1d(ids1, all_ids) notin2 = np.setdiff1d(ids2, all_ids) if notin1: print("the following ids are not present in file 1:", notin1) elif notin2: print("the following ids are not present in file 2:", notin2) else: # some ids must be duplicated if len(ids1) > len(all_ids): print("file 1 contain duplicate ids:", end=' ') uniques, dupes = unique_dupes(ids1) print(dupes) array1 = array1[uniques] if len(ids2) > len(all_ids): print("file 2 contain duplicate ids:", end=' ') uniques, dupes = unique_dupes(ids2) print(dupes) array2 = array2[uniques] fields1 = get_fields(array1) fields2 = get_fields(array2) fnames1 = set(array1.dtype.names) fnames2 = set(array2.dtype.names) # use merge_items instead of fnames1 | fnames2 to preserve ordering <|code_end|> . Use current file imports: import numpy as np import tables import sys import platform from liam2.data import index_table_light, get_fields from liam2.utils import PrettyTable, merge_items and context (classes, functions, or code) from other files: # Path: liam2/data.py # def index_table_light(table, index='period'): # """ # table is an iterable of rows, each row is a mapping (name -> value) # Rows must contain the index column and must be sorted by that column. # Returns a dict: {index_value: start_row, stop_row} # """ # rows_per_period = {} # current_value = None # start_row = None # # I don't know why but my attempts to only retrieve one column # # made the function slower, not faster (this is only used in diff_h5 & # # merge_h5 though). # for idx, row in enumerate(table): # value = row[index] # if value != current_value: # # 0 > None is True # if value < current_value: # msg = "data is not ordered by {} ({} at data line {} is < {})" # raise Exception(msg.format(index, value, idx + 1, current_value)) # if start_row is not None: # rows_per_period[current_value] = (start_row, idx) # start_row = idx # current_value = value # if current_value is not None: # rows_per_period[current_value] = (start_row, len(table)) # return rows_per_period # # def get_fields(array): # dtype = array.dtype # return [(name, normalize_type(dtype[name].type)) for name in dtype.names] # # Path: liam2/utils.py # class PrettyTable(object): # def __init__(self, data, missing=None): # assert isinstance(data, (tuple, list)) # self.data = data # self.missing = missing # # def __iter__(self): # if self.missing is not None: # return iter(self.convert_nans()) # else: # return iter(self.data) # # def __len__(self): # return len(self.data) # # def convert_nans(self): # missing = self.missing # for row in self.data: # formatted = [missing if value != value else value # for value in row] # yield formatted # # def __repr__(self): # missing = self.missing # if missing is None: # missing = 'nan' # else: # missing = str(missing) # return '\n' + table2str(self.data, missing) + '\n' # # def merge_items(item_sequences, merge_order='first_to_last', value_priority='first'): # """ # Returns a list of (key, value) pairs which is the result of merging all sequences of (key, value) pairs passed as # arguments. # Order of keys is preserved on a "first" merged basis. # If merge_order is 'first_to_last', items will be merged from first to last, appending if not present, otherwise the # merge happens from last to first. # # value_priority determines which sequence items will have priority over the others. 'first' means the value of # a key will be from the earliest sequence (relative to the order given in item_sequences, independently of the # merge order). # """ # assert merge_order in {'first_to_last', 'last_to_first'} # assert value_priority in {'first', 'last'} # # keep_first = value_priority == 'first' # if merge_order == 'last_to_first': # item_sequences = item_sequences[::-1] # keep_first = not keep_first # # result_keys = [] # values = {} # for items in item_sequences: # if keep_first: # for k, v in items: # if k not in values: # result_keys.append(k) # values[k] = v # else: # for k, v in items: # if k not in values: # result_keys.append(k) # values[k] = v # # return [(k, values[k]) for k in result_keys] . Output only the next line.
for fname, _ in merge_items((fields1, fields2)):
Using the snippet: <|code_start|> :param url: url of the remote repository :param branch: an optional branch (defaults to 'refs/heads/master') :return: name/hash of the last revision """ if branch is None: branch = 'refs/heads/master' output = call('git ls-remote %s %s' % (url, branch)) for line in output.splitlines(): if line.endswith(branch): return line.split()[0] raise Exception("Could not determine revision number") def branchname(statusline): """ computes the branch name from a "git status -b -s" line ## master...origin/master """ statusline = statusline.replace('#', '').strip() pos = statusline.find('...') return statusline[:pos] if pos != -1 else statusline def yes(msg, default='y'): choices = ' (%s/%s) ' % tuple(c.capitalize() if c == default else c for c in ('y', 'n')) answer = None while answer not in ('', 'y', 'n'): if answer is not None: print("answer should be 'y', 'n', or <return>") <|code_end|> , determine the next line of code. You have imports: import errno import fnmatch import os import re import stat import subprocess import sys import urllib import zipfile from datetime import date from os import chdir, makedirs from os.path import exists, abspath, dirname from shutil import copytree, copy2, rmtree as _rmtree from subprocess import check_output, STDOUT, CalledProcessError from liam2.compat import input and context (class names, function names, or code) available: # Path: liam2/compat.py # PY2 = sys.version_info[0] == 2 # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # def csv_open(filename, mode='r'): # class metaclass(meta): . Output only the next line.
answer = input(msg + choices).lower()
Using the snippet: <|code_start|> self.extra[key] = value def __delitem__(self, key): del self.extra[key] def __contains__(self, key): entity = self.entity period = self.eval_ctx.period array_period = entity.array_period # entity.array can be None! (eg. with "explore") keyinarray = (self.is_array_period and (key in entity.temp_variables or key in entity.array.dtype.fields)) # we need to check explicitly whether the key is in array_lag because # with output=None it can contain more fields than table. keyinlagarray = (entity.array_lag is not None and array_period is not None and period == array_period - 1 and key in entity.array_lag.dtype.fields) keyintable = (entity.table is not None and key in entity.table.dtype.fields) return key in self.extra or keyinarray or keyinlagarray or keyintable def keys(self, extra=True): res = list(self.entity.array.dtype.names) res.extend(sorted(self.entity.temp_variables.keys())) if extra: res.extend(sorted(self.extra.keys())) # in theory, this should not be needed because we present defining a function argument with the same # name than an entity field <|code_end|> , determine the next line of code. You have imports: import numpy as np from liam2.utils import unique from liam2.expr import Variable and context (class names, function names, or code) available: # Path: liam2/utils.py # def unique(iterable): # """ # List all elements once, preserving order. Remember all elements ever seen. # """ # # unique('AAAABBBCCDAABBB') --> A B C D # seen = set() # seen_add = seen.add # for element in iterable: # if element not in seen: # seen_add(element) # yield element . Output only the next line.
assert list(unique(res)) == res
Using the snippet: <|code_start|> def decorate(self, sizefunc, func): def decorated(*args, **kwargs): return self.safe_call(sizefunc(*args, **kwargs), func, *args, **kwargs) decorated.__name__ = func.__name__ return decorated def free(self, nbytes): print("mem is full, puring %d elements from cache" % len(self.cache)) self.cache.clear() class ManagedModule(object): def __init__(self, module, manager, sizefuncs): self.module = module self.manager = manager self.sizefuncs = sizefuncs def __getattr__(self, key): func = getattr(self.module, key) assert isinstance(func, (BuiltinFunctionType, FunctionType)) return self.manager.decorate(self.sizefuncs[key], func) if __name__ == '__main__': def generic(shape, dtype=float, *_, **__): if not isinstance(shape, tuple): shape = (shape,) dt = np.dtype(dtype) <|code_end|> , determine the next line of code. You have imports: import math import numpy as np from types import BuiltinFunctionType, FunctionType from liam2.utils import prod and context (class names, function names, or code) available: # Path: liam2/utils.py # def prod(values): # res = 1 # for value in values: # res *= value # return res . Output only the next line.
return prod(shape) * dt.itemsize
Using the snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. class TestMySqlRepo(base.BaseTestCase): def setUp(self): super(TestMySqlRepo, self).setUp() self.conf_default(group='mysql', host='localhost', port=3306, user='bar', passwd='1', db='2') @mock.patch('monasca_notification.common.repositories.mysql.mysql_repo.pymysql') def testReconnect(self, mock_mysql): m = mock.MagicMock() m.cursor.side_effect = pymysql.Error mock_mysql.connect.return_value = m mock_mysql.Error = pymysql.Error <|code_end|> , determine the next line of code. You have imports: from unittest import mock from monasca_notification.common.repositories import exceptions as exc from monasca_notification.common.repositories.mysql import mysql_repo from tests import base import pymysql and context (class names, function names, or code) available: # Path: monasca_notification/common/repositories/mysql/mysql_repo.py # class MysqlRepo(base_repo.BaseRepo): # def __init__(self, config): # def _connect_to_mysql(self): # def fetch_notifications(self, alarm): # def get_alarm_current_state(self, alarm_id): # def fetch_notification_method_types(self): # def insert_notification_method_types(self, notification_types): # def get_notification(self, notification_id): # # Path: tests/base.py # class DisableStatsdFixture(fixtures.Fixture): # class ConfigFixture(oo_cfg.Config): # class BaseTestCase(oslotest_base.BaseTestCase): # class PluginTestCase(BaseTestCase): # def setUp(self): # def __init__(self): # def setUp(self): # def _clean_config_loaded_flag(): # def setUp(self): # def conf_override(**kw): # def conf_default(**kw): # def setUp(self, register_opts=None): . Output only the next line.
repo = mysql_repo.MysqlRepo(base.config.CONF)
Here is a snippet: <|code_start|> def tearDown(self): super(TestHipchat, self).tearDown() self.assertTrue(self.trap.empty()) def _http_post_200(self, url, data, **kwargs): self.trap.put(url) self.trap.put(data) r = requestsResponse(200) return r @mock.patch('monasca_notification.plugins.hipchat_notifier.requests') def notify(self, http_func, mock_requests): mock_log = mock.MagicMock() mock_log.warn = self.trap.put mock_log.error = self.trap.put mock_log.exception = self.trap.put mock_requests.post = http_func hipchat = hipchat_notifier.HipChatNotifier(mock_log) hipchat.config() metric = [] metric_data = {'dimensions': {'hostname': 'foo1', 'service': 'bar1'}} metric.append(metric_data) alarm_dict = alarm(metric) <|code_end|> . Write the next line using the current file imports: import json import queue from unittest import mock from monasca_notification import notification as m_notification from monasca_notification.plugins import hipchat_notifier from tests import base and context from other files: # Path: monasca_notification/notification.py # class Notification(object): # def __init__(self, id, type, name, address, period, retry_count, alarm): # def __eq__(self, other): # def __ne__(self, other): # def to_json(self): # # Path: monasca_notification/plugins/hipchat_notifier.py # CONF = cfg.CONF # SEVERITY_COLORS = {"low": 'green', # 'medium': 'gray', # 'high': 'yellow', # 'critical': 'red'} # class HipChatNotifier(abstract_notifier.AbstractNotifier): # def __init__(self, log): # def config(self, config_dict=None): # def statsd_name(self): # def _build_hipchat_message(self, notification): # def _get_color(self, severity): # def send_notification(self, notification): # def register_opts(conf): # def list_opts(): # # Path: tests/base.py # class DisableStatsdFixture(fixtures.Fixture): # class ConfigFixture(oo_cfg.Config): # class BaseTestCase(oslotest_base.BaseTestCase): # class PluginTestCase(BaseTestCase): # def setUp(self): # def __init__(self): # def setUp(self): # def _clean_config_loaded_flag(): # def setUp(self): # def conf_override(**kw): # def conf_default(**kw): # def setUp(self, register_opts=None): , which may include functions, classes, or code. Output only the next line.
notification = m_notification.Notification(0, 'hipchat', 'hipchat notification',
Given the code snippet: <|code_start|># implied. # See the License for the specific language governing permissions and # limitations under the License. def alarm(metrics): return {"tenantId": "0", "alarmId": "0", "alarmDefinitionId": 0, "alarmName": "test Alarm", "alarmDescription": "test Alarm description", "oldState": "OK", "newState": "ALARM", "severity": "CRITICAL", "link": "some-link", "lifecycleState": "OPEN", "stateChangeReason": "I am alarming!", "timestamp": 1429023453632, "metrics": metrics} class requestsResponse(object): def __init__(self, status): self.status_code = status class TestHipchat(base.PluginTestCase): def setUp(self): <|code_end|> , generate the next line using the imports in this file: import json import queue from unittest import mock from monasca_notification import notification as m_notification from monasca_notification.plugins import hipchat_notifier from tests import base and context (functions, classes, or occasionally code) from other files: # Path: monasca_notification/notification.py # class Notification(object): # def __init__(self, id, type, name, address, period, retry_count, alarm): # def __eq__(self, other): # def __ne__(self, other): # def to_json(self): # # Path: monasca_notification/plugins/hipchat_notifier.py # CONF = cfg.CONF # SEVERITY_COLORS = {"low": 'green', # 'medium': 'gray', # 'high': 'yellow', # 'critical': 'red'} # class HipChatNotifier(abstract_notifier.AbstractNotifier): # def __init__(self, log): # def config(self, config_dict=None): # def statsd_name(self): # def _build_hipchat_message(self, notification): # def _get_color(self, severity): # def send_notification(self, notification): # def register_opts(conf): # def list_opts(): # # Path: tests/base.py # class DisableStatsdFixture(fixtures.Fixture): # class ConfigFixture(oo_cfg.Config): # class BaseTestCase(oslotest_base.BaseTestCase): # class PluginTestCase(BaseTestCase): # def setUp(self): # def __init__(self): # def setUp(self): # def _clean_config_loaded_flag(): # def setUp(self): # def conf_override(**kw): # def conf_default(**kw): # def setUp(self, register_opts=None): . Output only the next line.
super(TestHipchat, self).setUp(hipchat_notifier.register_opts)
Given snippet: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. def alarm(metrics): return {"tenantId": "0", "alarmId": "0", "alarmDefinitionId": 0, "alarmName": "test Alarm", "alarmDescription": "test Alarm description", "oldState": "OK", "newState": "ALARM", "severity": "CRITICAL", "link": "some-link", "lifecycleState": "OPEN", "stateChangeReason": "I am alarming!", "timestamp": 1429023453632, "metrics": metrics} class requestsResponse(object): def __init__(self, status): self.status_code = status <|code_end|> , continue by predicting the next line. Consider current file imports: import json import queue from unittest import mock from monasca_notification import notification as m_notification from monasca_notification.plugins import hipchat_notifier from tests import base and context: # Path: monasca_notification/notification.py # class Notification(object): # def __init__(self, id, type, name, address, period, retry_count, alarm): # def __eq__(self, other): # def __ne__(self, other): # def to_json(self): # # Path: monasca_notification/plugins/hipchat_notifier.py # CONF = cfg.CONF # SEVERITY_COLORS = {"low": 'green', # 'medium': 'gray', # 'high': 'yellow', # 'critical': 'red'} # class HipChatNotifier(abstract_notifier.AbstractNotifier): # def __init__(self, log): # def config(self, config_dict=None): # def statsd_name(self): # def _build_hipchat_message(self, notification): # def _get_color(self, severity): # def send_notification(self, notification): # def register_opts(conf): # def list_opts(): # # Path: tests/base.py # class DisableStatsdFixture(fixtures.Fixture): # class ConfigFixture(oo_cfg.Config): # class BaseTestCase(oslotest_base.BaseTestCase): # class PluginTestCase(BaseTestCase): # def setUp(self): # def __init__(self): # def setUp(self): # def _clean_config_loaded_flag(): # def setUp(self): # def conf_override(**kw): # def conf_default(**kw): # def setUp(self, register_opts=None): which might include code, classes, or functions. Output only the next line.
class TestHipchat(base.PluginTestCase):
Using the snippet: <|code_start|> log = logging.getLogger(__name__) CONF = cfg.CONF class RetryEngine(object): def __init__(self): self._statsd = get_statsd_client() self._consumer = client_factory.get_kafka_consumer( CONF.kafka.url, CONF.kafka.group, CONF.kafka.notification_retry_topic, CONF.zookeeper.url, CONF.zookeeper.notification_retry_path, CONF.kafka.legacy_kafka_client_enabled) self._producer = client_factory.get_kafka_producer( CONF.kafka.url, CONF.kafka.legacy_kafka_client_enabled) self._notifier = notification_processor.NotificationProcessor() self._db_repo = get_db_repo() def run(self): for raw_notification in self._consumer: message = raw_notification.value() notification_data = jsonutils.loads(message) <|code_end|> , determine the next line of code. You have imports: import time from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from monasca_common.kafka import client_factory from monasca_notification.common.utils import construct_notification_object from monasca_notification.common.utils import get_db_repo from monasca_notification.common.utils import get_statsd_client from monasca_notification.processors import notification_processor and context (class names, function names, or code) available: # Path: monasca_notification/common/utils.py # def construct_notification_object(db_repo, notification_json): # try: # notification = Notification(notification_json['id'], # notification_json['type'], # notification_json['name'], # notification_json['address'], # notification_json['period'], # notification_json['retry_count'], # notification_json['raw_alarm']) # # Grab notification method from database to see if it was changed # stored_notification = grab_stored_notification_method(db_repo, notification.id) # # Notification method was deleted # if stored_notification is None: # LOG.debug("Notification method {0} was deleted from database. " # "Will stop sending.".format(notification.id)) # return None # # Update notification method with most up to date values # else: # notification.name = stored_notification[0] # notification.type = stored_notification[1] # notification.address = stored_notification[2] # notification.period = stored_notification[3] # return notification # except exceptions.DatabaseException: # LOG.warn("Error querying mysql for notification method. " # "Using currently cached method.") # return notification # except Exception as e: # LOG.warn("Error when attempting to construct notification {0}".format(e)) # return None # # Path: monasca_notification/common/utils.py # def get_db_repo(): # repo_driver = CONF.database.repo_driver # LOG.debug('Enabling the %s RDB repository', repo_driver) # return repo_driver(CONF) # # Path: monasca_notification/common/utils.py # def get_statsd_client(dimensions=None): # local_dims = dimensions.copy() if dimensions else {} # local_dims.update(NOTIFICATION_DIMENSIONS) # if CONF.statsd.enable: # LOG.debug("Establishing connection with statsd on {0}:{1}" # .format(CONF.statsd.host, CONF.statsd.port)) # client = monascastatsd.Client(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # else: # LOG.warn("StatsD monitoring disabled. Overriding monascastatsd.Client to use it offline") # client = OfflineClient(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # return client # # Path: monasca_notification/processors/notification_processor.py # class NotificationProcessor(object): # def __init__(self): # def _remaining_plugin_types(self): # def insert_configured_plugins(self): # def send(self, notifications): . Output only the next line.
notification = construct_notification_object(self._db_repo, notification_data)
Predict the next line for this snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. log = logging.getLogger(__name__) CONF = cfg.CONF class RetryEngine(object): def __init__(self): self._statsd = get_statsd_client() self._consumer = client_factory.get_kafka_consumer( CONF.kafka.url, CONF.kafka.group, CONF.kafka.notification_retry_topic, CONF.zookeeper.url, CONF.zookeeper.notification_retry_path, CONF.kafka.legacy_kafka_client_enabled) self._producer = client_factory.get_kafka_producer( CONF.kafka.url, CONF.kafka.legacy_kafka_client_enabled) self._notifier = notification_processor.NotificationProcessor() <|code_end|> with the help of current file imports: import time from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from monasca_common.kafka import client_factory from monasca_notification.common.utils import construct_notification_object from monasca_notification.common.utils import get_db_repo from monasca_notification.common.utils import get_statsd_client from monasca_notification.processors import notification_processor and context from other files: # Path: monasca_notification/common/utils.py # def construct_notification_object(db_repo, notification_json): # try: # notification = Notification(notification_json['id'], # notification_json['type'], # notification_json['name'], # notification_json['address'], # notification_json['period'], # notification_json['retry_count'], # notification_json['raw_alarm']) # # Grab notification method from database to see if it was changed # stored_notification = grab_stored_notification_method(db_repo, notification.id) # # Notification method was deleted # if stored_notification is None: # LOG.debug("Notification method {0} was deleted from database. " # "Will stop sending.".format(notification.id)) # return None # # Update notification method with most up to date values # else: # notification.name = stored_notification[0] # notification.type = stored_notification[1] # notification.address = stored_notification[2] # notification.period = stored_notification[3] # return notification # except exceptions.DatabaseException: # LOG.warn("Error querying mysql for notification method. " # "Using currently cached method.") # return notification # except Exception as e: # LOG.warn("Error when attempting to construct notification {0}".format(e)) # return None # # Path: monasca_notification/common/utils.py # def get_db_repo(): # repo_driver = CONF.database.repo_driver # LOG.debug('Enabling the %s RDB repository', repo_driver) # return repo_driver(CONF) # # Path: monasca_notification/common/utils.py # def get_statsd_client(dimensions=None): # local_dims = dimensions.copy() if dimensions else {} # local_dims.update(NOTIFICATION_DIMENSIONS) # if CONF.statsd.enable: # LOG.debug("Establishing connection with statsd on {0}:{1}" # .format(CONF.statsd.host, CONF.statsd.port)) # client = monascastatsd.Client(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # else: # LOG.warn("StatsD monitoring disabled. Overriding monascastatsd.Client to use it offline") # client = OfflineClient(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # return client # # Path: monasca_notification/processors/notification_processor.py # class NotificationProcessor(object): # def __init__(self): # def _remaining_plugin_types(self): # def insert_configured_plugins(self): # def send(self, notifications): , which may contain function names, class names, or code. Output only the next line.
self._db_repo = get_db_repo()
Predict the next line for this snippet: <|code_start|># (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP # Copyright 2017 Fujitsu LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. log = logging.getLogger(__name__) CONF = cfg.CONF class RetryEngine(object): def __init__(self): <|code_end|> with the help of current file imports: import time from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from monasca_common.kafka import client_factory from monasca_notification.common.utils import construct_notification_object from monasca_notification.common.utils import get_db_repo from monasca_notification.common.utils import get_statsd_client from monasca_notification.processors import notification_processor and context from other files: # Path: monasca_notification/common/utils.py # def construct_notification_object(db_repo, notification_json): # try: # notification = Notification(notification_json['id'], # notification_json['type'], # notification_json['name'], # notification_json['address'], # notification_json['period'], # notification_json['retry_count'], # notification_json['raw_alarm']) # # Grab notification method from database to see if it was changed # stored_notification = grab_stored_notification_method(db_repo, notification.id) # # Notification method was deleted # if stored_notification is None: # LOG.debug("Notification method {0} was deleted from database. " # "Will stop sending.".format(notification.id)) # return None # # Update notification method with most up to date values # else: # notification.name = stored_notification[0] # notification.type = stored_notification[1] # notification.address = stored_notification[2] # notification.period = stored_notification[3] # return notification # except exceptions.DatabaseException: # LOG.warn("Error querying mysql for notification method. " # "Using currently cached method.") # return notification # except Exception as e: # LOG.warn("Error when attempting to construct notification {0}".format(e)) # return None # # Path: monasca_notification/common/utils.py # def get_db_repo(): # repo_driver = CONF.database.repo_driver # LOG.debug('Enabling the %s RDB repository', repo_driver) # return repo_driver(CONF) # # Path: monasca_notification/common/utils.py # def get_statsd_client(dimensions=None): # local_dims = dimensions.copy() if dimensions else {} # local_dims.update(NOTIFICATION_DIMENSIONS) # if CONF.statsd.enable: # LOG.debug("Establishing connection with statsd on {0}:{1}" # .format(CONF.statsd.host, CONF.statsd.port)) # client = monascastatsd.Client(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # else: # LOG.warn("StatsD monitoring disabled. Overriding monascastatsd.Client to use it offline") # client = OfflineClient(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # return client # # Path: monasca_notification/processors/notification_processor.py # class NotificationProcessor(object): # def __init__(self): # def _remaining_plugin_types(self): # def insert_configured_plugins(self): # def send(self, notifications): , which may contain function names, class names, or code. Output only the next line.
self._statsd = get_statsd_client()
Predict the next line after this snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. log = logging.getLogger(__name__) CONF = cfg.CONF class RetryEngine(object): def __init__(self): self._statsd = get_statsd_client() self._consumer = client_factory.get_kafka_consumer( CONF.kafka.url, CONF.kafka.group, CONF.kafka.notification_retry_topic, CONF.zookeeper.url, CONF.zookeeper.notification_retry_path, CONF.kafka.legacy_kafka_client_enabled) self._producer = client_factory.get_kafka_producer( CONF.kafka.url, CONF.kafka.legacy_kafka_client_enabled) <|code_end|> using the current file's imports: import time from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from monasca_common.kafka import client_factory from monasca_notification.common.utils import construct_notification_object from monasca_notification.common.utils import get_db_repo from monasca_notification.common.utils import get_statsd_client from monasca_notification.processors import notification_processor and any relevant context from other files: # Path: monasca_notification/common/utils.py # def construct_notification_object(db_repo, notification_json): # try: # notification = Notification(notification_json['id'], # notification_json['type'], # notification_json['name'], # notification_json['address'], # notification_json['period'], # notification_json['retry_count'], # notification_json['raw_alarm']) # # Grab notification method from database to see if it was changed # stored_notification = grab_stored_notification_method(db_repo, notification.id) # # Notification method was deleted # if stored_notification is None: # LOG.debug("Notification method {0} was deleted from database. " # "Will stop sending.".format(notification.id)) # return None # # Update notification method with most up to date values # else: # notification.name = stored_notification[0] # notification.type = stored_notification[1] # notification.address = stored_notification[2] # notification.period = stored_notification[3] # return notification # except exceptions.DatabaseException: # LOG.warn("Error querying mysql for notification method. " # "Using currently cached method.") # return notification # except Exception as e: # LOG.warn("Error when attempting to construct notification {0}".format(e)) # return None # # Path: monasca_notification/common/utils.py # def get_db_repo(): # repo_driver = CONF.database.repo_driver # LOG.debug('Enabling the %s RDB repository', repo_driver) # return repo_driver(CONF) # # Path: monasca_notification/common/utils.py # def get_statsd_client(dimensions=None): # local_dims = dimensions.copy() if dimensions else {} # local_dims.update(NOTIFICATION_DIMENSIONS) # if CONF.statsd.enable: # LOG.debug("Establishing connection with statsd on {0}:{1}" # .format(CONF.statsd.host, CONF.statsd.port)) # client = monascastatsd.Client(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # else: # LOG.warn("StatsD monitoring disabled. Overriding monascastatsd.Client to use it offline") # client = OfflineClient(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # return client # # Path: monasca_notification/processors/notification_processor.py # class NotificationProcessor(object): # def __init__(self): # def _remaining_plugin_types(self): # def insert_configured_plugins(self): # def send(self, notifications): . Output only the next line.
self._notifier = notification_processor.NotificationProcessor()
Predict the next line after this snippet: <|code_start|># Copyright 2015-2017 FUJITSU LIMITED # (C) Copyright 2015,2016 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. LOG = logging.getLogger(__name__) CONF = cfg.CONF class OrmRepo(object): def __init__(self): self._orm_engine = engine_from_config({ 'url': CONF.orm.url }, prefix='') metadata = MetaData() <|code_end|> using the current file's imports: from oslo_config import cfg from oslo_log import log as logging from sqlalchemy import engine_from_config, MetaData from sqlalchemy.sql import select, bindparam, and_, insert from sqlalchemy.exc import DatabaseError from monasca_notification.common.repositories import exceptions as exc from monasca_notification.common.repositories.orm import models and any relevant context from other files: # Path: monasca_notification/common/repositories/orm/models.py # ALARM_STATES = ('UNDETERMINED', 'OK', 'ALARM') # def create_alarm_action_model(metadata=None): # def create_notification_method_model(metadata=None): # def create_notification_method_type_model(metadata=None): # def create_alarm_model(metadata=None): . Output only the next line.
aa = models.create_alarm_action_model(metadata).alias('aa')
Based on the snippet: <|code_start|> """ Note: This plugin doesn't support multi tenancy. Multi tenancy requires support for multiple JIRA server url. JIRA doesn't support OAUTH2 tokens, we may need to get the user credentials in query params and store them in monasca DB which we don't want to do. That is the reason for not supporting true multitenancy. MultiTenancy can be achieved by creating issues in different project for different tenant on the same JIRA server. notification.address = https://<jira_url>/?project=<project_name> Jira Configuration 1) jira: user: username password: password Sample notification: monasca notification-create MyIssuer JIRA https://jira.hpcloud.net/?project=MyProject monasca notification-create MyIssuer1 JIRA https://jira.hpcloud.net/?project=MyProject& component=MyComponent """ CONF = cfg.CONF <|code_end|> , predict the immediate next line with the help of imports: from debtcollector import removals from jinja2 import Template from oslo_config import cfg from monasca_notification.plugins.abstract_notifier import AbstractNotifier import jira import simplejson as json import urllib import yaml and context (classes, functions, sometimes code) from other files: # Path: monasca_notification/plugins/abstract_notifier.py # class AbstractNotifier(object, metaclass=abc.ABCMeta): # # def __init__(self): # pass # # @abc.abstractproperty # def statsd_name(self): # pass # # @abc.abstractmethod # def config(self, config): # pass # # @abc.abstractmethod # def send_notification(self, notification): # pass . Output only the next line.
class JiraNotifier(AbstractNotifier):
Continue the code snippet: <|code_start|> CONF.kafka.legacy_kafka_client_enabled) self._notifier = notification_processor.NotificationProcessor() self._db_repo = get_db_repo() self._period = period def _keep_sending(self, alarm_id, original_state, period): try: current_state = self._db_repo.get_alarm_current_state(alarm_id) except exceptions.DatabaseException: log.debug('Database Error. Attempting reconnect') current_state = self._db_repo.get_alarm_current_state(alarm_id) # Alarm was deleted if current_state is None: return False # Alarm state changed if current_state != original_state: return False # Period changed if period != self._period: return False return True def run(self): for raw_notification in self._consumer: message = raw_notification.value() notification_data = jsonutils.loads(message) <|code_end|> . Use current file imports: import time from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from monasca_common.kafka import client_factory from monasca_notification.common.repositories import exceptions from monasca_notification.common.utils import construct_notification_object from monasca_notification.common.utils import get_db_repo from monasca_notification.common.utils import get_statsd_client from monasca_notification.processors import notification_processor and context (classes, functions, or code) from other files: # Path: monasca_notification/common/utils.py # def construct_notification_object(db_repo, notification_json): # try: # notification = Notification(notification_json['id'], # notification_json['type'], # notification_json['name'], # notification_json['address'], # notification_json['period'], # notification_json['retry_count'], # notification_json['raw_alarm']) # # Grab notification method from database to see if it was changed # stored_notification = grab_stored_notification_method(db_repo, notification.id) # # Notification method was deleted # if stored_notification is None: # LOG.debug("Notification method {0} was deleted from database. " # "Will stop sending.".format(notification.id)) # return None # # Update notification method with most up to date values # else: # notification.name = stored_notification[0] # notification.type = stored_notification[1] # notification.address = stored_notification[2] # notification.period = stored_notification[3] # return notification # except exceptions.DatabaseException: # LOG.warn("Error querying mysql for notification method. " # "Using currently cached method.") # return notification # except Exception as e: # LOG.warn("Error when attempting to construct notification {0}".format(e)) # return None # # Path: monasca_notification/common/utils.py # def get_db_repo(): # repo_driver = CONF.database.repo_driver # LOG.debug('Enabling the %s RDB repository', repo_driver) # return repo_driver(CONF) # # Path: monasca_notification/common/utils.py # def get_statsd_client(dimensions=None): # local_dims = dimensions.copy() if dimensions else {} # local_dims.update(NOTIFICATION_DIMENSIONS) # if CONF.statsd.enable: # LOG.debug("Establishing connection with statsd on {0}:{1}" # .format(CONF.statsd.host, CONF.statsd.port)) # client = monascastatsd.Client(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # else: # LOG.warn("StatsD monitoring disabled. Overriding monascastatsd.Client to use it offline") # client = OfflineClient(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # return client # # Path: monasca_notification/processors/notification_processor.py # class NotificationProcessor(object): # def __init__(self): # def _remaining_plugin_types(self): # def insert_configured_plugins(self): # def send(self, notifications): . Output only the next line.
notification = construct_notification_object(self._db_repo, notification_data)
Predict the next line for this snippet: <|code_start|># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. log = logging.getLogger(__name__) CONF = cfg.CONF class PeriodicEngine(object): def __init__(self, period): self._topic_name = CONF.kafka.periodic[str(period)] self._statsd = get_statsd_client() self._consumer = client_factory.get_kafka_consumer( CONF.kafka.url, CONF.kafka.group, self._topic_name, CONF.zookeeper.url, CONF.zookeeper.periodic_path[str(period)], CONF.kafka.legacy_kafka_client_enabled) self._producer = client_factory.get_kafka_producer( CONF.kafka.url, CONF.kafka.legacy_kafka_client_enabled) self._notifier = notification_processor.NotificationProcessor() <|code_end|> with the help of current file imports: import time from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from monasca_common.kafka import client_factory from monasca_notification.common.repositories import exceptions from monasca_notification.common.utils import construct_notification_object from monasca_notification.common.utils import get_db_repo from monasca_notification.common.utils import get_statsd_client from monasca_notification.processors import notification_processor and context from other files: # Path: monasca_notification/common/utils.py # def construct_notification_object(db_repo, notification_json): # try: # notification = Notification(notification_json['id'], # notification_json['type'], # notification_json['name'], # notification_json['address'], # notification_json['period'], # notification_json['retry_count'], # notification_json['raw_alarm']) # # Grab notification method from database to see if it was changed # stored_notification = grab_stored_notification_method(db_repo, notification.id) # # Notification method was deleted # if stored_notification is None: # LOG.debug("Notification method {0} was deleted from database. " # "Will stop sending.".format(notification.id)) # return None # # Update notification method with most up to date values # else: # notification.name = stored_notification[0] # notification.type = stored_notification[1] # notification.address = stored_notification[2] # notification.period = stored_notification[3] # return notification # except exceptions.DatabaseException: # LOG.warn("Error querying mysql for notification method. " # "Using currently cached method.") # return notification # except Exception as e: # LOG.warn("Error when attempting to construct notification {0}".format(e)) # return None # # Path: monasca_notification/common/utils.py # def get_db_repo(): # repo_driver = CONF.database.repo_driver # LOG.debug('Enabling the %s RDB repository', repo_driver) # return repo_driver(CONF) # # Path: monasca_notification/common/utils.py # def get_statsd_client(dimensions=None): # local_dims = dimensions.copy() if dimensions else {} # local_dims.update(NOTIFICATION_DIMENSIONS) # if CONF.statsd.enable: # LOG.debug("Establishing connection with statsd on {0}:{1}" # .format(CONF.statsd.host, CONF.statsd.port)) # client = monascastatsd.Client(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # else: # LOG.warn("StatsD monitoring disabled. Overriding monascastatsd.Client to use it offline") # client = OfflineClient(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # return client # # Path: monasca_notification/processors/notification_processor.py # class NotificationProcessor(object): # def __init__(self): # def _remaining_plugin_types(self): # def insert_configured_plugins(self): # def send(self, notifications): , which may contain function names, class names, or code. Output only the next line.
self._db_repo = get_db_repo()
Predict the next line after this snippet: <|code_start|># (C) Copyright 2016 Hewlett Packard Enterprise Development LP # Copyright 2017 Fujitsu LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. log = logging.getLogger(__name__) CONF = cfg.CONF class PeriodicEngine(object): def __init__(self, period): self._topic_name = CONF.kafka.periodic[str(period)] <|code_end|> using the current file's imports: import time from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from monasca_common.kafka import client_factory from monasca_notification.common.repositories import exceptions from monasca_notification.common.utils import construct_notification_object from monasca_notification.common.utils import get_db_repo from monasca_notification.common.utils import get_statsd_client from monasca_notification.processors import notification_processor and any relevant context from other files: # Path: monasca_notification/common/utils.py # def construct_notification_object(db_repo, notification_json): # try: # notification = Notification(notification_json['id'], # notification_json['type'], # notification_json['name'], # notification_json['address'], # notification_json['period'], # notification_json['retry_count'], # notification_json['raw_alarm']) # # Grab notification method from database to see if it was changed # stored_notification = grab_stored_notification_method(db_repo, notification.id) # # Notification method was deleted # if stored_notification is None: # LOG.debug("Notification method {0} was deleted from database. " # "Will stop sending.".format(notification.id)) # return None # # Update notification method with most up to date values # else: # notification.name = stored_notification[0] # notification.type = stored_notification[1] # notification.address = stored_notification[2] # notification.period = stored_notification[3] # return notification # except exceptions.DatabaseException: # LOG.warn("Error querying mysql for notification method. " # "Using currently cached method.") # return notification # except Exception as e: # LOG.warn("Error when attempting to construct notification {0}".format(e)) # return None # # Path: monasca_notification/common/utils.py # def get_db_repo(): # repo_driver = CONF.database.repo_driver # LOG.debug('Enabling the %s RDB repository', repo_driver) # return repo_driver(CONF) # # Path: monasca_notification/common/utils.py # def get_statsd_client(dimensions=None): # local_dims = dimensions.copy() if dimensions else {} # local_dims.update(NOTIFICATION_DIMENSIONS) # if CONF.statsd.enable: # LOG.debug("Establishing connection with statsd on {0}:{1}" # .format(CONF.statsd.host, CONF.statsd.port)) # client = monascastatsd.Client(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # else: # LOG.warn("StatsD monitoring disabled. Overriding monascastatsd.Client to use it offline") # client = OfflineClient(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # return client # # Path: monasca_notification/processors/notification_processor.py # class NotificationProcessor(object): # def __init__(self): # def _remaining_plugin_types(self): # def insert_configured_plugins(self): # def send(self, notifications): . Output only the next line.
self._statsd = get_statsd_client()
Predict the next line for this snippet: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. log = logging.getLogger(__name__) CONF = cfg.CONF class PeriodicEngine(object): def __init__(self, period): self._topic_name = CONF.kafka.periodic[str(period)] self._statsd = get_statsd_client() self._consumer = client_factory.get_kafka_consumer( CONF.kafka.url, CONF.kafka.group, self._topic_name, CONF.zookeeper.url, CONF.zookeeper.periodic_path[str(period)], CONF.kafka.legacy_kafka_client_enabled) self._producer = client_factory.get_kafka_producer( CONF.kafka.url, CONF.kafka.legacy_kafka_client_enabled) <|code_end|> with the help of current file imports: import time from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from monasca_common.kafka import client_factory from monasca_notification.common.repositories import exceptions from monasca_notification.common.utils import construct_notification_object from monasca_notification.common.utils import get_db_repo from monasca_notification.common.utils import get_statsd_client from monasca_notification.processors import notification_processor and context from other files: # Path: monasca_notification/common/utils.py # def construct_notification_object(db_repo, notification_json): # try: # notification = Notification(notification_json['id'], # notification_json['type'], # notification_json['name'], # notification_json['address'], # notification_json['period'], # notification_json['retry_count'], # notification_json['raw_alarm']) # # Grab notification method from database to see if it was changed # stored_notification = grab_stored_notification_method(db_repo, notification.id) # # Notification method was deleted # if stored_notification is None: # LOG.debug("Notification method {0} was deleted from database. " # "Will stop sending.".format(notification.id)) # return None # # Update notification method with most up to date values # else: # notification.name = stored_notification[0] # notification.type = stored_notification[1] # notification.address = stored_notification[2] # notification.period = stored_notification[3] # return notification # except exceptions.DatabaseException: # LOG.warn("Error querying mysql for notification method. " # "Using currently cached method.") # return notification # except Exception as e: # LOG.warn("Error when attempting to construct notification {0}".format(e)) # return None # # Path: monasca_notification/common/utils.py # def get_db_repo(): # repo_driver = CONF.database.repo_driver # LOG.debug('Enabling the %s RDB repository', repo_driver) # return repo_driver(CONF) # # Path: monasca_notification/common/utils.py # def get_statsd_client(dimensions=None): # local_dims = dimensions.copy() if dimensions else {} # local_dims.update(NOTIFICATION_DIMENSIONS) # if CONF.statsd.enable: # LOG.debug("Establishing connection with statsd on {0}:{1}" # .format(CONF.statsd.host, CONF.statsd.port)) # client = monascastatsd.Client(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # else: # LOG.warn("StatsD monitoring disabled. Overriding monascastatsd.Client to use it offline") # client = OfflineClient(name='monasca', # host=CONF.statsd.host, # port=CONF.statsd.port, # dimensions=local_dims) # return client # # Path: monasca_notification/processors/notification_processor.py # class NotificationProcessor(object): # def __init__(self): # def _remaining_plugin_types(self): # def insert_configured_plugins(self): # def send(self, notifications): , which may contain function names, class names, or code. Output only the next line.
self._notifier = notification_processor.NotificationProcessor()
Given the code snippet: <|code_start|> self._trap = queue.Queue() mock_log = mock.Mock() mock_log.info = self._trap.put mock_log.debug = self._trap.put mock_log.warn = self._trap.put mock_log.error = self._trap.put mock_log.exception = self._trap.put self._jr = jira_notifier.JiraNotifier(mock_log) @mock.patch('monasca_notification.plugins.jira_notifier.jira') def _notify(self, transitions_value, issue_status, address, mock_jira): alarm_dict = alarm() mock_jira_obj = mock.Mock() mock_jira.JIRA.return_value = mock_jira_obj mock_jira_issue = mock.Mock() if issue_status: mock_jira_obj.search_issues.return_value = [mock_jira_issue] mock_jira_issue.fields.status.name = issue_status else: mock_jira_obj.search_issues.return_value = [] mock_jira_obj.transitions.side_effect = transitions_value <|code_end|> , generate the next line using the imports in this file: from unittest import mock from monasca_notification import notification as m_notification from monasca_notification.plugins import jira_notifier from tests import base import queue and context (functions, classes, or occasionally code) from other files: # Path: monasca_notification/notification.py # class Notification(object): # def __init__(self, id, type, name, address, period, retry_count, alarm): # def __eq__(self, other): # def __ne__(self, other): # def to_json(self): # # Path: monasca_notification/plugins/jira_notifier.py # CONF = cfg.CONF # class JiraNotifier(AbstractNotifier): # def __init__(self, log): # def config(self, config_dict): # def statsd_name(self): # def _get_jira_custom_format_fields(self): # def _build_custom_jira_message(self, notification, jira_fields_format): # def _build_default_jira_message(self, notification): # def _build_jira_message(self, notification): # def send_notification(self, notification): # def jira_workflow(self, jira_fields, jira_obj, notification): # def register_opts(conf): # def list_opts(): # # Path: tests/base.py # class DisableStatsdFixture(fixtures.Fixture): # class ConfigFixture(oo_cfg.Config): # class BaseTestCase(oslotest_base.BaseTestCase): # class PluginTestCase(BaseTestCase): # def setUp(self): # def __init__(self): # def setUp(self): # def _clean_config_loaded_flag(): # def setUp(self): # def conf_override(**kw): # def conf_default(**kw): # def setUp(self, register_opts=None): . Output only the next line.
notification = m_notification.Notification(0, 'jira',
Based on the snippet: <|code_start|> 'project': {'key': 'MyProject'}, 'summary': 'Monasca alarm for alarm_defintion test Alarm status ' 'changed to ALARM for the alarm_id 0'}} if component: issue['fields'].update({'components': [{'name': 'MyComponent'}]}) if custom_config: alarm_value = alarm() issue['fields'].update({'description': alarm_value.get('alarmName')}) summary_format_string = 'Alarm created for {0} with severity {1} for {2}' summary = summary_format_string.format(alarm_value.get('alarmName'), alarm_value.get('newState'), alarm_value.get('alarmId')) issue['fields'].update({'summary': summary}) return issue class RequestsResponse(object): def __init__(self, status): self.status_code = status class TestJira(base.PluginTestCase): default_address = 'http://test.jira:3333/?project=MyProject' \ '&component=MyComponent' default_transitions_value = [[{'id': 100, 'name': 'reopen'}]] issue_status_resolved = 'resolved' def setUp(self): super(TestJira, self).setUp( <|code_end|> , predict the immediate next line with the help of imports: from unittest import mock from monasca_notification import notification as m_notification from monasca_notification.plugins import jira_notifier from tests import base import queue and context (classes, functions, sometimes code) from other files: # Path: monasca_notification/notification.py # class Notification(object): # def __init__(self, id, type, name, address, period, retry_count, alarm): # def __eq__(self, other): # def __ne__(self, other): # def to_json(self): # # Path: monasca_notification/plugins/jira_notifier.py # CONF = cfg.CONF # class JiraNotifier(AbstractNotifier): # def __init__(self, log): # def config(self, config_dict): # def statsd_name(self): # def _get_jira_custom_format_fields(self): # def _build_custom_jira_message(self, notification, jira_fields_format): # def _build_default_jira_message(self, notification): # def _build_jira_message(self, notification): # def send_notification(self, notification): # def jira_workflow(self, jira_fields, jira_obj, notification): # def register_opts(conf): # def list_opts(): # # Path: tests/base.py # class DisableStatsdFixture(fixtures.Fixture): # class ConfigFixture(oo_cfg.Config): # class BaseTestCase(oslotest_base.BaseTestCase): # class PluginTestCase(BaseTestCase): # def setUp(self): # def __init__(self): # def setUp(self): # def _clean_config_loaded_flag(): # def setUp(self): # def conf_override(**kw): # def conf_default(**kw): # def setUp(self, register_opts=None): . Output only the next line.
jira_notifier.register_opts
Here is a snippet: <|code_start|> 'stateChangeReason': 'I am alarming!', 'timestamp': 1429023453632, 'metrics': {'dimension': {'hostname': 'foo1', 'service': 'bar1'}}} def issue(component=True, custom_config=False): issue = {'fields': {'description': 'Monasca alarm', 'issuetype': {'name': 'Bug'}, 'project': {'key': 'MyProject'}, 'summary': 'Monasca alarm for alarm_defintion test Alarm status ' 'changed to ALARM for the alarm_id 0'}} if component: issue['fields'].update({'components': [{'name': 'MyComponent'}]}) if custom_config: alarm_value = alarm() issue['fields'].update({'description': alarm_value.get('alarmName')}) summary_format_string = 'Alarm created for {0} with severity {1} for {2}' summary = summary_format_string.format(alarm_value.get('alarmName'), alarm_value.get('newState'), alarm_value.get('alarmId')) issue['fields'].update({'summary': summary}) return issue class RequestsResponse(object): def __init__(self, status): self.status_code = status <|code_end|> . Write the next line using the current file imports: from unittest import mock from monasca_notification import notification as m_notification from monasca_notification.plugins import jira_notifier from tests import base import queue and context from other files: # Path: monasca_notification/notification.py # class Notification(object): # def __init__(self, id, type, name, address, period, retry_count, alarm): # def __eq__(self, other): # def __ne__(self, other): # def to_json(self): # # Path: monasca_notification/plugins/jira_notifier.py # CONF = cfg.CONF # class JiraNotifier(AbstractNotifier): # def __init__(self, log): # def config(self, config_dict): # def statsd_name(self): # def _get_jira_custom_format_fields(self): # def _build_custom_jira_message(self, notification, jira_fields_format): # def _build_default_jira_message(self, notification): # def _build_jira_message(self, notification): # def send_notification(self, notification): # def jira_workflow(self, jira_fields, jira_obj, notification): # def register_opts(conf): # def list_opts(): # # Path: tests/base.py # class DisableStatsdFixture(fixtures.Fixture): # class ConfigFixture(oo_cfg.Config): # class BaseTestCase(oslotest_base.BaseTestCase): # class PluginTestCase(BaseTestCase): # def setUp(self): # def __init__(self): # def setUp(self): # def _clean_config_loaded_flag(): # def setUp(self): # def conf_override(**kw): # def conf_default(**kw): # def setUp(self, register_opts=None): , which may include functions, classes, or code. Output only the next line.
class TestJira(base.PluginTestCase):
Predict the next line for this snippet: <|code_start|># Copyright 2017 FUJITSU LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. class TestOrmRepo(base.BaseTestCase): @mock.patch('monasca_notification.common.repositories.orm.orm_repo.engine_from_config') def setUp(self, mock_sql_engine_from_config): super(TestOrmRepo, self).setUp() self.conf_default( group='orm', url='mysql+pymysql://user:password@hostname:3306/mon' ) <|code_end|> with the help of current file imports: from unittest import mock from monasca_notification.common.repositories.orm import orm_repo from tests import base and context from other files: # Path: monasca_notification/common/repositories/orm/orm_repo.py # LOG = logging.getLogger(__name__) # CONF = cfg.CONF # class OrmRepo(object): # def __init__(self): # def fetch_notifications(self, alarm): # def get_alarm_current_state(self, alarm_id): # def fetch_notification_method_types(self): # def insert_notification_method_types(self, notification_types): # def get_notification(self, notification_id): # # Path: tests/base.py # class DisableStatsdFixture(fixtures.Fixture): # class ConfigFixture(oo_cfg.Config): # class BaseTestCase(oslotest_base.BaseTestCase): # class PluginTestCase(BaseTestCase): # def setUp(self): # def __init__(self): # def setUp(self): # def _clean_config_loaded_flag(): # def setUp(self): # def conf_override(**kw): # def conf_default(**kw): # def setUp(self, register_opts=None): , which may contain function names, class names, or code. Output only the next line.
self._rep = orm_repo.OrmRepo()
Predict the next line for this snippet: <|code_start|> alarm = self._create_raw_alarm(0, 3, alarm_dict) notifications, partition, offset = self._run_alarm_processor(alarm, None) self.assertEqual(notifications, []) self.assertEqual(partition, 0) self.assertEqual(offset, 3) def test_valid_notification(self): """Test a valid notification, being put onto the notification_queue """ alarm_dict = { "tenantId": "0", "alarmDefinitionId": "0", "alarmId": "1", "alarmName": "test Alarm", "oldState": "OK", "newState": "ALARM", "stateChangeReason": "I am alarming!", "timestamp": time.time() * 1000, "actionsEnabled": 1, "metrics": "cpu_util", "severity": "LOW", "link": "http://some-place.com", "lifecycleState": "OPEN"} alarm = self._create_raw_alarm(0, 4, alarm_dict) sql_response = [[1, 'EMAIL', 'test notification', 'me@here.com', 0]] notifications, partition, offset = self._run_alarm_processor(alarm, sql_response) <|code_end|> with the help of current file imports: import collections import json import time from unittest import mock from monasca_common.kafka import legacy_kafka_message from monasca_notification import notification as m_notification from monasca_notification.processors import alarm_processor from tests import base and context from other files: # Path: monasca_notification/notification.py # class Notification(object): # def __init__(self, id, type, name, address, period, retry_count, alarm): # def __eq__(self, other): # def __ne__(self, other): # def to_json(self): # # Path: monasca_notification/processors/alarm_processor.py # CONF = cfg.CONF # class AlarmProcessor(object): # def __init__(self): # def _parse_alarm(alarm_data): # def _alarm_is_valid(self, alarm): # def _build_notification(self, alarm): # def to_notification(self, raw_alarm): # # Path: tests/base.py # class DisableStatsdFixture(fixtures.Fixture): # class ConfigFixture(oo_cfg.Config): # class BaseTestCase(oslotest_base.BaseTestCase): # class PluginTestCase(BaseTestCase): # def setUp(self): # def __init__(self): # def setUp(self): # def _clean_config_loaded_flag(): # def setUp(self): # def conf_override(**kw): # def conf_default(**kw): # def setUp(self, register_opts=None): , which may contain function names, class names, or code. Output only the next line.
test_notification = m_notification.Notification(1, 'email', 'test notification',
Next line prediction: <|code_start|> json_msg = json.dumps({'alarm-transitioned': message}) msg_tuple = message_tuple(key, json_msg) return legacy_kafka_message.LegacyKafkaMessage([partition, alarm_tuple(offset, msg_tuple)]) @mock.patch('pymysql.connect') @mock.patch('monasca_notification.processors.alarm_processor.log') def _run_alarm_processor(self, alarm, sql_response, mock_log, mock_mysql): """Runs a mocked alarm processor reading from queue while running, returns (queue_message, log_message) """ # Since the log runs in another thread I can mock it directly, instead # change the methods to put to a queue mock_log.warn = self.trap.append mock_log.error = self.trap.append mock_log.exception = self.trap.append # Setup the sql response if sql_response is not None: mock_mysql.return_value = mock_mysql mock_mysql.cursor.return_value = mock_mysql mock_mysql.__iter__.return_value = sql_response self.conf_override(group='mysql', ssl=None, host='localhost', port='3306', user='mysql_user', db='dbname', passwd='mysql_passwd') self.conf_override(group='statsd', host='localhost', port=8125) <|code_end|> . Use current file imports: (import collections import json import time from unittest import mock from monasca_common.kafka import legacy_kafka_message from monasca_notification import notification as m_notification from monasca_notification.processors import alarm_processor from tests import base) and context including class names, function names, or small code snippets from other files: # Path: monasca_notification/notification.py # class Notification(object): # def __init__(self, id, type, name, address, period, retry_count, alarm): # def __eq__(self, other): # def __ne__(self, other): # def to_json(self): # # Path: monasca_notification/processors/alarm_processor.py # CONF = cfg.CONF # class AlarmProcessor(object): # def __init__(self): # def _parse_alarm(alarm_data): # def _alarm_is_valid(self, alarm): # def _build_notification(self, alarm): # def to_notification(self, raw_alarm): # # Path: tests/base.py # class DisableStatsdFixture(fixtures.Fixture): # class ConfigFixture(oo_cfg.Config): # class BaseTestCase(oslotest_base.BaseTestCase): # class PluginTestCase(BaseTestCase): # def setUp(self): # def __init__(self): # def setUp(self): # def _clean_config_loaded_flag(): # def setUp(self): # def conf_override(**kw): # def conf_default(**kw): # def setUp(self, register_opts=None): . Output only the next line.
processor = alarm_processor.AlarmProcessor()