Instruction:
Implement a Python 3 function for
deleting the specified certificate assosciated with the Provisioning Service Certificate.

Response:
def delete(
            self, resource_group_name, if_match, provisioning_service_name, certificate_name, certificatename=None, certificateraw_bytes=None, certificateis_verified=None, certificatepurpose=None, certificatecreated=None, certificatelast_updated=None, certificatehas_private_key=None, certificatenonce=None, custom_headers=None, raw=False, **operation_config):
        """Delete the Provisioning Service Certificate.

        Deletes the specified certificate assosciated with the Provisioning
        Service.

        :param resource_group_name: Resource group identifier.
        :type resource_group_name: str
        :param if_match: ETag of the certificate
        :type if_match: str
        :param provisioning_service_name: The name of the provisioning
         service.
        :type provisioning_service_name: str
        :param certificate_name: This is a mandatory field, and is the logical
         name of the certificate that the provisioning service will access by.
        :type certificate_name: str
        :param certificatename: This is optional, and it is the Common Name of
         the certificate.
        :type certificatename: str
        :param certificateraw_bytes: Raw data within the certificate.
        :type certificateraw_bytes: bytearray
        :param certificateis_verified: Indicates if certificate has been
         verified by owner of the private key.
        :type certificateis_verified: bool
        :param certificatepurpose: A description that mentions the purpose of
         the certificate. Possible values include: 'clientAuthentication',
         'serverAuthentication'
        :type certificatepurpose: str or
         ~azure.mgmt.iothubprovisioningservices.models.CertificatePurpose
        :param certificatecreated: Time the certificate is created.
        :type certificatecreated: datetime
        :param certificatelast_updated: Time the certificate is last updated.
        :type certificatelast_updated: datetime
        :param certificatehas_private_key: Indicates if the certificate
         contains a private key.
        :type certificatehas_private_key: bool
        :param certificatenonce: Random number generated to indicate Proof of
         Possession.
        :type certificatenonce: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorDetailsException<azure.mgmt.iothubprovisioningservices.models.ErrorDetailsException>`
        """
        # Construct URL
        url = self.delete.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'provisioningServiceName': self._serialize.url("provisioning_service_name", provisioning_service_name, 'str'),
            'certificateName': self._serialize.url("certificate_name", certificate_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if certificatename is not None:
            query_parameters['certificate.name'] = self._serialize.query("certificatename", certificatename, 'str')
        if certificateraw_bytes is not None:
            query_parameters['certificate.rawBytes'] = self._serialize.query("certificateraw_bytes", certificateraw_bytes, 'bytearray')
        if certificateis_verified is not None:
            query_parameters['certificate.isVerified'] = self._serialize.query("certificateis_verified", certificateis_verified, 'bool')
        if certificatepurpose is not None:
            query_parameters['certificate.purpose'] = self._serialize.query("certificatepurpose", certificatepurpose, 'str')
        if certificatecreated is not None:
            query_parameters['certificate.created'] = self._serialize.query("certificatecreated", certificatecreated, 'iso-8601')
        if certificatelast_updated is not None:
            query_parameters['certificate.lastUpdated'] = self._serialize.query("certificatelast_updated", certificatelast_updated, 'iso-8601')
        if certificatehas_private_key is not None:
            query_parameters['certificate.hasPrivateKey'] = self._serialize.query("certificatehas_private_key", certificatehas_private_key, 'bool')
        if certificatenonce is not None:
            query_parameters['certificate.nonce'] = self._serialize.query("certificatenonce", certificatenonce, 'str')
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str')
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.delete(url, query_parameters)
        response = self._client.send(request, header_parameters, stream=False, **operation_config)

        if response.status_code not in [200, 204]:
            raise models.ErrorDetailsException(self._deserialize, response)

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response


Instruction:
Explain what the following Python 3 code does
def list(
            self, skiptoken=None, skip=None, top=None, select=None, search=None, filter=None, view=None, group_name=None, cache_control="no-cache", custom_headers=None, raw=False, **operation_config):
        """List all entities (Management Groups, Subscriptions, etc.) for the
        authenticated user.

        :param skiptoken: Page continuation token is only used if a previous
         operation returned a partial result. If a previous response contains a
         nextLink element, the value of the nextLink element will include a
         token parameter that specifies a starting point to use for subsequent
         calls.
        :type skiptoken: str
        :param skip: Number of entities to skip over when retrieving results.
         Passing this in will override $skipToken.
        :type skip: int
        :param top: Number of elements to return when retrieving results.
         Passing this in will override $skipToken.
        :type top: int
        :param select: This parameter specifies the fields to include in the
         response. Can include any combination of
         Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g.
         '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'.
         When specified the $select parameter can override select in
         $skipToken.
        :type select: str
        :param search: The $search parameter is used in conjunction with the
         $filter parameter to return three different outputs depending on the
         parameter passed in. With $search=AllowedParents the API will return
         the entity info of all groups that the requested entity will be able
         to reparent to as determined by the user's permissions. With
         $search=AllowedChildren the API will return the entity info of all
         entities that can be added as children of the requested entity. With
         $search=ParentAndFirstLevelChildren the API will return the parent and
         first level of children that the user has either direct access to or
         indirect access via one of their descendants. Possible values include:
         'AllowedParents', 'AllowedChildren', 'ParentAndFirstLevelChildren',
         'ParentOnly', 'ChildrenOnly'
        :type search: str
        :param filter: The filter parameter allows you to filter on the name
         or display name fields. You can check for equality on the name field
         (e.g. name eq '{entityName}')  and you can check for substrings on
         either the name or display name fields(e.g. contains(name,
         '{substringToSearch}'), contains(displayName, '{substringToSearch')).
         Note that the '{entityName}' and '{substringToSearch}' fields are
         checked case insensitively.
        :type filter: str
        :param view: The view parameter allows clients to filter the type of
         data that is returned by the getEntities call. Possible values
         include: 'FullHierarchy', 'GroupsOnly', 'SubscriptionsOnly', 'Audit'
        :type view: str
        :param group_name: A filter which allows the get entities call to
         focus on a particular group (i.e. "$filter=name eq 'groupName'")
        :type group_name: str
        :param cache_control: Indicates that the request shouldn't utilize any
         caches.
        :type cache_control: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of EntityInfo
        :rtype:
         ~azure.mgmt.managementgroups.models.EntityInfoPaged[~azure.mgmt.managementgroups.models.EntityInfo]
        :raises:
         :class:`ErrorResponseException<azure.mgmt.managementgroups.models.ErrorResponseException>`
        """
        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = self.list.metadata['url']

                # Construct parameters
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
                if skiptoken is not None:
                    query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str')
                if skip is not None:
                    query_parameters['$skip'] = self._serialize.query("skip", skip, 'int')
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int')
                if select is not None:
                    query_parameters['$select'] = self._serialize.query("select", select, 'str')
                if search is not None:
                    query_parameters['$search'] = self._serialize.query("search", search, 'str')
                if filter is not None:
                    query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
                if view is not None:
                    query_parameters['$view'] = self._serialize.query("view", view, 'str')
                if group_name is not None:
                    query_parameters['groupName'] = self._serialize.query("group_name", group_name, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Accept'] = 'application/json'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if cache_control is not None:
                header_parameters['Cache-Control'] = self._serialize.header("cache_control", cache_control, 'str')
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.post(url, query_parameters, header_parameters)
            response = self._client.send(request, stream=False, **operation_config)

            if response.status_code not in [200]:
                raise models.ErrorResponseException(self._deserialize, response)

            return response

        # Deserialize response
        deserialized = models.EntityInfoPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.EntityInfoPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized

Response: This method returns a list of all entities in the specified base namespace.


Instruction:
Write a Python 3 function for
creating a new job for the content of the current content.

Response:
def create_job(
            self, team_name, content_type, content_id, workflow_name, job_content_type, content_value, call_back_endpoint=None, custom_headers=None, raw=False, **operation_config):
        """A job Id will be returned for the content posted on this endpoint.
        Once the content is evaluated against the Workflow provided the review
        will be created or ignored based on the workflow expression.
        <h3>CallBack Schemas </h3>
        <p>
        <h4>Job Completion CallBack Sample</h4><br/>
        {<br/>
        "JobId": "<Job Id>,<br/>
        "ReviewId": "<Review Id, if the Job resulted in a Review to be
        created>",<br/>
        "WorkFlowId": "default",<br/>
        "Status": "<This will be one of Complete, InProgress, Error>",<br/>
        "ContentType": "Image",<br/>
        "ContentId": "<This is the ContentId that was specified on
        input>",<br/>
        "CallBackType": "Job",<br/>
        "Metadata": {<br/>
        "adultscore": "0.xxx",<br/>
        "a": "False",<br/>
        "racyscore": "0.xxx",<br/>
        "r": "True"<br/>
        }<br/>
        }<br/>
        </p>
        <p>
        <h4>Review Completion CallBack Sample</h4><br/>
        {
        "ReviewId": "<Review Id>",<br/>
        "ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/>
        "ModifiedBy": "<Name of the Reviewer>",<br/>
        "CallBackType": "Review",<br/>
        "ContentId": "<The ContentId that was specified input>",<br/>
        "Metadata": {<br/>
        "adultscore": "0.xxx",
        "a": "False",<br/>
        "racyscore": "0.xxx",<br/>
        "r": "True"<br/>
        },<br/>
        "ReviewerResultTags": {<br/>
        "a": "False",<br/>
        "r": "True"<br/>
        }<br/>
        }<br/>
        </p>.

        :param team_name: Your team name.
        :type team_name: str
        :param content_type: Image, Text or Video. Possible values include:
         'Image', 'Text', 'Video'
        :type content_type: str
        :param content_id: Id/Name to identify the content submitted.
        :type content_id: str
        :param workflow_name: Workflow Name that you want to invoke.
        :type workflow_name: str
        :param job_content_type: The content type. Possible values include:
         'application/json', 'image/jpeg'
        :type job_content_type: str
        :param content_value: Content to evaluate for a job.
        :type content_value: str
        :param call_back_endpoint: Callback endpoint for posting the create
         job result.
        :type call_back_endpoint: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: JobId or ClientRawResponse if raw=true
        :rtype: ~azure.cognitiveservices.vision.contentmoderator.models.JobId
         or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`APIErrorException<azure.cognitiveservices.vision.contentmoderator.models.APIErrorException>`
        """
        content = models.Content(content_value=content_value)

        # Construct URL
        url = self.create_job.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
            'teamName': self._serialize.url("team_name", team_name, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['ContentType'] = self._serialize.query("content_type", content_type, 'str')
        query_parameters['ContentId'] = self._serialize.query("content_id", content_id, 'str')
        query_parameters['WorkflowName'] = self._serialize.query("workflow_name", workflow_name, 'str')
        if call_back_endpoint is not None:
            query_parameters['CallBackEndpoint'] = self._serialize.query("call_back_endpoint", call_back_endpoint, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['Content-Type'] = self._serialize.header("job_content_type", job_content_type, 'str')

        # Construct body
        body_content = self._serialize.body(content, 'Content')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.APIErrorException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('JobId', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized


Instruction:
Implement a Python 3 function for
getting a specific queue client.

Response:
def get_queue(self, queue_name):
        """Get a client for a queue entity.

        :param queue_name: The name of the queue.
        :type queue_name: str
        :rtype: ~azure.servicebus.servicebus_client.QueueClient
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
        :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the queue is not found.

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START get_queue_client]
                :end-before: [END get_queue_client]
                :language: python
                :dedent: 8
                :caption: Get the specific queue client from Service Bus client

        """
        try:
            queue = self.mgmt_client.get_queue(queue_name)
        except requests.exceptions.ConnectionError as e:
            raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e)
        except AzureServiceBusResourceNotFound:
            raise ServiceBusResourceNotFound("Specificed queue does not exist.")
        return QueueClient.from_entity(
            self._get_host(), queue,
            shared_access_key_name=self.shared_access_key_name,
            shared_access_key_value=self.shared_access_key_value,
            mgmt_client=self.mgmt_client,
            debug=self.debug)


Instruction:
Can you tell what is the following Python 3 function doing
def list_queues(self):
        try:
            queues = self.mgmt_client.list_queues()
        except requests.exceptions.ConnectionError as e:
            raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e)
        queue_clients = []
        for queue in queues:
            queue_clients.append(QueueClient.from_entity(
                self._get_host(), queue,
                shared_access_key_name=self.shared_access_key_name,
                shared_access_key_value=self.shared_access_key_value,
                mgmt_client=self.mgmt_client,
                debug=self.debug))
        return queue_clients

Response: List all queues in the namespace.


Instruction:
Write a Python 3 script for
getting a client for a specific topic.

Response:
def get_topic(self, topic_name):
        """Get a client for a topic entity.

        :param topic_name: The name of the topic.
        :type topic_name: str
        :rtype: ~azure.servicebus.servicebus_client.TopicClient
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
        :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found.

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START get_topic_client]
                :end-before: [END get_topic_client]
                :language: python
                :dedent: 8
                :caption: Get the specific topic client from Service Bus client

        """
        try:
            topic = self.mgmt_client.get_topic(topic_name)
        except requests.exceptions.ConnectionError as e:
            raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e)
        except AzureServiceBusResourceNotFound:
            raise ServiceBusResourceNotFound("Specificed topic does not exist.")
        return TopicClient.from_entity(
            self._get_host(), topic,
            shared_access_key_name=self.shared_access_key_name,
            shared_access_key_value=self.shared_access_key_value,
            debug=self.debug)


Instruction:
How would you code a function in Python 3 to
get a list of all topic clients in the namespace.

Response:
def list_topics(self):
        """Get a client for all topic entities in the namespace.

        :rtype: list[~azure.servicebus.servicebus_client.TopicClient]
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START list_topics]
                :end-before: [END list_topics]
                :language: python
                :dedent: 4
                :caption: List the topics from Service Bus client

        """
        try:
            topics = self.mgmt_client.list_topics()
        except requests.exceptions.ConnectionError as e:
            raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e)
        topic_clients = []
        for topic in topics:
            topic_clients.append(TopicClient.from_entity(
                self._get_host(), topic,
                shared_access_key_name=self.shared_access_key_name,
                shared_access_key_value=self.shared_access_key_value,
                debug=self.debug))
        return topic_clients


Instruction:
Here you have a function in Python 3, explain what it does
def peek(self, count=1, start_from=0, session=None, **kwargs):
        message = {'from-sequence-number': types.AMQPLong(start_from), 'message-count': int(count)}
        if self.entity and self.requires_session:
            if not session:
                raise ValueError("Sessions are required, please set session.")
            message['session-id'] = session

        with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:
            return handler._mgmt_request_response(  # pylint: disable=protected-access
                REQUEST_RESPONSE_PEEK_OPERATION,
                message,
                mgmt_handlers.peek_op)

Response: Browse messages currently pending in the queue.


Instruction:
Write a Python 3 script for
listing the pending messages in the queue.

Response:
def list_sessions(self, updated_since=None, max_results=100, skip=0, **kwargs):
        """List session IDs.

        List the Session IDs with pending messages in the queue where the state of the session
        has been updated since the timestamp provided. If no timestamp is provided, all will be returned.
        If the state of a session has never been set, it will not be returned regardless of whether
        there are messages pending.

        :param updated_since: The UTC datetime from which to return updated pending Session IDs.
        :type updated_since: datetime.datetime
        :param max_results: The maximum number of Session IDs to return. Default value is 100.
        :type max_results: int
        :param skip: The page value to jump to. Default value is 0.
        :type skip: int
        :rtype: list[str]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START list_sessions_service_bus]
                :end-before: [END list_sessions_service_bus]
                :language: python
                :dedent: 4
                :caption: Get the Ids of session which have messages pending in the queue

        """
        if self.entity and not self.requires_session:
            raise ValueError("This is not a sessionful entity.")
        message = {
            'last-updated-time': updated_since or datetime.datetime.utcfromtimestamp(0),
            'skip': types.AMQPInt(skip),
            'top': types.AMQPInt(max_results),
        }
        with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:
            return handler._mgmt_request_response(  # pylint: disable=protected-access
                REQUEST_RESPONSE_GET_MESSAGE_SESSIONS_OPERATION,
                message,
                mgmt_handlers.list_sessions_op)


Instruction:
Here you have a function in Python 3, explain what it does
def receive_deferred_messages(self, sequence_numbers, mode=ReceiveSettleMode.PeekLock, **kwargs):
        if (self.entity and self.requires_session) or kwargs.get('session'):
            raise ValueError("Sessionful deferred messages can only be received within a locked receive session.")
        if not sequence_numbers:
            raise ValueError("At least one sequence number must be specified.")
        try:
            receive_mode = mode.value.value
        except AttributeError:
            receive_mode = int(mode)
        message = {
            'sequence-numbers': types.AMQPArray([types.AMQPLong(s) for s in sequence_numbers]),
            'receiver-settle-mode': types.AMQPuInt(receive_mode)}
        mgmt_handler = functools.partial(mgmt_handlers.deferred_message_op, mode=receive_mode)
        with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:
            return handler._mgmt_request_response(  # pylint: disable=protected-access
                REQUEST_RESPONSE_RECEIVE_BY_SEQUENCE_NUMBER,
                message,
                mgmt_handler)

Response: Receive deferred messages from the service bus.


Instruction:
How would you explain what the following Python 3 function does
def settle_deferred_messages(self, settlement, messages, **kwargs):
        if (self.entity and self.requires_session) or kwargs.get('session'):
            raise ValueError("Sessionful deferred messages can only be settled within a locked receive session.")
        if settlement.lower() not in ['completed', 'suspended', 'abandoned']:
            raise ValueError("Settlement must be one of: 'completed', 'suspended', 'abandoned'")
        if not messages:
            raise ValueError("At least one message must be specified.")
        message = {
            'disposition-status': settlement.lower(),
            'lock-tokens': types.AMQPArray([m.lock_token for m in messages])}

        with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:
            return handler._mgmt_request_response(  # pylint: disable=protected-access
                REQUEST_RESPONSE_UPDATE_DISPOSTION_OPERATION,
                message,
                mgmt_handlers.default)

Response:
Settle messages that have been previously deferred.

        :param settlement: How the messages are to be settled. This must be a string
         of one of the following values: 'completed', 'suspended', 'abandoned'.
        :type settlement: str
        :param messages: A list of deferred messages to be settled.
        :type messages: list[~azure.servicebus.common.message.DeferredMessage]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START settle_deferred_messages_service_bus]
                :end-before: [END settle_deferred_messages_service_bus]
                :language: python
                :dedent: 8
                :caption: Settle deferred messages.


