Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|> class ResourceTests(TestCase): def setUp(self): self.TEST_URL = 'https://www.google.com' <|code_end|> , continue by predicting the next line. Consider current file imports: import os import requests from unittest import TestCase from mock import patch, call, Mock from newrelic_api.base import Resource from newrelic_api.exceptions import ConfigurationException, NewRelicAPIServerException and context: # Path: newrelic_api/base.py # class Resource(object): # """ # A base class for API resources # """ # URL = 'https://api.newrelic.com/v2/' # # def __init__(self, api_key=None): # """ # :type api_key: str # :param api_key: The API key. If no key is passed, the environment # variable NEW_RELIC_API_KEY is used. # :raises: If the api_key parameter is not present, and no environment # variable is present, a :class:`newrelic_api.exceptions.ConfigurationException` # is raised. # """ # self.api_key = api_key or os.environ.get('NEW_RELIC_API_KEY') or os.environ.get('NEWRELIC_API_KEY') # # if not self.api_key: # raise ConfigurationException('NEW_RELIC_API_KEY or NEWRELIC_API_KEY not present in environment!') # # self.headers = { # 'Content-type': 'application/json', # 'X-Api-Key': self.api_key, # } # # def _get(self, *args, **kwargs): # """ # A wrapper for getting things # # :returns: The response of your get # :rtype: dict # # :raises: This will raise a # :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>` # if there is an error from New Relic # """ # response = requests.get(*args, **kwargs) # if not response.ok: # raise NewRelicAPIServerException('{}: {}'.format(response.status_code, response.text)) # # json_response = response.json() # # if response.links: # json_response['pages'] = response.links # # return json_response # # def _put(self, *args, **kwargs): # """ # A wrapper for putting things. It will also json encode your 'data' parameter # # :returns: The response of your put # :rtype: dict # # :raises: This will raise a # :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>` # if there is an error from New Relic # """ # if 'data' in kwargs: # kwargs['data'] = json.dumps(kwargs['data']) # response = requests.put(*args, **kwargs) # if not response.ok: # raise NewRelicAPIServerException('{}: {}'.format(response.status_code, response.text)) # # return response.json() # # def _post(self, *args, **kwargs): # """ # A wrapper for posting things. It will also json encode your 'data' parameter # # :returns: The response of your post # :rtype: dict # # :raises: This will raise a # :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>` # if there is an error from New Relic # """ # if 'data' in kwargs: # kwargs['data'] = json.dumps(kwargs['data']) # response = requests.post(*args, **kwargs) # if not response.ok: # raise NewRelicAPIServerException('{}: {}'.format(response.status_code, response.text)) # # return response.json() # # def _delete(self, *args, **kwargs): # """ # A wrapper for deleting things # # :returns: The response of your delete # :rtype: dict # # :raises: This will raise a # :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>` # if there is an error from New Relic # """ # response = requests.delete(*args, **kwargs) # if not response.ok: # raise NewRelicAPIServerException('{}: {}'.format(response.status_code, response.text)) # # if response.text: # return response.json() # # return {} # # def build_param_string(self, params): # """ # This is a simple helper method to build a parameter string. It joins # all list elements that evaluate to True with an ampersand, '&' # # .. code-block:: python # # >>> parameters = Resource().build_param_string(['filter[name]=dev', None, 'page=1']) # >>> print parameters # filter[name]=dev&page=1 # # :type params: list # :param params: The parameters to build a string with # # :rtype: str # :return: The compiled parameter string # """ # return '&'.join([p for p in params if p]) # # Path: newrelic_api/exceptions.py # class ConfigurationException(Exception): # """ # An exception for Configuration errors # """ # message = 'There was an error in the configuration' # # class NewRelicAPIServerException(Exception): # """ # An exception for New Relic server errors # """ # message = 'There was an error from New Relic' which might include code, classes, or functions. Output only the next line.
@patch.object(os.environ, 'get', spec_set=True)
Given the following code snippet before the placeholder: <|code_start|> class NRLabelsTests(TestCase): def setUp(self): super(NRLabelsTests, self).setUp() self.label = Labels(api_key='dummy_key') label = { "key": "Ambition:Production", "category": "Ambition", <|code_end|> , predict the next line using imports from the current file: from unittest import TestCase from mock import patch, Mock from newrelic_api.labels import Labels import requests and context including class names, function names, and sometimes code from other files: # Path: newrelic_api/labels.py # class Labels(Resource): # """ # An interface for interacting with the NewRelic label API. # """ # def list(self, page=None): # """ # This API endpoint returns a paginated list of the Labels # associated with your New Relic account. # # :type page: int # :param page: Pagination index # # :rtype: dict # :return: The JSON response of the API, with an additional 'pages' key # if there are paginated results # # :: # # { # "labels": [ # { # "key": "string", # "category": "string", # "name": "string", # "links": { # "applications": [ # "integer" # ], # "servers": [ # "integer" # ] # } # } # ], # "pages": { # "last": { # "url": "https://api.newrelic.com/v2/labels.json?page=2", # "rel": "last" # }, # "next": { # "url": "https://api.newrelic.com/v2/labels.json?page=2", # "rel": "next" # } # } # } # # """ # # filters = [ # 'page={0}'.format(page) if page else None # ] # # return self._get( # url='{0}labels.json'.format(self.URL), # headers=self.headers, # params=self.build_param_string(filters) # ) # # def create(self, name, category, applications=None, servers=None): # """ # This API endpoint will create a new label with the provided name and # category # # :type name: str # :param name: The name of the label # # :type category: str # :param category: The Category # # :type applications: list of int # :param applications: An optional list of application ID's # # :type servers: list of int # :param servers: An optional list of server ID's # # :rtype: dict # :return: The JSON response of the API # # :: # # { # "label": { # "key": "string", # "category": "string", # "name": "string", # "links": { # "applications": [ # "integer" # ], # "servers": [ # "integer" # ] # } # } # } # # """ # # data = { # "label": { # "category": category, # "name": name, # "links": { # "applications": applications or [], # "servers": servers or [] # } # } # } # # return self._put( # url='{0}labels.json'.format(self.URL), # headers=self.headers, # data=data # ) # # def delete(self, key): # """ # When applications are provided, this endpoint will remove those # applications from the label. # # When no applications are provided, this endpoint will remove the label. # # :type key: str # :param key: Label key. Example: 'Language:Java' # # :rtype: dict # :return: The JSON response of the API # # :: # # { # "label": { # "key": "string", # "category": "string", # "name": "string", # "links": { # "applications": [ # "integer" # ], # "servers": [ # "integer" # ] # } # } # } # # """ # return self._delete( # url='{url}labels/labels/{key}.json'.format( # url=self.URL, # key=key), # headers=self.headers, # ) . Output only the next line.
"name": "Production",
Next line prediction: <|code_start|> class NRBrowserApplicationsTests(TestCase): def setUp(self): super(NRBrowserApplicationsTests, self).setUp() self.browser_application = BrowserApplications(api_key='dummy_key') browser_application = { "id": 1234567, "name": "Account Global", "browser_monitoring_key": "313ed76e08", "loader_script": ( "<script type=\"text/javascript\">" <|code_end|> . Use current file imports: (from unittest import TestCase from mock import patch, Mock from newrelic_api.browser_applications import BrowserApplications import requests) and context including class names, function names, or small code snippets from other files: # Path: newrelic_api/browser_applications.py # class BrowserApplications(Resource): # """ # An interface for interacting with the NewRelic Browser Application API. # """ # def list(self, filter_name=None, filter_ids=None, page=None): # """ # This API endpoint returns a list of the Browser Applications associated # with your New Relic account. # # Browser Applications can be filtered by their name, or by the # application IDs. # # :type filter_name: str # :param filter_name: Filter by application name # # :type filter_ids: list of ints # :param filter_ids: Filter by application ids # # :type page: int # :param page: Pagination index # # :rtype: dict # :return: The JSON response of the API, with an additional 'pages' key # if there are paginated results # # :: # # { # "browser_applications": [ # { # "id": "integer", # "name": "string", # "browser_monitoring_key": "string", # "loader_script": "string" # } # ], # "pages": { # "last": { # "url": "https://api.newrelic.com/v2/browser_applications.json?page=2", # "rel": "last" # }, # "next": { # "url": "https://api.newrelic.com/v2/browser_applications.json?page=2", # "rel": "next" # } # } # } # # """ # filters = [ # 'filter[name]={0}'.format(filter_name) if filter_name else None, # 'filter[ids]={0}'.format(','.join([str(app_id) for app_id in filter_ids])) if filter_ids else None, # 'page={0}'.format(page) if page else None # ] # # return self._get( # url='{0}browser_applications.json'.format(self.URL), # headers=self.headers, # params=self.build_param_string(filters) # ) # # def create(self, name): # """ # This API endpoint allows you to create a standalone Browser Application # # :type name: str # :param name: The name of the application # # :rtype: dict # :return: The JSON response of the API # # :: # # { # "browser_application": { # "id": "integer", # "name": "string", # "browser_monitoring_key": "string", # "loader_script": "string" # } # } # # """ # # data = { # "browser_application": { # "name": name # } # } # # return self._post( # url='{0}browser_applications.json'.format(self.URL), # headers=self.headers, # data=data # ) . Output only the next line.
"\n</script>\n"
Predict the next line for this snippet: <|code_start|> class NRNotificationChannelsTests(TestCase): def setUp(self): super(NRNotificationChannelsTests, self).setUp() self.channels = NotificationChannels(api_key='dummy_key') self.list_response = { "channels": [ <|code_end|> with the help of current file imports: from unittest import TestCase from mock import patch, Mock from newrelic_api.notification_channels import NotificationChannels import json import requests and context from other files: # Path: newrelic_api/notification_channels.py # class NotificationChannels(Resource): # """ # An interface for interacting with the NewRelic Notification Channels API. # """ # def list(self, page=None): # """ # This API endpoint returns a paginated list of the notification channels # associated with your New Relic account. # # :type page: int # :param page: Pagination index # # :rtype: dict # :return: The JSON response of the API, with an additional 'pages' key # if there are paginated results # """ # filters = [ # 'page={0}'.format(page) if page else None # ] # return self._get( # url='{0}alerts_channels.json'.format(self.URL), # headers=self.headers, # params=self.build_param_string(filters) # ) # # def create(self, name, type, configuration): # """ # This API endpoint allows you to create a notification channel, see # New Relic API docs for details of types and configuration # # :type name: str # :param name: The name of the channel # # :type type: str # :param type: Type of notification, eg. email, user, webhook # # :type configuration: hash # :param configuration: Configuration for notification # # :rtype: dict # :return: The JSON response of the API # # :: # # { # "channels": { # "id": "integer", # "name": "string", # "type": "string", # "configuration": { }, # "links": { # "policy_ids": [] # } # } # } # # """ # # data = { # "channel": { # "name": name, # "type": type, # "configuration": configuration # } # } # # return self._post( # url='{0}alerts_channels.json'.format(self.URL), # headers=self.headers, # data=data # ) # # def delete(self, id): # """ # This API endpoint allows you to delete a notification channel # # :type id: integer # :param id: The id of the channel # # :rtype: dict # :return: The JSON response of the API # # :: # # { # "channels": { # "id": "integer", # "name": "string", # "type": "string", # "configuration": { }, # "links": { # "policy_ids": [] # } # } # } # # """ # # return self._delete( # url='{0}alerts_channels/{1}.json'.format(self.URL, id), # headers=self.headers # ) , which may contain function names, class names, or code. Output only the next line.
{
Continue the code snippet: <|code_start|> def setUp(self): super(NRKeyTransactionsTests, self).setUp() self.key_transactions = KeyTransactions(api_key='dummy_key') self.key_transactions_list_response = { "key_transactions": [ { "id": 333112, "name": "login", "transaction_name": "Login Page", "application_summary": { "response_time": 170, "throughput": 3, "error_rate": 0, "apdex_target": 0, "apdex_score": 1 }, "end_user_summary": { "response_time": 300.0, "throughput": 4, "apdex_target": 0, "apdex_score": 1 }, "links": { "application": 123456 } } ] } self.key_transactions_show_response = { <|code_end|> . Use current file imports: from unittest import TestCase from mock import patch, Mock from newrelic_api.key_transactions import KeyTransactions import requests and context (classes, functions, or code) from other files: # Path: newrelic_api/key_transactions.py # class KeyTransactions(Resource): # """ # An interface for interacting with the NewRelic key transactions API. # """ # def list(self, filter_name=None, filter_ids=None, page=None): # """ # This API endpoint returns a paginated list of the key transactions # associated with your New Relic account. # # Key transactions can be filtered by their name or by a list of IDs. # # :type filter_name: str # :param filter_name: Filter by name # # :type filter_ids: list of ints # :param filter_ids: Filter by user ids # # :type page: int # :param page: Pagination index # # :rtype: dict # :return: The JSON response of the API, with an additional 'pages' key # if there are paginated results # # :: # # { # "key_transactions": [ # { # "id": "integer", # "name": "string", # "transaction_name": "string", # "application_summary": { # "response_time": "float", # "throughput": "float", # "error_rate": "float", # "apdex_target": "float", # "apdex_score": "float" # }, # "end_user_summary": { # "response_time": "float", # "throughput": "float", # "apdex_target": "float", # "apdex_score": "float" # }, # "links": { # "application": "integer" # } # } # ], # "pages": { # "last": { # "url": "https://api.newrelic.com/v2/key_transactions.json?page=2", # "rel": "last" # }, # "next": { # "url": "https://api.newrelic.com/v2/key_transactions.json?page=2", # "rel": "next" # } # } # } # # """ # filters = [ # 'filter[name]={0}'.format(filter_name) if filter_name else None, # 'filter[ids]={0}'.format(','.join([str(app_id) for app_id in filter_ids])) if filter_ids else None, # 'page={0}'.format(page) if page else None # ] # return self._get( # url='{0}key_transactions.json'.format(self.URL), # headers=self.headers, # params=self.build_param_string(filters) # ) # # def show(self, id): # """ # This API endpoint returns a single Key transaction, identified its ID. # # :type id: int # :param id: Key transaction ID # # :rtype: dict # :return: The JSON response of the API # # :: # # { # "key_transaction": { # "id": "integer", # "name": "string", # "transaction_name": "string", # "application_summary": { # "response_time": "float", # "throughput": "float", # "error_rate": "float", # "apdex_target": "float", # "apdex_score": "float" # }, # "end_user_summary": { # "response_time": "float", # "throughput": "float", # "apdex_target": "float", # "apdex_score": "float" # }, # "links": { # "application": "integer" # } # } # } # # """ # return self._get( # url='{root}key_transactions/{id}.json'.format( # root=self.URL, # id=id # ), # headers=self.headers, # ) . Output only the next line.
'key_transaction': self.key_transactions_list_response['key_transactions'][0]
Given snippet: <|code_start|> class NRUsersTests(TestCase): def setUp(self): super(NRUsersTests, self).setUp() self.user = Users(api_key='dummy_key') self.user_list_response = { 'users': [ { <|code_end|> , continue by predicting the next line. Consider current file imports: from unittest import TestCase from mock import patch, Mock from newrelic_api.users import Users import requests and context: # Path: newrelic_api/users.py # class Users(Resource): # """ # An interface for interacting with the NewRelic user API. # """ # def list(self, filter_email=None, filter_ids=None, page=None): # """ # This API endpoint returns a paginated list of the Users # associated with your New Relic account. Users can be filtered # by their email or by a list of user IDs. # # :type filter_email: str # :param filter_email: Filter by user email # # :type filter_ids: list of ints # :param filter_ids: Filter by user ids # # :type page: int # :param page: Pagination index # # :rtype: dict # :return: The JSON response of the API, with an additional 'pages' key # if there are paginated results # # :: # # { # "users": [ # { # "id": "integer", # "first_name": "string", # "last_name": "string", # "email": "string", # "role": "string" # } # ], # "pages": { # "last": { # "url": "https://api.newrelic.com/v2/users.json?page=2", # "rel": "last" # }, # "next": { # "url": "https://api.newrelic.com/v2/users.json?page=2", # "rel": "next" # } # } # } # """ # filters = [ # 'filter[email]={0}'.format(filter_email) if filter_email else None, # 'filter[ids]={0}'.format(','.join([str(app_id) for app_id in filter_ids])) if filter_ids else None, # 'page={0}'.format(page) if page else None # ] # # return self._get( # url='{0}users.json'.format(self.URL), # headers=self.headers, # params=self.build_param_string(filters) # ) # # def show(self, id): # """ # This API endpoint returns a single User, identified its ID. # # :type id: int # :param id: User ID # # :rtype: dict # :return: The JSON response of the API # # :: # # { # "user": { # "id": "integer", # "first_name": "string", # "last_name": "string", # "email": "string", # "role": "string" # } # } # # """ # return self._get( # url='{0}users/{1}.json'.format(self.URL, id), # headers=self.headers, # ) which might include code, classes, or functions. Output only the next line.
"id": 333113,
Given the following code snippet before the placeholder: <|code_start|> class ControllerPipeline(Pipeline): def definition(self): pass <|code_end|> , predict the next line using imports from the current file: from motorway.pipeline import Pipeline and context including class names, function names, and sometimes code from other files: # Path: motorway/pipeline.py # class Pipeline(object): # def __init__(self, controller_bind_address="0.0.0.0:7007", run_controller=True, run_webserver=True, run_connection_discovery=True): # self._streams = {} # self._stream_consumers = {} # self._processes = [] # self._ramp_result_streams = [] # self.controller_bind_address = "tcp://%s" % controller_bind_address # self.context = zmq.Context() # self.run_controller = run_controller # self.run_webserver = run_webserver # self.run_connection_discovery = run_connection_discovery # # def definition(self): # """ # Extend this method in your :class:`motorway.pipeline.Pipeline` subclass, e.g.:: # # class WordCountPipeline(Pipeline): # def definition(self): # self.add_ramp(WordRamp, 'sentence') # self.add_intersection(SentenceSplitIntersection, 'sentence', 'word', processes=2) # self.add_intersection(WordCountIntersection, 'word', 'word_count', grouper_cls=HashRingGrouper, processes=2) # self.add_intersection(AggregateIntersection, 'word_count', grouper_cls=HashRingGrouper, processes=1) # """ # raise NotImplementedError("You must implement a definition() on your pipeline") # # def _add_process(self, cls, process_instances, process_args, input_stream=None, output_stream=None, show_in_ui=True, process_start_number=0): # for i in range(process_start_number, process_instances + process_start_number): # process_uuid = uuid.uuid4() # process_name = "%s-%s" % (cls.__name__, process_uuid.hex) # kwargs = { # 'process_uuid': process_uuid # } # p = Process( # target=cls.run, # args=process_args, # kwargs=kwargs, # name=process_name # ) # self._processes.append(p) # if show_in_ui: # if output_stream: # if output_stream not in self._stream_consumers: # self._stream_consumers[output_stream] = {'producers': [], 'consumers': []} # self._stream_consumers[output_stream]['producers'].append(process_name) # if input_stream not in self._stream_consumers: # self._stream_consumers[input_stream] = {'producers': [], 'consumers': []} # self._stream_consumers[input_stream]['consumers'].append(process_name) # # def add_ramp(self, ramp_class, output_stream, processes=1): # ramp_result_stream = ramp_result_stream_name(ramp_class.__name__) # self._ramp_result_streams.append((ramp_class.__name__, ramp_result_stream)) # self._add_process( # ramp_class, # processes, # process_args=( # output_stream, # self.controller_bind_address, # self.run_controller # ), # output_stream=output_stream, # # ) # # def add_intersection(self, intersection_class, input_stream, output_stream=None, processes=1, grouper_cls=None): # self._add_process( # intersection_class, # processes, # process_args=( # input_stream, # output_stream, # self.controller_bind_address, # grouper_cls # ), # input_stream=input_stream, # output_stream=output_stream, # ) # # def run(self): # """ # Execute the entire pipeline in several sub processes. # # """ # # logger.info("Starting Pipeline %s!" % self.__class__.__name__) # # setproctitle("data-pipeline: main") # # # User jobs # self.definition() # logger.debug("Loaded definition") # # # Controller Transformer # if self.run_controller: # self.add_intersection(ControllerIntersection, '_message_ack', '_web_server') # # if self.run_connection_discovery: # self.add_intersection(ConnectionIntersection, '_update_connections') # # if self.run_webserver: # self.add_intersection(WebserverIntersection, '_web_server', grouper_cls=SendToAllGrouper) # all webservers should receive messages # # # The Controller, Connection, and Webserver-intersection must be started first so any # # other intersection and ramp can successfully connect to them. # # The list of processes should therefore be reversed to ensure that these intersections are started first. # self._processes.reverse() # # logger.debug("Running pipeline") # for process in self._processes: # process.start() # # try: # while True: # for process in self._processes: # assert process.is_alive(), "%s died" % process # time.sleep(5) # except Exception: # raise # finally: # self.kill() # logger.debug("Finished Pipeline!") # # def kill(self): # for process in self._processes: # logger.warn("Terminating %s" % process) # if process.is_alive(): # process.terminate() . Output only the next line.
if __name__ == '__main__':
Continue the code snippet: <|code_start|> logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'colored': { '()': 'colorlog.ColoredFormatter', 'format': "%(log_color)s%(levelname)-8s%(reset)s %(name)-32s %(processName)-32s %(blue)s%(message)s" } }, 'loggers': { 'motorway': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False }, 'werkzeug': { 'level': 'WARN', 'handlers': ['console'], 'propagate': False, <|code_end|> . Use current file imports: from motorway.pipeline import Pipeline import logging.config and context (classes, functions, or code) from other files: # Path: motorway/pipeline.py # class Pipeline(object): # def __init__(self, controller_bind_address="0.0.0.0:7007", run_controller=True, run_webserver=True, run_connection_discovery=True): # self._streams = {} # self._stream_consumers = {} # self._processes = [] # self._ramp_result_streams = [] # self.controller_bind_address = "tcp://%s" % controller_bind_address # self.context = zmq.Context() # self.run_controller = run_controller # self.run_webserver = run_webserver # self.run_connection_discovery = run_connection_discovery # # def definition(self): # """ # Extend this method in your :class:`motorway.pipeline.Pipeline` subclass, e.g.:: # # class WordCountPipeline(Pipeline): # def definition(self): # self.add_ramp(WordRamp, 'sentence') # self.add_intersection(SentenceSplitIntersection, 'sentence', 'word', processes=2) # self.add_intersection(WordCountIntersection, 'word', 'word_count', grouper_cls=HashRingGrouper, processes=2) # self.add_intersection(AggregateIntersection, 'word_count', grouper_cls=HashRingGrouper, processes=1) # """ # raise NotImplementedError("You must implement a definition() on your pipeline") # # def _add_process(self, cls, process_instances, process_args, input_stream=None, output_stream=None, show_in_ui=True, process_start_number=0): # for i in range(process_start_number, process_instances + process_start_number): # process_uuid = uuid.uuid4() # process_name = "%s-%s" % (cls.__name__, process_uuid.hex) # kwargs = { # 'process_uuid': process_uuid # } # p = Process( # target=cls.run, # args=process_args, # kwargs=kwargs, # name=process_name # ) # self._processes.append(p) # if show_in_ui: # if output_stream: # if output_stream not in self._stream_consumers: # self._stream_consumers[output_stream] = {'producers': [], 'consumers': []} # self._stream_consumers[output_stream]['producers'].append(process_name) # if input_stream not in self._stream_consumers: # self._stream_consumers[input_stream] = {'producers': [], 'consumers': []} # self._stream_consumers[input_stream]['consumers'].append(process_name) # # def add_ramp(self, ramp_class, output_stream, processes=1): # ramp_result_stream = ramp_result_stream_name(ramp_class.__name__) # self._ramp_result_streams.append((ramp_class.__name__, ramp_result_stream)) # self._add_process( # ramp_class, # processes, # process_args=( # output_stream, # self.controller_bind_address, # self.run_controller # ), # output_stream=output_stream, # # ) # # def add_intersection(self, intersection_class, input_stream, output_stream=None, processes=1, grouper_cls=None): # self._add_process( # intersection_class, # processes, # process_args=( # input_stream, # output_stream, # self.controller_bind_address, # grouper_cls # ), # input_stream=input_stream, # output_stream=output_stream, # ) # # def run(self): # """ # Execute the entire pipeline in several sub processes. # # """ # # logger.info("Starting Pipeline %s!" % self.__class__.__name__) # # setproctitle("data-pipeline: main") # # # User jobs # self.definition() # logger.debug("Loaded definition") # # # Controller Transformer # if self.run_controller: # self.add_intersection(ControllerIntersection, '_message_ack', '_web_server') # # if self.run_connection_discovery: # self.add_intersection(ConnectionIntersection, '_update_connections') # # if self.run_webserver: # self.add_intersection(WebserverIntersection, '_web_server', grouper_cls=SendToAllGrouper) # all webservers should receive messages # # # The Controller, Connection, and Webserver-intersection must be started first so any # # other intersection and ramp can successfully connect to them. # # The list of processes should therefore be reversed to ensure that these intersections are started first. # self._processes.reverse() # # logger.debug("Running pipeline") # for process in self._processes: # process.start() # # try: # while True: # for process in self._processes: # assert process.is_alive(), "%s died" % process # time.sleep(5) # except Exception: # raise # finally: # self.kill() # logger.debug("Finished Pipeline!") # # def kill(self): # for process in self._processes: # logger.warn("Terminating %s" % process) # if process.is_alive(): # process.terminate() . Output only the next line.
}
Here is a snippet: <|code_start|> compiler = scss.Scss(scss_opts = { 'style': 'compressed' if not app.debug else None }, search_paths=[ os.path.join(os.getcwd(), 'styles') ]) # Compile styles (scss) d = os.walk('styles') for f in list(d)[0][2]: if os.path.splitext(f)[1] == ".scss": with open(os.path.join('styles', f)) as r: output = compiler.compile(r.read()) parts = f.rsplit('.') css = '.'.join(parts[:-1]) + ".css" with open(os.path.join(app.static_folder, css), "w") as w: w.write(output) w.flush() else: copyfile(os.path.join('styles', f), os.path.join(app.static_folder, f)) # Compile scripts (coffeescript) try: d = os.walk('scripts') for f in list(d)[0][2]: outputpath = os.path.join(app.static_folder, os.path.basename(f)) inputpath = os.path.join('scripts', f) if os.path.splitext(f)[1] == ".js": <|code_end|> . Write the next line using the current file imports: from packages.app import app from packages.config import _cfg, _cfgi from shutil import rmtree, copyfile import os import scss import coffeescript and context from other files: # Path: packages/app.py # def load_user(username): # def handle_500(e): # def handle_404(e): # def version(): # def hook_publish(): # def inject(): # # Path: packages/config.py , which may include functions, classes, or code. Output only the next line.
copyfile(inputpath, outputpath)
Continue the code snippet: <|code_start|> app.static_folder = os.path.join(os.getcwd(), "static") def prepare(): if os.path.exists(app.static_folder): rmtree(app.static_folder) os.makedirs(app.static_folder) compiler = scss.Scss(scss_opts = { 'style': 'compressed' if not app.debug else None }, search_paths=[ os.path.join(os.getcwd(), 'styles') ]) # Compile styles (scss) d = os.walk('styles') for f in list(d)[0][2]: if os.path.splitext(f)[1] == ".scss": with open(os.path.join('styles', f)) as r: output = compiler.compile(r.read()) <|code_end|> . Use current file imports: from packages.app import app from packages.config import _cfg, _cfgi from shutil import rmtree, copyfile import os import scss import coffeescript and context (classes, functions, or code) from other files: # Path: packages/app.py # def load_user(username): # def handle_500(e): # def handle_404(e): # def version(): # def hook_publish(): # def inject(): # # Path: packages/config.py . Output only the next line.
parts = f.rsplit('.')
Using the snippet: <|code_start|> app.static_folder = os.path.join(os.getcwd(), "static") def prepare(): if os.path.exists(app.static_folder): rmtree(app.static_folder) os.makedirs(app.static_folder) compiler = scss.Scss(scss_opts = { 'style': 'compressed' if not app.debug else None <|code_end|> , determine the next line of code. You have imports: from packages.app import app from packages.config import _cfg, _cfgi from shutil import rmtree, copyfile import os import scss import coffeescript and context (class names, function names, or code) available: # Path: packages/app.py # def load_user(username): # def handle_500(e): # def handle_404(e): # def version(): # def hook_publish(): # def inject(): # # Path: packages/config.py . Output only the next line.
}, search_paths=[
Next line prediction: <|code_start|>from __future__ import with_statement sys.path.append(os.getcwd()) # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Python logging. # This line sets up loggers basically. <|code_end|> . Use current file imports: (import os, sys from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig from packages.app import app from packages.objects import Base) and context including class names, function names, or small code snippets from other files: # Path: packages/app.py # def load_user(username): # def handle_500(e): # def handle_404(e): # def version(): # def hook_publish(): # def inject(): # # Path: packages/objects.py # class User(Base): # class Package(Base): # def set_password(self, password): # def __init__(self, username, email, password): # def __repr__(self): # def is_authenticated(self): # def is_active(self): # def is_anonymous(self): # def get_id(self): # def __init__(self): # def __repr__(self): . Output only the next line.
fileConfig(config.config_file_name)
Next line prediction: <|code_start|>def confirm_user(username, confirmation): user = User.query.filter(User.username == username).first() if not user: return { 'success': False, 'error': 'User not found.' }, 404 if (not current_user or not current_user.admin) and (confirmation != user.confirmation): return { 'success': False, 'error': 'You do not have permission to confirm this user.' }, 403 user.confirmation = None db.commit() return { 'success': True } @api.route("/api/v1/user/<username>/unconfirm", methods=["POST"]) @json_output def unconfirm_user(username): user = User.query.filter(User.username == username).first() if not user: return { 'success': False, 'error': 'User not found.' }, 404 if not current_user or not current_user.admin: return { 'success': False, 'error': 'You do not have permission to unconfirm this user.' }, 403 if current_user.username == user.username: return { 'success': False, 'error': 'You cannot unconfirm your own account.' }, 403 user.confirmation = binascii.b2a_hex(os.urandom(20)).decode("utf-8") db.commit() return { 'success': True } @api.route("/api/v1/<repo>/<name>/remove", methods=["POST"]) @json_output def remove_package(repo, name): package = Package.query.filter(Package.name == name).filter(Package.repo == repo).first() if not package: return { 'success': False, 'error': 'Package not found.' }, 404 <|code_end|> . Use current file imports: (from flask import Blueprint, render_template, abort, request, redirect, session, url_for from flask.ext.login import current_user, login_user from sqlalchemy import desc from shutil import move from datetime import datetime from packages.objects import * from packages.common import * from packages.config import _cfg from packages.kpack import PackageInfo from packages.email import send_new_pacakge_email import os import binascii import zipfile import urllib import tempfile) and context including class names, function names, or small code snippets from other files: # Path: packages/config.py # # Path: packages/email.py # def send_new_pacakge_email(package): # if _cfg("smtp-host") == "": # return # smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) # smtp.ehlo() # smtp.starttls() # smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) # with open("emails/new-package") as f: # message = MIMEText(html.parser.HTMLParser().unescape(\ # pystache.render(f.read(), { 'url': _cfg("protocol") + "://" + _cfg("domain") + url_for("html.package", name=package.name, repo=package.repo) }))) # targets = [u.email for u in User.query.filter(User.admin == True)] # message['Subject'] = "New package pending approval" # message['From'] = _cfg("smtp-user") # message['To'] = ';'.join(targets) # smtp.sendmail(_cfg("smtp-user"), targets, message.as_string()) # smtp.quit() . Output only the next line.
if not current_user or not current_user.admin:
Given the following code snippet before the placeholder: <|code_start|> if not package: return { 'success': False, 'error': 'Package not found.' }, 404 if not current_user == package.user and not current_user.admin: return { 'success': False, 'error': 'You do not have permission to move this package.' }, 403 new_user = User.query.filter(User.username == username).first() if not new_user: return { 'success': False, 'error': 'User not found' }, 404 package.user = new_user db.commit() return { 'success': True } @api.route("/api/v1/upload", methods=['POST']) @json_output @loginrequired def upload_package(): package_file = request.files.get('package') if not package_file: return { 'success': False, 'error': 'You must include a package file.' } f, path = tempfile.mkstemp() package_file.save(path) info = None try: info = PackageInfo.read_package(path) if info.repo == None or info.name == None or info.version == None: return { 'success': False, 'error': 'This is not a valid KnightOS package.' }, 400 if not info.repo in ['core', 'extra', 'community', 'ports', 'nonfree']: return { 'success': False, 'error': '{0} is not an acceptable package repository.'.format(info.repo) }, 400 <|code_end|> , predict the next line using imports from the current file: from flask import Blueprint, render_template, abort, request, redirect, session, url_for from flask.ext.login import current_user, login_user from sqlalchemy import desc from shutil import move from datetime import datetime from packages.objects import * from packages.common import * from packages.config import _cfg from packages.kpack import PackageInfo from packages.email import send_new_pacakge_email import os import binascii import zipfile import urllib import tempfile and context including class names, function names, and sometimes code from other files: # Path: packages/config.py # # Path: packages/email.py # def send_new_pacakge_email(package): # if _cfg("smtp-host") == "": # return # smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) # smtp.ehlo() # smtp.starttls() # smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) # with open("emails/new-package") as f: # message = MIMEText(html.parser.HTMLParser().unescape(\ # pystache.render(f.read(), { 'url': _cfg("protocol") + "://" + _cfg("domain") + url_for("html.package", name=package.name, repo=package.repo) }))) # targets = [u.email for u in User.query.filter(User.admin == True)] # message['Subject'] = "New package pending approval" # message['From'] = _cfg("smtp-user") # message['To'] = ';'.join(targets) # smtp.sendmail(_cfg("smtp-user"), targets, message.as_string()) # smtp.quit() . Output only the next line.
if '/' in info.name:
Here is a snippet: <|code_start|> def __repr__(self): return '<User %r>' % self.username # Flask.Login stuff # We don't use most of these features def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.username class Package(Base): __tablename__ = 'package' # packages.knightos.org data id = Column(Integer, primary_key = True) updated = Column(DateTime) created = Column(DateTime) user_id = Column(Integer, ForeignKey('user.id')) user = relationship('User', backref=backref('package', order_by=id)) approved = Column(Boolean) contents = Column(Unicode(2048)) pkgrel = Column(Integer) downloads = Column(Integer) # From package metadata name = Column(String(128), nullable = False) repo = Column(String(128), nullable = False) version = Column(String(128), nullable = False) <|code_end|> . Write the next line using the current file imports: from sqlalchemy import Column, Integer, String, Unicode, Boolean, DateTime, ForeignKey, Table, UnicodeText, Text, text from sqlalchemy.orm import relationship, backref from .database import Base from datetime import datetime import bcrypt and context from other files: # Path: packages/database.py # def init_db(): , which may include functions, classes, or code. Output only the next line.
description = Column(Unicode(1024))
Given the code snippet: <|code_start|> allow = False for ip in _cfg("hook_ips").split(","): parts = ip.split("/") range = 32 if len(parts) != 1: range = int(parts[1]) addr = networkMask(parts[0], range) if addressInNetwork(dottedQuadToNum(request.remote_addr), addr): allow = True if not allow: return "unauthorized", 403 # Pull and restart site event = json.loads(request.data.decode("utf-8")) if not _cfg("hook_repository") == "%s/%s" % (event["repository"]["owner"]["name"], event["repository"]["name"]): return "ignored" if any("[noupdate]" in c["message"] for c in event["commits"]): return "ignored" if "refs/heads/" + _cfg("hook_branch") == event["ref"]: subprocess.call(["git", "pull", "origin", "master"]) subprocess.Popen(_cfg("restart_command").split()) return "thanks" return "ignored" @app.context_processor def inject(): return { 'root': _cfg("protocol") + "://" + _cfg("domain"), 'domain': _cfg("domain"), 'len': len, 'any': any, <|code_end|> , generate the next line using the imports in this file: from flask import Flask, render_template, request, g, Response, redirect, session, abort, send_file, url_for from flask.ext.login import LoginManager, current_user from jinja2 import FileSystemLoader, ChoiceLoader from werkzeug.utils import secure_filename from datetime import datetime, timedelta from shutil import rmtree, copyfile from sqlalchemy import desc from packages.config import _cfg, _cfgi from packages.database import db, init_db from packages.objects import User from packages.common import * from packages.network import * from packages.blueprints.api import api from packages.blueprints.html import html from logging.handlers import SMTPHandler import sys import os import subprocess import urllib import requests import json import zipfile import locale import traceback import xml.etree.ElementTree as ET import logging and context (functions, classes, or occasionally code) from other files: # Path: packages/config.py # # Path: packages/database.py # def init_db(): # # Path: packages/objects.py # class User(Base): # __tablename__ = 'user' # id = Column(Integer, primary_key = True) # username = Column(String(128), nullable = False, index = True) # email = Column(String(256), nullable = False, index = True) # admin = Column(Boolean()) # password = Column(String) # created = Column(DateTime) # confirmation = Column(String(128)) # passwordReset = Column(String(128)) # passwordResetExpiry = Column(DateTime) # packages = relationship('Package', order_by='Package.created') # # def set_password(self, password): # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # # def __init__(self, username, email, password): # self.email = email # self.username = username # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # self.admin = False # self.created = datetime.now() # # def __repr__(self): # return '<User %r>' % self.username # # # Flask.Login stuff # # We don't use most of these features # def is_authenticated(self): # return True # def is_active(self): # return True # def is_anonymous(self): # return False # def get_id(self): # return self.username # # Path: packages/blueprints/api.py # def login(): # def get_info(repo, name): # def approve_package(repo, name): # def unapprove_package(repo, name): # def set_admin(username): # def remove_admin(username): # def confirm_user(username, confirmation): # def unconfirm_user(username): # def remove_package(repo, name): # def transfer_package(repo, name, username): # def upload_package(): # # Path: packages/blueprints/html.py # def index(): # def register(): # def confirm(confirmation): # def login(): # def logout(): # def forgot_password(): # def reset_password(username, confirmation): # def pending(): # def upload(): # def package(repo, name): # def users(): # def user(username): # def repo(repo): # def search(): # def download(repo, name): # def guidelines(): # def help(): # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 . Output only the next line.
'request': request,
Predict the next line after this snippet: <|code_start|> app = Flask(__name__) app.secret_key = _cfg("secret-key") app.jinja_env.cache = None init_db() login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(username): return User.query.filter(User.username == username).first() login_manager.anonymous_user = lambda: None app.register_blueprint(api) app.register_blueprint(html) try: locale.setlocale(locale.LC_ALL, 'en_US') except: <|code_end|> using the current file's imports: from flask import Flask, render_template, request, g, Response, redirect, session, abort, send_file, url_for from flask.ext.login import LoginManager, current_user from jinja2 import FileSystemLoader, ChoiceLoader from werkzeug.utils import secure_filename from datetime import datetime, timedelta from shutil import rmtree, copyfile from sqlalchemy import desc from packages.config import _cfg, _cfgi from packages.database import db, init_db from packages.objects import User from packages.common import * from packages.network import * from packages.blueprints.api import api from packages.blueprints.html import html from logging.handlers import SMTPHandler import sys import os import subprocess import urllib import requests import json import zipfile import locale import traceback import xml.etree.ElementTree as ET import logging and any relevant context from other files: # Path: packages/config.py # # Path: packages/database.py # def init_db(): # # Path: packages/objects.py # class User(Base): # __tablename__ = 'user' # id = Column(Integer, primary_key = True) # username = Column(String(128), nullable = False, index = True) # email = Column(String(256), nullable = False, index = True) # admin = Column(Boolean()) # password = Column(String) # created = Column(DateTime) # confirmation = Column(String(128)) # passwordReset = Column(String(128)) # passwordResetExpiry = Column(DateTime) # packages = relationship('Package', order_by='Package.created') # # def set_password(self, password): # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # # def __init__(self, username, email, password): # self.email = email # self.username = username # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # self.admin = False # self.created = datetime.now() # # def __repr__(self): # return '<User %r>' % self.username # # # Flask.Login stuff # # We don't use most of these features # def is_authenticated(self): # return True # def is_active(self): # return True # def is_anonymous(self): # return False # def get_id(self): # return self.username # # Path: packages/blueprints/api.py # def login(): # def get_info(repo, name): # def approve_package(repo, name): # def unapprove_package(repo, name): # def set_admin(username): # def remove_admin(username): # def confirm_user(username, confirmation): # def unconfirm_user(username): # def remove_package(repo, name): # def transfer_package(repo, name, username): # def upload_package(): # # Path: packages/blueprints/html.py # def index(): # def register(): # def confirm(confirmation): # def login(): # def logout(): # def forgot_password(): # def reset_password(username, confirmation): # def pending(): # def upload(): # def package(repo, name): # def users(): # def user(username): # def repo(repo): # def search(): # def download(repo, name): # def guidelines(): # def help(): # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 . Output only the next line.
pass
Predict the next line after this snippet: <|code_start|> app = Flask(__name__) app.secret_key = _cfg("secret-key") app.jinja_env.cache = None init_db() login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(username): return User.query.filter(User.username == username).first() login_manager.anonymous_user = lambda: None app.register_blueprint(api) app.register_blueprint(html) try: locale.setlocale(locale.LC_ALL, 'en_US') except: pass if not app.debug: @app.errorhandler(500) def handle_500(e): # shit try: db.rollback() db.close() <|code_end|> using the current file's imports: from flask import Flask, render_template, request, g, Response, redirect, session, abort, send_file, url_for from flask.ext.login import LoginManager, current_user from jinja2 import FileSystemLoader, ChoiceLoader from werkzeug.utils import secure_filename from datetime import datetime, timedelta from shutil import rmtree, copyfile from sqlalchemy import desc from packages.config import _cfg, _cfgi from packages.database import db, init_db from packages.objects import User from packages.common import * from packages.network import * from packages.blueprints.api import api from packages.blueprints.html import html from logging.handlers import SMTPHandler import sys import os import subprocess import urllib import requests import json import zipfile import locale import traceback import xml.etree.ElementTree as ET import logging and any relevant context from other files: # Path: packages/config.py # # Path: packages/database.py # def init_db(): # # Path: packages/objects.py # class User(Base): # __tablename__ = 'user' # id = Column(Integer, primary_key = True) # username = Column(String(128), nullable = False, index = True) # email = Column(String(256), nullable = False, index = True) # admin = Column(Boolean()) # password = Column(String) # created = Column(DateTime) # confirmation = Column(String(128)) # passwordReset = Column(String(128)) # passwordResetExpiry = Column(DateTime) # packages = relationship('Package', order_by='Package.created') # # def set_password(self, password): # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # # def __init__(self, username, email, password): # self.email = email # self.username = username # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # self.admin = False # self.created = datetime.now() # # def __repr__(self): # return '<User %r>' % self.username # # # Flask.Login stuff # # We don't use most of these features # def is_authenticated(self): # return True # def is_active(self): # return True # def is_anonymous(self): # return False # def get_id(self): # return self.username # # Path: packages/blueprints/api.py # def login(): # def get_info(repo, name): # def approve_package(repo, name): # def unapprove_package(repo, name): # def set_admin(username): # def remove_admin(username): # def confirm_user(username, confirmation): # def unconfirm_user(username): # def remove_package(repo, name): # def transfer_package(repo, name, username): # def upload_package(): # # Path: packages/blueprints/html.py # def index(): # def register(): # def confirm(confirmation): # def login(): # def logout(): # def forgot_password(): # def reset_password(username, confirmation): # def pending(): # def upload(): # def package(repo, name): # def users(): # def user(username): # def repo(repo): # def search(): # def download(repo, name): # def guidelines(): # def help(): # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 . Output only the next line.
except:
Based on the snippet: <|code_start|> except: # shit shit sys.exit(1) return render_template("internal_error.html"), 500 # Error handler if _cfg("error-to") != "": mail_handler = SMTPHandler((_cfg("smtp-host"), _cfg("smtp-port")), _cfg("error-from"), [_cfg("error-to")], 'packages.knightos.org application exception occured', credentials=(_cfg("smtp-user"), _cfg("smtp-password"))) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) @app.errorhandler(404) def handle_404(e): return render_template("not_found.html"), 404 @app.route('/version') def version(): return Response(subprocess.check_output(["git", "log", "-1"]), mimetype="text/plain") @app.route('/hook', methods=['POST']) def hook_publish(): allow = False for ip in _cfg("hook_ips").split(","): parts = ip.split("/") range = 32 if len(parts) != 1: range = int(parts[1]) <|code_end|> , predict the immediate next line with the help of imports: from flask import Flask, render_template, request, g, Response, redirect, session, abort, send_file, url_for from flask.ext.login import LoginManager, current_user from jinja2 import FileSystemLoader, ChoiceLoader from werkzeug.utils import secure_filename from datetime import datetime, timedelta from shutil import rmtree, copyfile from sqlalchemy import desc from packages.config import _cfg, _cfgi from packages.database import db, init_db from packages.objects import User from packages.common import * from packages.network import * from packages.blueprints.api import api from packages.blueprints.html import html from logging.handlers import SMTPHandler import sys import os import subprocess import urllib import requests import json import zipfile import locale import traceback import xml.etree.ElementTree as ET import logging and context (classes, functions, sometimes code) from other files: # Path: packages/config.py # # Path: packages/database.py # def init_db(): # # Path: packages/objects.py # class User(Base): # __tablename__ = 'user' # id = Column(Integer, primary_key = True) # username = Column(String(128), nullable = False, index = True) # email = Column(String(256), nullable = False, index = True) # admin = Column(Boolean()) # password = Column(String) # created = Column(DateTime) # confirmation = Column(String(128)) # passwordReset = Column(String(128)) # passwordResetExpiry = Column(DateTime) # packages = relationship('Package', order_by='Package.created') # # def set_password(self, password): # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # # def __init__(self, username, email, password): # self.email = email # self.username = username # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # self.admin = False # self.created = datetime.now() # # def __repr__(self): # return '<User %r>' % self.username # # # Flask.Login stuff # # We don't use most of these features # def is_authenticated(self): # return True # def is_active(self): # return True # def is_anonymous(self): # return False # def get_id(self): # return self.username # # Path: packages/blueprints/api.py # def login(): # def get_info(repo, name): # def approve_package(repo, name): # def unapprove_package(repo, name): # def set_admin(username): # def remove_admin(username): # def confirm_user(username, confirmation): # def unconfirm_user(username): # def remove_package(repo, name): # def transfer_package(repo, name, username): # def upload_package(): # # Path: packages/blueprints/html.py # def index(): # def register(): # def confirm(confirmation): # def login(): # def logout(): # def forgot_password(): # def reset_password(username, confirmation): # def pending(): # def upload(): # def package(repo, name): # def users(): # def user(username): # def repo(repo): # def search(): # def download(repo, name): # def guidelines(): # def help(): # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 . Output only the next line.
addr = networkMask(parts[0], range)
Based on the snippet: <|code_start|> app = Flask(__name__) app.secret_key = _cfg("secret-key") app.jinja_env.cache = None init_db() login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(username): return User.query.filter(User.username == username).first() login_manager.anonymous_user = lambda: None app.register_blueprint(api) app.register_blueprint(html) try: locale.setlocale(locale.LC_ALL, 'en_US') except: <|code_end|> , predict the immediate next line with the help of imports: from flask import Flask, render_template, request, g, Response, redirect, session, abort, send_file, url_for from flask.ext.login import LoginManager, current_user from jinja2 import FileSystemLoader, ChoiceLoader from werkzeug.utils import secure_filename from datetime import datetime, timedelta from shutil import rmtree, copyfile from sqlalchemy import desc from packages.config import _cfg, _cfgi from packages.database import db, init_db from packages.objects import User from packages.common import * from packages.network import * from packages.blueprints.api import api from packages.blueprints.html import html from logging.handlers import SMTPHandler import sys import os import subprocess import urllib import requests import json import zipfile import locale import traceback import xml.etree.ElementTree as ET import logging and context (classes, functions, sometimes code) from other files: # Path: packages/config.py # # Path: packages/database.py # def init_db(): # # Path: packages/objects.py # class User(Base): # __tablename__ = 'user' # id = Column(Integer, primary_key = True) # username = Column(String(128), nullable = False, index = True) # email = Column(String(256), nullable = False, index = True) # admin = Column(Boolean()) # password = Column(String) # created = Column(DateTime) # confirmation = Column(String(128)) # passwordReset = Column(String(128)) # passwordResetExpiry = Column(DateTime) # packages = relationship('Package', order_by='Package.created') # # def set_password(self, password): # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # # def __init__(self, username, email, password): # self.email = email # self.username = username # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # self.admin = False # self.created = datetime.now() # # def __repr__(self): # return '<User %r>' % self.username # # # Flask.Login stuff # # We don't use most of these features # def is_authenticated(self): # return True # def is_active(self): # return True # def is_anonymous(self): # return False # def get_id(self): # return self.username # # Path: packages/blueprints/api.py # def login(): # def get_info(repo, name): # def approve_package(repo, name): # def unapprove_package(repo, name): # def set_admin(username): # def remove_admin(username): # def confirm_user(username, confirmation): # def unconfirm_user(username): # def remove_package(repo, name): # def transfer_package(repo, name, username): # def upload_package(): # # Path: packages/blueprints/html.py # def index(): # def register(): # def confirm(confirmation): # def login(): # def logout(): # def forgot_password(): # def reset_password(username, confirmation): # def pending(): # def upload(): # def package(repo, name): # def users(): # def user(username): # def repo(repo): # def search(): # def download(repo, name): # def guidelines(): # def help(): # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 # PAGE_SIZE = request.args.get('count') # PAGE_SIZE = '10' # PAGE_SIZE = int(PAGE_SIZE) # PAGE_SIZE = 10 # if PAGE_SIZE <= 0: PAGE_SIZE = 10 . Output only the next line.
pass
Using the snippet: <|code_start|> def send_confirmation(user): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/confirm-account") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"), 'confirmation': user.confirmation }))) message['Subject'] = "Confirm your account on the KnightOS Package Index" message['From'] = _cfg("smtp-user") message['To'] = user.email smtp.sendmail(_cfg("smtp-user"), [ user.email ], message.as_string()) smtp.quit() def send_reset(user): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/password-reset") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"), 'confirmation': user.passwordReset }))) <|code_end|> , determine the next line of code. You have imports: import smtplib import pystache import os import html.parser from email.mime.text import MIMEText from werkzeug.utils import secure_filename from flask import url_for from packages.database import db from packages.objects import User from packages.config import _cfg, _cfgi and context (class names, function names, or code) available: # Path: packages/database.py # def init_db(): # # Path: packages/objects.py # class User(Base): # __tablename__ = 'user' # id = Column(Integer, primary_key = True) # username = Column(String(128), nullable = False, index = True) # email = Column(String(256), nullable = False, index = True) # admin = Column(Boolean()) # password = Column(String) # created = Column(DateTime) # confirmation = Column(String(128)) # passwordReset = Column(String(128)) # passwordResetExpiry = Column(DateTime) # packages = relationship('Package', order_by='Package.created') # # def set_password(self, password): # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # # def __init__(self, username, email, password): # self.email = email # self.username = username # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # self.admin = False # self.created = datetime.now() # # def __repr__(self): # return '<User %r>' % self.username # # # Flask.Login stuff # # We don't use most of these features # def is_authenticated(self): # return True # def is_active(self): # return True # def is_anonymous(self): # return False # def get_id(self): # return self.username # # Path: packages/config.py . Output only the next line.
message['Subject'] = "Reset your password for the KnightOS Package Index"
Continue the code snippet: <|code_start|> def send_confirmation(user): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/confirm-account") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"), 'confirmation': user.confirmation }))) message['Subject'] = "Confirm your account on the KnightOS Package Index" message['From'] = _cfg("smtp-user") message['To'] = user.email smtp.sendmail(_cfg("smtp-user"), [ user.email ], message.as_string()) smtp.quit() def send_reset(user): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/password-reset") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"), 'confirmation': user.passwordReset }))) message['Subject'] = "Reset your password for the KnightOS Package Index" message['From'] = _cfg("smtp-user") <|code_end|> . Use current file imports: import smtplib import pystache import os import html.parser from email.mime.text import MIMEText from werkzeug.utils import secure_filename from flask import url_for from packages.database import db from packages.objects import User from packages.config import _cfg, _cfgi and context (classes, functions, or code) from other files: # Path: packages/database.py # def init_db(): # # Path: packages/objects.py # class User(Base): # __tablename__ = 'user' # id = Column(Integer, primary_key = True) # username = Column(String(128), nullable = False, index = True) # email = Column(String(256), nullable = False, index = True) # admin = Column(Boolean()) # password = Column(String) # created = Column(DateTime) # confirmation = Column(String(128)) # passwordReset = Column(String(128)) # passwordResetExpiry = Column(DateTime) # packages = relationship('Package', order_by='Package.created') # # def set_password(self, password): # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # # def __init__(self, username, email, password): # self.email = email # self.username = username # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # self.admin = False # self.created = datetime.now() # # def __repr__(self): # return '<User %r>' % self.username # # # Flask.Login stuff # # We don't use most of these features # def is_authenticated(self): # return True # def is_active(self): # return True # def is_anonymous(self): # return False # def get_id(self): # return self.username # # Path: packages/config.py . Output only the next line.
message['To'] = user.email
Given the following code snippet before the placeholder: <|code_start|> def send_reset(user): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/password-reset") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"), 'confirmation': user.passwordReset }))) message['Subject'] = "Reset your password for the KnightOS Package Index" message['From'] = _cfg("smtp-user") message['To'] = user.email smtp.sendmail(_cfg("smtp-user"), [ user.email ], message.as_string()) smtp.quit() def send_new_pacakge_email(package): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/new-package") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { 'url': _cfg("protocol") + "://" + _cfg("domain") + url_for("html.package", name=package.name, repo=package.repo) }))) targets = [u.email for u in User.query.filter(User.admin == True)] message['Subject'] = "New package pending approval" message['From'] = _cfg("smtp-user") <|code_end|> , predict the next line using imports from the current file: import smtplib import pystache import os import html.parser from email.mime.text import MIMEText from werkzeug.utils import secure_filename from flask import url_for from packages.database import db from packages.objects import User from packages.config import _cfg, _cfgi and context including class names, function names, and sometimes code from other files: # Path: packages/database.py # def init_db(): # # Path: packages/objects.py # class User(Base): # __tablename__ = 'user' # id = Column(Integer, primary_key = True) # username = Column(String(128), nullable = False, index = True) # email = Column(String(256), nullable = False, index = True) # admin = Column(Boolean()) # password = Column(String) # created = Column(DateTime) # confirmation = Column(String(128)) # passwordReset = Column(String(128)) # passwordResetExpiry = Column(DateTime) # packages = relationship('Package', order_by='Package.created') # # def set_password(self, password): # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # # def __init__(self, username, email, password): # self.email = email # self.username = username # self.password = bcrypt.hashpw(password, bcrypt.gensalt()) # self.admin = False # self.created = datetime.now() # # def __repr__(self): # return '<User %r>' % self.username # # # Flask.Login stuff # # We don't use most of these features # def is_authenticated(self): # return True # def is_active(self): # return True # def is_anonymous(self): # return False # def get_id(self): # return self.username # # Path: packages/config.py . Output only the next line.
message['To'] = ';'.join(targets)
Given the code snippet: <|code_start|> engine = create_engine(_cfg('connection-string')) db = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db.query_property() <|code_end|> , generate the next line using the imports in this file: from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base from .config import _cfg, _cfgi import packages.objects and context (functions, classes, or occasionally code) from other files: # Path: packages/config.py . Output only the next line.
def init_db():
Using the snippet: <|code_start|> print("Connected to " + str(ble_device.address)) @classmethod def on_disconnect(cls, adapter_address, device_address): print("Disconnected from " + device_address) @classmethod def uart_notify(cls, notifying, characteristic): if notifying: cls.tx_obj = characteristic else: cls.tx_obj = None @classmethod def update_tx(cls, value): if cls.tx_obj: print("Sending") cls.tx_obj.set_value(value) @classmethod def uart_write(cls, value, options): print('raw bytes:', value) print('With options:', options) print('Text value:', bytes(value).decode('utf-8')) cls.update_tx(value) def main(adapter_address): ble_uart = peripheral.Peripheral(adapter_address, local_name='BLE UART') ble_uart.add_service(srv_id=1, uuid=UART_SERVICE, primary=True) <|code_end|> , determine the next line of code. You have imports: from gi.repository import GLib from bluezero import adapter from bluezero import peripheral from bluezero import device and context (class names, function names, or code) available: # Path: bluezero/adapter.py # class AdapterError(Exception): # class Adapter: # def list_adapters(): # def available(): # def __new__(cls, adapter_addr=None, *args, **kwargs): # def __init__(self, adapter_addr=None): # def address(self): # def name(self): # def bt_class(self): # def alias(self): # def alias(self, new_alias): # def get_all(self): # def powered(self): # def powered(self, new_state): # def pairable(self): # def pairable(self, new_state): # def pairabletimeout(self): # def pairabletimeout(self, new_timeout): # def discoverable(self): # def discoverable(self, new_state): # def discoverabletimeout(self): # def discoverabletimeout(self, new_timeout): # def discovering(self): # def _discovering_timeout(self): # def uuids(self): # def nearby_discovery(self, timeout=10): # def show_duplicates(self): # def hide_duplicates(self): # def start_discovery(self): # def stop_discovery(self): # def remove_device(self, device_path): # def run(self): # def quit(self): # def _properties_changed(self, interface, changed, invalidated, path): # def _device_added(self, dbus_mngr, device_address): # def _interfaces_removed(self, path, device_info): # # Path: bluezero/peripheral.py # class Peripheral: # def __init__(self, adapter_address, local_name=None, appearance=None): # def add_service(self, srv_id, uuid, primary): # def add_characteristic(self, srv_id, chr_id, uuid, value, # notifying, flags, # read_callback=None, write_callback=None, # notify_callback=None): # def add_descriptor(self, srv_id, chr_id, dsc_id, uuid, value, flags): # def _create_advertisement(self): # def publish(self): # def on_connect(self): # def on_connect(self, callback): # def on_disconnect(self): # def on_disconnect(self, callback): # # Path: bluezero/device.py # class Device: # def available(adapter_address=None): # def __init__(self, adapter_addr, device_addr): # def address(self): # def name(self): # def icon(self): # def bt_class(self): # def appearance(self): # def uuids(self): # def paired(self): # def connected(self): # def trusted(self): # def trusted(self, new_state): # def blocked(self): # def blocked(self, new_state): # def alias(self): # def alias(self, new_alias): # def _adapter(self): # def adapter(self): # def legacy_pairing(self): # def legacy_pairing(self, new_status): # def modalias(self): # def RSSI(self): # pylint: disable=invalid-name # def tx_power(self): # def manufacturer_data(self): # def service_data(self): # def services_resolved(self): # def services_available(self): # def pair(self): # def cancel_pairing(self): # def connect(self, profile=None, timeout=35): # def disconnect(self): . Output only the next line.
ble_uart.add_characteristic(srv_id=1, chr_id=1, uuid=RX_CHARACTERISTIC,
Predict the next line for this snippet: <|code_start|> def on_connect(cls, ble_device: device.Device): print("Connected to " + str(ble_device.address)) @classmethod def on_disconnect(cls, adapter_address, device_address): print("Disconnected from " + device_address) @classmethod def uart_notify(cls, notifying, characteristic): if notifying: cls.tx_obj = characteristic else: cls.tx_obj = None @classmethod def update_tx(cls, value): if cls.tx_obj: print("Sending") cls.tx_obj.set_value(value) @classmethod def uart_write(cls, value, options): print('raw bytes:', value) print('With options:', options) print('Text value:', bytes(value).decode('utf-8')) cls.update_tx(value) def main(adapter_address): ble_uart = peripheral.Peripheral(adapter_address, local_name='BLE UART') <|code_end|> with the help of current file imports: from gi.repository import GLib from bluezero import adapter from bluezero import peripheral from bluezero import device and context from other files: # Path: bluezero/adapter.py # class AdapterError(Exception): # class Adapter: # def list_adapters(): # def available(): # def __new__(cls, adapter_addr=None, *args, **kwargs): # def __init__(self, adapter_addr=None): # def address(self): # def name(self): # def bt_class(self): # def alias(self): # def alias(self, new_alias): # def get_all(self): # def powered(self): # def powered(self, new_state): # def pairable(self): # def pairable(self, new_state): # def pairabletimeout(self): # def pairabletimeout(self, new_timeout): # def discoverable(self): # def discoverable(self, new_state): # def discoverabletimeout(self): # def discoverabletimeout(self, new_timeout): # def discovering(self): # def _discovering_timeout(self): # def uuids(self): # def nearby_discovery(self, timeout=10): # def show_duplicates(self): # def hide_duplicates(self): # def start_discovery(self): # def stop_discovery(self): # def remove_device(self, device_path): # def run(self): # def quit(self): # def _properties_changed(self, interface, changed, invalidated, path): # def _device_added(self, dbus_mngr, device_address): # def _interfaces_removed(self, path, device_info): # # Path: bluezero/peripheral.py # class Peripheral: # def __init__(self, adapter_address, local_name=None, appearance=None): # def add_service(self, srv_id, uuid, primary): # def add_characteristic(self, srv_id, chr_id, uuid, value, # notifying, flags, # read_callback=None, write_callback=None, # notify_callback=None): # def add_descriptor(self, srv_id, chr_id, dsc_id, uuid, value, flags): # def _create_advertisement(self): # def publish(self): # def on_connect(self): # def on_connect(self, callback): # def on_disconnect(self): # def on_disconnect(self, callback): # # Path: bluezero/device.py # class Device: # def available(adapter_address=None): # def __init__(self, adapter_addr, device_addr): # def address(self): # def name(self): # def icon(self): # def bt_class(self): # def appearance(self): # def uuids(self): # def paired(self): # def connected(self): # def trusted(self): # def trusted(self, new_state): # def blocked(self): # def blocked(self, new_state): # def alias(self): # def alias(self, new_alias): # def _adapter(self): # def adapter(self): # def legacy_pairing(self): # def legacy_pairing(self, new_status): # def modalias(self): # def RSSI(self): # pylint: disable=invalid-name # def tx_power(self): # def manufacturer_data(self): # def service_data(self): # def services_resolved(self): # def services_available(self): # def pair(self): # def cancel_pairing(self): # def connect(self, profile=None, timeout=35): # def disconnect(self): , which may contain function names, class names, or code. Output only the next line.
ble_uart.add_service(srv_id=1, uuid=UART_SERVICE, primary=True)
Using the snippet: <|code_start|> # Bluezero modules # constants UART_SERVICE = '6E400001-B5A3-F393-E0A9-E50E24DCCA9E' RX_CHARACTERISTIC = '6E400002-B5A3-F393-E0A9-E50E24DCCA9E' TX_CHARACTERISTIC = '6E400003-B5A3-F393-E0A9-E50E24DCCA9E' class UARTDevice: tx_obj = None <|code_end|> , determine the next line of code. You have imports: from gi.repository import GLib from bluezero import adapter from bluezero import peripheral from bluezero import device and context (class names, function names, or code) available: # Path: bluezero/adapter.py # class AdapterError(Exception): # class Adapter: # def list_adapters(): # def available(): # def __new__(cls, adapter_addr=None, *args, **kwargs): # def __init__(self, adapter_addr=None): # def address(self): # def name(self): # def bt_class(self): # def alias(self): # def alias(self, new_alias): # def get_all(self): # def powered(self): # def powered(self, new_state): # def pairable(self): # def pairable(self, new_state): # def pairabletimeout(self): # def pairabletimeout(self, new_timeout): # def discoverable(self): # def discoverable(self, new_state): # def discoverabletimeout(self): # def discoverabletimeout(self, new_timeout): # def discovering(self): # def _discovering_timeout(self): # def uuids(self): # def nearby_discovery(self, timeout=10): # def show_duplicates(self): # def hide_duplicates(self): # def start_discovery(self): # def stop_discovery(self): # def remove_device(self, device_path): # def run(self): # def quit(self): # def _properties_changed(self, interface, changed, invalidated, path): # def _device_added(self, dbus_mngr, device_address): # def _interfaces_removed(self, path, device_info): # # Path: bluezero/peripheral.py # class Peripheral: # def __init__(self, adapter_address, local_name=None, appearance=None): # def add_service(self, srv_id, uuid, primary): # def add_characteristic(self, srv_id, chr_id, uuid, value, # notifying, flags, # read_callback=None, write_callback=None, # notify_callback=None): # def add_descriptor(self, srv_id, chr_id, dsc_id, uuid, value, flags): # def _create_advertisement(self): # def publish(self): # def on_connect(self): # def on_connect(self, callback): # def on_disconnect(self): # def on_disconnect(self, callback): # # Path: bluezero/device.py # class Device: # def available(adapter_address=None): # def __init__(self, adapter_addr, device_addr): # def address(self): # def name(self): # def icon(self): # def bt_class(self): # def appearance(self): # def uuids(self): # def paired(self): # def connected(self): # def trusted(self): # def trusted(self, new_state): # def blocked(self): # def blocked(self, new_state): # def alias(self): # def alias(self, new_alias): # def _adapter(self): # def adapter(self): # def legacy_pairing(self): # def legacy_pairing(self, new_status): # def modalias(self): # def RSSI(self): # pylint: disable=invalid-name # def tx_power(self): # def manufacturer_data(self): # def service_data(self): # def services_resolved(self): # def services_available(self): # def pair(self): # def cancel_pairing(self): # def connect(self, profile=None, timeout=35): # def disconnect(self): . Output only the next line.
@classmethod
Predict the next line for this snippet: <|code_start|> def main(): eddystone_beacon.EddystoneURL('https://github.com/ukBaz') if __name__ == '__main__': <|code_end|> with the help of current file imports: from bluezero import eddystone_beacon and context from other files: # Path: bluezero/eddystone_beacon.py # class EddystoneURL: # def __init__(self, url, tx_power=0x08): , which may contain function names, class names, or code. Output only the next line.
main()
Using the snippet: <|code_start|> @property def repeat(self): """Return the repeat value""" return self.player_props.Get( constants.MEDIA_PLAYER_IFACE, 'Repeat') @repeat.setter def repeat(self, value): """Possible values: "off", "singletrack", "alltracks" or "group""" self.player_props.Set( constants.MEDIA_PLAYER_IFACE, 'Repeat', value) @property def shuffle(self): """Return the shuffle value""" return self.player_props.Get(constants.MEDIA_PLAYER_IFACE, 'Shuffle') @shuffle.setter def shuffle(self, value): """"Possible values: "off", "alltracks" or "group" """ self.player_props.Set(constants.MEDIA_PLAYER_IFACE, 'Shuffle', value) @property def status(self): """Return the status of the player Possible status: "playing", "stopped", "paused", "forward-seek", "reverse-seek" or "error" """ return self.player_props.Get(constants.MEDIA_PLAYER_IFACE, 'Status') <|code_end|> , determine the next line of code. You have imports: import dbus from bluezero import constants from bluezero import dbus_tools from bluezero import tools and context (class names, function names, or code) available: # Path: bluezero/constants.py # DBUS_OM_IFACE = 'org.freedesktop.DBus.ObjectManager' # DBUS_PROP_IFACE = 'org.freedesktop.DBus.Properties' # BLUEZ_SERVICE_NAME = 'org.bluez' # ADAPTER_INTERFACE = 'org.bluez.Adapter1' # DEVICE_INTERFACE = 'org.bluez.Device1' # GATT_MANAGER_IFACE = 'org.bluez.GattManager1' # GATT_PROFILE_IFACE = 'org.bluez.GattProfile1' # GATT_SERVICE_IFACE = 'org.bluez.GattService1' # GATT_CHRC_IFACE = 'org.bluez.GattCharacteristic1' # GATT_DESC_IFACE = 'org.bluez.GattDescriptor1' # LE_ADVERTISING_MANAGER_IFACE = 'org.bluez.LEAdvertisingManager1' # LE_ADVERTISEMENT_IFACE = 'org.bluez.LEAdvertisement1' # MEDIA_PLAYER_IFACE = 'org.bluez.MediaPlayer1' # BLUEZERO_DBUS_NAME = 'ukBaz.bluezero' # BLUEZERO_DBUS_OBJECT = '/ukBaz/bluezero' # # Path: bluezero/dbus_tools.py # def bluez_version(): # def bluez_experimental_mode(): # def interfaces_added(path, interfaces): # def properties_changed(interface, changed, invalidated, path): # def get_dbus_obj(dbus_path): # def get_dbus_iface(iface, dbus_obj): # def get_managed_objects(): # def get_mac_addr_from_dbus_path(path): # def get_device_address_from_dbus_path(path): # def get_adapter_address_from_dbus_path(path): # def _get_dbus_path2(objects, parent_path, iface_in, prop, value): # def get_dbus_path(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_profile_path(adapter, # device, # profile): # def get_iface(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_methods(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_props(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_services(path_obj): # def get_device_addresses(name_contains): # def get(dbus_prop_obj, dbus_iface, prop_name, default=None): # def str_to_dbusarray(word): # def bytes_to_dbusarray(bytesarray): # def dbus_to_python(data): # # Path: bluezero/tools.py # def int_to_uint16(value_in): # def sint16_to_int(byte_array): # def bytes_to_xyz(byte_array): # def int_to_uint32(value_in): # def bitwise_or_2lists(list1, list2): # def bitwise_and_2lists(list1, list2): # def bitwise_xor_2lists(list1, list2): # def url_to_advert(url, frame_type, tx_power): # def get_fn_parameters(fn): # def create_module_logger(module_name): . Output only the next line.
@property
Given snippet: <|code_start|> found_address = dbus_tools.get_device_address_from_dbus_path(path) if device_address == found_address: return path raise MediaPlayerError("No player found for the device") class MediaPlayer: """Bluetooth MediaPlayer Class. This class instantiates an object that is able to interact with the player of a Bluetooth device and get audio from its source. """ def __init__(self, device_addr): """Default initialiser. Creates the interface to the remote Bluetooth device. :param device_addr: Address of Bluetooth device player to use. """ self.player_path = _find_player_path(device_addr) self.player_object = dbus_tools.get_dbus_obj(self.player_path) self.player_methods = dbus_tools.get_dbus_iface( constants.MEDIA_PLAYER_IFACE, self.player_object) self.player_props = dbus_tools.get_dbus_iface( dbus.PROPERTIES_IFACE, self.player_object) @property def browsable(self): """If present indicates the player can be browsed using MediaFolder interface.""" <|code_end|> , continue by predicting the next line. Consider current file imports: import dbus from bluezero import constants from bluezero import dbus_tools from bluezero import tools and context: # Path: bluezero/constants.py # DBUS_OM_IFACE = 'org.freedesktop.DBus.ObjectManager' # DBUS_PROP_IFACE = 'org.freedesktop.DBus.Properties' # BLUEZ_SERVICE_NAME = 'org.bluez' # ADAPTER_INTERFACE = 'org.bluez.Adapter1' # DEVICE_INTERFACE = 'org.bluez.Device1' # GATT_MANAGER_IFACE = 'org.bluez.GattManager1' # GATT_PROFILE_IFACE = 'org.bluez.GattProfile1' # GATT_SERVICE_IFACE = 'org.bluez.GattService1' # GATT_CHRC_IFACE = 'org.bluez.GattCharacteristic1' # GATT_DESC_IFACE = 'org.bluez.GattDescriptor1' # LE_ADVERTISING_MANAGER_IFACE = 'org.bluez.LEAdvertisingManager1' # LE_ADVERTISEMENT_IFACE = 'org.bluez.LEAdvertisement1' # MEDIA_PLAYER_IFACE = 'org.bluez.MediaPlayer1' # BLUEZERO_DBUS_NAME = 'ukBaz.bluezero' # BLUEZERO_DBUS_OBJECT = '/ukBaz/bluezero' # # Path: bluezero/dbus_tools.py # def bluez_version(): # def bluez_experimental_mode(): # def interfaces_added(path, interfaces): # def properties_changed(interface, changed, invalidated, path): # def get_dbus_obj(dbus_path): # def get_dbus_iface(iface, dbus_obj): # def get_managed_objects(): # def get_mac_addr_from_dbus_path(path): # def get_device_address_from_dbus_path(path): # def get_adapter_address_from_dbus_path(path): # def _get_dbus_path2(objects, parent_path, iface_in, prop, value): # def get_dbus_path(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_profile_path(adapter, # device, # profile): # def get_iface(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_methods(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_props(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_services(path_obj): # def get_device_addresses(name_contains): # def get(dbus_prop_obj, dbus_iface, prop_name, default=None): # def str_to_dbusarray(word): # def bytes_to_dbusarray(bytesarray): # def dbus_to_python(data): # # Path: bluezero/tools.py # def int_to_uint16(value_in): # def sint16_to_int(byte_array): # def bytes_to_xyz(byte_array): # def int_to_uint32(value_in): # def bitwise_or_2lists(list1, list2): # def bitwise_and_2lists(list1, list2): # def bitwise_xor_2lists(list1, list2): # def url_to_advert(url, frame_type, tx_power): # def get_fn_parameters(fn): # def create_module_logger(module_name): which might include code, classes, or functions. Output only the next line.
return self.player_props.Get(
Here is a snippet: <|code_start|> """Bluetooth MediaPlayer Class. This class instantiates an object that is able to interact with the player of a Bluetooth device and get audio from its source. """ def __init__(self, device_addr): """Default initialiser. Creates the interface to the remote Bluetooth device. :param device_addr: Address of Bluetooth device player to use. """ self.player_path = _find_player_path(device_addr) self.player_object = dbus_tools.get_dbus_obj(self.player_path) self.player_methods = dbus_tools.get_dbus_iface( constants.MEDIA_PLAYER_IFACE, self.player_object) self.player_props = dbus_tools.get_dbus_iface( dbus.PROPERTIES_IFACE, self.player_object) @property def browsable(self): """If present indicates the player can be browsed using MediaFolder interface.""" return self.player_props.Get( constants.MEDIA_PLAYER_IFACE, 'Browsable') @property def searchable(self): """If present indicates the player can be searched using MediaFolder interface.""" <|code_end|> . Write the next line using the current file imports: import dbus from bluezero import constants from bluezero import dbus_tools from bluezero import tools and context from other files: # Path: bluezero/constants.py # DBUS_OM_IFACE = 'org.freedesktop.DBus.ObjectManager' # DBUS_PROP_IFACE = 'org.freedesktop.DBus.Properties' # BLUEZ_SERVICE_NAME = 'org.bluez' # ADAPTER_INTERFACE = 'org.bluez.Adapter1' # DEVICE_INTERFACE = 'org.bluez.Device1' # GATT_MANAGER_IFACE = 'org.bluez.GattManager1' # GATT_PROFILE_IFACE = 'org.bluez.GattProfile1' # GATT_SERVICE_IFACE = 'org.bluez.GattService1' # GATT_CHRC_IFACE = 'org.bluez.GattCharacteristic1' # GATT_DESC_IFACE = 'org.bluez.GattDescriptor1' # LE_ADVERTISING_MANAGER_IFACE = 'org.bluez.LEAdvertisingManager1' # LE_ADVERTISEMENT_IFACE = 'org.bluez.LEAdvertisement1' # MEDIA_PLAYER_IFACE = 'org.bluez.MediaPlayer1' # BLUEZERO_DBUS_NAME = 'ukBaz.bluezero' # BLUEZERO_DBUS_OBJECT = '/ukBaz/bluezero' # # Path: bluezero/dbus_tools.py # def bluez_version(): # def bluez_experimental_mode(): # def interfaces_added(path, interfaces): # def properties_changed(interface, changed, invalidated, path): # def get_dbus_obj(dbus_path): # def get_dbus_iface(iface, dbus_obj): # def get_managed_objects(): # def get_mac_addr_from_dbus_path(path): # def get_device_address_from_dbus_path(path): # def get_adapter_address_from_dbus_path(path): # def _get_dbus_path2(objects, parent_path, iface_in, prop, value): # def get_dbus_path(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_profile_path(adapter, # device, # profile): # def get_iface(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_methods(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_props(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_services(path_obj): # def get_device_addresses(name_contains): # def get(dbus_prop_obj, dbus_iface, prop_name, default=None): # def str_to_dbusarray(word): # def bytes_to_dbusarray(bytesarray): # def dbus_to_python(data): # # Path: bluezero/tools.py # def int_to_uint16(value_in): # def sint16_to_int(byte_array): # def bytes_to_xyz(byte_array): # def int_to_uint32(value_in): # def bitwise_or_2lists(list1, list2): # def bitwise_and_2lists(list1, list2): # def bitwise_xor_2lists(list1, list2): # def url_to_advert(url, frame_type, tx_power): # def get_fn_parameters(fn): # def create_module_logger(module_name): , which may include functions, classes, or code. Output only the next line.
return self.player_props.Get(
Using the snippet: <|code_start|> # all files called if len(list(set(ref_files) - set(test_files))) == 0: logger.info('All files are called during %s' % run_type) # some files not called if len(list(set(ref_files) - set(test_files))) != 0: names = ':'.join([name for name in list(set(ref_files) - set(test_files))]) logger.error('Files not called during %s are %s' % (run_type, names)) # files called that do not exist if len(list(set(ref_files) - set(test_files))) != 0: names = ':'.join([name for name in list(set(ref_files) - set(test_files))]) logger.error('Extra files called during %s are %s' % (run_type, names)) # files called multiple times duplicates = '' for test, count in collections.Counter(test_files).items(): if count > 1: duplicates += test if duplicates: logger.error('%s has the following duplicates: %s' % (run_type, duplicates)) def run_checks(tests_dir, local_run_file, git_run_file, debug=False): if debug: logger.setLevel(logging.DEBUG) files_test = find_test_files(tests_dir) local_run = find_run_files(local_run_file) git_run = find_run_files(git_run_file) if all_lists_match(files_test, local_run, git_run): logger.info('All match') else: <|code_end|> , determine the next line of code. You have imports: import collections import logging import re from pathlib import Path from bluezero.tools import create_module_logger and context (class names, function names, or code) available: # Path: bluezero/tools.py # def create_module_logger(module_name): # """helper function to create logger in Bluezero modules""" # logger = logging.getLogger(module_name) # if logger.hasHandlers(): # return logger # strm_hndlr = logging.StreamHandler() # formatter = logging.Formatter( # '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # strm_hndlr.setFormatter(formatter) # logger.addHandler(strm_hndlr) # return logger . Output only the next line.
logger.error('There is a mismatch. Running debug...')
Predict the next line for this snippet: <|code_start|> adapter_props = tests.obj_data.full_ubits def mock_get(iface, prop): return tests.obj_data.full_ubits['/org/bluez/hci0'][iface][prop] <|code_end|> with the help of current file imports: import unittest import tests.obj_data from unittest.mock import MagicMock from unittest.mock import patch from bluezero import constants from bluezero import advertisement from bluezero import dbus_tools and context from other files: # Path: bluezero/constants.py # DBUS_OM_IFACE = 'org.freedesktop.DBus.ObjectManager' # DBUS_PROP_IFACE = 'org.freedesktop.DBus.Properties' # BLUEZ_SERVICE_NAME = 'org.bluez' # ADAPTER_INTERFACE = 'org.bluez.Adapter1' # DEVICE_INTERFACE = 'org.bluez.Device1' # GATT_MANAGER_IFACE = 'org.bluez.GattManager1' # GATT_PROFILE_IFACE = 'org.bluez.GattProfile1' # GATT_SERVICE_IFACE = 'org.bluez.GattService1' # GATT_CHRC_IFACE = 'org.bluez.GattCharacteristic1' # GATT_DESC_IFACE = 'org.bluez.GattDescriptor1' # LE_ADVERTISING_MANAGER_IFACE = 'org.bluez.LEAdvertisingManager1' # LE_ADVERTISEMENT_IFACE = 'org.bluez.LEAdvertisement1' # MEDIA_PLAYER_IFACE = 'org.bluez.MediaPlayer1' # BLUEZERO_DBUS_NAME = 'ukBaz.bluezero' # BLUEZERO_DBUS_OBJECT = '/ukBaz/bluezero' , which may contain function names, class names, or code. Output only the next line.
def mock_set(iface, prop, value):
Next line prediction: <|code_start|># pi@RPi3:~ $ bluetoothctl # [bluetooth]# agent NoInputNoOutput # Agent registered # [bluetooth]# discoverable on # Changing discoverable on succeeded # [CHG] Controller B8:27:EB:22:57:E0 Discoverable: yes # # Now we have made the Raspberry Pi discoverable we can pair to it from the # mobile phone. Once it has paired you can tell the Raspberry Pi that it is a # trusted device # # [Nexus 5X]# trust 64:BC:0C:F6:22:F8 # # Now the phone is connected you can run this script to find which track is # playing # # pi@RPi3:~ $ python3 examples/control_media_player.py # Find the mac address of the first media player connected over Bluetooth mac_addr = None for dbus_path in dbus_tools.get_managed_objects(): if dbus_path.endswith('player0'): mac_addr = dbus_tools.get_device_address_from_dbus_path(dbus_path) if mac_addr: mp = media_player.MediaPlayer(mac_addr) track_details = mp.track for detail in track_details: <|code_end|> . Use current file imports: (from bluezero import dbus_tools from bluezero import media_player) and context including class names, function names, or small code snippets from other files: # Path: bluezero/dbus_tools.py # def bluez_version(): # def bluez_experimental_mode(): # def interfaces_added(path, interfaces): # def properties_changed(interface, changed, invalidated, path): # def get_dbus_obj(dbus_path): # def get_dbus_iface(iface, dbus_obj): # def get_managed_objects(): # def get_mac_addr_from_dbus_path(path): # def get_device_address_from_dbus_path(path): # def get_adapter_address_from_dbus_path(path): # def _get_dbus_path2(objects, parent_path, iface_in, prop, value): # def get_dbus_path(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_profile_path(adapter, # device, # profile): # def get_iface(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_methods(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_props(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_services(path_obj): # def get_device_addresses(name_contains): # def get(dbus_prop_obj, dbus_iface, prop_name, default=None): # def str_to_dbusarray(word): # def bytes_to_dbusarray(bytesarray): # def dbus_to_python(data): # # Path: bluezero/media_player.py # class MediaPlayerError(Exception): # class MediaPlayer: # def _find_player_path(device_address): # def __init__(self, device_addr): # def browsable(self): # def searchable(self): # def track(self): # def device(self): # def playlist(self): # def equalizer(self): # def equalizer(self, value): # def name(self): # def repeat(self): # def repeat(self, value): # def shuffle(self): # def shuffle(self, value): # def status(self): # def subtype(self): # def type(self, player_type): # def position(self): # def next(self): # def play(self): # def pause(self): # def stop(self): # def previous(self): # def fast_forward(self): # def rewind(self): . Output only the next line.
print(f'{detail} : {track_details[detail]}')
Given the following code snippet before the placeholder: <|code_start|># bluetoothctl tool # pi@RPi3:~ $ bluetoothctl # [bluetooth]# agent NoInputNoOutput # Agent registered # [bluetooth]# discoverable on # Changing discoverable on succeeded # [CHG] Controller B8:27:EB:22:57:E0 Discoverable: yes # # Now we have made the Raspberry Pi discoverable we can pair to it from the # mobile phone. Once it has paired you can tell the Raspberry Pi that it is a # trusted device # # [Nexus 5X]# trust 64:BC:0C:F6:22:F8 # # Now the phone is connected you can run this script to find which track is # playing # # pi@RPi3:~ $ python3 examples/control_media_player.py # Find the mac address of the first media player connected over Bluetooth mac_addr = None for dbus_path in dbus_tools.get_managed_objects(): if dbus_path.endswith('player0'): mac_addr = dbus_tools.get_device_address_from_dbus_path(dbus_path) if mac_addr: mp = media_player.MediaPlayer(mac_addr) track_details = mp.track <|code_end|> , predict the next line using imports from the current file: from bluezero import dbus_tools from bluezero import media_player and context including class names, function names, and sometimes code from other files: # Path: bluezero/dbus_tools.py # def bluez_version(): # def bluez_experimental_mode(): # def interfaces_added(path, interfaces): # def properties_changed(interface, changed, invalidated, path): # def get_dbus_obj(dbus_path): # def get_dbus_iface(iface, dbus_obj): # def get_managed_objects(): # def get_mac_addr_from_dbus_path(path): # def get_device_address_from_dbus_path(path): # def get_adapter_address_from_dbus_path(path): # def _get_dbus_path2(objects, parent_path, iface_in, prop, value): # def get_dbus_path(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_profile_path(adapter, # device, # profile): # def get_iface(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_methods(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_props(adapter=None, # device=None, # service=None, # characteristic=None, # descriptor=None): # def get_services(path_obj): # def get_device_addresses(name_contains): # def get(dbus_prop_obj, dbus_iface, prop_name, default=None): # def str_to_dbusarray(word): # def bytes_to_dbusarray(bytesarray): # def dbus_to_python(data): # # Path: bluezero/media_player.py # class MediaPlayerError(Exception): # class MediaPlayer: # def _find_player_path(device_address): # def __init__(self, device_addr): # def browsable(self): # def searchable(self): # def track(self): # def device(self): # def playlist(self): # def equalizer(self): # def equalizer(self, value): # def name(self): # def repeat(self): # def repeat(self, value): # def shuffle(self): # def shuffle(self, value): # def status(self): # def subtype(self): # def type(self, player_type): # def position(self): # def next(self): # def play(self): # def pause(self): # def stop(self): # def previous(self): # def fast_forward(self): # def rewind(self): . Output only the next line.
for detail in track_details:
Next line prediction: <|code_start|> def main(): alt = broadcaster.Beacon() alt.add_manufacturer_data( 'ffff', # Manufacturer ID (0xffff = Not for production) b'\xBE\xAC' # beacon code for Alt Beacon + 16 * b'\xbe' # Beacon UUID + 4 * b'\x00' # Free + b'\x01') # Transmit power <|code_end|> . Use current file imports: (from bluezero import broadcaster) and context including class names, function names, or small code snippets from other files: # Path: bluezero/broadcaster.py # class Beacon: # def __init__(self, adapter_addr=None): # def add_service_data(self, service, data): # def add_manufacturer_data(self, manufacturer, data): # def include_tx_power(self, show_power=None): # def start_beacon(self): . Output only the next line.
alt.start_beacon()
Based on the snippet: <|code_start|> return large_query_client @pytest.fixture(scope="function") def large_query(large_query_client): # Use the client for this test instead of the global. return large_query_client.query( kind=populate_datastore.LARGE_CHARACTER_KIND, namespace=populate_datastore.LARGE_CHARACTER_NAMESPACE, ) @pytest.mark.parametrize( "limit,offset,expected", [ # with no offset there are the correct # of results (None, None, populate_datastore.LARGE_CHARACTER_TOTAL_OBJECTS,), # with no limit there are results (offset provided) (None, 900, populate_datastore.LARGE_CHARACTER_TOTAL_OBJECTS - 900,), # Offset beyond items larger: verify 200 items found (200, 1100, 200,), # offset within range, expect 50 despite larger limit") (100, populate_datastore.LARGE_CHARACTER_TOTAL_OBJECTS - 50, 50), # Offset beyond items larger Verify no items found") (200, populate_datastore.LARGE_CHARACTER_TOTAL_OBJECTS + 1000, 0), ], ) def test_large_query(large_query, limit, offset, expected): page_query = large_query page_query.add_filter("family", "=", "Stark") <|code_end|> , predict the immediate next line with the help of imports: import pytest from google.api_core import exceptions from test_utils.retry import RetryErrors from .utils import clear_datastore from .utils import populate_datastore from . import _helpers and context (classes, functions, sometimes code) from other files: # Path: tests/system/utils/clear_datastore.py # FETCH_MAX = 20 # ALL_KINDS = ( # "Character", # "Company", # "Kind", # "Person", # "Post", # "uuid_key", # "timestamp_key", # ) # TRANSACTION_MAX_GROUPS = 5 # MAX_DEL_ENTITIES = 500 # def print_func(message): # def get_ancestors(entities): # def delete_chunks(client, results): # def remove_kind(kind, client): # def remove_all_entities(client): # def main(): # # Path: tests/system/utils/populate_datastore.py # ANCESTOR = ("Book", "GoT") # RICKARD = ANCESTOR + ("Character", "Rickard") # EDDARD = RICKARD + ("Character", "Eddard") # KEY_PATHS = ( # RICKARD, # EDDARD, # ANCESTOR + ("Character", "Catelyn"), # EDDARD + ("Character", "Arya"), # EDDARD + ("Character", "Sansa"), # EDDARD + ("Character", "Robb"), # EDDARD + ("Character", "Bran"), # EDDARD + ("Character", "Jon Snow"), # ) # CHARACTERS = ( # {"name": u"Rickard", "family": u"Stark", "appearances": 0, "alive": False}, # {"name": u"Eddard", "family": u"Stark", "appearances": 9, "alive": False}, # { # "name": u"Catelyn", # "family": [u"Stark", u"Tully"], # "appearances": 26, # "alive": False, # }, # {"name": u"Arya", "family": u"Stark", "appearances": 33, "alive": True}, # {"name": u"Sansa", "family": u"Stark", "appearances": 31, "alive": True}, # {"name": u"Robb", "family": u"Stark", "appearances": 22, "alive": False}, # {"name": u"Bran", "family": u"Stark", "appearances": 25, "alive": True}, # {"name": u"Jon Snow", "family": u"Stark", "appearances": 32, "alive": True}, # ) # LARGE_CHARACTER_TOTAL_OBJECTS = 2500 # LARGE_CHARACTER_NAMESPACE = "LargeCharacterEntity" # LARGE_CHARACTER_KIND = "LargeCharacter" # MAX_STRING = (string.ascii_lowercase * 58)[:1500] # ENTITIES_TO_BATCH = 25 # def print_func(message): # def add_large_character_entities(client=None): # def put_objects(count): # def add_characters(client=None): # def add_uid_keys(client=None): # def add_timestamp_keys(client=None): # def main(): . Output only the next line.
page_query.add_filter("alive", "=", False)
Given snippet: <|code_start|> assert len(entities) == expected_matches def test_query_w_multiple_filters(ancestor_query): query = ancestor_query query.add_filter("appearances", ">=", 26) query = query.add_filter("family", "=", "Stark") expected_matches = 4 # We expect 4, but allow the query to get 1 extra. entities = _do_fetch(query, limit=expected_matches + 1) assert len(entities) == expected_matches def test_query_key_filter(query_client, ancestor_query): # Use the client for this test instead of the global. query = ancestor_query rickard_key = query_client.key(*populate_datastore.RICKARD) query.key_filter(rickard_key) expected_matches = 1 # We expect 1, but allow the query to get 1 extra. entities = _do_fetch(query, limit=expected_matches + 1) assert len(entities) == expected_matches def test_query_w_order(ancestor_query): query = ancestor_query <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from google.api_core import exceptions from test_utils.retry import RetryErrors from .utils import clear_datastore from .utils import populate_datastore from . import _helpers and context: # Path: tests/system/utils/clear_datastore.py # FETCH_MAX = 20 # ALL_KINDS = ( # "Character", # "Company", # "Kind", # "Person", # "Post", # "uuid_key", # "timestamp_key", # ) # TRANSACTION_MAX_GROUPS = 5 # MAX_DEL_ENTITIES = 500 # def print_func(message): # def get_ancestors(entities): # def delete_chunks(client, results): # def remove_kind(kind, client): # def remove_all_entities(client): # def main(): # # Path: tests/system/utils/populate_datastore.py # ANCESTOR = ("Book", "GoT") # RICKARD = ANCESTOR + ("Character", "Rickard") # EDDARD = RICKARD + ("Character", "Eddard") # KEY_PATHS = ( # RICKARD, # EDDARD, # ANCESTOR + ("Character", "Catelyn"), # EDDARD + ("Character", "Arya"), # EDDARD + ("Character", "Sansa"), # EDDARD + ("Character", "Robb"), # EDDARD + ("Character", "Bran"), # EDDARD + ("Character", "Jon Snow"), # ) # CHARACTERS = ( # {"name": u"Rickard", "family": u"Stark", "appearances": 0, "alive": False}, # {"name": u"Eddard", "family": u"Stark", "appearances": 9, "alive": False}, # { # "name": u"Catelyn", # "family": [u"Stark", u"Tully"], # "appearances": 26, # "alive": False, # }, # {"name": u"Arya", "family": u"Stark", "appearances": 33, "alive": True}, # {"name": u"Sansa", "family": u"Stark", "appearances": 31, "alive": True}, # {"name": u"Robb", "family": u"Stark", "appearances": 22, "alive": False}, # {"name": u"Bran", "family": u"Stark", "appearances": 25, "alive": True}, # {"name": u"Jon Snow", "family": u"Stark", "appearances": 32, "alive": True}, # ) # LARGE_CHARACTER_TOTAL_OBJECTS = 2500 # LARGE_CHARACTER_NAMESPACE = "LargeCharacterEntity" # LARGE_CHARACTER_KIND = "LargeCharacter" # MAX_STRING = (string.ascii_lowercase * 58)[:1500] # ENTITIES_TO_BATCH = 25 # def print_func(message): # def add_large_character_entities(client=None): # def put_objects(count): # def add_characters(client=None): # def add_uid_keys(client=None): # def add_timestamp_keys(client=None): # def main(): which might include code, classes, or functions. Output only the next line.
query.order = "appearances"
Predict the next line for this snippet: <|code_start|> __protobuf__ = proto.module( package="google.datastore.v1", manifest={ "EntityResult", "Query", "KindExpression", "PropertyReference", "Projection", "PropertyOrder", "Filter", "CompositeFilter", "PropertyFilter", "GqlQuery", "GqlQueryParameter", "QueryResultBatch", }, ) class EntityResult(proto.Message): r"""The result of fetching an entity from Datastore. Attributes: entity (google.cloud.datastore_v1.types.Entity): The resulting entity. version (int): The version of the entity, a strictly positive number that monotonically increases with changes to the entity. <|code_end|> with the help of current file imports: import proto # type: ignore from google.cloud.datastore_v1.types import entity as gd_entity from google.protobuf import wrappers_pb2 # type: ignore and context from other files: # Path: google/cloud/datastore_v1/types/entity.py # class PartitionId(proto.Message): # class Key(proto.Message): # class PathElement(proto.Message): # class ArrayValue(proto.Message): # class Value(proto.Message): # class Entity(proto.Message): , which may contain function names, class names, or code. Output only the next line.
This field is set for
Predict the next line for this snippet: <|code_start|> The mutations to perform. When mode is ``TRANSACTIONAL``, mutations affecting a single entity are applied in order. The following sequences of mutations affecting a single entity are not permitted in a single ``Commit`` request: - ``insert`` followed by ``insert`` - ``update`` followed by ``insert`` - ``upsert`` followed by ``insert`` - ``delete`` followed by ``update`` When mode is ``NON_TRANSACTIONAL``, no two mutations may affect a single entity. """ class Mode(proto.Enum): r"""The modes available for commits.""" MODE_UNSPECIFIED = 0 TRANSACTIONAL = 1 NON_TRANSACTIONAL = 2 project_id = proto.Field(proto.STRING, number=8,) mode = proto.Field(proto.ENUM, number=5, enum=Mode,) transaction = proto.Field(proto.BYTES, number=1, oneof="transaction_selector",) mutations = proto.RepeatedField(proto.MESSAGE, number=6, message="Mutation",) class CommitResponse(proto.Message): r"""The response for <|code_end|> with the help of current file imports: import proto # type: ignore from google.cloud.datastore_v1.types import entity from google.cloud.datastore_v1.types import query as gd_query and context from other files: # Path: google/cloud/datastore_v1/types/entity.py # class PartitionId(proto.Message): # class Key(proto.Message): # class PathElement(proto.Message): # class ArrayValue(proto.Message): # class Value(proto.Message): # class Entity(proto.Message): # # Path: google/cloud/datastore_v1/types/query.py # class EntityResult(proto.Message): # class ResultType(proto.Enum): # class Query(proto.Message): # class KindExpression(proto.Message): # class PropertyReference(proto.Message): # class Projection(proto.Message): # class PropertyOrder(proto.Message): # class Direction(proto.Enum): # class Filter(proto.Message): # class CompositeFilter(proto.Message): # class Operator(proto.Enum): # class PropertyFilter(proto.Message): # class Operator(proto.Enum): # class GqlQuery(proto.Message): # class GqlQueryParameter(proto.Message): # class QueryResultBatch(proto.Message): # class MoreResultsType(proto.Enum): # RESULT_TYPE_UNSPECIFIED = 0 # FULL = 1 # PROJECTION = 2 # KEY_ONLY = 3 # DIRECTION_UNSPECIFIED = 0 # ASCENDING = 1 # DESCENDING = 2 # OPERATOR_UNSPECIFIED = 0 # AND = 1 # OPERATOR_UNSPECIFIED = 0 # LESS_THAN = 1 # LESS_THAN_OR_EQUAL = 2 # GREATER_THAN = 3 # GREATER_THAN_OR_EQUAL = 4 # EQUAL = 5 # HAS_ANCESTOR = 11 # MORE_RESULTS_TYPE_UNSPECIFIED = 0 # NOT_FINISHED = 1 # MORE_RESULTS_AFTER_LIMIT = 2 # MORE_RESULTS_AFTER_CURSOR = 4 # NO_MORE_RESULTS = 3 , which may contain function names, class names, or code. Output only the next line.
[Datastore.Commit][google.datastore.v1.Datastore.Commit].
Using the 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. # __protobuf__ = proto.module( package="google.datastore.v1", manifest={ "LookupRequest", "LookupResponse", "RunQueryRequest", "RunQueryResponse", "BeginTransactionRequest", "BeginTransactionResponse", "RollbackRequest", "RollbackResponse", "CommitRequest", "CommitResponse", "AllocateIdsRequest", "AllocateIdsResponse", "ReserveIdsRequest", "ReserveIdsResponse", "Mutation", "MutationResult", "ReadOptions", "TransactionOptions", <|code_end|> , determine the next line of code. You have imports: import proto # type: ignore from google.cloud.datastore_v1.types import entity from google.cloud.datastore_v1.types import query as gd_query and context (class names, function names, or code) available: # Path: google/cloud/datastore_v1/types/entity.py # class PartitionId(proto.Message): # class Key(proto.Message): # class PathElement(proto.Message): # class ArrayValue(proto.Message): # class Value(proto.Message): # class Entity(proto.Message): # # Path: google/cloud/datastore_v1/types/query.py # class EntityResult(proto.Message): # class ResultType(proto.Enum): # class Query(proto.Message): # class KindExpression(proto.Message): # class PropertyReference(proto.Message): # class Projection(proto.Message): # class PropertyOrder(proto.Message): # class Direction(proto.Enum): # class Filter(proto.Message): # class CompositeFilter(proto.Message): # class Operator(proto.Enum): # class PropertyFilter(proto.Message): # class Operator(proto.Enum): # class GqlQuery(proto.Message): # class GqlQueryParameter(proto.Message): # class QueryResultBatch(proto.Message): # class MoreResultsType(proto.Enum): # RESULT_TYPE_UNSPECIFIED = 0 # FULL = 1 # PROJECTION = 2 # KEY_ONLY = 3 # DIRECTION_UNSPECIFIED = 0 # ASCENDING = 1 # DESCENDING = 2 # OPERATOR_UNSPECIFIED = 0 # AND = 1 # OPERATOR_UNSPECIFIED = 0 # LESS_THAN = 1 # LESS_THAN_OR_EQUAL = 2 # GREATER_THAN = 3 # GREATER_THAN_OR_EQUAL = 4 # EQUAL = 5 # HAS_ANCESTOR = 11 # MORE_RESULTS_TYPE_UNSPECIFIED = 0 # NOT_FINISHED = 1 # MORE_RESULTS_AFTER_LIMIT = 2 # MORE_RESULTS_AFTER_CURSOR = 4 # NO_MORE_RESULTS = 3 . Output only the next line.
},
Here is a snippet: <|code_start|> OPERATION_TYPE_UNSPECIFIED = 0 EXPORT_ENTITIES = 1 IMPORT_ENTITIES = 2 CREATE_INDEX = 3 DELETE_INDEX = 4 class CommonMetadata(proto.Message): r"""Metadata common to all Datastore Admin operations. Attributes: start_time (google.protobuf.timestamp_pb2.Timestamp): The time that work began on the operation. end_time (google.protobuf.timestamp_pb2.Timestamp): The time the operation ended, either successfully or otherwise. operation_type (google.cloud.datastore_admin_v1.types.OperationType): The type of the operation. Can be used as a filter in ListOperationsRequest. labels (Dict[str, str]): The client-assigned labels which were provided when the operation was created. May also include additional labels. state (google.cloud.datastore_admin_v1.types.CommonMetadata.State): The current state of the Operation. """ class State(proto.Enum): r"""The various possible states for an ongoing Operation.""" STATE_UNSPECIFIED = 0 <|code_end|> . Write the next line using the current file imports: import proto # type: ignore from google.cloud.datastore_admin_v1.types import index as gda_index from google.cloud.datastore_admin_v1.types import migration from google.protobuf import timestamp_pb2 # type: ignore and context from other files: # Path: google/cloud/datastore_admin_v1/types/index.py # class Index(proto.Message): # class AncestorMode(proto.Enum): # class Direction(proto.Enum): # class State(proto.Enum): # class IndexedProperty(proto.Message): # ANCESTOR_MODE_UNSPECIFIED = 0 # NONE = 1 # ALL_ANCESTORS = 2 # DIRECTION_UNSPECIFIED = 0 # ASCENDING = 1 # DESCENDING = 2 # STATE_UNSPECIFIED = 0 # CREATING = 1 # READY = 2 # DELETING = 3 # ERROR = 4 # # Path: google/cloud/datastore_admin_v1/types/migration.py # class MigrationState(proto.Enum): # class MigrationStep(proto.Enum): # class MigrationStateEvent(proto.Message): # class MigrationProgressEvent(proto.Message): # class ConcurrencyMode(proto.Enum): # class PrepareStepDetails(proto.Message): # class RedirectWritesStepDetails(proto.Message): # MIGRATION_STATE_UNSPECIFIED = 0 # RUNNING = 1 # PAUSED = 2 # COMPLETE = 3 # MIGRATION_STEP_UNSPECIFIED = 0 # PREPARE = 6 # START = 1 # APPLY_WRITES_SYNCHRONOUSLY = 7 # COPY_AND_VERIFY = 2 # REDIRECT_EVENTUALLY_CONSISTENT_READS = 3 # REDIRECT_STRONGLY_CONSISTENT_READS = 4 # REDIRECT_WRITES = 5 # CONCURRENCY_MODE_UNSPECIFIED = 0 # PESSIMISTIC = 1 # OPTIMISTIC = 2 , which may include functions, classes, or code. Output only the next line.
INITIALIZING = 1
Based on the snippet: <|code_start|> class CommonMetadata(proto.Message): r"""Metadata common to all Datastore Admin operations. Attributes: start_time (google.protobuf.timestamp_pb2.Timestamp): The time that work began on the operation. end_time (google.protobuf.timestamp_pb2.Timestamp): The time the operation ended, either successfully or otherwise. operation_type (google.cloud.datastore_admin_v1.types.OperationType): The type of the operation. Can be used as a filter in ListOperationsRequest. labels (Dict[str, str]): The client-assigned labels which were provided when the operation was created. May also include additional labels. state (google.cloud.datastore_admin_v1.types.CommonMetadata.State): The current state of the Operation. """ class State(proto.Enum): r"""The various possible states for an ongoing Operation.""" STATE_UNSPECIFIED = 0 INITIALIZING = 1 PROCESSING = 2 CANCELLING = 3 FINALIZING = 4 SUCCESSFUL = 5 FAILED = 6 <|code_end|> , predict the immediate next line with the help of imports: import proto # type: ignore from google.cloud.datastore_admin_v1.types import index as gda_index from google.cloud.datastore_admin_v1.types import migration from google.protobuf import timestamp_pb2 # type: ignore and context (classes, functions, sometimes code) from other files: # Path: google/cloud/datastore_admin_v1/types/index.py # class Index(proto.Message): # class AncestorMode(proto.Enum): # class Direction(proto.Enum): # class State(proto.Enum): # class IndexedProperty(proto.Message): # ANCESTOR_MODE_UNSPECIFIED = 0 # NONE = 1 # ALL_ANCESTORS = 2 # DIRECTION_UNSPECIFIED = 0 # ASCENDING = 1 # DESCENDING = 2 # STATE_UNSPECIFIED = 0 # CREATING = 1 # READY = 2 # DELETING = 3 # ERROR = 4 # # Path: google/cloud/datastore_admin_v1/types/migration.py # class MigrationState(proto.Enum): # class MigrationStep(proto.Enum): # class MigrationStateEvent(proto.Message): # class MigrationProgressEvent(proto.Message): # class ConcurrencyMode(proto.Enum): # class PrepareStepDetails(proto.Message): # class RedirectWritesStepDetails(proto.Message): # MIGRATION_STATE_UNSPECIFIED = 0 # RUNNING = 1 # PAUSED = 2 # COMPLETE = 3 # MIGRATION_STEP_UNSPECIFIED = 0 # PREPARE = 6 # START = 1 # APPLY_WRITES_SYNCHRONOUSLY = 7 # COPY_AND_VERIFY = 2 # REDIRECT_EVENTUALLY_CONSISTENT_READS = 3 # REDIRECT_STRONGLY_CONSISTENT_READS = 4 # REDIRECT_WRITES = 5 # CONCURRENCY_MODE_UNSPECIFIED = 0 # PESSIMISTIC = 1 # OPTIMISTIC = 2 . Output only the next line.
CANCELLED = 7
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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. # try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( "google-cloud-datastore-admin", ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() <|code_end|> , predict the next line using imports from the current file: import abc import pkg_resources import google.auth # type: ignore import google.api_core from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.api_core import operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.datastore_admin_v1.types import datastore_admin from google.cloud.datastore_admin_v1.types import index from google.longrunning import operations_pb2 # type: ignore and context including class names, function names, and sometimes code from other files: # Path: google/cloud/datastore_admin_v1/types/datastore_admin.py # class OperationType(proto.Enum): # class CommonMetadata(proto.Message): # class State(proto.Enum): # class Progress(proto.Message): # class ExportEntitiesRequest(proto.Message): # class ImportEntitiesRequest(proto.Message): # class ExportEntitiesResponse(proto.Message): # class ExportEntitiesMetadata(proto.Message): # class ImportEntitiesMetadata(proto.Message): # class EntityFilter(proto.Message): # class CreateIndexRequest(proto.Message): # class DeleteIndexRequest(proto.Message): # class GetIndexRequest(proto.Message): # class ListIndexesRequest(proto.Message): # class ListIndexesResponse(proto.Message): # class IndexOperationMetadata(proto.Message): # class DatastoreFirestoreMigrationMetadata(proto.Message): # OPERATION_TYPE_UNSPECIFIED = 0 # EXPORT_ENTITIES = 1 # IMPORT_ENTITIES = 2 # CREATE_INDEX = 3 # DELETE_INDEX = 4 # STATE_UNSPECIFIED = 0 # INITIALIZING = 1 # PROCESSING = 2 # CANCELLING = 3 # FINALIZING = 4 # SUCCESSFUL = 5 # FAILED = 6 # CANCELLED = 7 # def raw_page(self): # # Path: google/cloud/datastore_admin_v1/types/index.py # class Index(proto.Message): # class AncestorMode(proto.Enum): # class Direction(proto.Enum): # class State(proto.Enum): # class IndexedProperty(proto.Message): # ANCESTOR_MODE_UNSPECIFIED = 0 # NONE = 1 # ALL_ANCESTORS = 2 # DIRECTION_UNSPECIFIED = 0 # ASCENDING = 1 # DESCENDING = 2 # STATE_UNSPECIFIED = 0 # CREATING = 1 # READY = 2 # DELETING = 3 # ERROR = 4 . Output only the next line.
class DatastoreAdminTransport(abc.ABC):
Predict the next line after 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. @pytest.mark.skipif(not _HAVE_GRPC, reason="No gRPC") @mock.patch( "google.cloud.datastore_v1.services.datastore.client.DatastoreClient", return_value=mock.sentinel.ds_client, ) @mock.patch( "google.cloud.datastore_v1.services.datastore.transports.grpc.DatastoreGrpcTransport", return_value=mock.sentinel.transport, ) @mock.patch( "google.cloud.datastore._gapic.make_secure_channel", return_value=mock.sentinel.channel, ) def test_live_api(make_chan, mock_transport, mock_klass): base_url = "https://datastore.googleapis.com:443" client = mock.Mock( _base_url=base_url, _credentials=mock.sentinel.credentials, _client_info=mock.sentinel.client_info, spec=["_base_url", "_credentials", "_client_info"], ) <|code_end|> using the current file's imports: import mock import pytest from google.cloud.datastore.client import _HAVE_GRPC from google.cloud._http import DEFAULT_USER_AGENT from google.cloud.datastore._gapic import make_datastore_api from google.cloud.datastore._gapic import make_datastore_api and any relevant context from other files: # Path: google/cloud/datastore/client.py # _HAVE_GRPC = False . Output only the next line.
ds_api = make_datastore_api(client)
Given the code snippet: <|code_start|> # +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # generate the solution string from the array data @staticmethod def solutionToString(length, depthPhase1=- 1): s = [] for i in range(length): step = '' if Search.ax[i] == 0: step = "U" elif Search.ax[i] == 1: step = "R" elif Search.ax[i] == 2: step = "F" elif Search.ax[i] == 3: step = "D" elif Search.ax[i] == 4: step = "L" elif Search.ax[i] == 5: step = "B" if Search.po[i] == 2: step += "2" elif Search.po[i] == 3: step += "'" if i == (depthPhase1 - 1): step = ". " s.append(step) return s <|code_end|> , generate the next line using the imports in this file: import time import rubik_solver.FaceCube as FaceCube import rubik_solver.CoordCube as CoordCube from rubik_solver.Enums import Color from rubik_solver.CubieCube import DupedEdge and context (functions, classes, or occasionally code) from other files: # Path: rubik_solver/Enums.py # def enum(*sequential, **named): # # Path: rubik_solver/CubieCube.py # class DupedEdge(Exception): pass . Output only the next line.
@staticmethod
Here is a snippet: <|code_start|>__author__ = 'Victor' class DupedFacelet(Exception): pass class NoSolution(Exception): pass class SolverTimeoutError(Exception): pass class Search(object): <|code_end|> . Write the next line using the current file imports: import time import rubik_solver.FaceCube as FaceCube import rubik_solver.CoordCube as CoordCube from rubik_solver.Enums import Color from rubik_solver.CubieCube import DupedEdge and context from other files: # Path: rubik_solver/Enums.py # def enum(*sequential, **named): # # Path: rubik_solver/CubieCube.py # class DupedEdge(Exception): pass , which may include functions, classes, or code. Output only the next line.
ax = [0] * 31 # The axis of the move
Continue the code snippet: <|code_start|> self.assertTrue(m.clockwise) self.assertFalse(m.counterclockwise) self.assertFalse(m.double) m.double = True self.assertFalse(m.clockwise) self.assertFalse(m.counterclockwise) self.assertTrue(m.double) m.double = False self.assertTrue(m.clockwise) self.assertFalse(m.counterclockwise) self.assertFalse(m.double) m.counterclockwise = True self.assertFalse(m.clockwise) self.assertTrue(m.counterclockwise) self.assertFalse(m.double) m.counterclockwise = False self.assertTrue(m.clockwise) self.assertFalse(m.counterclockwise) self.assertFalse(m.double) def test_reverse(self): m = Move(self.allowed_moves[0]) m1 = m.reverse() self.assertFalse(m1.clockwise) <|code_end|> . Use current file imports: from rubik_solver.Move import Move import string import unittest and context (classes, functions, or code) from other files: # Path: rubik_solver/Move.py # class Move(object): # def __init__(self, move): # if not re.match("[fblrudxyzmse]'?2?", move, re.I): # raise ValueError("Invalid move format, must be [face]' or [face]2, got %s" % move) # # self.raw = move.upper() # # @property # def face(self): # return self.raw[0].upper() # # @face.setter # def face(self, new_face): # self.raw = new_face + self.raw[1:] # # @property # def double(self): # return '2' in self.raw # # @double.setter # def double(self, new_double): # if new_double: # self.raw = self.raw.replace('2', '').replace("'", '') + '2' # else: # self.raw = self.raw.replace('2', '').replace("'", '') # # @property # def counterclockwise(self): # return "'" in self.raw # # @counterclockwise.setter # def counterclockwise(self, value): # if value: # self.raw = self.raw.replace("'", '').replace("2", '') + "'" # else: # self.raw = self.raw.replace("'", '').replace("2", '') # # @property # def clockwise(self): # return not self.counterclockwise and not self.double # # @clockwise.setter # def clockwise(self, value): # self.counterclockwise = not value # # def reverse(self): # return Move(self.face + ("'" if self.clockwise else "2" if self.double else "")) # # def __eq__(self, move): # if isinstance(move, (str, basestring)): # return self.raw == move.upper() # elif isinstance(move, Move): # return self.raw == move.raw # else: # return False # # def __str__(self): # return self.raw # # def __repr__(self): # return str(self) # # def __ne__(self, move): # return not self == move # # def __add__(self, move): # if isinstance(move, (str, basestring)): # return self + Move(move) # elif move is None: # return self # elif isinstance(move, Move): # if self.face != move.face: # raise ValueError("Only same faces can be added") # # if self.clockwise and move.counterclockwise: # return None # if self.double and move.double: # return None # # offset = ( # (self.clockwise + (self.double * 2) + (self.counterclockwise * 3)) + # (move.clockwise + (move.double * 2) + (move.counterclockwise * 3)) # ) % 4 # # if offset == 0: # return None # # return Move(self.face + [None, "", "2", "'"][offset]) # else: # raise ValueError("Unable to add %s and %s" %(self.raw, str(move))) # # def __mul__(self, times): # offset = ((self.clockwise + (self.double * 2) + (self.counterclockwise * 3)) * times % 4) # # if offset == 0: # return None # # return Move(self.face + [None, "", "2", "'"][offset]) . Output only the next line.
self.assertTrue(m1.counterclockwise)
Continue the code snippet: <|code_start|> """""" _name = 'infrastructure.server_docker_image' _description = 'Server Docker Image' _rec_name = 'docker_image_id' docker_image_id = fields.Many2one( 'infrastructure.docker_image', 'Docker Image', required=True, ) server_id = fields.Many2one( 'infrastructure.server', 'Server', required=True, ondelete='cascade', ) _sql_constraints = [ ('image_uniq', 'unique(docker_image_id, server_id)', 'Docker Image Must be Unique per server'), ] @api.multi def pull_image(self, context=None, detached=False): """ Tuvimos que ponerle el context porque desde la vista lo pasa sin enmascararlo en self""" self.server_id.get_env() image = self.docker_image_id image_name = image.pull_name # if any tag, pull the first one <|code_end|> . Use current file imports: from openerp import models, fields, api from .server import custom_sudo as sudo import logging and context (classes, functions, or code) from other files: # Path: infrastructure/models/server.py # def custom_sudo(command, user=False, group=False, dont_raise=False): # # TODO esto habria que pasrlo con *args, **kwargs # env.warn_only = True # if user and group: # res = sudo(command, user=user, group=group) # elif user: # res = sudo(command, user=user) # elif group: # res = sudo(command, group=group) # else: # res = sudo(command) # if res.failed: # if dont_raise: # _logger.warning(( # "Can not run command:\n%s\nThis is what we get:\n%s") % ( # res.real_command, unicode(res.stdout, 'utf-8'))) # else: # raise ValidationError(_( # "Can not run command:\n%s\nThis is what we get:\n%s") % ( # res.real_command, unicode(res.stdout, 'utf-8'))) # env.warn_only = False # return res . Output only the next line.
if image.tag_ids:
Predict the next line after this snippet: <|code_start|> start-stop-daemon --stop --quiet --pidfile /var/run/${NAME}.pid \ --oknodo sleep 1 start-stop-daemon --start --quiet --pidfile /var/run/${NAME}.pid \ --chuid ${USER} --background --make-pidfile \ --exec ${DAEMON} -- --config=${CONFIG} \ echo "${NAME}." ;; restart-with-update) start-stop-daemon --stop --quiet --pidfile /var/run/${NAME}.pid \ --oknodo sleep 1 if [ -z ${2} ] then echo -n "Restarting ${DESC}: " start-stop-daemon --start --quiet --pidfile /var/run/${NAME}.pid \ --chuid ${USER} --background --make-pidfile \ --exec ${DAEMON} -- --config=${CONFIG} \ else if [ -z ${3} ] then echo -n "Restarting with update ${DESC} all modules on database ${2}: " <|code_end|> using the current file's imports: from openerp import models, fields, api, _ from openerp.exceptions import except_orm, ValidationError from .server import custom_sudo as sudo from fabric.contrib.files import exists, append, sed from erppeek import Client import os import re import logging import fabtools and any relevant context from other files: # Path: infrastructure/models/server.py # def custom_sudo(command, user=False, group=False, dont_raise=False): # # TODO esto habria que pasrlo con *args, **kwargs # env.warn_only = True # if user and group: # res = sudo(command, user=user, group=group) # elif user: # res = sudo(command, user=user) # elif group: # res = sudo(command, group=group) # else: # res = sudo(command) # if res.failed: # if dont_raise: # _logger.warning(( # "Can not run command:\n%s\nThis is what we get:\n%s") % ( # res.real_command, unicode(res.stdout, 'utf-8'))) # else: # raise ValidationError(_( # "Can not run command:\n%s\nThis is what we get:\n%s") % ( # res.real_command, unicode(res.stdout, 'utf-8'))) # env.warn_only = False # return res . Output only the next line.
start-stop-daemon --start --quiet --pidfile /var/run/${NAME}.pid \
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in module root # directory ############################################################################## _logger = logging.getLogger(__name__) _update_state_vals = [ ('unknown', 'Unknown'), ('init_and_conf_required', 'Init and Config Required'), ('update_required', 'Update Required'), ('optional_update', 'Optional Update'), ('on_to_install', 'On To Install'), ('on_to_remove', 'On To Remove'), ('on_to_upgrade', 'On To Upgrade'), <|code_end|> with the help of current file imports: from openerp import models, fields, api, SUPERUSER_ID, _ from openerp.exceptions import except_orm from openerp.tools.parse_version import parse_version from dateutil.relativedelta import relativedelta from openerp.addons.server_mode.mode import get_mode from datetime import datetime from datetime import date from .server import custom_sudo as sudo from fabric.contrib.files import exists, append, sed from erppeek import Client from openerp.exceptions import ValidationError import xmlrpclib import operator import socket import urlparse import urllib import time import uuid import os import requests import simplejson import logging and context from other files: # Path: infrastructure/models/server.py # def custom_sudo(command, user=False, group=False, dont_raise=False): # # TODO esto habria que pasrlo con *args, **kwargs # env.warn_only = True # if user and group: # res = sudo(command, user=user, group=group) # elif user: # res = sudo(command, user=user) # elif group: # res = sudo(command, group=group) # else: # res = sudo(command) # if res.failed: # if dont_raise: # _logger.warning(( # "Can not run command:\n%s\nThis is what we get:\n%s") % ( # res.real_command, unicode(res.stdout, 'utf-8'))) # else: # raise ValidationError(_( # "Can not run command:\n%s\nThis is what we get:\n%s") % ( # res.real_command, unicode(res.stdout, 'utf-8'))) # env.warn_only = False # return res , which may contain function names, class names, or code. Output only the next line.
('unmet_deps', 'Unmet Dependencies'),
Here is a snippet: <|code_start|> def cli(args=None) -> int: parser = argparse.ArgumentParser( prog='sismic-bdd', description='Command-line utility to execute Gherkin feature files using Behave.\n' 'Extra parameters will be passed to Behave.') parser.add_argument('statechart', metavar='statechart', type=str, help='A YAML file describing a statechart') parser.add_argument('--features', metavar='features', nargs='+', type=str, required=True, help='A list of files containing features') parser.add_argument('--steps', metavar='steps', nargs='+', type=str, help='A list of files containing steps implementation') parser.add_argument( '--properties', metavar='properties', nargs='+', type=str, help='A list of filepaths pointing to YAML property statecharts. They will be checked ' 'at runtime following a fail fast approach.') parser.add_argument( '--show-steps', action='store_true', default=False, help='Display a list of available steps (equivalent to Behave\'s --steps parameter') parser.add_argument('--debug-on-error', action='store_true', default=False, help='Drop in a debugger in case of step failure (ipdb if available)') args, parameters = parser.parse_known_args(args) <|code_end|> . Write the next line using the current file imports: import argparse import sys from ..io import import_from_yaml from .wrappers import execute_bdd and context from other files: # Path: sismic/io/yaml.py # def import_from_yaml( # text: str = None, filepath: str = None, *, ignore_schema: bool = False, # ignore_validation: bool = False) -> Statechart: # """ # Import a statechart from a YAML representation (first argument) or a YAML file (filepath # argument). # # Unless specified, the structure contained in the YAML is validated against a predefined # schema (see *sismic.io.SCHEMA*), and the resulting statechart is validated using its # *validate()* method. # # :param text: A YAML text. If not provided, filepath argument has to be provided. # :param filepath: A path to a YAML file. # :param ignore_schema: set to *True* to disable yaml validation. # :param ignore_validation: set to *True* to disable statechart validation. # :return: a *Statechart* instance # """ # if not text and not filepath: # raise TypeError( # 'A YAML must be provided, either using first argument or filepath argument.') # elif text and filepath: # raise TypeError('Either provide first argument or filepath argument, not both.') # elif filepath: # with open(filepath, 'r') as f: # text = f.read() # # if yaml.version_info < (0, 15): # data = yaml.safe_load(text) # type: dict # else: # yml = yaml.YAML(typ='safe', pure=True) # data = yml.load(text) # # if not ignore_schema: # try: # data = schema.Schema(SCHEMA.statechart).validate(data) # except schema.SchemaError as e: # raise StatechartError('YAML validation failed') from e # # sc = import_from_dict(data) # # if not ignore_validation: # sc.validate() # return sc # # Path: sismic/bdd/wrappers.py # def execute_bdd(statechart: Statechart, # feature_filepaths: List[str], # *, # step_filepaths: List[str] = None, # property_statecharts: List[Statechart] = None, # interpreter_klass: Callable[[Statechart], Interpreter] = Interpreter, # debug_on_error: bool = False, # behave_parameters: List[str] = None) -> int: # """ # Execute BDD tests for a statechart. # # :param statechart: statechart to test # :param feature_filepaths: list of filepaths to feature files. # :param step_filepaths: list of filepaths to step definitions. # :param property_statecharts: list of property statecharts # :param interpreter_klass: a callable that accepts a statechart and an optional clock # and returns an Interpreter # :param debug_on_error: set to True to drop to (i)pdb in case of error. # :param behave_parameters: additional CLI parameters used by Behave # (see http://behave.readthedocs.io/en/latest/behave.html#command-line-arguments) # :return: exit code of behave CLI. # """ # # Default values # step_filepaths = step_filepaths if step_filepaths else [] # property_statecharts = property_statecharts if property_statecharts else [] # behave_parameters = behave_parameters if behave_parameters else [] # # # If debug_on_error, disable captured stdout, otherwise it hangs # if debug_on_error and '--capture' not in behave_parameters: # behave_parameters.append('--no-capture') # # # Create temporary directory to put everything inside # with tempfile.TemporaryDirectory() as tempdir: # # Create configuration for Behave # config = Configuration(behave_parameters) # # # Paths to features # config.paths = feature_filepaths # # # Copy environment # with open(os.path.join(tempdir, 'environment.py'), 'w') as environment: # environment.write('from sismic.bdd.environment import *') # # # Path to environment # config.environment_file = os.path.join(tempdir, 'environment.py') # # # Add predefined steps # os.mkdir(os.path.join(tempdir, 'steps')) # with open(os.path.join(tempdir, 'steps', '__steps.py'), 'w') as step: # step.write('from sismic.bdd.steps import *') # # # Copy provided steps, if any # for step_filepath in step_filepaths: # shutil.copy(step_filepath, os.path.join( # tempdir, 'steps', os.path.split(step_filepath)[-1])) # # # Path to steps # config.steps_dir = os.path.join(tempdir, 'steps') # # # Put statechart and properties in user data # config.update_userdata({ # 'statechart': statechart, # 'interpreter_klass': interpreter_klass, # 'property_statecharts': property_statecharts, # 'debug_on_error': debug_on_error, # }) # # # Run behave # return run_behave(config) , which may include functions, classes, or code. Output only the next line.
if args.show_steps:
Here is a snippet: <|code_start|> def test_deprecated_interpreter(self, microwave): with pytest.warns(DeprecationWarning): microwave.bind_property_statechart(microwave) def test_synchronised_time(self, microwave, property_statechart): assert microwave.time == property_statechart.time microwave.clock.time += 10 assert microwave.time == property_statechart.time def test_empty_step(self, microwave, property_statechart): microwave.execute() assert property_statechart.queue.call_args_list[0][0][0] == MetaEvent('step started', time=0) assert property_statechart.queue.call_args_list[-1][0][0] == MetaEvent('step ended') for call in property_statechart.queue.call_args_list: assert isinstance(call[0][0], MetaEvent) def test_event_sent(self, microwave, property_statechart): # Add send to a state state = microwave.statechart.state_for('door closed') state.on_entry = 'send("test")' microwave.execute() assert MetaEvent('event sent', event=InternalEvent('test')) in [x[0][0] for x in property_statechart.queue.call_args_list] def test_meta_event_sent(self, microwave, property_statechart): # Add meta to a state state = microwave.statechart.state_for('door closed') <|code_end|> . Write the next line using the current file imports: import pytest from sismic.interpreter import Event, MetaEvent, InternalEvent from sismic.exceptions import PropertyStatechartError and context from other files: # Path: sismic/model/events.py # class Event: # """ # An event with a name and (optionally) some data passed as named parameters. # # The list of parameters can be obtained using *dir(event)*. Notice that # *name* and *data* are reserved names. If a *delay* parameter is provided, # then this event will be considered as a delayed event (and won't be # executed until given delay has elapsed). # # When two events are compared, they are considered equal if their names # and their data are equal. # # :param name: name of the event. # :param data: additional data passed as named parameters. # """ # # __slots__ = ['name', 'data'] # # def __init__(self, name: str, **additional_parameters: Any) -> None: # self.name = name # self.data = additional_parameters # # def __eq__(self, other): # if isinstance(other, Event): # return (self.name == other.name and self.data == other.data) # else: # return NotImplemented # # def __getattr__(self, attr): # try: # return self.data[attr] # except KeyError: # raise AttributeError('{} has no attribute {}'.format(self, attr)) # # def __getstate__(self): # # For pickle and implicitly for multiprocessing # return self.name, self.data # # def __setstate__(self, state): # # For pickle and implicitly for multiprocessing # self.name, self.data = state # # def __hash__(self): # return hash(self.name) # # def __dir__(self): # return ['name'] + list(self.data.keys()) # # def __repr__(self): # if self.data: # return '{}({!r}, {})'.format( # self.__class__.__name__, self.name, ', '.join( # '{}={!r}'.format(k, v) for k, v in self.data.items())) # else: # return '{}({!r})'.format(self.__class__.__name__, self.name) # # class InternalEvent(Event): # """ # Subclass of Event that represents an internal event. # """ # pass # # class MetaEvent(Event): # """ # Subclass of Event that represents a MetaEvent, as used in property statecharts. # """ # pass # # Path: sismic/exceptions.py # class PropertyStatechartError(SismicError): # """ # Raised when a property statechart reaches a final state. # # :param property_statechart: the property statechart that reaches a final state # """ # # def __init__(self, property_statechart): # super().__init__() # self._property = property_statechart # # @property # def property_statechart(self): # return self._property # # def __str__(self): # return '{}\nProperty is not satisfied, {} has reached a final state'.format( # self.__class__.__name__, self._property) , which may include functions, classes, or code. Output only the next line.
state.on_entry = 'notify("test", x=1, y="hello")'
Predict the next line after this snippet: <|code_start|> class TestInterpreterMetaEvents: @pytest.fixture def property_statechart(self, microwave, mocker): prop_sc = mocker.MagicMock(name='Interpreter', spec=microwave) prop_sc.queue = mocker.MagicMock(return_value=None) prop_sc.execute = mocker.MagicMock(return_value=None) prop_sc.final = False prop_sc.time = 0 def prop_sc_call(statechart, clock): return prop_sc # Bind it microwave.bind_property_statechart(None, interpreter_klass=prop_sc_call) return prop_sc def test_deprecated_interpreter(self, microwave): <|code_end|> using the current file's imports: import pytest from sismic.interpreter import Event, MetaEvent, InternalEvent from sismic.exceptions import PropertyStatechartError and any relevant context from other files: # Path: sismic/model/events.py # class Event: # """ # An event with a name and (optionally) some data passed as named parameters. # # The list of parameters can be obtained using *dir(event)*. Notice that # *name* and *data* are reserved names. If a *delay* parameter is provided, # then this event will be considered as a delayed event (and won't be # executed until given delay has elapsed). # # When two events are compared, they are considered equal if their names # and their data are equal. # # :param name: name of the event. # :param data: additional data passed as named parameters. # """ # # __slots__ = ['name', 'data'] # # def __init__(self, name: str, **additional_parameters: Any) -> None: # self.name = name # self.data = additional_parameters # # def __eq__(self, other): # if isinstance(other, Event): # return (self.name == other.name and self.data == other.data) # else: # return NotImplemented # # def __getattr__(self, attr): # try: # return self.data[attr] # except KeyError: # raise AttributeError('{} has no attribute {}'.format(self, attr)) # # def __getstate__(self): # # For pickle and implicitly for multiprocessing # return self.name, self.data # # def __setstate__(self, state): # # For pickle and implicitly for multiprocessing # self.name, self.data = state # # def __hash__(self): # return hash(self.name) # # def __dir__(self): # return ['name'] + list(self.data.keys()) # # def __repr__(self): # if self.data: # return '{}({!r}, {})'.format( # self.__class__.__name__, self.name, ', '.join( # '{}={!r}'.format(k, v) for k, v in self.data.items())) # else: # return '{}({!r})'.format(self.__class__.__name__, self.name) # # class InternalEvent(Event): # """ # Subclass of Event that represents an internal event. # """ # pass # # class MetaEvent(Event): # """ # Subclass of Event that represents a MetaEvent, as used in property statecharts. # """ # pass # # Path: sismic/exceptions.py # class PropertyStatechartError(SismicError): # """ # Raised when a property statechart reaches a final state. # # :param property_statechart: the property statechart that reaches a final state # """ # # def __init__(self, property_statechart): # super().__init__() # self._property = property_statechart # # @property # def property_statechart(self): # return self._property # # def __str__(self): # return '{}\nProperty is not satisfied, {} has reached a final state'.format( # self.__class__.__name__, self._property) . Output only the next line.
with pytest.warns(DeprecationWarning):
Based on the snippet: <|code_start|> microwave.execute() assert property_statechart.queue.call_args_list[0][0][0] == MetaEvent('step started', time=0) assert property_statechart.queue.call_args_list[-1][0][0] == MetaEvent('step ended') for call in property_statechart.queue.call_args_list: assert isinstance(call[0][0], MetaEvent) def test_event_sent(self, microwave, property_statechart): # Add send to a state state = microwave.statechart.state_for('door closed') state.on_entry = 'send("test")' microwave.execute() assert MetaEvent('event sent', event=InternalEvent('test')) in [x[0][0] for x in property_statechart.queue.call_args_list] def test_meta_event_sent(self, microwave, property_statechart): # Add meta to a state state = microwave.statechart.state_for('door closed') state.on_entry = 'notify("test", x=1, y="hello")' microwave.execute() assert MetaEvent('event sent', event=MetaEvent('test', x=1, y='hello')) not in [x[0][0] for x in property_statechart.queue.call_args_list] assert MetaEvent('test', x=1, y='hello') in [x[0][0] for x in property_statechart.queue.call_args_list] def test_trace(self, microwave, property_statechart): microwave.queue('door_opened') microwave.execute() <|code_end|> , predict the immediate next line with the help of imports: import pytest from sismic.interpreter import Event, MetaEvent, InternalEvent from sismic.exceptions import PropertyStatechartError and context (classes, functions, sometimes code) from other files: # Path: sismic/model/events.py # class Event: # """ # An event with a name and (optionally) some data passed as named parameters. # # The list of parameters can be obtained using *dir(event)*. Notice that # *name* and *data* are reserved names. If a *delay* parameter is provided, # then this event will be considered as a delayed event (and won't be # executed until given delay has elapsed). # # When two events are compared, they are considered equal if their names # and their data are equal. # # :param name: name of the event. # :param data: additional data passed as named parameters. # """ # # __slots__ = ['name', 'data'] # # def __init__(self, name: str, **additional_parameters: Any) -> None: # self.name = name # self.data = additional_parameters # # def __eq__(self, other): # if isinstance(other, Event): # return (self.name == other.name and self.data == other.data) # else: # return NotImplemented # # def __getattr__(self, attr): # try: # return self.data[attr] # except KeyError: # raise AttributeError('{} has no attribute {}'.format(self, attr)) # # def __getstate__(self): # # For pickle and implicitly for multiprocessing # return self.name, self.data # # def __setstate__(self, state): # # For pickle and implicitly for multiprocessing # self.name, self.data = state # # def __hash__(self): # return hash(self.name) # # def __dir__(self): # return ['name'] + list(self.data.keys()) # # def __repr__(self): # if self.data: # return '{}({!r}, {})'.format( # self.__class__.__name__, self.name, ', '.join( # '{}={!r}'.format(k, v) for k, v in self.data.items())) # else: # return '{}({!r})'.format(self.__class__.__name__, self.name) # # class InternalEvent(Event): # """ # Subclass of Event that represents an internal event. # """ # pass # # class MetaEvent(Event): # """ # Subclass of Event that represents a MetaEvent, as used in property statecharts. # """ # pass # # Path: sismic/exceptions.py # class PropertyStatechartError(SismicError): # """ # Raised when a property statechart reaches a final state. # # :param property_statechart: the property statechart that reaches a final state # """ # # def __init__(self, property_statechart): # super().__init__() # self._property = property_statechart # # @property # def property_statechart(self): # return self._property # # def __str__(self): # return '{}\nProperty is not satisfied, {} has reached a final state'.format( # self.__class__.__name__, self._property) . Output only the next line.
call_list = [
Given snippet: <|code_start|> class TestInterpreterMetaEvents: @pytest.fixture def property_statechart(self, microwave, mocker): prop_sc = mocker.MagicMock(name='Interpreter', spec=microwave) prop_sc.queue = mocker.MagicMock(return_value=None) prop_sc.execute = mocker.MagicMock(return_value=None) prop_sc.final = False prop_sc.time = 0 def prop_sc_call(statechart, clock): return prop_sc # Bind it microwave.bind_property_statechart(None, interpreter_klass=prop_sc_call) return prop_sc def test_deprecated_interpreter(self, microwave): with pytest.warns(DeprecationWarning): <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from sismic.interpreter import Event, MetaEvent, InternalEvent from sismic.exceptions import PropertyStatechartError and context: # Path: sismic/model/events.py # class Event: # """ # An event with a name and (optionally) some data passed as named parameters. # # The list of parameters can be obtained using *dir(event)*. Notice that # *name* and *data* are reserved names. If a *delay* parameter is provided, # then this event will be considered as a delayed event (and won't be # executed until given delay has elapsed). # # When two events are compared, they are considered equal if their names # and their data are equal. # # :param name: name of the event. # :param data: additional data passed as named parameters. # """ # # __slots__ = ['name', 'data'] # # def __init__(self, name: str, **additional_parameters: Any) -> None: # self.name = name # self.data = additional_parameters # # def __eq__(self, other): # if isinstance(other, Event): # return (self.name == other.name and self.data == other.data) # else: # return NotImplemented # # def __getattr__(self, attr): # try: # return self.data[attr] # except KeyError: # raise AttributeError('{} has no attribute {}'.format(self, attr)) # # def __getstate__(self): # # For pickle and implicitly for multiprocessing # return self.name, self.data # # def __setstate__(self, state): # # For pickle and implicitly for multiprocessing # self.name, self.data = state # # def __hash__(self): # return hash(self.name) # # def __dir__(self): # return ['name'] + list(self.data.keys()) # # def __repr__(self): # if self.data: # return '{}({!r}, {})'.format( # self.__class__.__name__, self.name, ', '.join( # '{}={!r}'.format(k, v) for k, v in self.data.items())) # else: # return '{}({!r})'.format(self.__class__.__name__, self.name) # # class InternalEvent(Event): # """ # Subclass of Event that represents an internal event. # """ # pass # # class MetaEvent(Event): # """ # Subclass of Event that represents a MetaEvent, as used in property statecharts. # """ # pass # # Path: sismic/exceptions.py # class PropertyStatechartError(SismicError): # """ # Raised when a property statechart reaches a final state. # # :param property_statechart: the property statechart that reaches a final state # """ # # def __init__(self, property_statechart): # super().__init__() # self._property = property_statechart # # @property # def property_statechart(self): # return self._property # # def __str__(self): # return '{}\nProperty is not satisfied, {} has reached a final state'.format( # self.__class__.__name__, self._property) which might include code, classes, or functions. Output only the next line.
microwave.bind_property_statechart(microwave)
Predict the next line after this snippet: <|code_start|> def test_writer(writer): writer.queue( Event('keyPress', key='bonjour '), Event('toggle'), Event('keyPress', key='a '), Event('toggle'), Event('toggle_bold'), Event('keyPress', key='tous !'), Event('leave') ) <|code_end|> using the current file's imports: import pytest import os from subprocess import check_call from sismic.interpreter import Event from sismic import testing and any relevant context from other files: # Path: sismic/model/events.py # class Event: # """ # An event with a name and (optionally) some data passed as named parameters. # # The list of parameters can be obtained using *dir(event)*. Notice that # *name* and *data* are reserved names. If a *delay* parameter is provided, # then this event will be considered as a delayed event (and won't be # executed until given delay has elapsed). # # When two events are compared, they are considered equal if their names # and their data are equal. # # :param name: name of the event. # :param data: additional data passed as named parameters. # """ # # __slots__ = ['name', 'data'] # # def __init__(self, name: str, **additional_parameters: Any) -> None: # self.name = name # self.data = additional_parameters # # def __eq__(self, other): # if isinstance(other, Event): # return (self.name == other.name and self.data == other.data) # else: # return NotImplemented # # def __getattr__(self, attr): # try: # return self.data[attr] # except KeyError: # raise AttributeError('{} has no attribute {}'.format(self, attr)) # # def __getstate__(self): # # For pickle and implicitly for multiprocessing # return self.name, self.data # # def __setstate__(self, state): # # For pickle and implicitly for multiprocessing # self.name, self.data = state # # def __hash__(self): # return hash(self.name) # # def __dir__(self): # return ['name'] + list(self.data.keys()) # # def __repr__(self): # if self.data: # return '{}({!r}, {})'.format( # self.__class__.__name__, self.name, ', '.join( # '{}={!r}'.format(k, v) for k, v in self.data.items())) # else: # return '{}({!r})'.format(self.__class__.__name__, self.name) # # Path: sismic/testing.py # def state_is_entered(steps: MacroSteps, name: str) -> bool: # def state_is_exited(steps: MacroSteps, name: str) -> bool: # def event_is_fired( # steps: MacroSteps, name: Optional[str], # parameters: Mapping[str, Any] = None) -> bool: # def event_is_consumed( # steps: MacroSteps, name: Optional[str], # parameters: Mapping[str, Any] = None) -> bool: # def transition_is_processed(steps: MacroSteps, transition: Optional[Transition] = None) -> bool: # def expression_holds(interpreter: Interpreter, expression: str) -> bool: . Output only the next line.
writer.execute()
Continue the code snippet: <|code_start|> def test_writer(writer): writer.queue( Event('keyPress', key='bonjour '), Event('toggle'), Event('keyPress', key='a '), Event('toggle'), Event('toggle_bold'), Event('keyPress', key='tous !'), Event('leave') <|code_end|> . Use current file imports: import pytest import os from subprocess import check_call from sismic.interpreter import Event from sismic import testing and context (classes, functions, or code) from other files: # Path: sismic/model/events.py # class Event: # """ # An event with a name and (optionally) some data passed as named parameters. # # The list of parameters can be obtained using *dir(event)*. Notice that # *name* and *data* are reserved names. If a *delay* parameter is provided, # then this event will be considered as a delayed event (and won't be # executed until given delay has elapsed). # # When two events are compared, they are considered equal if their names # and their data are equal. # # :param name: name of the event. # :param data: additional data passed as named parameters. # """ # # __slots__ = ['name', 'data'] # # def __init__(self, name: str, **additional_parameters: Any) -> None: # self.name = name # self.data = additional_parameters # # def __eq__(self, other): # if isinstance(other, Event): # return (self.name == other.name and self.data == other.data) # else: # return NotImplemented # # def __getattr__(self, attr): # try: # return self.data[attr] # except KeyError: # raise AttributeError('{} has no attribute {}'.format(self, attr)) # # def __getstate__(self): # # For pickle and implicitly for multiprocessing # return self.name, self.data # # def __setstate__(self, state): # # For pickle and implicitly for multiprocessing # self.name, self.data = state # # def __hash__(self): # return hash(self.name) # # def __dir__(self): # return ['name'] + list(self.data.keys()) # # def __repr__(self): # if self.data: # return '{}({!r}, {})'.format( # self.__class__.__name__, self.name, ', '.join( # '{}={!r}'.format(k, v) for k, v in self.data.items())) # else: # return '{}({!r})'.format(self.__class__.__name__, self.name) # # Path: sismic/testing.py # def state_is_entered(steps: MacroSteps, name: str) -> bool: # def state_is_exited(steps: MacroSteps, name: str) -> bool: # def event_is_fired( # steps: MacroSteps, name: Optional[str], # parameters: Mapping[str, Any] = None) -> bool: # def event_is_consumed( # steps: MacroSteps, name: Optional[str], # parameters: Mapping[str, Any] = None) -> bool: # def transition_is_processed(steps: MacroSteps, transition: Optional[Transition] = None) -> bool: # def expression_holds(interpreter: Interpreter, expression: str) -> bool: . Output only the next line.
)
Given snippet: <|code_start|> def test_speed_with_automatic(self, clock): clock.speed = 2 clock.start() sleep(0.1) assert clock.time >= 0.2 clock.stop() clock.time = 10 clock.speed = 0.1 clock.start() sleep(0.1) clock.stop() assert 10 < clock.time < 10.1 def test_start_stop(self, clock): clock.start() sleep(0.1) clock.stop() sleep(0.1) clock.start() sleep(0.1) clock.stop() assert 0.2 <= clock.time < 0.3 class TestUtcClock: @pytest.fixture() <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from time import sleep from sismic.clock import SimulatedClock, UtcClock, SynchronizedClock and context: # Path: sismic/clock/clock.py # class SimulatedClock(Clock): # """ # A simulated clock, starting from 0, that can be manually or automatically # incremented. # # Manual incrementation can be done by setting a new value to the time attribute. # Automatic incrementation occurs when start() is called, until stop() is called. # In that case, clock speed can be adjusted with the speed attribute. # A value strictly greater than 1 increases clock speed while a value strictly # lower than 1 slows down the clock. # """ # # def __init__(self) -> None: # self._base = time() # self._time = 0 # self._play = False # self._speed = 1 # # @property # def _elapsed(self): # return (time() - self._base) * self._speed if self._play else 0 # # def start(self) -> None: # """ # Clock will be automatically updated both based on real time and # its speed attribute. # """ # if not self._play: # self._base = time() # self._play = True # # def stop(self) -> None: # """ # Clock won't be automatically updated. # """ # if self._play: # self._time += self._elapsed # self._play = False # # @property # def speed(self) -> float: # """ # Speed of the current clock. Only affects time if start() is called. # """ # return self._speed # # @speed.setter # def speed(self, speed): # self._time += self._elapsed # self._base = time() # self._speed = speed # # @property # def time(self) -> float: # """ # Time value of this clock. # """ # return self._time + self._elapsed # # @time.setter # def time(self, new_time): # """ # Set the time of this clock. # # :param new_time: new time # """ # current_time = self.time # if new_time < current_time: # raise ValueError('Time must be monotonic, cannot change time from {} to {}'.format( # current_time, new_time)) # # self._time = new_time # self._base = time() # # def __str__(self): # return '{:.2f}'.format(float(self.time)) # # def __repr__(self): # return '{}[{:.2f},x{},{}]'.format( # self.__class__.__name__, # self.time, # self._speed, # '>' if self._play else '=', # ) # # class UtcClock(Clock): # """ # A clock that simulates a wall clock in UTC. # # The returned time value is based on Python time.time() function. # """ # # @property # def time(self) -> float: # return time() # # class SynchronizedClock(Clock): # """ # A clock that is synchronized with a given interpreter. # # The synchronization is based on the interpreter's internal time value, not # on its clock. As a consequence, the time value of a SynchronizedClock only # changes when the underlying interpreter is executed. # # :param interpreter: an interpreter instance # """ # # def __init__(self, interpreter) -> None: # self._interpreter = interpreter # # @property # def time(self) -> float: # return self._interpreter.time which might include code, classes, or functions. Output only the next line.
def clock(self):
Continue the code snippet: <|code_start|> assert clock.time >= 0.2 clock.stop() clock.time = 10 clock.speed = 0.1 clock.start() sleep(0.1) clock.stop() assert 10 < clock.time < 10.1 def test_start_stop(self, clock): clock.start() sleep(0.1) clock.stop() sleep(0.1) clock.start() sleep(0.1) clock.stop() assert 0.2 <= clock.time < 0.3 class TestUtcClock: @pytest.fixture() def clock(self): return UtcClock() def test_increase(self, clock): <|code_end|> . Use current file imports: import pytest from time import sleep from sismic.clock import SimulatedClock, UtcClock, SynchronizedClock and context (classes, functions, or code) from other files: # Path: sismic/clock/clock.py # class SimulatedClock(Clock): # """ # A simulated clock, starting from 0, that can be manually or automatically # incremented. # # Manual incrementation can be done by setting a new value to the time attribute. # Automatic incrementation occurs when start() is called, until stop() is called. # In that case, clock speed can be adjusted with the speed attribute. # A value strictly greater than 1 increases clock speed while a value strictly # lower than 1 slows down the clock. # """ # # def __init__(self) -> None: # self._base = time() # self._time = 0 # self._play = False # self._speed = 1 # # @property # def _elapsed(self): # return (time() - self._base) * self._speed if self._play else 0 # # def start(self) -> None: # """ # Clock will be automatically updated both based on real time and # its speed attribute. # """ # if not self._play: # self._base = time() # self._play = True # # def stop(self) -> None: # """ # Clock won't be automatically updated. # """ # if self._play: # self._time += self._elapsed # self._play = False # # @property # def speed(self) -> float: # """ # Speed of the current clock. Only affects time if start() is called. # """ # return self._speed # # @speed.setter # def speed(self, speed): # self._time += self._elapsed # self._base = time() # self._speed = speed # # @property # def time(self) -> float: # """ # Time value of this clock. # """ # return self._time + self._elapsed # # @time.setter # def time(self, new_time): # """ # Set the time of this clock. # # :param new_time: new time # """ # current_time = self.time # if new_time < current_time: # raise ValueError('Time must be monotonic, cannot change time from {} to {}'.format( # current_time, new_time)) # # self._time = new_time # self._base = time() # # def __str__(self): # return '{:.2f}'.format(float(self.time)) # # def __repr__(self): # return '{}[{:.2f},x{},{}]'.format( # self.__class__.__name__, # self.time, # self._speed, # '>' if self._play else '=', # ) # # class UtcClock(Clock): # """ # A clock that simulates a wall clock in UTC. # # The returned time value is based on Python time.time() function. # """ # # @property # def time(self) -> float: # return time() # # class SynchronizedClock(Clock): # """ # A clock that is synchronized with a given interpreter. # # The synchronization is based on the interpreter's internal time value, not # on its clock. As a consequence, the time value of a SynchronizedClock only # changes when the underlying interpreter is executed. # # :param interpreter: an interpreter instance # """ # # def __init__(self, interpreter) -> None: # self._interpreter = interpreter # # @property # def time(self) -> float: # return self._interpreter.time . Output only the next line.
current_time = clock.time
Based on the snippet: <|code_start|> def test_initial_value(self, clock): assert clock.time == 0 def test_manual_increment(self, clock): clock.time += 1 assert clock.time == 1 def test_monotonicity(self, clock): clock.time = 10 with pytest.raises(ValueError): clock.time = 0 def test_automatic_increment(self, clock): clock.start() sleep(0.1) assert clock.time >= 0.1 clock.stop() value = clock.time sleep(0.1) assert clock.time == value def test_increment(self, clock): clock.start() sleep(0.1) assert clock.time >= 0.1 clock.time = 10 assert 10 <= clock.time < 10.1 clock.stop() <|code_end|> , predict the immediate next line with the help of imports: import pytest from time import sleep from sismic.clock import SimulatedClock, UtcClock, SynchronizedClock and context (classes, functions, sometimes code) from other files: # Path: sismic/clock/clock.py # class SimulatedClock(Clock): # """ # A simulated clock, starting from 0, that can be manually or automatically # incremented. # # Manual incrementation can be done by setting a new value to the time attribute. # Automatic incrementation occurs when start() is called, until stop() is called. # In that case, clock speed can be adjusted with the speed attribute. # A value strictly greater than 1 increases clock speed while a value strictly # lower than 1 slows down the clock. # """ # # def __init__(self) -> None: # self._base = time() # self._time = 0 # self._play = False # self._speed = 1 # # @property # def _elapsed(self): # return (time() - self._base) * self._speed if self._play else 0 # # def start(self) -> None: # """ # Clock will be automatically updated both based on real time and # its speed attribute. # """ # if not self._play: # self._base = time() # self._play = True # # def stop(self) -> None: # """ # Clock won't be automatically updated. # """ # if self._play: # self._time += self._elapsed # self._play = False # # @property # def speed(self) -> float: # """ # Speed of the current clock. Only affects time if start() is called. # """ # return self._speed # # @speed.setter # def speed(self, speed): # self._time += self._elapsed # self._base = time() # self._speed = speed # # @property # def time(self) -> float: # """ # Time value of this clock. # """ # return self._time + self._elapsed # # @time.setter # def time(self, new_time): # """ # Set the time of this clock. # # :param new_time: new time # """ # current_time = self.time # if new_time < current_time: # raise ValueError('Time must be monotonic, cannot change time from {} to {}'.format( # current_time, new_time)) # # self._time = new_time # self._base = time() # # def __str__(self): # return '{:.2f}'.format(float(self.time)) # # def __repr__(self): # return '{}[{:.2f},x{},{}]'.format( # self.__class__.__name__, # self.time, # self._speed, # '>' if self._play else '=', # ) # # class UtcClock(Clock): # """ # A clock that simulates a wall clock in UTC. # # The returned time value is based on Python time.time() function. # """ # # @property # def time(self) -> float: # return time() # # class SynchronizedClock(Clock): # """ # A clock that is synchronized with a given interpreter. # # The synchronization is based on the interpreter's internal time value, not # on its clock. As a consequence, the time value of a SynchronizedClock only # changes when the underlying interpreter is executed. # # :param interpreter: an interpreter instance # """ # # def __init__(self, interpreter) -> None: # self._interpreter = interpreter # # @property # def time(self) -> float: # return self._interpreter.time . Output only the next line.
clock.time = 20
Here is a snippet: <|code_start|> def before_scenario(context, scenario): # Create interpreter statechart = context.config.userdata.get('statechart') interpreter_klass = context.config.userdata.get('interpreter_klass') context.interpreter = interpreter_klass(statechart) # Log trace context.trace = log_trace(context.interpreter) context._monitoring = False context.monitored_trace = None # Bind property statecharts for property_statechart in context.config.userdata.get('property_statecharts'): context.interpreter.bind_property_statechart( property_statechart, interpreter_klass=interpreter_klass) <|code_end|> . Write the next line using the current file imports: from sismic.helpers import log_trace import ipdb as pdb import pdb and context from other files: # Path: sismic/helpers.py # def log_trace(interpreter: Interpreter) -> List[MacroStep]: # """ # Return a list that will be populated by each value returned by the *execute_once* method # of given interpreter. # # :param interpreter: an *Interpreter* instance # :return: a list of *MacroStep* # """ # func = interpreter.execute_once # trace = [] # # @wraps(func) # def new_func(): # step = func() # if step: # trace.append(step) # return step # # interpreter.execute_once = new_func # type: ignore # return trace , which may include functions, classes, or code. Output only the next line.
def before_step(context, step):
Given the following code snippet before the placeholder: <|code_start|> raise exceptions.UnsupportedLibraryError(NO_CRYPTO_MSG) hasher = hashing.Hash(hashing.SHA1(), backend=backends.default_backend()) hasher.update(b'\x99') hasher.update(struct.pack(">H", len(pubkey_packet_data))) hasher.update(bytes(pubkey_packet_data)) return binascii.hexlify(hasher.finalize()).decode("ascii") def parse_subpacket_header(data): """ Parse out subpacket header as per RFC4880 5.2.3.1. Signature Subpacket Specification. """ # NOTE: Although the RFC does not state it explicitly, the length encoded # in the header must be greater equal 1, as it includes the mandatory # subpacket type octet. # Hence, passed bytearrays like [0] or [255, 0, 0, 0, 0], which encode a # subpacket length 0 are invalid. # The caller has to deal with the resulting IndexError. if data[0] < 192: length_len = 1 length = data[0] elif data[0] >= 192 and data[0] < 255: length_len = 2 length = ((data[0] - 192 << 8) + (data[1] + 192)) elif data[0] == 255: length_len = 5 length = struct.unpack(">I", data[1:length_len])[0] <|code_end|> , predict the next line using imports from the current file: import struct import binascii import re import logging from distutils.version import StrictVersion # pylint: disable=no-name-in-module,import-error from cryptography.hazmat import backends from cryptography.hazmat.primitives import hashes as hashing from securesystemslib import exceptions from securesystemslib import process from securesystemslib.gpg import constants from securesystemslib.gpg.exceptions import PacketParsingError and context including class names, function names, and sometimes code from other files: # Path: securesystemslib/exceptions.py # class Error(Exception): # class Warning(Warning): # class FormatError(Error): # class InvalidMetadataJSONError(FormatError): # class UnsupportedAlgorithmError(Error): # class BadHashError(Error): # class BadPasswordError(Error): # class CryptoError(Error): # class BadSignatureError(CryptoError): # class UnknownMethodError(CryptoError): # class UnsupportedLibraryError(Error): # class InvalidNameError(Error): # class NotFoundError(Error): # class URLMatchesNoPatternError(Error): # class InvalidConfigurationError(Error): # class StorageError(Error): # def __init__(self, exception): # def __str__(self): # def __init__(self, expected_hash, observed_hash): # def __str__(self): # def __init__(self, metadata_role_name): # def __str__(self): # # Path: securesystemslib/process.py # DEVNULL = subprocess.DEVNULL # PIPE = subprocess.PIPE # def _default_timeout(): # def run(cmd, check=True, timeout=_default_timeout(), **kwargs): # def run_duplicate_streams(cmd, timeout=_default_timeout()): # def _duplicate_streams(): # # Path: securesystemslib/gpg/constants.py # def is_available_gnupg(gnupg): # GPG_COMMAND = "" # HAVE_GPG = False # GPG_ENV_COMMAND = os.environ.get('GNUPG') # GPG2_COMMAND = "gpg2" # GPG1_COMMAND = "gpg" # GPG_COMMAND = GPG_ENV_COMMAND # GPG_COMMAND = GPG2_COMMAND # GPG_COMMAND = GPG1_COMMAND # HAVE_GPG = True # GPG_VERSION_COMMAND = GPG_COMMAND + " --version" # FULLY_SUPPORTED_MIN_VERSION = "2.1.0" # NO_GPG_MSG = "GPG support requires a GPG client. 'gpg2' or 'gpg' with version {} or newer is" \ # " fully supported.".format(FULLY_SUPPORTED_MIN_VERSION) # GPG_SIGN_COMMAND = GPG_COMMAND + \ # " --detach-sign --digest-algo SHA256 {keyarg} {homearg}" # GPG_EXPORT_PUBKEY_COMMAND = GPG_COMMAND + " {homearg} --export {keyid}" # PACKET_TYPE_SIGNATURE = 0x02 # PACKET_TYPE_PRIMARY_KEY = 0x06 # PACKET_TYPE_USER_ID = 0x0D # PACKET_TYPE_USER_ATTR = 0x11 # PACKET_TYPE_SUB_KEY = 0x0E # SUPPORTED_SIGNATURE_PACKET_VERSIONS = {0x04} # SUPPORTED_PUBKEY_PACKET_VERSIONS = {0x04} # SHA1 = 0x02 # SHA256 = 0x08 # SHA512 = 0x0A # SIGNATURE_TYPE_BINARY = 0x00 # SIGNATURE_TYPE_SUB_KEY_BINDING = 0x18 # SIGNATURE_TYPE_CERTIFICATES = {0x10, 0x11, 0x12, 0x13} # SIG_CREATION_SUBPACKET = 0x02 # PARTIAL_KEYID_SUBPACKET = 0x10 # KEY_EXPIRATION_SUBPACKET = 0x09 # PRIMARY_USERID_SUBPACKET = 0x19 # FULL_KEYID_SUBPACKET = 0x21 # # Path: securesystemslib/gpg/exceptions.py # class PacketParsingError(Exception): # pass . Output only the next line.
else: # pragma: no cover (unreachable)
Continue the code snippet: <|code_start|> """ if not CRYPTO: # pragma: no cover raise exceptions.UnsupportedLibraryError(NO_CRYPTO_MSG) hasher = hashing.Hash(hashing.SHA1(), backend=backends.default_backend()) hasher.update(b'\x99') hasher.update(struct.pack(">H", len(pubkey_packet_data))) hasher.update(bytes(pubkey_packet_data)) return binascii.hexlify(hasher.finalize()).decode("ascii") def parse_subpacket_header(data): """ Parse out subpacket header as per RFC4880 5.2.3.1. Signature Subpacket Specification. """ # NOTE: Although the RFC does not state it explicitly, the length encoded # in the header must be greater equal 1, as it includes the mandatory # subpacket type octet. # Hence, passed bytearrays like [0] or [255, 0, 0, 0, 0], which encode a # subpacket length 0 are invalid. # The caller has to deal with the resulting IndexError. if data[0] < 192: length_len = 1 length = data[0] elif data[0] >= 192 and data[0] < 255: length_len = 2 length = ((data[0] - 192 << 8) + (data[1] + 192)) elif data[0] == 255: length_len = 5 <|code_end|> . Use current file imports: import struct import binascii import re import logging from distutils.version import StrictVersion # pylint: disable=no-name-in-module,import-error from cryptography.hazmat import backends from cryptography.hazmat.primitives import hashes as hashing from securesystemslib import exceptions from securesystemslib import process from securesystemslib.gpg import constants from securesystemslib.gpg.exceptions import PacketParsingError and context (classes, functions, or code) from other files: # Path: securesystemslib/exceptions.py # class Error(Exception): # class Warning(Warning): # class FormatError(Error): # class InvalidMetadataJSONError(FormatError): # class UnsupportedAlgorithmError(Error): # class BadHashError(Error): # class BadPasswordError(Error): # class CryptoError(Error): # class BadSignatureError(CryptoError): # class UnknownMethodError(CryptoError): # class UnsupportedLibraryError(Error): # class InvalidNameError(Error): # class NotFoundError(Error): # class URLMatchesNoPatternError(Error): # class InvalidConfigurationError(Error): # class StorageError(Error): # def __init__(self, exception): # def __str__(self): # def __init__(self, expected_hash, observed_hash): # def __str__(self): # def __init__(self, metadata_role_name): # def __str__(self): # # Path: securesystemslib/process.py # DEVNULL = subprocess.DEVNULL # PIPE = subprocess.PIPE # def _default_timeout(): # def run(cmd, check=True, timeout=_default_timeout(), **kwargs): # def run_duplicate_streams(cmd, timeout=_default_timeout()): # def _duplicate_streams(): # # Path: securesystemslib/gpg/constants.py # def is_available_gnupg(gnupg): # GPG_COMMAND = "" # HAVE_GPG = False # GPG_ENV_COMMAND = os.environ.get('GNUPG') # GPG2_COMMAND = "gpg2" # GPG1_COMMAND = "gpg" # GPG_COMMAND = GPG_ENV_COMMAND # GPG_COMMAND = GPG2_COMMAND # GPG_COMMAND = GPG1_COMMAND # HAVE_GPG = True # GPG_VERSION_COMMAND = GPG_COMMAND + " --version" # FULLY_SUPPORTED_MIN_VERSION = "2.1.0" # NO_GPG_MSG = "GPG support requires a GPG client. 'gpg2' or 'gpg' with version {} or newer is" \ # " fully supported.".format(FULLY_SUPPORTED_MIN_VERSION) # GPG_SIGN_COMMAND = GPG_COMMAND + \ # " --detach-sign --digest-algo SHA256 {keyarg} {homearg}" # GPG_EXPORT_PUBKEY_COMMAND = GPG_COMMAND + " {homearg} --export {keyid}" # PACKET_TYPE_SIGNATURE = 0x02 # PACKET_TYPE_PRIMARY_KEY = 0x06 # PACKET_TYPE_USER_ID = 0x0D # PACKET_TYPE_USER_ATTR = 0x11 # PACKET_TYPE_SUB_KEY = 0x0E # SUPPORTED_SIGNATURE_PACKET_VERSIONS = {0x04} # SUPPORTED_PUBKEY_PACKET_VERSIONS = {0x04} # SHA1 = 0x02 # SHA256 = 0x08 # SHA512 = 0x0A # SIGNATURE_TYPE_BINARY = 0x00 # SIGNATURE_TYPE_SUB_KEY_BINDING = 0x18 # SIGNATURE_TYPE_CERTIFICATES = {0x10, 0x11, 0x12, 0x13} # SIG_CREATION_SUBPACKET = 0x02 # PARTIAL_KEYID_SUBPACKET = 0x10 # KEY_EXPIRATION_SUBPACKET = 0x09 # PRIMARY_USERID_SUBPACKET = 0x19 # FULL_KEYID_SUBPACKET = 0x21 # # Path: securesystemslib/gpg/exceptions.py # class PacketParsingError(Exception): # pass . Output only the next line.
length = struct.unpack(">I", data[1:length_len])[0]
Continue the code snippet: <|code_start|> hasher.update(bytes(pubkey_packet_data)) return binascii.hexlify(hasher.finalize()).decode("ascii") def parse_subpacket_header(data): """ Parse out subpacket header as per RFC4880 5.2.3.1. Signature Subpacket Specification. """ # NOTE: Although the RFC does not state it explicitly, the length encoded # in the header must be greater equal 1, as it includes the mandatory # subpacket type octet. # Hence, passed bytearrays like [0] or [255, 0, 0, 0, 0], which encode a # subpacket length 0 are invalid. # The caller has to deal with the resulting IndexError. if data[0] < 192: length_len = 1 length = data[0] elif data[0] >= 192 and data[0] < 255: length_len = 2 length = ((data[0] - 192 << 8) + (data[1] + 192)) elif data[0] == 255: length_len = 5 length = struct.unpack(">I", data[1:length_len])[0] else: # pragma: no cover (unreachable) raise PacketParsingError("Invalid subpacket header") return data[length_len], length_len + 1, length - 1, length_len + length <|code_end|> . Use current file imports: import struct import binascii import re import logging from distutils.version import StrictVersion # pylint: disable=no-name-in-module,import-error from cryptography.hazmat import backends from cryptography.hazmat.primitives import hashes as hashing from securesystemslib import exceptions from securesystemslib import process from securesystemslib.gpg import constants from securesystemslib.gpg.exceptions import PacketParsingError and context (classes, functions, or code) from other files: # Path: securesystemslib/exceptions.py # class Error(Exception): # class Warning(Warning): # class FormatError(Error): # class InvalidMetadataJSONError(FormatError): # class UnsupportedAlgorithmError(Error): # class BadHashError(Error): # class BadPasswordError(Error): # class CryptoError(Error): # class BadSignatureError(CryptoError): # class UnknownMethodError(CryptoError): # class UnsupportedLibraryError(Error): # class InvalidNameError(Error): # class NotFoundError(Error): # class URLMatchesNoPatternError(Error): # class InvalidConfigurationError(Error): # class StorageError(Error): # def __init__(self, exception): # def __str__(self): # def __init__(self, expected_hash, observed_hash): # def __str__(self): # def __init__(self, metadata_role_name): # def __str__(self): # # Path: securesystemslib/process.py # DEVNULL = subprocess.DEVNULL # PIPE = subprocess.PIPE # def _default_timeout(): # def run(cmd, check=True, timeout=_default_timeout(), **kwargs): # def run_duplicate_streams(cmd, timeout=_default_timeout()): # def _duplicate_streams(): # # Path: securesystemslib/gpg/constants.py # def is_available_gnupg(gnupg): # GPG_COMMAND = "" # HAVE_GPG = False # GPG_ENV_COMMAND = os.environ.get('GNUPG') # GPG2_COMMAND = "gpg2" # GPG1_COMMAND = "gpg" # GPG_COMMAND = GPG_ENV_COMMAND # GPG_COMMAND = GPG2_COMMAND # GPG_COMMAND = GPG1_COMMAND # HAVE_GPG = True # GPG_VERSION_COMMAND = GPG_COMMAND + " --version" # FULLY_SUPPORTED_MIN_VERSION = "2.1.0" # NO_GPG_MSG = "GPG support requires a GPG client. 'gpg2' or 'gpg' with version {} or newer is" \ # " fully supported.".format(FULLY_SUPPORTED_MIN_VERSION) # GPG_SIGN_COMMAND = GPG_COMMAND + \ # " --detach-sign --digest-algo SHA256 {keyarg} {homearg}" # GPG_EXPORT_PUBKEY_COMMAND = GPG_COMMAND + " {homearg} --export {keyid}" # PACKET_TYPE_SIGNATURE = 0x02 # PACKET_TYPE_PRIMARY_KEY = 0x06 # PACKET_TYPE_USER_ID = 0x0D # PACKET_TYPE_USER_ATTR = 0x11 # PACKET_TYPE_SUB_KEY = 0x0E # SUPPORTED_SIGNATURE_PACKET_VERSIONS = {0x04} # SUPPORTED_PUBKEY_PACKET_VERSIONS = {0x04} # SHA1 = 0x02 # SHA256 = 0x08 # SHA512 = 0x0A # SIGNATURE_TYPE_BINARY = 0x00 # SIGNATURE_TYPE_SUB_KEY_BINDING = 0x18 # SIGNATURE_TYPE_CERTIFICATES = {0x10, 0x11, 0x12, 0x13} # SIG_CREATION_SUBPACKET = 0x02 # PARTIAL_KEYID_SUBPACKET = 0x10 # KEY_EXPIRATION_SUBPACKET = 0x09 # PRIMARY_USERID_SUBPACKET = 0x19 # FULL_KEYID_SUBPACKET = 0x21 # # Path: securesystemslib/gpg/exceptions.py # class PacketParsingError(Exception): # pass . Output only the next line.
def parse_subpackets(data):
Using the snippet: <|code_start|> None <Returns> The RFC4880-compliant hashed buffer """ if not CRYPTO: # pragma: no cover raise exceptions.UnsupportedLibraryError(NO_CRYPTO_MSG) hasher = hashing.Hash(hashing.SHA1(), backend=backends.default_backend()) hasher.update(b'\x99') hasher.update(struct.pack(">H", len(pubkey_packet_data))) hasher.update(bytes(pubkey_packet_data)) return binascii.hexlify(hasher.finalize()).decode("ascii") def parse_subpacket_header(data): """ Parse out subpacket header as per RFC4880 5.2.3.1. Signature Subpacket Specification. """ # NOTE: Although the RFC does not state it explicitly, the length encoded # in the header must be greater equal 1, as it includes the mandatory # subpacket type octet. # Hence, passed bytearrays like [0] or [255, 0, 0, 0, 0], which encode a # subpacket length 0 are invalid. # The caller has to deal with the resulting IndexError. if data[0] < 192: length_len = 1 length = data[0] elif data[0] >= 192 and data[0] < 255: length_len = 2 <|code_end|> , determine the next line of code. You have imports: import struct import binascii import re import logging from distutils.version import StrictVersion # pylint: disable=no-name-in-module,import-error from cryptography.hazmat import backends from cryptography.hazmat.primitives import hashes as hashing from securesystemslib import exceptions from securesystemslib import process from securesystemslib.gpg import constants from securesystemslib.gpg.exceptions import PacketParsingError and context (class names, function names, or code) available: # Path: securesystemslib/exceptions.py # class Error(Exception): # class Warning(Warning): # class FormatError(Error): # class InvalidMetadataJSONError(FormatError): # class UnsupportedAlgorithmError(Error): # class BadHashError(Error): # class BadPasswordError(Error): # class CryptoError(Error): # class BadSignatureError(CryptoError): # class UnknownMethodError(CryptoError): # class UnsupportedLibraryError(Error): # class InvalidNameError(Error): # class NotFoundError(Error): # class URLMatchesNoPatternError(Error): # class InvalidConfigurationError(Error): # class StorageError(Error): # def __init__(self, exception): # def __str__(self): # def __init__(self, expected_hash, observed_hash): # def __str__(self): # def __init__(self, metadata_role_name): # def __str__(self): # # Path: securesystemslib/process.py # DEVNULL = subprocess.DEVNULL # PIPE = subprocess.PIPE # def _default_timeout(): # def run(cmd, check=True, timeout=_default_timeout(), **kwargs): # def run_duplicate_streams(cmd, timeout=_default_timeout()): # def _duplicate_streams(): # # Path: securesystemslib/gpg/constants.py # def is_available_gnupg(gnupg): # GPG_COMMAND = "" # HAVE_GPG = False # GPG_ENV_COMMAND = os.environ.get('GNUPG') # GPG2_COMMAND = "gpg2" # GPG1_COMMAND = "gpg" # GPG_COMMAND = GPG_ENV_COMMAND # GPG_COMMAND = GPG2_COMMAND # GPG_COMMAND = GPG1_COMMAND # HAVE_GPG = True # GPG_VERSION_COMMAND = GPG_COMMAND + " --version" # FULLY_SUPPORTED_MIN_VERSION = "2.1.0" # NO_GPG_MSG = "GPG support requires a GPG client. 'gpg2' or 'gpg' with version {} or newer is" \ # " fully supported.".format(FULLY_SUPPORTED_MIN_VERSION) # GPG_SIGN_COMMAND = GPG_COMMAND + \ # " --detach-sign --digest-algo SHA256 {keyarg} {homearg}" # GPG_EXPORT_PUBKEY_COMMAND = GPG_COMMAND + " {homearg} --export {keyid}" # PACKET_TYPE_SIGNATURE = 0x02 # PACKET_TYPE_PRIMARY_KEY = 0x06 # PACKET_TYPE_USER_ID = 0x0D # PACKET_TYPE_USER_ATTR = 0x11 # PACKET_TYPE_SUB_KEY = 0x0E # SUPPORTED_SIGNATURE_PACKET_VERSIONS = {0x04} # SUPPORTED_PUBKEY_PACKET_VERSIONS = {0x04} # SHA1 = 0x02 # SHA256 = 0x08 # SHA512 = 0x0A # SIGNATURE_TYPE_BINARY = 0x00 # SIGNATURE_TYPE_SUB_KEY_BINDING = 0x18 # SIGNATURE_TYPE_CERTIFICATES = {0x10, 0x11, 0x12, 0x13} # SIG_CREATION_SUBPACKET = 0x02 # PARTIAL_KEYID_SUBPACKET = 0x10 # KEY_EXPIRATION_SUBPACKET = 0x09 # PRIMARY_USERID_SUBPACKET = 0x19 # FULL_KEYID_SUBPACKET = 0x21 # # Path: securesystemslib/gpg/exceptions.py # class PacketParsingError(Exception): # pass . Output only the next line.
length = ((data[0] - 192 << 8) + (data[1] + 192))
Given the following code snippet before the placeholder: <|code_start|>GPG_DSA_PUBKEY_SCHEMA = _create_gpg_pubkey_with_subkey_schema( _GPG_DSA_PUBKEY_SCHEMA) GPG_ED25519_PUBKEYVAL_SCHEMA = SCHEMA.Object( object_name = "GPG_ED25519_PUBKEYVAL_SCHEMA", q = HEX_SCHEMA, ) # C.f. comment above _GPG_RSA_PUBKEY_SCHEMA definition _GPG_ED25519_PUBKEY_SCHEMA = SCHEMA.Object( object_name = "GPG_ED25519_PUBKEY_SCHEMA", type = SCHEMA.String("eddsa"), method = SCHEMA.String(GPG_ED25519_PUBKEY_METHOD_STRING), hashes = SCHEMA.ListOf(SCHEMA.String(GPG_HASH_ALGORITHM_STRING)), creation_time = SCHEMA.Optional(UNIX_TIMESTAMP_SCHEMA), validity_period = SCHEMA.Optional(SCHEMA.Integer(lo=0)), keyid = KEYID_SCHEMA, keyval = SCHEMA.Object( public = GPG_ED25519_PUBKEYVAL_SCHEMA, private = SCHEMA.String("") ) ) GPG_ED25519_PUBKEY_SCHEMA = _create_gpg_pubkey_with_subkey_schema( _GPG_ED25519_PUBKEY_SCHEMA) GPG_PUBKEY_SCHEMA = SCHEMA.OneOf([GPG_RSA_PUBKEY_SCHEMA, GPG_DSA_PUBKEY_SCHEMA, GPG_ED25519_PUBKEY_SCHEMA]) GPG_SIGNATURE_SCHEMA = SCHEMA.Object( object_name = "SIGNATURE_SCHEMA", <|code_end|> , predict the next line using imports from the current file: import binascii import calendar import re import datetime import time from securesystemslib import exceptions from securesystemslib import schema as SCHEMA and context including class names, function names, and sometimes code from other files: # Path: securesystemslib/exceptions.py # class Error(Exception): # class Warning(Warning): # class FormatError(Error): # class InvalidMetadataJSONError(FormatError): # class UnsupportedAlgorithmError(Error): # class BadHashError(Error): # class BadPasswordError(Error): # class CryptoError(Error): # class BadSignatureError(CryptoError): # class UnknownMethodError(CryptoError): # class UnsupportedLibraryError(Error): # class InvalidNameError(Error): # class NotFoundError(Error): # class URLMatchesNoPatternError(Error): # class InvalidConfigurationError(Error): # class StorageError(Error): # def __init__(self, exception): # def __str__(self): # def __init__(self, expected_hash, observed_hash): # def __str__(self): # def __init__(self, metadata_role_name): # def __str__(self): # # Path: securesystemslib/schema.py # class Schema: # class Any(Schema): # class String(Schema): # class AnyString(Schema): # class AnyNonemptyString(AnyString): # class AnyBytes(Schema): # class LengthString(Schema): # class LengthBytes(Schema): # class OneOf(Schema): # class AllOf(Schema): # class Boolean(Schema): # class ListOf(Schema): # class Integer(Schema): # class DictOf(Schema): # class Optional(Schema): # class Object(Schema): # class Struct(Schema): # class RegularExpression(Schema): # def matches(self, object): # def check_match(self, object): # def __init__(self): # def check_match(self, object): # def __init__(self, string): # def check_match(self, object): # def __init__(self): # def check_match(self, object): # def check_match(self, object): # def __init__(self): # def check_match(self, object): # def __init__(self, length): # def check_match(self, object): # def __init__(self, length): # def check_match(self, object): # def __init__(self, alternatives): # def check_match(self, object): # def __init__(self, required_schemas): # def check_match(self, object): # def __init__(self): # def check_match(self, object): # def __init__(self, schema, min_count=0, max_count=sys.maxsize, list_name='list'): # def check_match(self, object): # def __init__(self, lo = -2147483648, hi = 2147483647): # def check_match(self, object): # def __init__(self, key_schema, value_schema): # def check_match(self, object): # def __init__(self, schema): # def check_match(self, object): # def __init__(self, object_name='object', **required): # def check_match(self, object): # def __init__(self, sub_schemas, optional_schemas=None, allow_more=False, # struct_name='list'): # def check_match(self, object): # def __init__(self, pattern=None, modifiers=0, re_object=None, re_name=None): # def check_match(self, object): . Output only the next line.
keyid = KEYID_SCHEMA,
Based on the snippet: <|code_start|># An ed25519 key. ED25519KEY_SCHEMA = SCHEMA.Object( object_name = 'ED25519KEY_SCHEMA', keytype = SCHEMA.String('ed25519'), scheme = ED25519_SIG_SCHEMA, keyid = KEYID_SCHEMA, keyid_hash_algorithms = SCHEMA.Optional(HASHALGORITHMS_SCHEMA), keyval = KEYVAL_SCHEMA) # GPG key scheme definitions GPG_HASH_ALGORITHM_STRING = "pgp+SHA2" GPG_RSA_PUBKEY_METHOD_STRING = "pgp+rsa-pkcsv1.5" GPG_DSA_PUBKEY_METHOD_STRING = "pgp+dsa-fips-180-2" GPG_ED25519_PUBKEY_METHOD_STRING = "pgp+eddsa-ed25519" def _create_gpg_pubkey_with_subkey_schema(pubkey_schema): """Helper method to extend the passed public key schema with an optional dictionary of sub public keys "subkeys" with the same schema.""" schema = pubkey_schema subkey_schema_tuple = ("subkeys", SCHEMA.Optional( SCHEMA.DictOf( key_schema=KEYID_SCHEMA, value_schema=pubkey_schema ) ) ) # Any subclass of `securesystemslib.schema.Object` stores the schemas that # define the attributes of the object in its `_required` property, even if # such a schema is of type `Optional`. # TODO: Find a way that does not require to access a protected member <|code_end|> , predict the immediate next line with the help of imports: import binascii import calendar import re import datetime import time from securesystemslib import exceptions from securesystemslib import schema as SCHEMA and context (classes, functions, sometimes code) from other files: # Path: securesystemslib/exceptions.py # class Error(Exception): # class Warning(Warning): # class FormatError(Error): # class InvalidMetadataJSONError(FormatError): # class UnsupportedAlgorithmError(Error): # class BadHashError(Error): # class BadPasswordError(Error): # class CryptoError(Error): # class BadSignatureError(CryptoError): # class UnknownMethodError(CryptoError): # class UnsupportedLibraryError(Error): # class InvalidNameError(Error): # class NotFoundError(Error): # class URLMatchesNoPatternError(Error): # class InvalidConfigurationError(Error): # class StorageError(Error): # def __init__(self, exception): # def __str__(self): # def __init__(self, expected_hash, observed_hash): # def __str__(self): # def __init__(self, metadata_role_name): # def __str__(self): # # Path: securesystemslib/schema.py # class Schema: # class Any(Schema): # class String(Schema): # class AnyString(Schema): # class AnyNonemptyString(AnyString): # class AnyBytes(Schema): # class LengthString(Schema): # class LengthBytes(Schema): # class OneOf(Schema): # class AllOf(Schema): # class Boolean(Schema): # class ListOf(Schema): # class Integer(Schema): # class DictOf(Schema): # class Optional(Schema): # class Object(Schema): # class Struct(Schema): # class RegularExpression(Schema): # def matches(self, object): # def check_match(self, object): # def __init__(self): # def check_match(self, object): # def __init__(self, string): # def check_match(self, object): # def __init__(self): # def check_match(self, object): # def check_match(self, object): # def __init__(self): # def check_match(self, object): # def __init__(self, length): # def check_match(self, object): # def __init__(self, length): # def check_match(self, object): # def __init__(self, alternatives): # def check_match(self, object): # def __init__(self, required_schemas): # def check_match(self, object): # def __init__(self): # def check_match(self, object): # def __init__(self, schema, min_count=0, max_count=sys.maxsize, list_name='list'): # def check_match(self, object): # def __init__(self, lo = -2147483648, hi = 2147483647): # def check_match(self, object): # def __init__(self, key_schema, value_schema): # def check_match(self, object): # def __init__(self, schema): # def check_match(self, object): # def __init__(self, object_name='object', **required): # def check_match(self, object): # def __init__(self, sub_schemas, optional_schemas=None, allow_more=False, # struct_name='list'): # def check_match(self, object): # def __init__(self, pattern=None, modifiers=0, re_object=None, re_name=None): # def check_match(self, object): . Output only the next line.
schema._required.append(subkey_schema_tuple) # pylint: disable=protected-access
Given snippet: <|code_start|> Neither D801 nor DC0C are in the appropriate set. This form cannot be used to map to the character which is expressed as D801 DC0C in UTF-16, specifically U+1040C. This character can be correctly mapped by using the glyph name "u1040C. """ with pytest.raises(KeyError): name2unicode("uniD801DC0C") def test_name2unicode_uni_empty_string_long_lowercase(): """The name "uniD801DC0C" has a single component, which is mapped to an empty string Neither D801 nor DC0C are in the appropriate set. This form cannot be used to map to the character which is expressed as D801 DC0C in UTF-16, specifically U+1040C. This character can be correctly mapped by using the glyph name "u1040C.""" with pytest.raises(KeyError): name2unicode("uniD801DC0C") def test_name2unicode_uni_pua(): """ "Ogoneksmall" and "uniF6FB" both map to the string that corresponds to U+F6FB.""" assert "\uF6FB" == name2unicode("uniF6FB") <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest from pdfminer.encodingdb import name2unicode, EncodingDB from pdfminer.psparser import PSLiteral and context: # Path: pdfminer/encodingdb.py # def name2unicode(name: str) -> str: # """Converts Adobe glyph names to Unicode numbers. # # In contrast to the specification, this raises a KeyError instead of return # an empty string when the key is unknown. # This way the caller must explicitly define what to do # when there is not a match. # # Reference: # https://github.com/adobe-type-tools/agl-specification#2-the-mapping # # :returns unicode character if name resembles something, # otherwise a KeyError # """ # name = name.split(".")[0] # components = name.split("_") # # if len(components) > 1: # return "".join(map(name2unicode, components)) # # else: # if name in glyphname2unicode: # return glyphname2unicode[name] # # elif name.startswith("uni"): # name_without_uni = name.strip("uni") # # if HEXADECIMAL.match(name_without_uni) and len(name_without_uni) % 4 == 0: # unicode_digits = [ # int(name_without_uni[i : i + 4], base=16) # for i in range(0, len(name_without_uni), 4) # ] # for digit in unicode_digits: # raise_key_error_for_invalid_unicode(digit) # characters = map(chr, unicode_digits) # return "".join(characters) # # elif name.startswith("u"): # name_without_u = name.strip("u") # # if HEXADECIMAL.match(name_without_u) and 4 <= len(name_without_u) <= 6: # unicode_digit = int(name_without_u, base=16) # raise_key_error_for_invalid_unicode(unicode_digit) # return chr(unicode_digit) # # raise KeyError( # 'Could not convert unicode name "%s" to character because ' # "it does not match specification" % name # ) # # class EncodingDB: # # std2unicode: Dict[int, str] = {} # mac2unicode: Dict[int, str] = {} # win2unicode: Dict[int, str] = {} # pdf2unicode: Dict[int, str] = {} # for (name, std, mac, win, pdf) in ENCODING: # c = name2unicode(name) # if std: # std2unicode[std] = c # if mac: # mac2unicode[mac] = c # if win: # win2unicode[win] = c # if pdf: # pdf2unicode[pdf] = c # # encodings = { # "StandardEncoding": std2unicode, # "MacRomanEncoding": mac2unicode, # "WinAnsiEncoding": win2unicode, # "PDFDocEncoding": pdf2unicode, # } # # @classmethod # def get_encoding( # cls, name: str, diff: Optional[Iterable[object]] = None # ) -> Dict[int, str]: # cid2unicode = cls.encodings.get(name, cls.std2unicode) # if diff: # cid2unicode = cid2unicode.copy() # cid = 0 # for x in diff: # if isinstance(x, int): # cid = x # elif isinstance(x, PSLiteral): # try: # cid2unicode[cid] = name2unicode(cast(str, x.name)) # except (KeyError, ValueError) as e: # log.debug(str(e)) # cid += 1 # return cid2unicode # # Path: pdfminer/psparser.py # class PSLiteral(PSObject): # # """A class that represents a PostScript literal. # # Postscript literals are used as identifiers, such as # variable names, property names and dictionary keys. # Literals are case sensitive and denoted by a preceding # slash sign (e.g. "/Name") # # Note: Do not create an instance of PSLiteral directly. # Always use PSLiteralTable.intern(). # """ # # NameType = Union[str, bytes] # # def __init__(self, name: NameType) -> None: # self.name = name # # def __repr__(self) -> str: # name = self.name # return "/%r" % name which might include code, classes, or functions. Output only the next line.
def test_name2unicode_uni_pua_lowercase():
Based on the snippet: <|code_start|> Neither D801 nor DC0C are in the appropriate set. This form cannot be used to map to the character which is expressed as D801 DC0C in UTF-16, specifically U+1040C. This character can be correctly mapped by using the glyph name "u1040C. """ with pytest.raises(KeyError): name2unicode("uniD801DC0C") def test_name2unicode_uni_empty_string_long_lowercase(): """The name "uniD801DC0C" has a single component, which is mapped to an empty string Neither D801 nor DC0C are in the appropriate set. This form cannot be used to map to the character which is expressed as D801 DC0C in UTF-16, specifically U+1040C. This character can be correctly mapped by using the glyph name "u1040C.""" with pytest.raises(KeyError): name2unicode("uniD801DC0C") def test_name2unicode_uni_pua(): """ "Ogoneksmall" and "uniF6FB" both map to the string that corresponds to U+F6FB.""" assert "\uF6FB" == name2unicode("uniF6FB") <|code_end|> , predict the immediate next line with the help of imports: import pytest from pdfminer.encodingdb import name2unicode, EncodingDB from pdfminer.psparser import PSLiteral and context (classes, functions, sometimes code) from other files: # Path: pdfminer/encodingdb.py # def name2unicode(name: str) -> str: # """Converts Adobe glyph names to Unicode numbers. # # In contrast to the specification, this raises a KeyError instead of return # an empty string when the key is unknown. # This way the caller must explicitly define what to do # when there is not a match. # # Reference: # https://github.com/adobe-type-tools/agl-specification#2-the-mapping # # :returns unicode character if name resembles something, # otherwise a KeyError # """ # name = name.split(".")[0] # components = name.split("_") # # if len(components) > 1: # return "".join(map(name2unicode, components)) # # else: # if name in glyphname2unicode: # return glyphname2unicode[name] # # elif name.startswith("uni"): # name_without_uni = name.strip("uni") # # if HEXADECIMAL.match(name_without_uni) and len(name_without_uni) % 4 == 0: # unicode_digits = [ # int(name_without_uni[i : i + 4], base=16) # for i in range(0, len(name_without_uni), 4) # ] # for digit in unicode_digits: # raise_key_error_for_invalid_unicode(digit) # characters = map(chr, unicode_digits) # return "".join(characters) # # elif name.startswith("u"): # name_without_u = name.strip("u") # # if HEXADECIMAL.match(name_without_u) and 4 <= len(name_without_u) <= 6: # unicode_digit = int(name_without_u, base=16) # raise_key_error_for_invalid_unicode(unicode_digit) # return chr(unicode_digit) # # raise KeyError( # 'Could not convert unicode name "%s" to character because ' # "it does not match specification" % name # ) # # class EncodingDB: # # std2unicode: Dict[int, str] = {} # mac2unicode: Dict[int, str] = {} # win2unicode: Dict[int, str] = {} # pdf2unicode: Dict[int, str] = {} # for (name, std, mac, win, pdf) in ENCODING: # c = name2unicode(name) # if std: # std2unicode[std] = c # if mac: # mac2unicode[mac] = c # if win: # win2unicode[win] = c # if pdf: # pdf2unicode[pdf] = c # # encodings = { # "StandardEncoding": std2unicode, # "MacRomanEncoding": mac2unicode, # "WinAnsiEncoding": win2unicode, # "PDFDocEncoding": pdf2unicode, # } # # @classmethod # def get_encoding( # cls, name: str, diff: Optional[Iterable[object]] = None # ) -> Dict[int, str]: # cid2unicode = cls.encodings.get(name, cls.std2unicode) # if diff: # cid2unicode = cid2unicode.copy() # cid = 0 # for x in diff: # if isinstance(x, int): # cid = x # elif isinstance(x, PSLiteral): # try: # cid2unicode[cid] = name2unicode(cast(str, x.name)) # except (KeyError, ValueError) as e: # log.debug(str(e)) # cid += 1 # return cid2unicode # # Path: pdfminer/psparser.py # class PSLiteral(PSObject): # # """A class that represents a PostScript literal. # # Postscript literals are used as identifiers, such as # variable names, property names and dictionary keys. # Literals are case sensitive and denoted by a preceding # slash sign (e.g. "/Name") # # Note: Do not create an instance of PSLiteral directly. # Always use PSLiteralTable.intern(). # """ # # NameType = Union[str, bytes] # # def __init__(self, name: NameType) -> None: # self.name = name # # def __repr__(self) -> str: # name = self.name # return "/%r" % name . Output only the next line.
def test_name2unicode_uni_pua_lowercase():
Based on the snippet: <|code_start|> def test_name2unicode_u_with_4_digits(): """The components "Lcommaaccent," "uni013B," and "u013B" all map to the string U+013B""" assert "\u013B" == name2unicode("u013B") def test_name2unicode_u_with_4_digits_lowercase(): """The components "Lcommaaccent," "uni013B," and "u013B" all map to the string U+013B""" assert "\u013B" == name2unicode("u013b") def test_name2unicode_u_with_5_digits(): """The name "u1040C" has a single component, which is mapped to the string U+1040C""" assert "\U0001040C" == name2unicode("u1040C") def test_name2unicode_u_with_5_digits_lowercase(): """The name "u1040C" has a single component, which is mapped to the string U+1040C""" assert "\U0001040C" == name2unicode("u1040c") def test_name2unicode_multiple_components(): """The name "Lcommaaccent_uni20AC0308_u1040C.alternate" is mapped to the string U+013B U+20AC U+0308 U+1040C""" assert "\u013B\u20AC\u0308\U0001040C" == name2unicode( <|code_end|> , predict the immediate next line with the help of imports: import pytest from pdfminer.encodingdb import name2unicode, EncodingDB from pdfminer.psparser import PSLiteral and context (classes, functions, sometimes code) from other files: # Path: pdfminer/encodingdb.py # def name2unicode(name: str) -> str: # """Converts Adobe glyph names to Unicode numbers. # # In contrast to the specification, this raises a KeyError instead of return # an empty string when the key is unknown. # This way the caller must explicitly define what to do # when there is not a match. # # Reference: # https://github.com/adobe-type-tools/agl-specification#2-the-mapping # # :returns unicode character if name resembles something, # otherwise a KeyError # """ # name = name.split(".")[0] # components = name.split("_") # # if len(components) > 1: # return "".join(map(name2unicode, components)) # # else: # if name in glyphname2unicode: # return glyphname2unicode[name] # # elif name.startswith("uni"): # name_without_uni = name.strip("uni") # # if HEXADECIMAL.match(name_without_uni) and len(name_without_uni) % 4 == 0: # unicode_digits = [ # int(name_without_uni[i : i + 4], base=16) # for i in range(0, len(name_without_uni), 4) # ] # for digit in unicode_digits: # raise_key_error_for_invalid_unicode(digit) # characters = map(chr, unicode_digits) # return "".join(characters) # # elif name.startswith("u"): # name_without_u = name.strip("u") # # if HEXADECIMAL.match(name_without_u) and 4 <= len(name_without_u) <= 6: # unicode_digit = int(name_without_u, base=16) # raise_key_error_for_invalid_unicode(unicode_digit) # return chr(unicode_digit) # # raise KeyError( # 'Could not convert unicode name "%s" to character because ' # "it does not match specification" % name # ) # # class EncodingDB: # # std2unicode: Dict[int, str] = {} # mac2unicode: Dict[int, str] = {} # win2unicode: Dict[int, str] = {} # pdf2unicode: Dict[int, str] = {} # for (name, std, mac, win, pdf) in ENCODING: # c = name2unicode(name) # if std: # std2unicode[std] = c # if mac: # mac2unicode[mac] = c # if win: # win2unicode[win] = c # if pdf: # pdf2unicode[pdf] = c # # encodings = { # "StandardEncoding": std2unicode, # "MacRomanEncoding": mac2unicode, # "WinAnsiEncoding": win2unicode, # "PDFDocEncoding": pdf2unicode, # } # # @classmethod # def get_encoding( # cls, name: str, diff: Optional[Iterable[object]] = None # ) -> Dict[int, str]: # cid2unicode = cls.encodings.get(name, cls.std2unicode) # if diff: # cid2unicode = cid2unicode.copy() # cid = 0 # for x in diff: # if isinstance(x, int): # cid = x # elif isinstance(x, PSLiteral): # try: # cid2unicode[cid] = name2unicode(cast(str, x.name)) # except (KeyError, ValueError) as e: # log.debug(str(e)) # cid += 1 # return cid2unicode # # Path: pdfminer/psparser.py # class PSLiteral(PSObject): # # """A class that represents a PostScript literal. # # Postscript literals are used as identifiers, such as # variable names, property names and dictionary keys. # Literals are case sensitive and denoted by a preceding # slash sign (e.g. "/Name") # # Note: Do not create an instance of PSLiteral directly. # Always use PSLiteralTable.intern(). # """ # # NameType = Union[str, bytes] # # def __init__(self, name: NameType) -> None: # self.name = name # # def __repr__(self) -> str: # name = self.name # return "/%r" % name . Output only the next line.
"Lcommaaccent_uni20AC0308_u1040C.alternate"
Predict the next line after this snippet: <|code_start|> LITERAL_DEVICE_GRAY = LIT("DeviceGray") LITERAL_DEVICE_RGB = LIT("DeviceRGB") LITERAL_DEVICE_CMYK = LIT("DeviceCMYK") class PDFColorSpace: def __init__(self, name: str, ncomponents: int) -> None: self.name = name self.ncomponents = ncomponents def __repr__(self) -> str: return "<PDFColorSpace: %s, ncomponents=%d>" % (self.name, self.ncomponents) PREDEFINED_COLORSPACE: Dict[str, PDFColorSpace] = collections.OrderedDict() for (name, n) in [ ("DeviceGray", 1), # default value first ("CalRGB", 3), ("CalGray", 1), ("Lab", 3), ("DeviceRGB", 3), ("DeviceCMYK", 4), ("Separation", 1), ("Indexed", 1), <|code_end|> using the current file's imports: import collections from typing import Dict from .psparser import LIT and any relevant context from other files: # Path: pdfminer/psparser.py # LIT = PSLiteralTable.intern . Output only the next line.
("Pattern", 1),
Given the following code snippet before the placeholder: <|code_start|>def dehex(b): """decode('hex')""" return binascii.unhexlify(b) class TestAscii85: def test_ascii85decode(self): """The sample string is taken from: http://en.wikipedia.org/w/index.php?title=Ascii85""" assert ascii85decode(b"9jqo^BlbD-BleB1DJ+*+F(f,q") == b"Man is distinguished" assert ascii85decode(b"E,9)oF*2M7/c~>") == b"pleasure." def test_asciihexdecode(self): assert asciihexdecode(b"61 62 2e6364 65") == b"ab.cde" assert asciihexdecode(b"61 62 2e6364 657>") == b"ab.cdep" assert asciihexdecode(b"7>") == b"p" class TestArcfour: def test(self): assert hex(Arcfour(b"Key").process(b"Plaintext")) == b"bbf316e8d940af0ad3" assert hex(Arcfour(b"Wiki").process(b"pedia")) == b"1021bf0420" assert ( hex(Arcfour(b"Secret").process(b"Attack at dawn")) == b"45a01f645fc35b383552544b9bf5" ) class TestLzw: def test_lzwdecode(self): <|code_end|> , predict the next line using imports from the current file: import binascii from pdfminer.arcfour import Arcfour from pdfminer.ascii85 import asciihexdecode, ascii85decode from pdfminer.lzw import lzwdecode from pdfminer.runlength import rldecode and context including class names, function names, and sometimes code from other files: # Path: pdfminer/arcfour.py # class Arcfour: # def __init__(self, key: Sequence[int]) -> None: # # because Py3 range is not indexable # s = [i for i in range(256)] # j = 0 # klen = len(key) # for i in range(256): # j = (j + s[i] + key[i % klen]) % 256 # (s[i], s[j]) = (s[j], s[i]) # self.s = s # (self.i, self.j) = (0, 0) # # def process(self, data: bytes) -> bytes: # (i, j) = (self.i, self.j) # s = self.s # r = b"" # for c in iter(data): # i = (i + 1) % 256 # j = (j + s[i]) % 256 # (s[i], s[j]) = (s[j], s[i]) # k = s[(s[i] + s[j]) % 256] # r += bytes((c ^ k,)) # (self.i, self.j) = (i, j) # return r # # encrypt = decrypt = process # # Path: pdfminer/ascii85.py # def asciihexdecode(data: bytes) -> bytes: # """ # ASCIIHexDecode filter: PDFReference v1.4 section 3.3.1 # For each pair of ASCII hexadecimal digits (0-9 and A-F or a-f), the # ASCIIHexDecode filter produces one byte of binary data. All white-space # characters are ignored. A right angle bracket character (>) indicates # EOD. Any other characters will cause an error. If the filter encounters # the EOD marker after reading an odd number of hexadecimal digits, it # will behave as if a 0 followed the last digit. # """ # # def decode(x: bytes) -> bytes: # i = int(x, 16) # return bytes((i,)) # # out = b"" # for x in hex_re.findall(data): # out += decode(x) # # m = trail_re.search(data) # if m: # out += decode(m.group(1) + b"0") # return out # # def ascii85decode(data: bytes) -> bytes: # """ # In ASCII85 encoding, every four bytes are encoded with five ASCII # letters, using 85 different types of characters (as 256**4 < 85**5). # When the length of the original bytes is not a multiple of 4, a special # rule is used for round up. # # The Adobe's ASCII85 implementation is slightly different from # its original in handling the last characters. # # """ # n = b = 0 # out = b"" # for i in iter(data): # c = bytes((i,)) # if b"!" <= c and c <= b"u": # n += 1 # b = b * 85 + (ord(c) - 33) # if n == 5: # out += struct.pack(">L", b) # n = b = 0 # elif c == b"z": # assert n == 0, str(n) # out += b"\0\0\0\0" # elif c == b"~": # if n: # for _ in range(5 - n): # b = b * 85 + 84 # out += struct.pack(">L", b)[: n - 1] # break # return out # # Path: pdfminer/lzw.py # def lzwdecode(data: bytes) -> bytes: # fp = BytesIO(data) # s = LZWDecoder(fp).run() # return b"".join(s) # # Path: pdfminer/runlength.py # def rldecode(data: bytes) -> bytes: # """ # RunLength decoder (Adobe version) implementation based on PDF Reference # version 1.4 section 3.3.4: # The RunLengthDecode filter decodes data that has been encoded in a # simple byte-oriented format based on run length. The encoded data # is a sequence of runs, where each run consists of a length byte # followed by 1 to 128 bytes of data. If the length byte is in the # range 0 to 127, the following length + 1 (1 to 128) bytes are # copied literally during decompression. If length is in the range # 129 to 255, the following single byte is to be copied 257 - length # (2 to 128) times during decompression. A length value of 128 # denotes EOD. # """ # decoded = b"" # i = 0 # while i < len(data): # length = data[i] # if length == 128: # break # # if length >= 0 and length < 128: # for j in range(i + 1, (i + 1) + (length + 1)): # decoded += bytes((data[j],)) # i = (i + 1) + (length + 1) # # if length > 128: # run = bytes((data[i + 1],)) * (257 - length) # decoded += run # i = (i + 1) + 1 # # return decoded . Output only the next line.
assert (
Predict the next line for this snippet: <|code_start|>def dehex(b): """decode('hex')""" return binascii.unhexlify(b) class TestAscii85: def test_ascii85decode(self): """The sample string is taken from: http://en.wikipedia.org/w/index.php?title=Ascii85""" assert ascii85decode(b"9jqo^BlbD-BleB1DJ+*+F(f,q") == b"Man is distinguished" assert ascii85decode(b"E,9)oF*2M7/c~>") == b"pleasure." def test_asciihexdecode(self): assert asciihexdecode(b"61 62 2e6364 65") == b"ab.cde" assert asciihexdecode(b"61 62 2e6364 657>") == b"ab.cdep" assert asciihexdecode(b"7>") == b"p" class TestArcfour: def test(self): assert hex(Arcfour(b"Key").process(b"Plaintext")) == b"bbf316e8d940af0ad3" assert hex(Arcfour(b"Wiki").process(b"pedia")) == b"1021bf0420" assert ( hex(Arcfour(b"Secret").process(b"Attack at dawn")) == b"45a01f645fc35b383552544b9bf5" ) class TestLzw: def test_lzwdecode(self): <|code_end|> with the help of current file imports: import binascii from pdfminer.arcfour import Arcfour from pdfminer.ascii85 import asciihexdecode, ascii85decode from pdfminer.lzw import lzwdecode from pdfminer.runlength import rldecode and context from other files: # Path: pdfminer/arcfour.py # class Arcfour: # def __init__(self, key: Sequence[int]) -> None: # # because Py3 range is not indexable # s = [i for i in range(256)] # j = 0 # klen = len(key) # for i in range(256): # j = (j + s[i] + key[i % klen]) % 256 # (s[i], s[j]) = (s[j], s[i]) # self.s = s # (self.i, self.j) = (0, 0) # # def process(self, data: bytes) -> bytes: # (i, j) = (self.i, self.j) # s = self.s # r = b"" # for c in iter(data): # i = (i + 1) % 256 # j = (j + s[i]) % 256 # (s[i], s[j]) = (s[j], s[i]) # k = s[(s[i] + s[j]) % 256] # r += bytes((c ^ k,)) # (self.i, self.j) = (i, j) # return r # # encrypt = decrypt = process # # Path: pdfminer/ascii85.py # def asciihexdecode(data: bytes) -> bytes: # """ # ASCIIHexDecode filter: PDFReference v1.4 section 3.3.1 # For each pair of ASCII hexadecimal digits (0-9 and A-F or a-f), the # ASCIIHexDecode filter produces one byte of binary data. All white-space # characters are ignored. A right angle bracket character (>) indicates # EOD. Any other characters will cause an error. If the filter encounters # the EOD marker after reading an odd number of hexadecimal digits, it # will behave as if a 0 followed the last digit. # """ # # def decode(x: bytes) -> bytes: # i = int(x, 16) # return bytes((i,)) # # out = b"" # for x in hex_re.findall(data): # out += decode(x) # # m = trail_re.search(data) # if m: # out += decode(m.group(1) + b"0") # return out # # def ascii85decode(data: bytes) -> bytes: # """ # In ASCII85 encoding, every four bytes are encoded with five ASCII # letters, using 85 different types of characters (as 256**4 < 85**5). # When the length of the original bytes is not a multiple of 4, a special # rule is used for round up. # # The Adobe's ASCII85 implementation is slightly different from # its original in handling the last characters. # # """ # n = b = 0 # out = b"" # for i in iter(data): # c = bytes((i,)) # if b"!" <= c and c <= b"u": # n += 1 # b = b * 85 + (ord(c) - 33) # if n == 5: # out += struct.pack(">L", b) # n = b = 0 # elif c == b"z": # assert n == 0, str(n) # out += b"\0\0\0\0" # elif c == b"~": # if n: # for _ in range(5 - n): # b = b * 85 + 84 # out += struct.pack(">L", b)[: n - 1] # break # return out # # Path: pdfminer/lzw.py # def lzwdecode(data: bytes) -> bytes: # fp = BytesIO(data) # s = LZWDecoder(fp).run() # return b"".join(s) # # Path: pdfminer/runlength.py # def rldecode(data: bytes) -> bytes: # """ # RunLength decoder (Adobe version) implementation based on PDF Reference # version 1.4 section 3.3.4: # The RunLengthDecode filter decodes data that has been encoded in a # simple byte-oriented format based on run length. The encoded data # is a sequence of runs, where each run consists of a length byte # followed by 1 to 128 bytes of data. If the length byte is in the # range 0 to 127, the following length + 1 (1 to 128) bytes are # copied literally during decompression. If length is in the range # 129 to 255, the following single byte is to be copied 257 - length # (2 to 128) times during decompression. A length value of 128 # denotes EOD. # """ # decoded = b"" # i = 0 # while i < len(data): # length = data[i] # if length == 128: # break # # if length >= 0 and length < 128: # for j in range(i + 1, (i + 1) + (length + 1)): # decoded += bytes((data[j],)) # i = (i + 1) + (length + 1) # # if length > 128: # run = bytes((data[i + 1],)) * (257 - length) # decoded += run # i = (i + 1) + 1 # # return decoded , which may contain function names, class names, or code. Output only the next line.
assert (
Given the following code snippet before the placeholder: <|code_start|>def dehex(b): """decode('hex')""" return binascii.unhexlify(b) class TestAscii85: def test_ascii85decode(self): """The sample string is taken from: http://en.wikipedia.org/w/index.php?title=Ascii85""" assert ascii85decode(b"9jqo^BlbD-BleB1DJ+*+F(f,q") == b"Man is distinguished" assert ascii85decode(b"E,9)oF*2M7/c~>") == b"pleasure." def test_asciihexdecode(self): assert asciihexdecode(b"61 62 2e6364 65") == b"ab.cde" assert asciihexdecode(b"61 62 2e6364 657>") == b"ab.cdep" assert asciihexdecode(b"7>") == b"p" class TestArcfour: def test(self): assert hex(Arcfour(b"Key").process(b"Plaintext")) == b"bbf316e8d940af0ad3" assert hex(Arcfour(b"Wiki").process(b"pedia")) == b"1021bf0420" assert ( hex(Arcfour(b"Secret").process(b"Attack at dawn")) == b"45a01f645fc35b383552544b9bf5" ) class TestLzw: def test_lzwdecode(self): <|code_end|> , predict the next line using imports from the current file: import binascii from pdfminer.arcfour import Arcfour from pdfminer.ascii85 import asciihexdecode, ascii85decode from pdfminer.lzw import lzwdecode from pdfminer.runlength import rldecode and context including class names, function names, and sometimes code from other files: # Path: pdfminer/arcfour.py # class Arcfour: # def __init__(self, key: Sequence[int]) -> None: # # because Py3 range is not indexable # s = [i for i in range(256)] # j = 0 # klen = len(key) # for i in range(256): # j = (j + s[i] + key[i % klen]) % 256 # (s[i], s[j]) = (s[j], s[i]) # self.s = s # (self.i, self.j) = (0, 0) # # def process(self, data: bytes) -> bytes: # (i, j) = (self.i, self.j) # s = self.s # r = b"" # for c in iter(data): # i = (i + 1) % 256 # j = (j + s[i]) % 256 # (s[i], s[j]) = (s[j], s[i]) # k = s[(s[i] + s[j]) % 256] # r += bytes((c ^ k,)) # (self.i, self.j) = (i, j) # return r # # encrypt = decrypt = process # # Path: pdfminer/ascii85.py # def asciihexdecode(data: bytes) -> bytes: # """ # ASCIIHexDecode filter: PDFReference v1.4 section 3.3.1 # For each pair of ASCII hexadecimal digits (0-9 and A-F or a-f), the # ASCIIHexDecode filter produces one byte of binary data. All white-space # characters are ignored. A right angle bracket character (>) indicates # EOD. Any other characters will cause an error. If the filter encounters # the EOD marker after reading an odd number of hexadecimal digits, it # will behave as if a 0 followed the last digit. # """ # # def decode(x: bytes) -> bytes: # i = int(x, 16) # return bytes((i,)) # # out = b"" # for x in hex_re.findall(data): # out += decode(x) # # m = trail_re.search(data) # if m: # out += decode(m.group(1) + b"0") # return out # # def ascii85decode(data: bytes) -> bytes: # """ # In ASCII85 encoding, every four bytes are encoded with five ASCII # letters, using 85 different types of characters (as 256**4 < 85**5). # When the length of the original bytes is not a multiple of 4, a special # rule is used for round up. # # The Adobe's ASCII85 implementation is slightly different from # its original in handling the last characters. # # """ # n = b = 0 # out = b"" # for i in iter(data): # c = bytes((i,)) # if b"!" <= c and c <= b"u": # n += 1 # b = b * 85 + (ord(c) - 33) # if n == 5: # out += struct.pack(">L", b) # n = b = 0 # elif c == b"z": # assert n == 0, str(n) # out += b"\0\0\0\0" # elif c == b"~": # if n: # for _ in range(5 - n): # b = b * 85 + 84 # out += struct.pack(">L", b)[: n - 1] # break # return out # # Path: pdfminer/lzw.py # def lzwdecode(data: bytes) -> bytes: # fp = BytesIO(data) # s = LZWDecoder(fp).run() # return b"".join(s) # # Path: pdfminer/runlength.py # def rldecode(data: bytes) -> bytes: # """ # RunLength decoder (Adobe version) implementation based on PDF Reference # version 1.4 section 3.3.4: # The RunLengthDecode filter decodes data that has been encoded in a # simple byte-oriented format based on run length. The encoded data # is a sequence of runs, where each run consists of a length byte # followed by 1 to 128 bytes of data. If the length byte is in the # range 0 to 127, the following length + 1 (1 to 128) bytes are # copied literally during decompression. If length is in the range # 129 to 255, the following single byte is to be copied 257 - length # (2 to 128) times during decompression. A length value of 128 # denotes EOD. # """ # decoded = b"" # i = 0 # while i < len(data): # length = data[i] # if length == 128: # break # # if length >= 0 and length < 128: # for j in range(i + 1, (i + 1) + (length + 1)): # decoded += bytes((data[j],)) # i = (i + 1) + (length + 1) # # if length > 128: # run = bytes((data[i + 1],)) * (257 - length) # decoded += run # i = (i + 1) + 1 # # return decoded . Output only the next line.
assert (
Based on the snippet: <|code_start|>def hex(b): """encode('hex')""" return binascii.hexlify(b) def dehex(b): """decode('hex')""" return binascii.unhexlify(b) class TestAscii85: def test_ascii85decode(self): """The sample string is taken from: http://en.wikipedia.org/w/index.php?title=Ascii85""" assert ascii85decode(b"9jqo^BlbD-BleB1DJ+*+F(f,q") == b"Man is distinguished" assert ascii85decode(b"E,9)oF*2M7/c~>") == b"pleasure." def test_asciihexdecode(self): assert asciihexdecode(b"61 62 2e6364 65") == b"ab.cde" assert asciihexdecode(b"61 62 2e6364 657>") == b"ab.cdep" assert asciihexdecode(b"7>") == b"p" class TestArcfour: def test(self): assert hex(Arcfour(b"Key").process(b"Plaintext")) == b"bbf316e8d940af0ad3" assert hex(Arcfour(b"Wiki").process(b"pedia")) == b"1021bf0420" assert ( hex(Arcfour(b"Secret").process(b"Attack at dawn")) == b"45a01f645fc35b383552544b9bf5" <|code_end|> , predict the immediate next line with the help of imports: import binascii from pdfminer.arcfour import Arcfour from pdfminer.ascii85 import asciihexdecode, ascii85decode from pdfminer.lzw import lzwdecode from pdfminer.runlength import rldecode and context (classes, functions, sometimes code) from other files: # Path: pdfminer/arcfour.py # class Arcfour: # def __init__(self, key: Sequence[int]) -> None: # # because Py3 range is not indexable # s = [i for i in range(256)] # j = 0 # klen = len(key) # for i in range(256): # j = (j + s[i] + key[i % klen]) % 256 # (s[i], s[j]) = (s[j], s[i]) # self.s = s # (self.i, self.j) = (0, 0) # # def process(self, data: bytes) -> bytes: # (i, j) = (self.i, self.j) # s = self.s # r = b"" # for c in iter(data): # i = (i + 1) % 256 # j = (j + s[i]) % 256 # (s[i], s[j]) = (s[j], s[i]) # k = s[(s[i] + s[j]) % 256] # r += bytes((c ^ k,)) # (self.i, self.j) = (i, j) # return r # # encrypt = decrypt = process # # Path: pdfminer/ascii85.py # def asciihexdecode(data: bytes) -> bytes: # """ # ASCIIHexDecode filter: PDFReference v1.4 section 3.3.1 # For each pair of ASCII hexadecimal digits (0-9 and A-F or a-f), the # ASCIIHexDecode filter produces one byte of binary data. All white-space # characters are ignored. A right angle bracket character (>) indicates # EOD. Any other characters will cause an error. If the filter encounters # the EOD marker after reading an odd number of hexadecimal digits, it # will behave as if a 0 followed the last digit. # """ # # def decode(x: bytes) -> bytes: # i = int(x, 16) # return bytes((i,)) # # out = b"" # for x in hex_re.findall(data): # out += decode(x) # # m = trail_re.search(data) # if m: # out += decode(m.group(1) + b"0") # return out # # def ascii85decode(data: bytes) -> bytes: # """ # In ASCII85 encoding, every four bytes are encoded with five ASCII # letters, using 85 different types of characters (as 256**4 < 85**5). # When the length of the original bytes is not a multiple of 4, a special # rule is used for round up. # # The Adobe's ASCII85 implementation is slightly different from # its original in handling the last characters. # # """ # n = b = 0 # out = b"" # for i in iter(data): # c = bytes((i,)) # if b"!" <= c and c <= b"u": # n += 1 # b = b * 85 + (ord(c) - 33) # if n == 5: # out += struct.pack(">L", b) # n = b = 0 # elif c == b"z": # assert n == 0, str(n) # out += b"\0\0\0\0" # elif c == b"~": # if n: # for _ in range(5 - n): # b = b * 85 + 84 # out += struct.pack(">L", b)[: n - 1] # break # return out # # Path: pdfminer/lzw.py # def lzwdecode(data: bytes) -> bytes: # fp = BytesIO(data) # s = LZWDecoder(fp).run() # return b"".join(s) # # Path: pdfminer/runlength.py # def rldecode(data: bytes) -> bytes: # """ # RunLength decoder (Adobe version) implementation based on PDF Reference # version 1.4 section 3.3.4: # The RunLengthDecode filter decodes data that has been encoded in a # simple byte-oriented format based on run length. The encoded data # is a sequence of runs, where each run consists of a length byte # followed by 1 to 128 bytes of data. If the length byte is in the # range 0 to 127, the following length + 1 (1 to 128) bytes are # copied literally during decompression. If length is in the range # 129 to 255, the following single byte is to be copied 257 - length # (2 to 128) times during decompression. A length value of 128 # denotes EOD. # """ # decoded = b"" # i = 0 # while i < len(data): # length = data[i] # if length == 128: # break # # if length >= 0 and length < 128: # for j in range(i + 1, (i + 1) + (length + 1)): # decoded += bytes((data[j],)) # i = (i + 1) + (length + 1) # # if length > 128: # run = bytes((data[i + 1],)) * (257 - length) # decoded += run # i = (i + 1) + 1 # # return decoded . Output only the next line.
)
Here is a snippet: <|code_start|>def hex(b): """encode('hex')""" return binascii.hexlify(b) def dehex(b): """decode('hex')""" return binascii.unhexlify(b) class TestAscii85: def test_ascii85decode(self): """The sample string is taken from: http://en.wikipedia.org/w/index.php?title=Ascii85""" assert ascii85decode(b"9jqo^BlbD-BleB1DJ+*+F(f,q") == b"Man is distinguished" assert ascii85decode(b"E,9)oF*2M7/c~>") == b"pleasure." def test_asciihexdecode(self): assert asciihexdecode(b"61 62 2e6364 65") == b"ab.cde" assert asciihexdecode(b"61 62 2e6364 657>") == b"ab.cdep" assert asciihexdecode(b"7>") == b"p" class TestArcfour: def test(self): assert hex(Arcfour(b"Key").process(b"Plaintext")) == b"bbf316e8d940af0ad3" assert hex(Arcfour(b"Wiki").process(b"pedia")) == b"1021bf0420" assert ( hex(Arcfour(b"Secret").process(b"Attack at dawn")) == b"45a01f645fc35b383552544b9bf5" <|code_end|> . Write the next line using the current file imports: import binascii from pdfminer.arcfour import Arcfour from pdfminer.ascii85 import asciihexdecode, ascii85decode from pdfminer.lzw import lzwdecode from pdfminer.runlength import rldecode and context from other files: # Path: pdfminer/arcfour.py # class Arcfour: # def __init__(self, key: Sequence[int]) -> None: # # because Py3 range is not indexable # s = [i for i in range(256)] # j = 0 # klen = len(key) # for i in range(256): # j = (j + s[i] + key[i % klen]) % 256 # (s[i], s[j]) = (s[j], s[i]) # self.s = s # (self.i, self.j) = (0, 0) # # def process(self, data: bytes) -> bytes: # (i, j) = (self.i, self.j) # s = self.s # r = b"" # for c in iter(data): # i = (i + 1) % 256 # j = (j + s[i]) % 256 # (s[i], s[j]) = (s[j], s[i]) # k = s[(s[i] + s[j]) % 256] # r += bytes((c ^ k,)) # (self.i, self.j) = (i, j) # return r # # encrypt = decrypt = process # # Path: pdfminer/ascii85.py # def asciihexdecode(data: bytes) -> bytes: # """ # ASCIIHexDecode filter: PDFReference v1.4 section 3.3.1 # For each pair of ASCII hexadecimal digits (0-9 and A-F or a-f), the # ASCIIHexDecode filter produces one byte of binary data. All white-space # characters are ignored. A right angle bracket character (>) indicates # EOD. Any other characters will cause an error. If the filter encounters # the EOD marker after reading an odd number of hexadecimal digits, it # will behave as if a 0 followed the last digit. # """ # # def decode(x: bytes) -> bytes: # i = int(x, 16) # return bytes((i,)) # # out = b"" # for x in hex_re.findall(data): # out += decode(x) # # m = trail_re.search(data) # if m: # out += decode(m.group(1) + b"0") # return out # # def ascii85decode(data: bytes) -> bytes: # """ # In ASCII85 encoding, every four bytes are encoded with five ASCII # letters, using 85 different types of characters (as 256**4 < 85**5). # When the length of the original bytes is not a multiple of 4, a special # rule is used for round up. # # The Adobe's ASCII85 implementation is slightly different from # its original in handling the last characters. # # """ # n = b = 0 # out = b"" # for i in iter(data): # c = bytes((i,)) # if b"!" <= c and c <= b"u": # n += 1 # b = b * 85 + (ord(c) - 33) # if n == 5: # out += struct.pack(">L", b) # n = b = 0 # elif c == b"z": # assert n == 0, str(n) # out += b"\0\0\0\0" # elif c == b"~": # if n: # for _ in range(5 - n): # b = b * 85 + 84 # out += struct.pack(">L", b)[: n - 1] # break # return out # # Path: pdfminer/lzw.py # def lzwdecode(data: bytes) -> bytes: # fp = BytesIO(data) # s = LZWDecoder(fp).run() # return b"".join(s) # # Path: pdfminer/runlength.py # def rldecode(data: bytes) -> bytes: # """ # RunLength decoder (Adobe version) implementation based on PDF Reference # version 1.4 section 3.3.4: # The RunLengthDecode filter decodes data that has been encoded in a # simple byte-oriented format based on run length. The encoded data # is a sequence of runs, where each run consists of a length byte # followed by 1 to 128 bytes of data. If the length byte is in the # range 0 to 127, the following length + 1 (1 to 128) bytes are # copied literally during decompression. If length is in the range # 129 to 255, the following single byte is to be copied 257 - length # (2 to 128) times during decompression. A length value of 128 # denotes EOD. # """ # decoded = b"" # i = 0 # while i < len(data): # length = data[i] # if length == 128: # break # # if length >= 0 and length < 128: # for j in range(i + 1, (i + 1) + (length + 1)): # decoded += bytes((data[j],)) # i = (i + 1) + (length + 1) # # if length > 128: # run = bytes((data[i + 1],)) * (257 - length) # decoded += run # i = (i + 1) + 1 # # return decoded , which may include functions, classes, or code. Output only the next line.
)
Given snippet: <|code_start|> def test_font_size(): path = absolute_sample_path("font-size-test.pdf") for page in extract_pages(path): <|code_end|> , continue by predicting the next line. Consider current file imports: from helpers import absolute_sample_path from pdfminer.high_level import extract_pages from pdfminer.layout import LTChar, LTTextBox and context: # Path: pdfminer/high_level.py # def extract_pages( # pdf_file: FileOrName, # password: str = "", # page_numbers: Optional[Container[int]] = None, # maxpages: int = 0, # caching: bool = True, # laparams: Optional[LAParams] = None, # ) -> Iterator[LTPage]: # """Extract and yield LTPage objects # # :param pdf_file: Either a file path or a file-like object for the PDF file # to be worked on. # :param password: For encrypted PDFs, the password to decrypt. # :param page_numbers: List of zero-indexed page numbers to extract. # :param maxpages: The maximum number of pages to parse # :param caching: If resources should be cached # :param laparams: An LAParams object from pdfminer.layout. If None, uses # some default settings that often work well. # :return: # """ # if laparams is None: # laparams = LAParams() # # with open_filename(pdf_file, "rb") as fp: # fp = cast(BinaryIO, fp) # we opened in binary mode # resource_manager = PDFResourceManager(caching=caching) # device = PDFPageAggregator(resource_manager, laparams=laparams) # interpreter = PDFPageInterpreter(resource_manager, device) # for page in PDFPage.get_pages( # fp, page_numbers, maxpages=maxpages, password=password, caching=caching # ): # interpreter.process_page(page) # layout = device.get_result() # yield layout # # Path: pdfminer/layout.py # class LTChar(LTComponent, LTText): # """Actual letter in the text as a Unicode string.""" # # def __init__( # self, # matrix: Matrix, # font: PDFFont, # fontsize: float, # scaling: float, # rise: float, # text: str, # textwidth: float, # textdisp: Union[float, Tuple[Optional[float], float]], # ncs: PDFColorSpace, # graphicstate: PDFGraphicState, # ) -> None: # LTText.__init__(self) # self._text = text # self.matrix = matrix # self.fontname = font.fontname # self.ncs = ncs # self.graphicstate = graphicstate # self.adv = textwidth * fontsize * scaling # # compute the boundary rectangle. # if font.is_vertical(): # # vertical # assert isinstance(textdisp, tuple) # (vx, vy) = textdisp # if vx is None: # vx = fontsize * 0.5 # else: # vx = vx * fontsize * 0.001 # vy = (1000 - vy) * fontsize * 0.001 # bbox_lower_left = (-vx, vy + rise + self.adv) # bbox_upper_right = (-vx + fontsize, vy + rise) # else: # # horizontal # descent = font.get_descent() * fontsize # bbox_lower_left = (0, descent + rise) # bbox_upper_right = (self.adv, descent + rise + fontsize) # (a, b, c, d, e, f) = self.matrix # self.upright = 0 < a * d * scaling and b * c <= 0 # (x0, y0) = apply_matrix_pt(self.matrix, bbox_lower_left) # (x1, y1) = apply_matrix_pt(self.matrix, bbox_upper_right) # if x1 < x0: # (x0, x1) = (x1, x0) # if y1 < y0: # (y0, y1) = (y1, y0) # LTComponent.__init__(self, (x0, y0, x1, y1)) # if font.is_vertical(): # self.size = self.width # else: # self.size = self.height # return # # def __repr__(self) -> str: # return "<%s %s matrix=%s font=%r adv=%s text=%r>" % ( # self.__class__.__name__, # bbox2str(self.bbox), # matrix2str(self.matrix), # self.fontname, # self.adv, # self.get_text(), # ) # # def get_text(self) -> str: # return self._text # # def is_compatible(self, obj: object) -> bool: # """Returns True if two characters can coexist in the same line.""" # return True # # class LTTextBox(LTTextContainer[LTTextLine]): # """Represents a group of text chunks in a rectangular area. # # Note that this box is created by geometric analysis and does not # necessarily represents a logical boundary of the text. It contains a list # of LTTextLine objects. # """ # # def __init__(self) -> None: # LTTextContainer.__init__(self) # self.index: int = -1 # return # # def __repr__(self) -> str: # return "<%s(%s) %s %r>" % ( # self.__class__.__name__, # self.index, # bbox2str(self.bbox), # self.get_text(), # ) # # def get_writing_mode(self) -> str: # raise NotImplementedError which might include code, classes, or functions. Output only the next line.
for text_box in page:
Given snippet: <|code_start|> def test_font_size(): path = absolute_sample_path("font-size-test.pdf") for page in extract_pages(path): <|code_end|> , continue by predicting the next line. Consider current file imports: from helpers import absolute_sample_path from pdfminer.high_level import extract_pages from pdfminer.layout import LTChar, LTTextBox and context: # Path: pdfminer/high_level.py # def extract_pages( # pdf_file: FileOrName, # password: str = "", # page_numbers: Optional[Container[int]] = None, # maxpages: int = 0, # caching: bool = True, # laparams: Optional[LAParams] = None, # ) -> Iterator[LTPage]: # """Extract and yield LTPage objects # # :param pdf_file: Either a file path or a file-like object for the PDF file # to be worked on. # :param password: For encrypted PDFs, the password to decrypt. # :param page_numbers: List of zero-indexed page numbers to extract. # :param maxpages: The maximum number of pages to parse # :param caching: If resources should be cached # :param laparams: An LAParams object from pdfminer.layout. If None, uses # some default settings that often work well. # :return: # """ # if laparams is None: # laparams = LAParams() # # with open_filename(pdf_file, "rb") as fp: # fp = cast(BinaryIO, fp) # we opened in binary mode # resource_manager = PDFResourceManager(caching=caching) # device = PDFPageAggregator(resource_manager, laparams=laparams) # interpreter = PDFPageInterpreter(resource_manager, device) # for page in PDFPage.get_pages( # fp, page_numbers, maxpages=maxpages, password=password, caching=caching # ): # interpreter.process_page(page) # layout = device.get_result() # yield layout # # Path: pdfminer/layout.py # class LTChar(LTComponent, LTText): # """Actual letter in the text as a Unicode string.""" # # def __init__( # self, # matrix: Matrix, # font: PDFFont, # fontsize: float, # scaling: float, # rise: float, # text: str, # textwidth: float, # textdisp: Union[float, Tuple[Optional[float], float]], # ncs: PDFColorSpace, # graphicstate: PDFGraphicState, # ) -> None: # LTText.__init__(self) # self._text = text # self.matrix = matrix # self.fontname = font.fontname # self.ncs = ncs # self.graphicstate = graphicstate # self.adv = textwidth * fontsize * scaling # # compute the boundary rectangle. # if font.is_vertical(): # # vertical # assert isinstance(textdisp, tuple) # (vx, vy) = textdisp # if vx is None: # vx = fontsize * 0.5 # else: # vx = vx * fontsize * 0.001 # vy = (1000 - vy) * fontsize * 0.001 # bbox_lower_left = (-vx, vy + rise + self.adv) # bbox_upper_right = (-vx + fontsize, vy + rise) # else: # # horizontal # descent = font.get_descent() * fontsize # bbox_lower_left = (0, descent + rise) # bbox_upper_right = (self.adv, descent + rise + fontsize) # (a, b, c, d, e, f) = self.matrix # self.upright = 0 < a * d * scaling and b * c <= 0 # (x0, y0) = apply_matrix_pt(self.matrix, bbox_lower_left) # (x1, y1) = apply_matrix_pt(self.matrix, bbox_upper_right) # if x1 < x0: # (x0, x1) = (x1, x0) # if y1 < y0: # (y0, y1) = (y1, y0) # LTComponent.__init__(self, (x0, y0, x1, y1)) # if font.is_vertical(): # self.size = self.width # else: # self.size = self.height # return # # def __repr__(self) -> str: # return "<%s %s matrix=%s font=%r adv=%s text=%r>" % ( # self.__class__.__name__, # bbox2str(self.bbox), # matrix2str(self.matrix), # self.fontname, # self.adv, # self.get_text(), # ) # # def get_text(self) -> str: # return self._text # # def is_compatible(self, obj: object) -> bool: # """Returns True if two characters can coexist in the same line.""" # return True # # class LTTextBox(LTTextContainer[LTTextLine]): # """Represents a group of text chunks in a rectangular area. # # Note that this box is created by geometric analysis and does not # necessarily represents a logical boundary of the text. It contains a list # of LTTextLine objects. # """ # # def __init__(self) -> None: # LTTextContainer.__init__(self) # self.index: int = -1 # return # # def __repr__(self) -> str: # return "<%s(%s) %s %r>" % ( # self.__class__.__name__, # self.index, # bbox2str(self.bbox), # self.get_text(), # ) # # def get_writing_mode(self) -> str: # raise NotImplementedError which might include code, classes, or functions. Output only the next line.
for text_box in page:
Predict the next line for this snippet: <|code_start|> def run(filename, options=None): absolute_path = absolute_sample_path(filename) with TemporaryFilePath() as output_file_name: if options: s = "dumppdf -o %s %s %s" % (output_file_name, options, absolute_path) else: s = "dumppdf -o %s %s" % (output_file_name, absolute_path) dumppdf.main(s.split(" ")[1:]) class TestDumpPDF(unittest.TestCase): def test_simple1(self): run("simple1.pdf", "-t -a") def test_simple2(self): <|code_end|> with the help of current file imports: import unittest import pytest from helpers import absolute_sample_path from tempfilepath import TemporaryFilePath from tools import dumppdf and context from other files: # Path: tools/dumppdf.py # def dumppdf( # outfp: TextIO, # fname: str, # objids: Iterable[int], # pagenos: Container[int], # password: str = "", # dumpall: bool = False, # codec: Optional[str] = None, # extractdir: Optional[str] = None, # show_fallback_xref: bool = False, # ) -> None: # fp = open(fname, "rb") # parser = PDFParser(fp) # doc = PDFDocument(parser, password) # if objids: # for objid in objids: # obj = doc.getobj(objid) # dumpxml(outfp, obj, codec=codec) # if pagenos: # for (pageno, page) in enumerate(PDFPage.create_pages(doc)): # if pageno in pagenos: # if codec: # for obj in page.contents: # obj = stream_value(obj) # dumpxml(outfp, obj, codec=codec) # else: # dumpxml(outfp, page.attrs) # if dumpall: # dumpallobjs(outfp, doc, codec, show_fallback_xref) # if (not objids) and (not pagenos) and (not dumpall): # dumptrailers(outfp, doc, show_fallback_xref) # fp.close() # if codec not in ("raw", "binary"): # outfp.write("\n") # return , which may contain function names, class names, or code. Output only the next line.
run("simple2.pdf", "-t -a")
Here is a snippet: <|code_start|># Copyright (c) 2015 Huawei Technologies India Pvt.Limited. # All Rights Reserved. # # 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. PORT_CHAIN_RESOURCE = 'port_chain' class PortChain(extension.NeutronClientExtension): resource = PORT_CHAIN_RESOURCE resource_plural = '%ss' % resource object_path = '/sfc/%s' % resource_plural resource_path = '/sfc/%s/%%s' % resource_plural <|code_end|> . Write the next line using the current file imports: from neutronclient.common import extension from neutronclient.common import utils from neutronclient.neutron import v2_0 as neutronv20 from networking_sfc._i18n import _ from networking_sfc.cli import flow_classifier as fc from networking_sfc.cli import port_pair_group as ppg and context from other files: # Path: networking_sfc/_i18n.py # DOMAIN = "networking_sfc" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_sfc/cli/flow_classifier.py # FLOW_CLASSIFIER_RESOURCE = 'flow_classifier' # def get_flowclassifier_id(client, id_or_name): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def _fill_protocol_port_info(self, body, port_type, port_val): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def extend_list(self, data, parsed_args): # def _get_protocol_port_details(self, data, type): # class FlowClassifier(extension.NeutronClientExtension): # class FlowClassifierCreate(extension.ClientExtensionCreate, # FlowClassifier): # class FlowClassifierUpdate(extension.ClientExtensionUpdate, # FlowClassifier): # class FlowClassifierDelete(extension.ClientExtensionDelete, # FlowClassifier): # class FlowClassifierList(extension.ClientExtensionList, # FlowClassifier): # class FlowClassifierShow(extension.ClientExtensionShow, FlowClassifier): # # Path: networking_sfc/cli/port_pair_group.py # PORT_PAIR_GROUP_RESOURCE = 'port_pair_group' # def get_port_pair_group_id(client, id_or_name): # def add_common_arguments(parser): # def update_common_args2body(client, body, parsed_args): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # class PortPairGroup(extension.NeutronClientExtension): # class PortPairGroupCreate(extension.ClientExtensionCreate, PortPairGroup): # class PortPairGroupUpdate(extension.ClientExtensionUpdate, PortPairGroup): # class PortPairGroupDelete(extension.ClientExtensionDelete, PortPairGroup): # class PortPairGroupList(extension.ClientExtensionList, PortPairGroup): # class PortPairGroupShow(extension.ClientExtensionShow, PortPairGroup): , which may include functions, classes, or code. Output only the next line.
versions = ['2.0']
Here is a snippet: <|code_start|># Copyright (c) 2015 Huawei Technologies India Pvt.Limited. # All Rights Reserved. # # 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. PORT_CHAIN_RESOURCE = 'port_chain' class PortChain(extension.NeutronClientExtension): resource = PORT_CHAIN_RESOURCE resource_plural = '%ss' % resource object_path = '/sfc/%s' % resource_plural <|code_end|> . Write the next line using the current file imports: from neutronclient.common import extension from neutronclient.common import utils from neutronclient.neutron import v2_0 as neutronv20 from networking_sfc._i18n import _ from networking_sfc.cli import flow_classifier as fc from networking_sfc.cli import port_pair_group as ppg and context from other files: # Path: networking_sfc/_i18n.py # DOMAIN = "networking_sfc" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_sfc/cli/flow_classifier.py # FLOW_CLASSIFIER_RESOURCE = 'flow_classifier' # def get_flowclassifier_id(client, id_or_name): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def _fill_protocol_port_info(self, body, port_type, port_val): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def extend_list(self, data, parsed_args): # def _get_protocol_port_details(self, data, type): # class FlowClassifier(extension.NeutronClientExtension): # class FlowClassifierCreate(extension.ClientExtensionCreate, # FlowClassifier): # class FlowClassifierUpdate(extension.ClientExtensionUpdate, # FlowClassifier): # class FlowClassifierDelete(extension.ClientExtensionDelete, # FlowClassifier): # class FlowClassifierList(extension.ClientExtensionList, # FlowClassifier): # class FlowClassifierShow(extension.ClientExtensionShow, FlowClassifier): # # Path: networking_sfc/cli/port_pair_group.py # PORT_PAIR_GROUP_RESOURCE = 'port_pair_group' # def get_port_pair_group_id(client, id_or_name): # def add_common_arguments(parser): # def update_common_args2body(client, body, parsed_args): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # class PortPairGroup(extension.NeutronClientExtension): # class PortPairGroupCreate(extension.ClientExtensionCreate, PortPairGroup): # class PortPairGroupUpdate(extension.ClientExtensionUpdate, PortPairGroup): # class PortPairGroupDelete(extension.ClientExtensionDelete, PortPairGroup): # class PortPairGroupList(extension.ClientExtensionList, PortPairGroup): # class PortPairGroupShow(extension.ClientExtensionShow, PortPairGroup): , which may include functions, classes, or code. Output only the next line.
resource_path = '/sfc/%s/%%s' % resource_plural
Here is a snippet: <|code_start|># Copyright (c) 2015 Huawei Technologies India Pvt.Limited. # All Rights Reserved. # # 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. PORT_CHAIN_RESOURCE = 'port_chain' class PortChain(extension.NeutronClientExtension): resource = PORT_CHAIN_RESOURCE resource_plural = '%ss' % resource object_path = '/sfc/%s' % resource_plural <|code_end|> . Write the next line using the current file imports: from neutronclient.common import extension from neutronclient.common import utils from neutronclient.neutron import v2_0 as neutronv20 from networking_sfc._i18n import _ from networking_sfc.cli import flow_classifier as fc from networking_sfc.cli import port_pair_group as ppg and context from other files: # Path: networking_sfc/_i18n.py # DOMAIN = "networking_sfc" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_sfc/cli/flow_classifier.py # FLOW_CLASSIFIER_RESOURCE = 'flow_classifier' # def get_flowclassifier_id(client, id_or_name): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def _fill_protocol_port_info(self, body, port_type, port_val): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def extend_list(self, data, parsed_args): # def _get_protocol_port_details(self, data, type): # class FlowClassifier(extension.NeutronClientExtension): # class FlowClassifierCreate(extension.ClientExtensionCreate, # FlowClassifier): # class FlowClassifierUpdate(extension.ClientExtensionUpdate, # FlowClassifier): # class FlowClassifierDelete(extension.ClientExtensionDelete, # FlowClassifier): # class FlowClassifierList(extension.ClientExtensionList, # FlowClassifier): # class FlowClassifierShow(extension.ClientExtensionShow, FlowClassifier): # # Path: networking_sfc/cli/port_pair_group.py # PORT_PAIR_GROUP_RESOURCE = 'port_pair_group' # def get_port_pair_group_id(client, id_or_name): # def add_common_arguments(parser): # def update_common_args2body(client, body, parsed_args): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # class PortPairGroup(extension.NeutronClientExtension): # class PortPairGroupCreate(extension.ClientExtensionCreate, PortPairGroup): # class PortPairGroupUpdate(extension.ClientExtensionUpdate, PortPairGroup): # class PortPairGroupDelete(extension.ClientExtensionDelete, PortPairGroup): # class PortPairGroupList(extension.ClientExtensionList, PortPairGroup): # class PortPairGroupShow(extension.ClientExtensionShow, PortPairGroup): , which may include functions, classes, or code. Output only the next line.
resource_path = '/sfc/%s/%%s' % resource_plural
Next line prediction: <|code_start|> base.RULE_ANY, 'Create a port chain', [ { 'method': 'POST', 'path': '/sfc/port_chains', }, ] ), policy.DocumentedRuleDefault( 'update_port_chain', base.RULE_ADMIN_OR_OWNER, 'Update a port chain', [ { 'method': 'PUT', 'path': '/sfc/port_chains/{id}', }, ] ), policy.DocumentedRuleDefault( 'delete_port_chain', base.RULE_ADMIN_OR_OWNER, 'Delete a port chain', [ { 'method': 'DELETE', 'path': '/sfc/port_chains/{id}', }, ] <|code_end|> . Use current file imports: (from oslo_policy import policy from networking_sfc.policies import base) and context including class names, function names, or small code snippets from other files: # Path: networking_sfc/policies/base.py # RULE_ADMIN_OR_OWNER = 'rule:admin_or_owner' # RULE_ADMIN_ONLY = 'rule:admin_only' # RULE_ANY = 'rule:regular_user' . Output only the next line.
),
Based on the snippet: <|code_start|># Copyright (c) 2015 Huawei Technologies India Pvt.Limited. # All Rights Reserved. # # 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. PORT_PAIR_GROUP_RESOURCE = 'port_pair_group' def get_port_pair_group_id(client, id_or_name): return neutronv20.find_resourceid_by_name_or_id(client, <|code_end|> , predict the immediate next line with the help of imports: from neutronclient.common import extension from neutronclient.common import utils from neutronclient.neutron import v2_0 as neutronv20 from networking_sfc._i18n import _ from networking_sfc.cli import port_pair as pp and context (classes, functions, sometimes code) from other files: # Path: networking_sfc/_i18n.py # DOMAIN = "networking_sfc" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_sfc/cli/port_pair.py # PORT_RESOURCE = 'port' # PORT_PAIR_RESOURCE = 'port_pair' # def get_port_id(client, id_or_name): # def get_port_pair_id(client, id_or_name): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # class PortPair(extension.NeutronClientExtension): # class PortPairCreate(extension.ClientExtensionCreate, PortPair): # class PortPairUpdate(extension.ClientExtensionUpdate, PortPair): # class PortPairDelete(extension.ClientExtensionDelete, PortPair): # class PortPairList(extension.ClientExtensionList, PortPair): # class PortPairShow(extension.ClientExtensionShow, PortPair): . Output only the next line.
PORT_PAIR_GROUP_RESOURCE,
Based on the 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. PORT_PAIR_GROUP_RESOURCE = 'port_pair_group' def get_port_pair_group_id(client, id_or_name): return neutronv20.find_resourceid_by_name_or_id(client, PORT_PAIR_GROUP_RESOURCE, id_or_name) class PortPairGroup(extension.NeutronClientExtension): resource = PORT_PAIR_GROUP_RESOURCE resource_plural = '%ss' % resource object_path = '/sfc/%s' % resource_plural resource_path = '/sfc/%s/%%s' % resource_plural versions = ['2.0'] def add_common_arguments(parser): parser.add_argument( '--description', help=_('Description for the Port Pair Group.')) parser.add_argument( '--port-pair', <|code_end|> , predict the immediate next line with the help of imports: from neutronclient.common import extension from neutronclient.common import utils from neutronclient.neutron import v2_0 as neutronv20 from networking_sfc._i18n import _ from networking_sfc.cli import port_pair as pp and context (classes, functions, sometimes code) from other files: # Path: networking_sfc/_i18n.py # DOMAIN = "networking_sfc" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_sfc/cli/port_pair.py # PORT_RESOURCE = 'port' # PORT_PAIR_RESOURCE = 'port_pair' # def get_port_id(client, id_or_name): # def get_port_pair_id(client, id_or_name): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # class PortPair(extension.NeutronClientExtension): # class PortPairCreate(extension.ClientExtensionCreate, PortPair): # class PortPairUpdate(extension.ClientExtensionUpdate, PortPair): # class PortPairDelete(extension.ClientExtensionDelete, PortPair): # class PortPairList(extension.ClientExtensionList, PortPair): # class PortPairShow(extension.ClientExtensionShow, PortPair): . Output only the next line.
metavar='PORT-PAIR',
Given the following code snippet before the placeholder: <|code_start|> policy.DocumentedRuleDefault( 'update_port_pair_group', base.RULE_ADMIN_OR_OWNER, 'Update a port pair group', [ { 'method': 'PUT', 'path': '/sfc/port_pair_groups/{id}', }, ] ), policy.DocumentedRuleDefault( 'delete_port_pair_group', base.RULE_ADMIN_OR_OWNER, 'Delete a port pair group', [ { 'method': 'DELETE', 'path': '/sfc/port_pair_groups/{id}', }, ] ), policy.DocumentedRuleDefault( 'get_port_pair_group', base.RULE_ADMIN_OR_OWNER, 'Get port pair groups', [ { 'method': 'GET', 'path': '/sfc/port_pair_groups', <|code_end|> , predict the next line using imports from the current file: from oslo_policy import policy from networking_sfc.policies import base and context including class names, function names, and sometimes code from other files: # Path: networking_sfc/policies/base.py # RULE_ADMIN_OR_OWNER = 'rule:admin_or_owner' # RULE_ADMIN_ONLY = 'rule:admin_only' # RULE_ANY = 'rule:regular_user' . Output only the next line.
},
Here is a 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. PORT_RESOURCE = 'port' PORT_PAIR_RESOURCE = 'port_pair' def get_port_id(client, id_or_name): return neutronv20.find_resourceid_by_name_or_id(client, PORT_RESOURCE, id_or_name) def get_port_pair_id(client, id_or_name): return neutronv20.find_resourceid_by_name_or_id(client, PORT_PAIR_RESOURCE, id_or_name) class PortPair(extension.NeutronClientExtension): resource = PORT_PAIR_RESOURCE resource_plural = '%ss' % resource <|code_end|> . Write the next line using the current file imports: from neutronclient.common import extension from neutronclient.common import utils from neutronclient.neutron import v2_0 as neutronv20 from networking_sfc._i18n import _ and context from other files: # Path: networking_sfc/_i18n.py # DOMAIN = "networking_sfc" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): , which may include functions, classes, or code. Output only the next line.
object_path = '/sfc/%s' % resource_plural
Predict the next line after this 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. # source_port_UUID = uuidutils.generate_uuid() destination_port_UUID = uuidutils.generate_uuid() class CLITestV20FCExtensionJSON(test_cli20.CLITestV20Base): def setUp(self): super(CLITestV20FCExtensionJSON, self).setUp() self._mock_extension_loading() self.register_non_admin_status_resource('flow_classifier') def _create_patch(self, name, func=None): patcher = mock.patch(name) thing = patcher.start() self.addCleanup(patcher.stop) return thing def _mock_extension_loading(self): <|code_end|> using the current file's imports: import sys from unittest import mock from neutronclient import shell from neutronclient.tests.unit import test_cli20 from networking_sfc.cli import flow_classifier as fc from oslo_utils import uuidutils and any relevant context from other files: # Path: networking_sfc/cli/flow_classifier.py # FLOW_CLASSIFIER_RESOURCE = 'flow_classifier' # def get_flowclassifier_id(client, id_or_name): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def _fill_protocol_port_info(self, body, port_type, port_val): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def extend_list(self, data, parsed_args): # def _get_protocol_port_details(self, data, type): # class FlowClassifier(extension.NeutronClientExtension): # class FlowClassifierCreate(extension.ClientExtensionCreate, # FlowClassifier): # class FlowClassifierUpdate(extension.ClientExtensionUpdate, # FlowClassifier): # class FlowClassifierDelete(extension.ClientExtensionDelete, # FlowClassifier): # class FlowClassifierList(extension.ClientExtensionList, # FlowClassifier): # class FlowClassifierShow(extension.ClientExtensionShow, FlowClassifier): . Output only the next line.
ext_pkg = 'neutronclient.common.extension'
Predict the next line after this snippet: <|code_start|># Copyright (c) 2015 Huawei Technologies India Pvt.Limited. # All Rights Reserved. # # 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. FLOW_CLASSIFIER_RESOURCE = 'flow_classifier' def get_flowclassifier_id(client, id_or_name): return neutronv20.find_resourceid_by_name_or_id(client, FLOW_CLASSIFIER_RESOURCE, id_or_name) class FlowClassifier(extension.NeutronClientExtension): resource = FLOW_CLASSIFIER_RESOURCE resource_plural = '%ss' % resource object_path = '/sfc/%s' % resource_plural <|code_end|> using the current file's imports: from neutronclient.common import extension from neutronclient.common import utils from neutronclient.neutron import v2_0 as neutronv20 from networking_sfc._i18n import _ from networking_sfc.cli import port_pair as pp and any relevant context from other files: # Path: networking_sfc/_i18n.py # DOMAIN = "networking_sfc" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): # # Path: networking_sfc/cli/port_pair.py # PORT_RESOURCE = 'port' # PORT_PAIR_RESOURCE = 'port_pair' # def get_port_id(client, id_or_name): # def get_port_pair_id(client, id_or_name): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # class PortPair(extension.NeutronClientExtension): # class PortPairCreate(extension.ClientExtensionCreate, PortPair): # class PortPairUpdate(extension.ClientExtensionUpdate, PortPair): # class PortPairDelete(extension.ClientExtensionDelete, PortPair): # class PortPairList(extension.ClientExtensionList, PortPair): # class PortPairShow(extension.ClientExtensionShow, PortPair): . Output only the next line.
resource_path = '/sfc/%s/%%s' % resource_plural
Based on the snippet: <|code_start|> [ { 'method': 'PUT', 'path': '/sfc/port_pairs/{id}', }, ] ), policy.DocumentedRuleDefault( 'delete_port_pair', base.RULE_ADMIN_OR_OWNER, 'Delete a port pair', [ { 'method': 'DELETE', 'path': '/sfc/port_pairs/{id}', }, ] ), policy.DocumentedRuleDefault( 'get_port_pair', base.RULE_ADMIN_OR_OWNER, 'Get port pairs', [ { 'method': 'GET', 'path': '/sfc/port_pairs', }, { 'method': 'GET', 'path': '/sfc/port_pairs/{id}', <|code_end|> , predict the immediate next line with the help of imports: from oslo_policy import policy from networking_sfc.policies import base and context (classes, functions, sometimes code) from other files: # Path: networking_sfc/policies/base.py # RULE_ADMIN_OR_OWNER = 'rule:admin_or_owner' # RULE_ADMIN_ONLY = 'rule:admin_only' # RULE_ANY = 'rule:regular_user' . Output only the next line.
},
Given the code 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. # EXTERNAL_TABLES should contain all names of tables that are not related to # current repo. EXTERNAL_TABLES = set(external.TABLES) VERSION_TABLE = 'alembic_version_sfc' class _TestModelsMigrationsSFC(test_migrations._TestModelsMigrations): def db_sync(self, engine): cfg.CONF.set_override('connection', engine.url, group='database') for conf in migration.get_alembic_configs(): self.alembic_config = conf self.alembic_config.neutron_config = cfg.CONF migration.do_alembic_command(conf, 'upgrade', 'heads') def get_metadata(self): return head.get_metadata() def include_object(self, object_, name, type_, reflected, compare_to): <|code_end|> , generate the next line using the imports in this file: from oslo_config import cfg from neutron.db.migration.alembic_migrations import external from neutron.db.migration import cli as migration from neutron.tests.functional.db import test_migrations from neutron.tests.unit import testlib_api from networking_sfc.db.migration.models import head and context (functions, classes, or occasionally code) from other files: # Path: networking_sfc/db/migration/models/head.py # def get_metadata(): . Output only the next line.
if type_ == 'table' and (name.startswith('alembic') or
Predict the next line for this snippet: <|code_start|> class SfcAgentExtensionTestCase(base.BaseTestCase): def setUp(self): super(SfcAgentExtensionTestCase, self).setUp() conn_patcher = mock.patch('neutron.agent.ovsdb.impl_idl._connection') conn_patcher.start() self.addCleanup(conn_patcher.stop) self.sfc_ext = sfc.SfcAgentExtension() self.context = context.get_admin_context() self.connection = mock.Mock() os_ken_app = mock.Mock() self.agent_api = ovs_ext_api.OVSAgentExtensionAPI( ovs_bridge.OVSAgentBridge('br-int', os_ken_app=os_ken_app), ovs_bridge.OVSAgentBridge('br-tun', os_ken_app=os_ken_app)) self.sfc_ext.consume_api(self.agent_api) # Don't rely on used driver mock.patch( 'neutron.manager.NeutronManager.load_class_for_provider', return_value=lambda: mock.Mock(spec=sfc.SfcAgentDriver) ).start() self.sfc_ext.initialize( self.connection, ovs_consts.EXTENSION_DRIVER_TYPE) def test_update_empty_flow_rules(self): <|code_end|> with the help of current file imports: from unittest import mock from neutron.plugins.ml2.drivers.openvswitch.agent import ( ovs_agent_extension_api as ovs_ext_api) from neutron.plugins.ml2.drivers.openvswitch.agent.openflow.native import ( ovs_bridge) from neutron.tests import base from neutron_lib import context from neutron_lib.plugins.ml2 import ovs_constants as ovs_consts from networking_sfc.services.sfc.agent.extensions import sfc and context from other files: # Path: networking_sfc/services/sfc/agent/extensions/sfc.py # LOG = logging.getLogger(__name__) # class SfcPluginApi(): # class SfcAgentDriver(metaclass=abc.ABCMeta): # class SfcAgentExtension(l2_extension.L2AgentExtension): # def __init__(self, topic, host): # def update_flowrules_status(self, context, flowrules_status): # def get_flowrules_by_host_portid(self, context, port_id): # def initialize(self): # def consume_api(self, agent_api): # def update_flow_rules(self, flowrule, flowrule_status): # def delete_flow_rule(self, flowrule, flowrule_status): # def initialize(self, connection, driver_type): # def consume_api(self, agent_api): # def handle_port(self, context, port): # def delete_port(self, context, port): # def update_flow_rules(self, context, **kwargs): # def delete_flow_rules(self, context, **kwargs): # def _sfc_setup_rpc(self): # def _delete_ports_flowrules_by_id(self, context, ports_id): , which may contain function names, class names, or code. Output only the next line.
self.sfc_ext.update_flow_rules(self.context, flowrule_entries={})
Given snippet: <|code_start|># Copyright 2015 Huawei Technologies India Pvt. Ltd. # All Rights Reserved # # 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. # FAKE_port_pair_group1_UUID = uuidutils.generate_uuid() FAKE_port_pair_group2_UUID = uuidutils.generate_uuid() FAKE_FC1_UUID = uuidutils.generate_uuid() FAKE_FC2_UUID = uuidutils.generate_uuid() FAKE_PARAM1_UUID = uuidutils.generate_uuid() FAKE_PARAM2_UUID = uuidutils.generate_uuid() class CLITestV20PortChainExtensionJSON(test_cli20.CLITestV20Base): <|code_end|> , continue by predicting the next line. Consider current file imports: import sys from unittest import mock from neutronclient import shell from neutronclient.tests.unit import test_cli20 from networking_sfc.cli import port_chain as pc from oslo_utils import uuidutils and context: # Path: networking_sfc/cli/port_chain.py # PORT_CHAIN_RESOURCE = 'port_chain' # class PortChain(extension.NeutronClientExtension): # class PortChainCreate(extension.ClientExtensionCreate, PortChain): # class PortChainUpdate(extension.ClientExtensionUpdate, PortChain): # class PortChainDelete(extension.ClientExtensionDelete, PortChain): # class PortChainList(extension.ClientExtensionList, PortChain): # class PortChainShow(extension.ClientExtensionShow, PortChain): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): # def add_known_arguments(self, parser): # def args2body(self, parsed_args): which might include code, classes, or functions. Output only the next line.
def setUp(self):
Using the snippet: <|code_start|> rules = [ policy.DocumentedRuleDefault( 'create_service_graph', base.RULE_ANY, 'Create a service graph', [ { 'method': 'POST', 'path': '/sfc/service_graphs', }, ] ), policy.DocumentedRuleDefault( 'update_service_graph', base.RULE_ADMIN_OR_OWNER, 'Update a service graph', [ { 'method': 'PUT', 'path': '/sfc/service_graphs/{id}', }, ] ), policy.DocumentedRuleDefault( 'delete_service_graph', base.RULE_ADMIN_OR_OWNER, <|code_end|> , determine the next line of code. You have imports: from oslo_policy import policy from networking_sfc.policies import base and context (class names, function names, or code) available: # Path: networking_sfc/policies/base.py # RULE_ADMIN_OR_OWNER = 'rule:admin_or_owner' # RULE_ADMIN_ONLY = 'rule:admin_only' # RULE_ANY = 'rule:regular_user' . Output only the next line.
'Delete a service graph',
Predict the next line for this 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. LOG = logging.getLogger(__name__) class SfcPluginApi(): def __init__(self, topic, host): self.host = host self.target = oslo_messaging.Target(topic=topic, version='1.0') self.client = n_rpc.get_client(self.target) def update_flowrules_status(self, context, flowrules_status): cctxt = self.client.prepare() return cctxt.call( context, 'update_flowrules_status', flowrules_status=flowrules_status) def get_flowrules_by_host_portid(self, context, port_id): cctxt = self.client.prepare() return cctxt.call( context, 'get_flowrules_by_host_portid', <|code_end|> with the help of current file imports: import abc import oslo_messaging from neutron.agent import rpc as agent_rpc from neutron import manager from neutron_lib.agent import l2_extension from neutron_lib.agent import topics from neutron_lib import rpc as n_rpc from oslo_config import cfg from oslo_log import log as logging from networking_sfc.services.sfc.drivers.ovs import rpc_topics as sfc_topics and context from other files: # Path: networking_sfc/services/sfc/drivers/ovs/rpc_topics.py # AGENT = 'q-agent-notifier' # SFC_PLUGIN = 'q-sfc-plugin' # SFC_AGENT = 'q-sfc-agent' # SFC_FLOW = 'q-sfc-flow' # PORTFLOW = 'portflowrule' , which may contain function names, class names, or code. Output only the next line.
host=self.host, port_id=port_id)
Predict the next line for this snippet: <|code_start|> ) def test_invalid_max_port(self): self.assertRaises( exceptions.InvalidInput, ovs_ext_lib.get_port_mask, 100, 65536 ) def test_invalid_port_range(self): self.assertRaises( exceptions.InvalidInput, ovs_ext_lib.get_port_mask, 100, 99 ) def test_one_port_mask(self): masks = ovs_ext_lib.get_port_mask(100, 101) self.assertEqual(['0x64/0xfffe'], masks) masks = ovs_ext_lib.get_port_mask(100, 103) self.assertEqual(['0x64/0xfffc'], masks) masks = ovs_ext_lib.get_port_mask(32768, 65535) self.assertEqual(['0x8000/0x8000'], masks) def test_multi_port_masks(self): masks = ovs_ext_lib.get_port_mask(101, 102) self.assertEqual(['0x65/0xffff', '0x66/0xffff'], masks) masks = ovs_ext_lib.get_port_mask(101, 104) self.assertEqual( ['0x65/0xffff', '0x66/0xfffe', '0x68/0xffff'], <|code_end|> with the help of current file imports: from neutron_lib import exceptions from neutron.tests import base from networking_sfc.services.sfc.common import ovs_ext_lib and context from other files: # Path: networking_sfc/services/sfc/common/ovs_ext_lib.py # LOG = logging.getLogger(__name__) # def get_port_mask(min_port, max_port): # def __init__(self, ovs_bridge): # def __getattr__(self, name): # def do_action_groups(self, action, kwargs_list): # def add_group(self, **kwargs): # def mod_group(self, **kwargs): # def delete_group(self, **kwargs): # def dump_group_for_id(self, group_id): # def get_bridge_ports(self): # def _build_group_expr_str(group_dict, cmd): # class SfcOVSBridgeExt(): , which may contain function names, class names, or code. Output only the next line.
masks
Based on the snippet: <|code_start|> 'method': 'POST', 'path': '/sfc/flow_classifiers', }, ] ), policy.DocumentedRuleDefault( 'update_flow_classifier', base.RULE_ADMIN_OR_OWNER, 'Update a flow classifier', [ { 'method': 'PUT', 'path': '/sfc/flow_classifiers/{id}', }, ] ), policy.DocumentedRuleDefault( 'delete_flow_classifier', base.RULE_ADMIN_OR_OWNER, 'Delete a flow classifier', [ { 'method': 'DELETE', 'path': '/sfc/flow_classifiers/{id}', }, ] ), policy.DocumentedRuleDefault( 'get_flow_classifier', base.RULE_ADMIN_OR_OWNER, <|code_end|> , predict the immediate next line with the help of imports: from oslo_policy import policy from networking_sfc.policies import base and context (classes, functions, sometimes code) from other files: # Path: networking_sfc/policies/base.py # RULE_ADMIN_OR_OWNER = 'rule:admin_or_owner' # RULE_ADMIN_ONLY = 'rule:admin_only' # RULE_ANY = 'rule:regular_user' . Output only the next line.
'Get flow classifiers',
Next line prediction: <|code_start|> 'mpls_label': 61641, 'priority': 1, 'table': 10 }], self.added_flows ) self.assertEqual( {}, self.group_mapping ) self.assertEqual( [{ 'eth_type': 34887, 'in_port': 42, 'mpls_label': 61640, 'priority': 30, 'table': 0, 'strict': True }], self.deleted_flows ) self.assertEqual( [], self.deleted_groups ) def test_reverse_ufr_lastsf_node_graph_dependency_same_h_a_nsh(self): # notice branch_point=False, which but could missing too, like in # test_update_flow_rules_sf_node_empty_next_hops_a_d_no_proxy() self._prepare_update_flow_rules_lastsf_node_graph_dependency_same_h_a( <|code_end|> . Use current file imports: (from unittest import mock from oslo_config import cfg from oslo_utils import importutils from oslo_utils import uuidutils from neutron.agent.common import ovs_lib from neutron.agent.common import utils from neutron.plugins.ml2.drivers.openvswitch.agent import ( ovs_agent_extension_api as ovs_ext_api) from neutron.plugins.ml2.drivers.openvswitch.agent.openflow.native import ( ovs_bridge) from neutron.tests.unit.plugins.ml2.drivers.openvswitch.agent import ( ovs_test_base) from networking_sfc.services.sfc.agent.extensions.openvswitch import sfc_driver from networking_sfc.services.sfc.common import ovs_ext_lib) and context including class names, function names, or small code snippets from other files: # Path: networking_sfc/services/sfc/agent/extensions/openvswitch/sfc_driver.py # LOG = logging.getLogger(__name__) # ACROSS_SUBNET_TABLE = 5 # INGRESS_TABLE = 10 # PC_DEF_PRI = 20 # PC_INGRESS_PRI = 30 # REVERSE_GROUP_NUMBER_OFFSET = 7000 # TAP_CLASSIFIER_TABLE = 7 # TAP_TUNNEL_OUTPUT_TABLE = 25 # RESUBMIT_TAP_TABLE = ',resubmit(,%s)' % TAP_CLASSIFIER_TABLE # NORMAL_ACTION = ",NORMAL" # class SfcOVSAgentDriver(sfc.SfcAgentDriver): # def __init__(self): # def consume_api(self, agent_api): # def initialize(self): # def update_flow_rules(self, flowrule, flowrule_status): # def delete_flow_rule(self, flowrule, flowrule_status): # def _clear_sfc_flow_on_int_br(self): # def _parse_flow_classifier(self, flow_classifier): # def _get_flow_infos_from_flow_classifier(self, flow_classifier, flowrule): # def _get_flow_infos_from_flow_classifier_list(self, flow_classifier_list, # flowrule): # def _match_by_header(self, match_info, nsp, nsi): # def _setup_local_switch_flows_on_int_br(self, flowrule, # flow_classifier_list, actions, # add_flow=True, match_inport=True): # def _setup_egress_flow_rules(self, flowrule, match_inport=True): # def _get_vlan_by_port(self, port_id): # def _setup_ingress_flow_rules(self, flowrule): # def _build_classification_match_sfc_mpls(self, flowrule, match_info): # def _build_classification_match_sfc_nsh(self, flowrule, match_info): # def _build_push_mpls(self, nsp, nsi): # def _build_push_nsh(self, nsp, nsi): # def _build_ingress_common_match_field(self, vif_port, vlan): # def _build_ingress_match_field_sfc_mpls(self, flowrule, vif_port, vlan): # def _build_ingress_match_field_sfc_nsh(self, flowrule, vif_port, vlan): # def _build_proxy_sfc_mpls(self, flowrule, vif_port, vlan): # def _build_proxy_sfc_nsh(self, flowrule, vif_port, vlan): # def _build_forward_sfc_mpls(self, flowrule, vif_port, vlan): # def _build_forward_sfc_nsh(self, flowrule, vif_port, vlan): # def _delete_flows_mpls(self, flowrule, vif_port): # def _add_group_table(self, buckets, flowrule, group_id): # def _configure_across_subnet_flow(self, flowrule, item, # subnet_actions_list, eth_type): # def _add_tap_classification_flows(self, flowrule, item, # subnet_actions_list): # def _get_eth_type(self, flowrule, item, ovs_rule): # def _configure_tunnel_bridge_flows(self, flowrule, item, vif_mac): # def _build_buckets(self, buckets, flowrule, item): # def _update_enc_actions(self, enc_actions, flow_rule, # next_hop_tap_enabled): # def _delete_across_subnet_table_flows(self, flowrule): # def _add_tap_ingress_flow(self, flowrule, vif_port, vlan): # def _build_tap_ingress_match_field_sfc_mpls(self, flowrule, vif_port, # vlan): # def _delete_tunnel_bridge_flows(self, flowrule, src_mac): # def _clear_sfc_flow_on_tun_br(self): # def _delete_flows_nsh(self, flowrule, vif_port): # # Path: networking_sfc/services/sfc/common/ovs_ext_lib.py # LOG = logging.getLogger(__name__) # def get_port_mask(min_port, max_port): # def __init__(self, ovs_bridge): # def __getattr__(self, name): # def do_action_groups(self, action, kwargs_list): # def add_group(self, **kwargs): # def mod_group(self, **kwargs): # def delete_group(self, **kwargs): # def dump_group_for_id(self, group_id): # def get_bridge_ports(self): # def _build_group_expr_str(group_dict, cmd): # class SfcOVSBridgeExt(): . Output only the next line.
'nsh', False)
Here is a snippet: <|code_start|> class PortPairDetailNotFound(n_exc.NotFound): message = _("Portchain port brief %(port_id)s could not be found") class NodeNotFound(n_exc.NotFound): message = _("Portchain node %(node_id)s could not be found") # name changed to ChainPathId class UuidIntidAssoc(model_base.BASEV2, model_base.HasId): __tablename__ = 'sfc_uuid_intid_associations' uuid = sa.Column(sa.String(36), primary_key=True) intid = sa.Column(sa.Integer, unique=True, nullable=False) type_ = sa.Column(sa.String(32), nullable=False) def __init__(self, uuid, intid, type_): self.uuid = uuid self.intid = intid self.type_ = type_ def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] <|code_end|> . Write the next line using the current file imports: from neutron_lib import context as n_context from neutron_lib.db import api as db_api from neutron_lib.db import model_base from neutron_lib.db import model_query from neutron_lib.db import utils as db_utils from neutron_lib import exceptions as n_exc from sqlalchemy import orm from sqlalchemy.orm import exc from sqlalchemy import sql from oslo_utils import uuidutils from networking_sfc._i18n import _ import sqlalchemy as sa and context from other files: # Path: networking_sfc/_i18n.py # DOMAIN = "networking_sfc" # _C = _translators.contextual_form # _P = _translators.plural_form # def get_available_languages(): , which may include functions, classes, or code. Output only the next line.
return getinstance