Instruction:
Here you have a function in Python 3, explain what it does
def get_site(self, webspace_name, website_name):
        '''
        List the web sites defined on this webspace.

        webspace_name:
            The name of the webspace.
        website_name:
            The name of the website.
        '''
        return self._perform_get(self._get_sites_details_path(webspace_name,
                                                              website_name),
                                 Site)

Response: Get the site details for the given webspace and website name.


Instruction:
Can you create a Python 3 function that
creates a website. webspace_name: The name of the webspace. website_name: The name of the website. geo_region: The geographical region of the webspace that will be created. host_names: An array of fully qualified domain names for website. Only one hostname can be specified in the azurewebsites.net domain. The hostname should match the name of the website. Custom domains can only be specified for Shared or Standard websites. plan: This value must be 'VirtualDedicatedPlan'. compute_mode: This value should be 'Shared' for the Free or Paid Shared offerings, or 'Dedicated' for the Standard offering. The default value is 'Shared'. If you set it to 'Dedicated', you must specify a value for the server_farm parameter. server_farm: The name of the Server Farm associated with this website. This is a required value for Standard mode. site_mode: Can be None, 'Limited' or 'Basic'. This value is 'Limited' for the Free offering, and 'Basic' for the Paid Shared offering. Standard mode does not use the site_mode parameter; it uses the compute_mode parameter.

Response:
def create_site(self, webspace_name, website_name, geo_region, host_names,
                    plan='VirtualDedicatedPlan', compute_mode='Shared',
                    server_farm=None, site_mode=None):
        '''
        Create a website.

        webspace_name:
            The name of the webspace.
        website_name:
            The name of the website.
        geo_region:
            The geographical region of the webspace that will be created.
        host_names:
            An array of fully qualified domain names for website. Only one
            hostname can be specified in the azurewebsites.net domain.
            The hostname should match the name of the website. Custom domains
            can only be specified for Shared or Standard websites.
        plan:
            This value must be 'VirtualDedicatedPlan'.
        compute_mode:
            This value should be 'Shared' for the Free or Paid Shared
            offerings, or 'Dedicated' for the Standard offering. The default
            value is 'Shared'. If you set it to 'Dedicated', you must specify
            a value for the server_farm parameter.
        server_farm:
            The name of the Server Farm associated with this website. This is
            a required value for Standard mode.
        site_mode:
            Can be None, 'Limited' or 'Basic'. This value is 'Limited' for the
            Free offering, and 'Basic' for the Paid Shared offering. Standard
            mode does not use the site_mode parameter; it uses the compute_mode
            parameter.
        '''
        xml = _XmlSerializer.create_website_to_xml(webspace_name, website_name, geo_region, plan, host_names, compute_mode, server_farm, site_mode)
        return self._perform_post(
            self._get_sites_path(webspace_name),
            xml,
            Site)


Instruction:
Can you create a Python 3 function that
deletes a website. webspace_name: The name of the webspace. website_name: The name of the website. delete_empty_server_farm: If the site being deleted is the last web site in a server farm, you can delete the server farm by setting this to True. delete_metrics: To also delete the metrics for the site that you are deleting, you can set this to True.

Response:
def delete_site(self, webspace_name, website_name,
                    delete_empty_server_farm=False, delete_metrics=False):
        '''
        Delete a website.

        webspace_name:
            The name of the webspace.
        website_name:
            The name of the website.
        delete_empty_server_farm:
            If the site being deleted is the last web site in a server farm,
            you can delete the server farm by setting this to True.
        delete_metrics:
            To also delete the metrics for the site that you are deleting, you
            can set this to True.
        '''
        path = self._get_sites_details_path(webspace_name, website_name)
        query = ''
        if delete_empty_server_farm:
            query += '&deleteEmptyServerFarm=true'
        if delete_metrics:
            query += '&deleteMetrics=true'
        if query:
            path = path + '?' + query.lstrip('&')
        return self._perform_delete(path)


Instruction:
How would you code a function in Python 3 to
update a web site.

Response:
def update_site(self, webspace_name, website_name, state=None):
        '''
        Update a web site.

        webspace_name:
            The name of the webspace.
        website_name:
            The name of the website.
        state:
            The wanted state ('Running' or 'Stopped' accepted)
        '''
        xml = _XmlSerializer.update_website_to_xml(state)
        return self._perform_put(
            self._get_sites_details_path(webspace_name, website_name),
            xml, as_async=True)


Instruction:
How would you explain what the following Python 3 function does
def restart_site(self, webspace_name, website_name):
        '''
        Restart a web site.

        webspace_name:
            The name of the webspace.
        website_name:
            The name of the website.
        '''
        return self._perform_post(
            self._get_restart_path(webspace_name, website_name),
            None, as_async=True)

Response: Restarts a web site.


Instruction:
Make a summary of the following Python 3 code
def get_historical_usage_metrics(self, webspace_name, website_name,
                                     metrics = None, start_time=None, end_time=None, time_grain=None):
        '''
        Get historical usage metrics.

        webspace_name:
            The name of the webspace.
        website_name:
            The name of the website.
        metrics:
            Optional. List of metrics name. Otherwise, all metrics returned.
        start_time:
            Optional. An ISO8601 date. Otherwise, current hour is used.
        end_time:
            Optional. An ISO8601 date. Otherwise, current time is used.
        time_grain:
            Optional. A rollup name, as P1D. OTherwise, default rollup for the metrics is used.
        More information and metrics name at:
        http://msdn.microsoft.com/en-us/library/azure/dn166964.aspx
        '''
        metrics = ('names='+','.join(metrics)) if metrics else ''
        start_time = ('StartTime='+start_time) if start_time else ''
        end_time = ('EndTime='+end_time) if end_time else ''
        time_grain = ('TimeGrain='+time_grain) if time_grain else ''
        parameters = ('&'.join(v for v in (metrics, start_time, end_time, time_grain) if v))
        parameters = '?'+parameters if parameters else ''
        return self._perform_get(self._get_historical_usage_metrics_path(webspace_name, website_name) + parameters,
                                 MetricResponses)

Response: Get historical usage metrics.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_metric_definitions(self, webspace_name, website_name):
        '''
        Get metric definitions of metrics available of this web site.

        webspace_name:
            The name of the webspace.
        website_name:
            The name of the website.
        '''
        return self._perform_get(self._get_metric_definitions_path(webspace_name, website_name),
                                 MetricDefinitions)

Response: Get the list of metric definitions available for this website.


Instruction:
Write a Python 3 script for
getting a site s publish profile as a string.

Response:
def get_publish_profile_xml(self, webspace_name, website_name):
        '''
        Get a site's publish profile as a string

        webspace_name:
            The name of the webspace.
        website_name:
            The name of the website.
        '''
        return self._perform_get(self._get_publishxml_path(webspace_name, website_name),
                                 None).body.decode("utf-8")


Instruction:
Create a Python 3 function for
getting a site s publish profile as an object

Response:
def get_publish_profile(self, webspace_name, website_name):
        '''
        Get a site's publish profile as an object

        webspace_name:
            The name of the webspace.
        website_name:
            The name of the website.
        '''
        return self._perform_get(self._get_publishxml_path(webspace_name, website_name),
                                 PublishData)


Instruction:
Implement a Python 3 function for
adding authorization header, and encrypts and signs the request if supported on the specific request. :param request: unprotected request to apply security protocol :return: protected request with appropriate security protocal applied

Response:
def protect_request(self, request):
        """
        Adds authorization header, and encrypts and signs the request if supported on the specific request.
        :param request: unprotected request to apply security protocol
        :return: protected request with appropriate security protocal applied
        """
        # Setup the auth header on the request
        # Due to limitations in the service we hard code the auth scheme to 'Bearer' as the service will fail with any
        # other scheme or a different casing such as 'bearer', once this is fixed the following line should be replaced:
        # request.headers['Authorization'] = '{} {}'.format(auth[0], auth[1])
        request.headers['Authorization'] = '{} {}'.format('Bearer', self.client_security_token)

        # if the current message security doesn't support message protection, or the body is empty
        # skip protection and return the original request
        if not self.supports_protection() or len(request.body) == 0:
            return request

        plain_text = request.body

        # if the client encryption key is specified add it to the body of the request
        if self.client_encryption_key:
            # note that this assumes that the body is already json and not simple string content
            # this is true for all requests which currently support message encryption, but might
            # need to be revisited when the types of
            body_dict = json.loads(plain_text)
            body_dict['rek'] = {'jwk': self.client_encryption_key.to_jwk().serialize()}
            plain_text = json.dumps(body_dict).encode(encoding='utf8')

        # build the header for the jws body
        jws_header = _JwsHeader()
        jws_header.alg = 'RS256'
        jws_header.kid = self.client_signature_key.kid
        jws_header.at = self.client_security_token
        jws_header.ts = int(time.time())
        jws_header.typ = 'PoP'

        jws = _JwsObject()

        jws.protected = jws_header.to_compact_header()
        jws.payload = self._protect_payload(plain_text)
        data = (jws.protected + '.' + jws.payload).encode('ascii')
        jws.signature = _bstr_to_b64url(self.client_signature_key.sign(data))

        request.headers['Content-Type'] = 'application/jose+json'

        request.prepare_body(data=jws.to_flattened_jws(), files=None)

        return request


Instruction:
Can you write a function in Python 3 where it
removes protection from the specified response :param request: response from the key vault service :return: unprotected response with any security protocal encryption removed

Response:
def unprotect_response(self, response, **kwargs):
        """
        Removes protection from the specified response
        :param request: response from the key vault service
        :return: unprotected response with any security protocal encryption removed
        """
        body = response.content
        # if the current message security doesn't support message protection, the body is empty, or the request failed
        # skip protection and return the original response
        if not self.supports_protection() or len(response.content) == 0 or response.status_code != 200:
            return response

        # ensure the content-type is application/jose+json
        if 'application/jose+json' not in response.headers.get('content-type', '').lower():
            raise ValueError('Invalid protected response')

        # deserialize the response into a JwsObject, using response.text so requests handles the encoding
        jws = _JwsObject().deserialize(body)

        # deserialize the protected header
        jws_header = _JwsHeader.from_compact_header(jws.protected)

        # ensure the jws signature kid matches the key from original challenge
        # and the alg matches expected signature alg
        if jws_header.kid != self.server_signature_key.kid \
                or jws_header.alg != 'RS256':
            raise ValueError('Invalid protected response')

        # validate the signature of the jws
        data = (jws.protected + '.' + jws.payload).encode('ascii')
        # verify will raise an InvalidSignature exception if the signature doesn't match
        self.server_signature_key.verify(signature=_b64_to_bstr(jws.signature), data=data)

        # get the unprotected response body
        decrypted = self._unprotect_payload(jws.payload)

        response._content = decrypted
        response.headers['Content-Type'] = 'application/json'

        return response


Instruction:
How would you explain what the following Python 3 function does
def supports_protection(self):
        return self.client_signature_key \
               and self.client_encryption_key \
               and self.server_signature_key \
               and self.server_encryption_key

Response: Determines if the current object supports the message protection protocol.


Instruction:
Write a Python 3 script for
updating the policies for the specified container registry.

Response:
def update_policies(
            self, resource_group_name, registry_name, quarantine_policy=None, trust_policy=None, custom_headers=None, raw=False, polling=True, **operation_config):
        """Updates the policies for the specified container registry.

        :param resource_group_name: The name of the resource group to which
         the container registry belongs.
        :type resource_group_name: str
        :param registry_name: The name of the container registry.
        :type registry_name: str
        :param quarantine_policy: An object that represents quarantine policy
         for a container registry.
        :type quarantine_policy:
         ~azure.mgmt.containerregistry.v2018_02_01_preview.models.QuarantinePolicy
        :param trust_policy: An object that represents content trust policy
         for a container registry.
        :type trust_policy:
         ~azure.mgmt.containerregistry.v2018_02_01_preview.models.TrustPolicy
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: The poller return type is ClientRawResponse, the
         direct response alongside the deserialized response
        :param polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :return: An instance of LROPoller that returns RegistryPolicies or
         ClientRawResponse<RegistryPolicies> if raw==True
        :rtype:
         ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.containerregistry.v2018_02_01_preview.models.RegistryPolicies]
         or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.containerregistry.v2018_02_01_preview.models.RegistryPolicies]]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        raw_result = self._update_policies_initial(
            resource_group_name=resource_group_name,
            registry_name=registry_name,
            quarantine_policy=quarantine_policy,
            trust_policy=trust_policy,
            custom_headers=custom_headers,
            raw=True,
            **operation_config
        )

        def get_long_running_output(response):
            deserialized = self._deserialize('RegistryPolicies', response)

            if raw:
                client_raw_response = ClientRawResponse(deserialized, response)
                return client_raw_response

            return deserialized

        lro_delay = operation_config.get(
            'long_running_operation_timeout',
            self.config.long_running_operation_timeout)
        if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        return LROPoller(self._client, raw_result, get_long_running_output, polling_method)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_cloud_service(self, cloud_service_id, label, description, geo_region):
        '''
        The Create Cloud Service request creates a new cloud service. When job
        collections are created, they are hosted within a cloud service.
        A cloud service groups job collections together in a given region.
        Once a cloud service has been created, job collections can then be
        created and contained within it.

        cloud_service_id:
            The cloud service id
        label:
            The name of the cloud service.
        description:
            The description of the cloud service.
        geo_region:
            The geographical region of the webspace that will be created.
        '''
        _validate_not_none('cloud_service_id', cloud_service_id)
        _validate_not_none('label', label)
        _validate_not_none('description', description)
        _validate_not_none('geo_region', geo_region)

        path = self._get_cloud_services_path(cloud_service_id)
        body = _SchedulerManagementXmlSerializer.create_cloud_service_to_xml(
            label, description, geo_region)

        return self._perform_put(path, body, as_async=True)

Response: Creates a new cloud service.


Instruction:
Make a summary of the following Python 3 code
def get_cloud_service(self, cloud_service_id):
        '''
        The Get Cloud Service operation gets all the resources (job collections)
        in the cloud service.

        cloud_service_id:
            The cloud service id
        '''
        _validate_not_none('cloud_service_id', cloud_service_id)
        path = self._get_cloud_services_path(cloud_service_id)
        return self._perform_get(path, CloudService)

Response: Get the details of a specific cloud service.


Instruction:
Can you tell what is the following Python 3 function doing
def delete_cloud_service(self, cloud_service_id):
        '''
        The Get Cloud Service operation gets all the resources (job collections)
        in the cloud service.

        cloud_service_id:
            The cloud service id
        '''
        _validate_not_none('cloud_service_id', cloud_service_id)
        path = self._get_cloud_services_path(cloud_service_id)
        return self._perform_delete(path, as_async=True)

Response: Delete the resources in the specified cloud service.


Instruction:
Here you have a function in Python 3, explain what it does
def check_job_collection_name(self, cloud_service_id, job_collection_id):
        '''
        The Check Name Availability operation checks if a new job collection with
        the given name may be created, or if it is unavailable. The result of the
        operation is a Boolean true or false.

        cloud_service_id:
            The cloud service id
        job_collection_id:
            The name of the job_collection_id.
        '''
        _validate_not_none('cloud_service_id', cloud_service_id)
        _validate_not_none('job_collection_id', job_collection_id)

        path = self._get_cloud_services_path(
            cloud_service_id, "scheduler", "jobCollections")
        path += "?op=checknameavailability&resourceName=" + job_collection_id
        return self._perform_post(path, None, AvailabilityResponse)

Response: The Check Name Availability operation checks if a new job collection with the given name is available.


Instruction:
Can you create a Python 3 function that
creates a job collection for the specified hosted service.

Response:
def create_job_collection(self, cloud_service_id, job_collection_id, plan="Standard"):
        '''
        The Create Job Collection request is specified as follows. Replace <subscription-id>
        with your subscription ID, <cloud-service-id> with your cloud service ID, and
        <job-collection-id> with the ID of the job collection you\'d like to create.
        There are no "default" pre-existing job collections every job collection
        must be manually created.

        cloud_service_id:
            The cloud service id
        job_collection_id:
            Name of the hosted service.
        '''
        _validate_not_none('cloud_service_id', cloud_service_id)
        _validate_not_none('job_collection_id', job_collection_id)

        path = self._get_cloud_services_path(
            cloud_service_id, "scheduler", "jobCollections")

        path += '/' + _str(job_collection_id)
        body = _SchedulerManagementXmlSerializer.create_job_collection_to_xml(
            plan)

        return self._perform_put(path, body, as_async=True)


Instruction:
Here you have a function in Python 3, explain what it does
def delete_job_collection(self, cloud_service_id, job_collection_id):
        '''
        The Delete Job Collection request is specified as follows. Replace <subscription-id>
        with your subscription ID, <cloud-service-id> with your cloud service ID, and
        <job-collection-id> with the ID of the job collection you\'d like to delete.

        cloud_service_id:
            The cloud service id
        job_collection_id:
            Name of the hosted service.
        '''
        _validate_not_none('cloud_service_id', cloud_service_id)
        _validate_not_none('job_collection_id', job_collection_id)

        path = self._get_cloud_services_path(
            cloud_service_id, "scheduler", "jobCollections")

        path += '/' + _str(job_collection_id)

        return self._perform_delete(path, as_async=True)

Response: This method deletes the specified job collection from the specified hosted service.


Instruction:
Can you tell what is the following Python 3 function doing
def get_job_collection(self, cloud_service_id, job_collection_id):
        '''
        The Get Job Collection operation gets the details of a job collection

        cloud_service_id:
            The cloud service id
        job_collection_id:
            Name of the hosted service.
        '''
        _validate_not_none('cloud_service_id', cloud_service_id)
        _validate_not_none('job_collection_id', job_collection_id)

        path = self._get_job_collection_path(
            cloud_service_id, job_collection_id)

        return self._perform_get(path, Resource)

Response: The Get Job Collection operation gets the details of a job collection.


Instruction:
Here you have a function in Python 3, explain what it does
def create_job(self, cloud_service_id, job_collection_id, job_id, job):
        '''
        The Create Job request creates a new job.
        cloud_service_id:
            The cloud service id
        job_collection_id:
            Name of the hosted service.
        job_id:
            The job id you wish to create.
        job:
            A dictionary of the payload
        '''
        _validate_not_none('cloud_service_id', cloud_service_id)
        _validate_not_none('job_collection_id', job_collection_id)
        _validate_not_none('job_id', job_id)
        _validate_not_none('job', job)

        path = self._get_job_collection_path(
            cloud_service_id, job_collection_id, job_id)

        self.content_type = "application/json"
        return self._perform_put(path, JSONEncoder().encode(job), as_async=True)

Response: This method creates a new job in the specified collection.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def delete_job(self, cloud_service_id, job_collection_id, job_id):
        '''
        The Delete Job request creates a new job.
        cloud_service_id:
            The cloud service id
        job_collection_id:
            Name of the hosted service.
        job_id:
            The job id you wish to create.
        '''
        _validate_not_none('cloud_service_id', cloud_service_id)
        _validate_not_none('job_collection_id', job_collection_id)
        _validate_not_none('job_id', job_id)

        path = self._get_job_collection_path(
            cloud_service_id, job_collection_id, job_id)
        return self._perform_delete(path, as_async=True)

Response: This method deletes a job from the hosted service.


Instruction:
How would you explain what the following Python 3 function does
def get_job(self, cloud_service_id, job_collection_id, job_id):
        '''
        The Get Job operation gets the details (including the current job status)
        of the specified job from the specified job collection.

        The return type is

        cloud_service_id:
            The cloud service id
        job_collection_id:
            Name of the hosted service.
        job_id:
            The job id you wish to create.
        '''
        _validate_not_none('cloud_service_id', cloud_service_id)
        _validate_not_none('job_collection_id', job_collection_id)
        _validate_not_none('job_id', job_id)

        path = self._get_job_collection_path(
            cloud_service_id, job_collection_id, job_id)

        self.content_type = "application/json"
        payload = self._perform_get(path).body.decode()
        return json.loads(payload)

Response: Get the details of a job from the specified job collection.


Instruction:
Write a Python 3 script to
complete the restore operation on a managed database.

Response:
def complete_restore(
            self, location_name, operation_id, last_backup_name, custom_headers=None, raw=False, polling=True, **operation_config):
        """Completes the restore operation on a managed database.

        :param location_name: The name of the region where the resource is
         located.
        :type location_name: str
        :param operation_id: Management operation id that this request tries
         to complete.
        :type operation_id: str
        :param last_backup_name: The last backup name to apply
        :type last_backup_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: The poller return type is ClientRawResponse, the
         direct response alongside the deserialized response
        :param polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :return: An instance of LROPoller that returns None or
         ClientRawResponse<None> if raw==True
        :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        raw_result = self._complete_restore_initial(
            location_name=location_name,
            operation_id=operation_id,
            last_backup_name=last_backup_name,
            custom_headers=custom_headers,
            raw=True,
            **operation_config
        )

        def get_long_running_output(response):
            if raw:
                client_raw_response = ClientRawResponse(None, response)
                return client_raw_response

        lro_delay = operation_config.get(
            'long_running_operation_timeout',
            self.config.long_running_operation_timeout)
        if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        return LROPoller(self._client, raw_result, get_long_running_output, polling_method)


Instruction:
Write a Python 3 script to
return a list of models that can be used to create the keyvault object.

Response:
def models(self):
        """Module depends on the API version:
            * 2016-10-01: :mod:`v2016_10_01.models<azure.keyvault.v2016_10_01.models>`
            * 7.0: :mod:`v7_0.models<azure.keyvault.v7_0.models>`
         """
        api_version = self._get_api_version(None)

        if api_version == v7_0_VERSION:
            from azure.keyvault.v7_0 import models as implModels
        elif api_version == v2016_10_01_VERSION:
            from azure.keyvault.v2016_10_01 import models as implModels
        else:
            raise NotImplementedError("APIVersion {} is not available".format(api_version))
        return implModels


Instruction:
Can you write a function in Python 3 where it
gets the versioned client implementation corresponding to the current profile.

Response:
def _get_client_impl(self):
        """
        Get the versioned client implementation corresponding to the current profile.
        :return:  The versioned client implementation.
        """
        api_version = self._get_api_version(None)
        if api_version not in self._client_impls:
            self._create_client_impl(api_version)
        return self._client_impls[api_version]


Instruction:
Make a summary of the following Python 3 code
def _create_client_impl(self, api_version):
        if api_version == v7_0_VERSION:
            from azure.keyvault.v7_0 import KeyVaultClient as ImplClient
        elif api_version == v2016_10_01_VERSION:
            from azure.keyvault.v2016_10_01 import KeyVaultClient as ImplClient
        else:
            raise NotImplementedError("APIVersion {} is not available".format(api_version))

        impl = ImplClient(credentials=self._credentials)
        impl.config = self.config

        # if __enter__ has previously been called and the impl client has __enter__ defined we need to call it
        if self._entered and hasattr(impl, '__enter__'):
            impl.__enter__()

        self._client_impls[api_version] = impl
        return impl

Response: Creates the client implementation corresponding to the specifeid api_version.


Instruction:
How would you code a function in Python 3 to
send one or more messages to be enqueued at a specific time.

Response:
async def schedule(self, schedule_time, *messages):
        """Send one or more messages to be enqueued at a specific time.

        Returns a list of the sequence numbers of the enqueued messages.

        :param schedule_time: The date and time to enqueue the messages.
        :type schedule_time: ~datetime.datetime
        :param messages: The messages to schedule.
        :type messages: ~azure.servicebus.aio.async_message.Message
        :rtype: list[int]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START schedule_messages]
                :end-before: [END schedule_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.

        """
        if not self.running:
            await self.open()
        request_body = self._build_schedule_request(schedule_time, *messages)
        return await self._mgmt_request_response(
            REQUEST_RESPONSE_SCHEDULE_MESSAGE_OPERATION,
            request_body,
            mgmt_handlers.schedule_op)


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def cancel_scheduled_messages(self, *sequence_numbers):
        if not self.running:
            await self.open()
        numbers = [types.AMQPLong(s) for s in sequence_numbers]
        request_body = {'sequence-numbers': types.AMQPArray(numbers)}
        return await self._mgmt_request_response(
            REQUEST_RESPONSE_CANCEL_SCHEDULED_MESSAGE_OPERATION,
            request_body,
            mgmt_handlers.default)

Response: Cancel one or more scheduled messages.


Instruction:
Can you implement a function in Python 3 that
sends all pending messages.

Response:
async def send_pending_messages(self):
        """Wait until all pending messages have been sent.

        :returns: A list of the send results of all the pending messages. Each
         send result is a tuple with two values. The first is a boolean, indicating `True`
         if the message sent, or `False` if it failed. The second is an error if the message
         failed, otherwise it will be `None`.
        :rtype: list[tuple[bool, ~azure.servicebus.common.errors.MessageSendFailed]]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START queue_sender_messages]
                :end-before: [END queue_sender_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.

        """
        if not self.running:
            await self.open()
        try:
            pending = self._handler._pending_messages[:]  # pylint: disable=protected-access
            await self._handler.wait_async()
            results = []
            for m in pending:
                if m.state == constants.MessageState.SendFailed:
                    results.append((False, MessageSendFailed(m._response)))  # pylint: disable=protected-access
                else:
                    results.append((True, None))
            return results
        except Exception as e:  # pylint: disable=broad-except
            raise MessageSendFailed(e)


Instruction:
Here you have a function in Python 3, explain what it does
async def reconnect(self):
        unsent_events = self._handler.pending_messages
        await super(Sender, self).reconnect()
        try:
            self._handler.queue_message(*unsent_events)
            await self._handler.wait_async()
        except Exception as e:  # pylint: disable=broad-except
            await self._handle_exception(e)

Response:
Reconnect the handler.

        If the handler was disconnected from the service with
        a retryable error - attempt to reconnect.
        This method will be called automatically for most retryable errors.
        Also attempts to re-queue any messages that were pending before the reconnect.


Instruction:
Implement a function in Python 3 to
send a message and blocks until acknowledgement is received.

Response:
async def send(self, message):
        """Send a message and blocks until acknowledgement is received or the operation fails.

        If neither the Sender nor the message has a session ID, a `ValueError` will be raised.

        :param message: The message to be sent.
        :type message: ~azure.servicebus.aio.async_message.Message
        :raises: ~azure.servicebus.common.errors.MessageSendFailed if the message fails to
         send.

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START open_close_session_sender_context]
                :end-before: [END open_close_session_sender_context]
                :language: python
                :dedent: 4
                :caption: Open a sessionful Sender and send messages.

        """
        if not isinstance(message, Message):
            raise TypeError("Value of message must be of type 'Message'.")
        if not self.session_id and not message.properties.group_id:
            raise ValueError("Message must have Session ID.")
        return await super(SessionSender, self).send(message)


Instruction:
Write a Python 3 script to
read a certificate file from a publish settings file.

Response:
def get_certificate_from_publish_settings(publish_settings_path, path_to_write_certificate, subscription_id=None):
    '''
    Writes a certificate file to the specified location.  This can then be used
    to instantiate ServiceManagementService.  Returns the subscription ID.

    publish_settings_path:
        Path to subscription file downloaded from
        http://go.microsoft.com/fwlink/?LinkID=301775
    path_to_write_certificate:
        Path to write the certificate file.
    subscription_id:
        (optional)  Provide a subscription id here if you wish to use a
        specific subscription under the publish settings file.
    '''
    import base64

    try:
        from xml.etree import cElementTree as ET
    except ImportError:
        from xml.etree import ElementTree as ET

    try:
        import OpenSSL.crypto as crypto
    except:
        raise Exception("pyopenssl is required to use get_certificate_from_publish_settings")

    _validate_not_none('publish_settings_path', publish_settings_path)
    _validate_not_none('path_to_write_certificate', path_to_write_certificate)

    # parse the publishsettings file and find the ManagementCertificate Entry
    tree = ET.parse(publish_settings_path)
    subscriptions = tree.getroot().findall("./PublishProfile/Subscription")

    # Default to the first subscription in the file if they don't specify
    # or get the matching subscription or return none.
    if subscription_id:
        subscription = next((s for s in subscriptions if s.get('Id').lower() == subscription_id.lower()), None)
    else:
        subscription = subscriptions[0]

    # validate that subscription was found
    if subscription is None:
        raise ValueError("The provided subscription_id '{}' was not found in the publish settings file provided at '{}'".format(subscription_id, publish_settings_path))

    cert_string = _decode_base64_to_bytes(subscription.get('ManagementCertificate'))

    # Load the string in pkcs12 format.  Don't provide a password as it isn't encrypted.
    cert = crypto.load_pkcs12(cert_string, b'')

    # Write the data out as a PEM format to a random location in temp for use under this run.
    with open(path_to_write_certificate, 'wb') as f:
        f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert.get_certificate()))
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, cert.get_privatekey()))

    return subscription.get('Id')