Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_web_index_page(self, container, page):
        headers = {"X-Container-Meta-Web-Index": "%s" % page}
        self.api.cdn_request("/%s" % utils.get_name(container), method="POST",
                headers=headers)

Response: Sets the header indicating the index page in a container when creating a static website.


Instruction:
How would you implement a function in Python 3 that
removes an object from CDN - enabled public access before the TTL expires.

Response:
def purge_cdn_object(self, container, obj, email_addresses=None):
        """
        Removes a CDN-enabled object from public access before the TTL expires.
        Please note that there is a limit (at this time) of 25 such requests;
        if you need to purge more than that, you must contact support.

        If one or more email_addresses are included, an email confirming the
        purge is sent to each address.
        """
        return container.purge_cdn_object(obj, email_addresses=email_addresses)


Instruction:
How would you explain what the following Python 3 function does
def list_objects(self, container, limit=None, marker=None, prefix=None,
            delimiter=None, end_marker=None, full_listing=False):
        """
        Return a list of StorageObjects representing the objects in this
        container. You can use the marker, end_marker, and limit params to
        handle pagination, and the prefix and delimiter params to filter the
        objects returned. By default only the first 10,000 objects are
        returned; if you need to access more than that, set the 'full_listing'
        parameter to True.
        """
        if full_listing:
            return container.list_all(prefix=prefix)
        return container.list(limit=limit, marker=marker, prefix=prefix,
                delimiter=delimiter, end_marker=end_marker)

Response: List the objects in a container.


Instruction:
Can you generate the documentation for the following Python 3 function
def list_object_names(self, container, marker=None, limit=None, prefix=None,
            delimiter=None, end_marker=None, full_listing=False):
        """
        Return a list of then names of the objects in this container. You can
        use the marker, end_marker, and limit params to handle pagination, and
        the prefix and delimiter params to filter the objects returned. By
        default only the first 10,000 objects are returned; if you need to
        access more than that, set the 'full_listing' parameter to True.
        """
        return container.list_object_names(marker=marker, limit=limit,
                prefix=prefix, delimiter=delimiter, end_marker=end_marker,
                full_listing=full_listing)

Response: List the object names in this container.


Instruction:
Can you create a Python 3 function that
returns a list of all directories in the specified container.

Response:
def list_subdirs(self, container, marker=None, limit=None, prefix=None,
            delimiter=None, full_listing=False):
        """
        Returns a list of StorageObjects representing the pseudo-subdirectories
        in the specified container. You can use the marker and limit params to
        handle pagination, and the prefix param to filter the objects returned.
        The 'delimiter' parameter is ignored, as the only meaningful value is
        '/'.
        """
        mthd = container.list_all if full_listing else container.list
        objs = mthd(marker=marker, limit=limit, prefix=prefix, delimiter="/",
                return_raw=True)
        sdirs = [obj for obj in objs if "subdir" in obj]
        mgr = container.object_manager
        return [StorageObject(mgr, sdir) for sdir in sdirs]


Instruction:
Implement a function in Python 3 to
download the specified object from storage and writes it to the specified directory.

Response:
def download_object(self, container, obj, directory, structure=True):
        """
        Fetches the object from storage, and writes it to the specified
        directory. The directory must exist before calling this method.

        If the object name represents a nested folder structure, such as
        "foo/bar/baz.txt", that folder structure will be created in the target
        directory by default. If you do not want the nested folders to be
        created, pass `structure=False` in the parameters.
        """
        return container.download(obj, directory, structure=structure)


Instruction:
How would you implement a function in Python 3 that
copies the object to the new container optionally giving it a new name.

Response:
def copy_object(self, container, obj, new_container, new_obj_name=None,
            content_type=None):
        """
        Copies the object to the new container, optionally giving it a new name.
        If you copy to the same container, you must supply a different name.

        Returns the etag of the newly-copied object.

        You can optionally change the content_type of the object by supplying
        that in the 'content_type' parameter.
        """
        nm = new_obj_name or utils.get_name(obj)
        uri = "/%s/%s" % (utils.get_name(new_container), nm)
        copy_from = "/%s/%s" % (utils.get_name(container), utils.get_name(obj))
        headers = {"X-Copy-From": copy_from,
                "Content-Length": "0"}
        if content_type:
            headers["Content-Type"] = content_type
        resp, resp_body = self.api.method_put(uri, headers=headers)
        return resp.headers.get("etag")


Instruction:
Can you write a function in Python 3 where it
moves an object from one container to another.

Response:
def move_object(self, container, obj, new_container, new_obj_name=None,
            new_reference=False, content_type=None):
        """
        Works just like copy_object, except that the source object is deleted
        after a successful copy.

        You can optionally change the content_type of the object by supplying
        that in the 'content_type' parameter.

        NOTE: any references to the original object will no longer be valid;
        you will have to get a reference to the new object by passing True for
        the 'new_reference' parameter. When this is True, a reference to the
        newly moved object is returned. Otherwise, the etag for the moved
        object is returned.
        """
        new_obj_etag = self.copy_object(container, obj, new_container,
                new_obj_name=new_obj_name, content_type=content_type)
        if not new_obj_etag:
            return
        # Copy succeeded; delete the original.
        self.delete_object(container, obj)
        if new_reference:
            nm = new_obj_name or utils.get_name(obj)
            return self.get_object(new_container, nm)
        return new_obj_etag


Instruction:
Write a Python 3 function for
copying an object to itself but applies a new content - type.

Response:
def change_object_content_type(self, container, obj, new_ctype,
            guess=False):
        """
        Copies object to itself, but applies a new content-type. The guess
        feature requires the container to be CDN-enabled. If not, then the
        content-type must be supplied. If using guess with a CDN-enabled
        container, new_ctype can be set to None. Failure during the put will
        result in an exception.
        """
        cname = utils.get_name(container)
        oname = utils.get_name(obj)
        if guess and container.cdn_enabled:
            # Test against the CDN url to guess the content-type.
            obj_url = "%s/%s" % (container.cdn_uri, oname)
            new_ctype = mimetypes.guess_type(obj_url)[0]
        return self.copy_object(container, obj, container,
                content_type=new_ctype)


Instruction:
Write a Python 3 function that can
set the object in the specified container to be deleted after the specified number of seconds.

Response:
def delete_object_in_seconds(self, cont, obj, seconds, extra_info=None):
        """
        Sets the object in the specified container to be deleted after the
        specified number of seconds.

        The 'extra_info' parameter is included for backwards compatibility. It
        is no longer used at all, and will not be modified with swiftclient
        info, since swiftclient is not used any more.
        """
        meta = {"X-Delete-After": seconds}
        self.set_object_metadata(cont, obj, meta, clear=True, prefix="")


Instruction:
How would you explain what the following Python 3 function does
def set_object_metadata(self, container, obj, metadata, clear=False,
            extra_info=None, prefix=None):
        """
        Accepts a dictionary of metadata key/value pairs and updates the
        specified object metadata with them.

        If 'clear' is True, any existing metadata is deleted and only the
        passed metadata is retained. Otherwise, the values passed here update
        the object's metadata.

        'extra_info; is an optional dictionary which will be populated with
        'status', 'reason', and 'headers' keys from the underlying swiftclient
        call.

        By default, the standard object metadata prefix ('X-Object-Meta-') is
        prepended to the header name if it isn't present. For non-standard
        headers, you must include a non-None prefix, such as an empty string.
        """
        return container.set_object_metadata(obj, metadata, clear=clear,
                prefix=prefix)

Response: Sets the object s metadata to the passed dictionary.


Instruction:
Can you implement a function in Python 3 that
fetches the object from storage.

Response:
def get(self, include_meta=False, chunk_size=None):
        """
        Fetches the object from storage.

        If 'include_meta' is False, only the bytes representing the
        file is returned.

        Note: if 'chunk_size' is defined, you must fully read the object's
        contents before making another request.

        When 'include_meta' is True, what is returned from this method is a
        2-tuple:
            Element 0: a dictionary containing metadata about the file.
            Element 1: a stream of bytes representing the object's contents.
        """
        return self.manager.fetch(obj=self, include_meta=include_meta,
                chunk_size=chunk_size)


Instruction:
Implement a function in Python 3 to
download the object from storage and writes it to the specified directory.

Response:
def download(self, directory, structure=True):
        """
        Fetches the object from storage, and writes it to the specified
        directory. The directory must exist before calling this method.

        If the object name represents a nested folder structure, such as
        "foo/bar/baz.txt", that folder structure will be created in the target
        directory by default. If you do not want the nested folders to be
        created, pass `structure=False` in the parameters.
        """
        return self.manager.download(self, directory, structure=structure)


Instruction:
Can you tell what is the following Python 3 function doing
def copy(self, new_container, new_obj_name=None, extra_info=None):
        return self.container.copy_object(self, new_container,
                new_obj_name=new_obj_name)

Response:
Copies this object to a new container optionally giving it a new
        name.


Instruction:
Create a Python 3 function to
move this object to another container.

Response:
def move(self, new_container, new_obj_name=None, extra_info=None):
        """
        Works just like copy_object, except that this object is deleted after a
        successful copy. This means that this storage_object reference will no
        longer be valid.
        """
        return self.container.move_object(self, new_container,
                new_obj_name=new_obj_name)


Instruction:
Can you tell what is the following Python 3 function doing
def change_content_type(self, new_ctype, guess=False):
        self.container.change_object_content_type(self, new_ctype=new_ctype,
                guess=guess)

Response: Copies the object to itself but applies a new content - type.


Instruction:
Here you have a function in Python 3, explain what it does
def remove_metadata_key(self, key, prefix=None):
        self.manager.remove_metadata_key(self, key, prefix=prefix)

Response: Removes the specified key from the storage object s metadata.


Instruction:
Implement a function in Python 3 to
return a URL that can be used to access this object.

Response:
def get_temp_url(self, seconds, method="GET"):
        """
        Returns a URL that can be used to access this object. The URL will
        expire after `seconds` seconds.

        The only methods supported are GET and PUT. Anything else will raise
        an InvalidTemporaryURLMethod exception.
        """
        return self.container.get_temp_url(self, seconds=seconds,
                method=method)


Instruction:
Here you have a function in Python 3, explain what it does
def get(self, obj):
        name = utils.get_name(obj)
        uri = "/%s/%s" % (self.uri_base, name)
        resp, resp_body = self.api.method_head(uri)
        hdrs = resp.headers
        try:
            content_length = int(hdrs.get("content-length"))
        except (TypeError, ValueError):
            content_length = None
        data = {"name": name,
                "bytes": content_length,
                "content_type": hdrs.get("content-type"),
                "hash": hdrs.get("etag"),
                "last_modified": hdrs.get("last-modified"),
                "timestamp": hdrs.get("x-timestamp"),
                }
        return StorageObject(self, data, loaded=True)

Response: Gets the information about the specified object.


Instruction:
Here you have a function in Python 3, explain what it does
def create(self, file_or_path=None, data=None, obj_name=None,
            content_type=None, etag=None, content_encoding=None,
            content_length=None, ttl=None, chunked=False, metadata=None,
            chunk_size=None, headers=None, return_none=False):
        """
        Creates or replaces a storage object in this container.

        The content of the object can either be a stream of bytes (`data`), or
        a file on disk (`file_or_path`). The disk file can be either an open
        file-like object, or an absolute path to the file on disk.

        When creating object from a data stream, you must specify the name of
        the object to be created in the container via the `obj_name` parameter.
        When working with a file, though, if no `obj_name` value is specified,
        the file`s name will be used.

        You may optionally set the `content_type` and `content_encoding`
        parameters; pyrax will create the appropriate headers when the object
        is stored. If no `content_type` is specified, the object storage system
        will make an intelligent guess based on the content of the object.

        If the size of the file is known, it can be passed as `content_length`.

        If you wish for the object to be temporary, specify the time it should
        be stored in seconds in the `ttl` parameter. If this is specified, the
        object will be deleted after that number of seconds.

        If you wish to store a stream of data (i.e., where you don't know the
        total size in advance), set the `chunked` parameter to True, and omit
        the `content_length` and `etag` parameters. This allows the data to be
        streamed to the object in the container without having to be written to
        disk first.
        """
        # First make sure that there is a content source.
        if (data, file_or_path) == (None, None):
            raise exc.NoContentSpecified("You must specify either a file path, "
                    "an open file-like object, or a stream of bytes when "
                    "creating an object.")
        src = data if data else file_or_path
        if src is file_or_path:
            obj_name = _validate_file_or_path(file_or_path, obj_name)
        if not obj_name:
            raise exc.MissingName("No name for the object to be created has "
                    "been specified, and none can be inferred from context")
        if chunk_size:
            chunked = True
        if chunked:
            chunk_size = chunk_size or DEFAULT_CHUNKSIZE
        headers = headers or {}
        if metadata:
            metadata = _massage_metakeys(metadata, OBJECT_META_PREFIX)
            headers = metadata
        if ttl is not None:
            headers["X-Delete-After"] = ttl
        if src is data:
            self._upload(obj_name, data, content_type,
                    content_encoding, content_length, etag, chunked,
                    chunk_size, headers)
        elif hasattr(file_or_path, "read"):
            self._upload(obj_name, file_or_path, content_type,
                    content_encoding, content_length, etag, False,
                    chunk_size, headers)
        else:
            # Need to wrap the call in a context manager
            with open(file_or_path, "rb") as ff:
                self._upload(obj_name, ff, content_type,
                        content_encoding, content_length, etag, False,
                        chunk_size, headers)
        if return_none:
            return
        return self.get(obj_name)

Response: Creates or replaces a storage object in this container.


Instruction:
Implement a function in Python 3 to
upload the object to the object store.

Response:
def _upload(self, obj_name, content, content_type, content_encoding,
            content_length, etag, chunked, chunk_size, headers):
        """
        Handles the uploading of content, including working around the 5GB
        maximum file size.
        """
        if content_type is not None:
            headers["Content-Type"] = content_type
        if content_encoding is not None:
            headers["Content-Encoding"] = content_encoding
        if isinstance(content, six.string_types):
            fsize = len(content)
        else:
            if chunked:
                fsize = None
            elif content_length is None:
                fsize = get_file_size(content)
            else:
                fsize = content_length
        if fsize is None or fsize <= MAX_FILE_SIZE:
            # We can just upload it as-is.
            return self._store_object(obj_name, content=content, etag=etag,
                    chunked=chunked, chunk_size=chunk_size, headers=headers)
        # Files larger than MAX_FILE_SIZE must be segmented
        # and uploaded separately.
        num_segments = int(math.ceil(float(fsize) / MAX_FILE_SIZE))
        digits = int(math.log10(num_segments)) + 1
        # NOTE: This could be greatly improved with threading or other
        # async design.
        for segment in range(num_segments):
            sequence = str(segment + 1).zfill(digits)
            seg_name = "%s.%s" % (obj_name, sequence)
            with utils.SelfDeletingTempfile() as tmpname:
                with open(tmpname, "wb") as tmp:
                    tmp.write(content.read(MAX_FILE_SIZE))
                with open(tmpname, "rb") as tmp:
                    # We have to calculate the etag for each segment
                    etag = utils.get_checksum(tmp)
                    self._store_object(seg_name, content=tmp, etag=etag,
                            chunked=False, headers=headers)
        # Upload the manifest
        headers.pop("ETag", "")
        headers["X-Object-Manifest"] = "%s/%s." % (self.name, obj_name)
        self._store_object(obj_name, content=None, headers=headers)


Instruction:
Can you implement a function in Python 3 that
stores the contents of an object in the object store.

Response:
def _store_object(self, obj_name, content, etag=None, chunked=False,
            chunk_size=None, headers=None):
        """
        Handles the low-level creation of a storage object and the uploading of
        the contents of that object.
        """
        head_etag = headers.pop("ETag", "")
        if chunked:
            headers.pop("Content-Length", "")
            headers["Transfer-Encoding"] = "chunked"
        elif etag is None and content is not None:
            etag = utils.get_checksum(content)
        if etag:
            headers["ETag"] = etag
        if not headers.get("Content-Type"):
            headers["Content-Type"] = None
        uri = "/%s/%s" % (self.uri_base, obj_name)
        resp, resp_body = self.api.method_put(uri, data=content,
                headers=headers)


Instruction:
Given the following Python 3 function, write the documentation
def fetch(self, obj, include_meta=False, chunk_size=None, size=None,
            extra_info=None):
        """
        Fetches the object from storage.

        If 'include_meta' is False, only the bytes representing the
        stored object are returned.

        Note: if 'chunk_size' is defined, the 'include_meta' parameter is
        ignored.

        If 'size' is specified, only the first 'size' bytes of the object will
        be returned. If the object if smaller than 'size', the entire object is
        returned.

        When 'include_meta' is True, what is returned from this method is a
        2-tuple:
            Element 0: a dictionary containing metadata about the file.
            Element 1: a stream of bytes representing the object's contents.

        The 'extra_info' parameter is included for backwards compatibility. It
        is no longer used at all, and will not be modified with swiftclient
        info, since swiftclient is not used any more.
        """
        uri = "/%s/%s" % (self.uri_base, utils.get_name(obj))
        if chunk_size:
            # Need the total size of the object
            if not isinstance(obj, StorageObject):
                obj = self.get(obj)
            obj_size = obj.total_bytes
            return self._fetch_chunker(uri, chunk_size, size, obj_size)
        headers = {}
        if size:
            headers = {"Range": "bytes=0-%s" % size}
        resp, resp_body = self.api.method_get(uri, headers=headers,
                raw_content=True)
        if include_meta:
            meta_resp, meta_body = self.api.method_head(uri)
            return (meta_resp.headers, resp_body)
        return resp_body

Response: Fetches the object from storage.


Instruction:
How would you explain what the following Python 3 function does
def _fetch_chunker(self, uri, chunk_size, size, obj_size):
        pos = 0
        total_bytes = 0
        size = size or obj_size
        max_size = min(size, obj_size)
        while True:
            endpos = min(obj_size, pos + chunk_size - 1)
            headers = {"Range": "bytes=%s-%s" % (pos, endpos)}
            resp, resp_body = self.api.method_get(uri, headers=headers,
                    raw_content=True)
            pos = endpos + 1
            if not resp_body:
                # End of file
                return
            yield resp_body
            total_bytes += len(resp_body)
            if total_bytes >= max_size:
                return

Response: Returns a generator that returns an object in chunks.


Instruction:
Write a Python 3 function that can
delete all objects in this container.

Response:
def delete_all_objects(self, nms, async_=False):
        """
        Deletes all objects from this container.

        By default the call will block until all objects have been deleted. By
        passing True for the 'async_' parameter, this method will not block, and
        instead return an object that can be used to follow the progress of the
        deletion. When deletion is complete the bulk deletion object's
        'results' attribute will be populated with the information returned
        from the API call. In synchronous mode this is the value that is
        returned when the call completes. It is a dictionary with the following
        keys:

            deleted - the number of objects deleted
            not_found - the number of objects not found
            status - the HTTP return status code. '200 OK' indicates success
            errors - a list of any errors returned by the bulk delete call
        """
        if nms is None:
            nms = self.api.list_object_names(self.name, full_listing=True)
        return self.api.bulk_delete(self.name, nms, async_=async_)


Instruction:
Explain what the following Python 3 code does
def download(self, obj, directory, structure=True):
        if not os.path.isdir(directory):
            raise exc.FolderNotFound("The directory '%s' does not exist." %
                    directory)
        obj_name = utils.get_name(obj)
        path, fname = os.path.split(obj_name)
        if structure:
            fullpath = os.path.join(directory, path)
            if not os.path.exists(fullpath):
                os.makedirs(fullpath)
            target = os.path.join(fullpath, fname)
        else:
            target = os.path.join(directory, fname)
        with open(target, "wb") as dl:
            content = self.fetch(obj)
            try:
                dl.write(content)
            except UnicodeEncodeError:
                encoding = pyrax.get_encoding()
                dl.write(content.encode(encoding))

Response: Downloads the object from storage and writes it to the specified directory.


Instruction:
Implement a Python 3 function for
removing an object from public access before the TTL expires.

Response:
def purge(self, obj, email_addresses=None):
        """
        Removes a CDN-enabled object from public access before the TTL expires.
        Please note that there is a limit (at this time) of 25 such requests;
        if you need to purge more than that, you must contact support.

        If one or more email_addresses are included, an email confirming the
        purge is sent to each address.
        """
        cname = utils.get_name(self.container)
        oname = utils.get_name(obj)
        headers = {}
        if email_addresses:
            email_addresses = utils.coerce_to_list(email_addresses)
            headers["X-Purge-Email"] = ", ".join(email_addresses)
        uri = "/%s/%s" % (cname, oname)
        resp, resp_body = self.api.cdn_request(uri, method="DELETE",
                headers=headers)


Instruction:
Implement a Python 3 function for
returning the metadata for the specified object as a dict.

Response:
def get_metadata(self, obj, prefix=None):
        """
        Returns the metadata for the specified object as a dict.
        """
        uri = "/%s/%s" % (self.uri_base, utils.get_name(obj))
        resp, resp_body = self.api.method_head(uri)
        ret = {}
        # Add the metadata prefix, if needed.
        if prefix is None:
            prefix = OBJECT_META_PREFIX
        low_prefix = prefix.lower()
        for hkey, hval in list(resp.headers.items()):
            lowkey = hkey.lower()
            if lowkey.startswith(low_prefix):
                cleaned = hkey.replace(low_prefix, "").replace("-", "_")
                ret[cleaned] = hval
        return ret


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_metadata(self, obj, metadata, clear=False, prefix=None):
        # Add the metadata prefix, if needed.
        if prefix is None:
            prefix = OBJECT_META_PREFIX
        massaged = _massage_metakeys(metadata, prefix)
        cname = utils.get_name(self.container)
        oname = utils.get_name(obj)
        new_meta = {}
        # Note that the API for object POST is the opposite of that for
        # container POST: for objects, all current metadata is deleted,
        # whereas for containers you need to set the values to an empty
        # string to delete them.
        if not clear:
            obj_meta = self.get_metadata(obj, prefix=prefix)
            new_meta = _massage_metakeys(obj_meta, prefix)
        utils.case_insensitive_update(new_meta, massaged)
        # Remove any empty values, since the object metadata API will
        # store them.
        to_pop = []
        for key, val in six.iteritems(new_meta):
            if not val:
                to_pop.append(key)
        for key in to_pop:
            new_meta.pop(key)
        uri = "/%s/%s" % (cname, oname)
        resp, resp_body = self.api.method_post(uri, headers=new_meta)

Response: Sets the metadata of the specified object.


Instruction:
Can you tell what is the following Python 3 function doing
def remove_metadata_key(self, obj, key):
        meta_dict = {key: ""}
        return self.set_metadata(obj, meta_dict)

Response: Removes the specified key from the object s metadata.


Instruction:
Can you generate the documentation for the following Python 3 function
def _configure_cdn(self):
        ident = self.identity
        cdn_svc = ident.services.get("object_cdn")
        if cdn_svc:
            ep = cdn_svc.endpoints.get(self.region_name)
            if ep:
                self.cdn_management_url = ep.public_url

Response: Initialize CDN - related endpoints if available.


Instruction:
Can you generate the documentation for the following Python 3 function
def _backwards_aliases(self):
        self.list_containers = self.list_container_names
        self.get_all_containers = self.list
        self.get_container = self.get
        self.create_container = self.create
        self.delete_container = self.delete
        self.get_container_objects = self.list_container_objects
        self.get_container_object_names = self.list_container_object_names
        self.get_info = self.get_account_info

Response: In order to keep this backwards - compatible with previous versions of the old names to the new names to the new names.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get(self, item):
        if isinstance(item, six.string_types):
            item = super(StorageClient, self).get(item)
        return item

Response: Returns the container whose name is provided as item.


Instruction:
Can you implement a function in Python 3 that
creates a manager to handle interacting with Containers.

Response:
def _configure_manager(self):
        """
        Creates a manager to handle interacting with Containers.
        """
        self._manager = ContainerManager(self, resource_class=Container,
                response_key="", uri_base="")


Instruction:
Implement a Python 3 function for
returning a dictionary containing information about the account.

Response:
def get_account_details(self):
        """
        Returns a dictionary containing information about the account.
        """
        headers = self._manager.get_account_headers()
        acct_prefix = "x-account-"
        meta_prefix = ACCOUNT_META_PREFIX.lower()
        ret = {}
        for hkey, hval in list(headers.items()):
            lowkey = hkey.lower()
            if lowkey.startswith(acct_prefix):
                if not lowkey.startswith(meta_prefix):
                    cleaned = hkey.replace(acct_prefix, "").replace("-", "_")
                    try:
                        # Most values are ints
                        ret[cleaned] = int(hval)
                    except ValueError:
                        ret[cleaned] = hval
        return ret


Instruction:
Can you implement a function in Python 3 that
returns a tuple for the number of containers and total bytes in the current account.

Response:
def get_account_info(self):
        """
        Returns a tuple for the number of containers and total bytes in the
        account.
        """
        headers = self._manager.get_account_headers()
        return (headers.get("x-account-container-count"),
                headers.get("x-account-bytes-used"))


Instruction:
Write a Python 3 function for
setting the metadata for the given account.

Response:
def set_account_metadata(self, metadata, clear=False, prefix=None,
            extra_info=None):
        """
        Accepts a dictionary of metadata key/value pairs and updates the
        account's metadata with them.

        If 'clear' is True, any existing metadata is deleted and only the
        passed metadata is retained. Otherwise, the values passed here update
        the account's metadata.

        By default, the standard account metadata prefix ('X-Account-Meta-') is
        prepended to the header name if it isn't present. For non-standard
        headers, you must include a non-None prefix, such as an empty string.

        The 'extra_info' parameter is included for backwards compatibility. It
        is no longer used at all, and will not be modified with swiftclient
        info, since swiftclient is not used any more.
        """
        return self._manager.set_account_metadata(metadata, clear=clear,
                prefix=prefix)


Instruction:
Can you tell what is the following Python 3 function doing
def get_temp_url_key(self, cached=True):
        meta = self._cached_temp_url_key
        if not cached or not meta:
            key = "temp_url_key"
            meta = self.get_account_metadata().get(key)
            self._cached_temp_url_key = meta
        return meta

Response: Returns the current TempURL key or None if it has not been set.


Instruction:
Make a summary of the following Python 3 code
def set_temp_url_key(self, key=None):
        if key is None:
            key = uuid.uuid4().hex
        meta = {"Temp-Url-Key": key}
        self.set_account_metadata(meta)
        self._cached_temp_url_key = key

Response: Sets the key for the Temporary URL for the account.


Instruction:
Here you have a function in Python 3, explain what it does
def get_temp_url(self, container, obj, seconds, method="GET", key=None,
            cached=True):
        """
        Given a storage object in a container, returns a URL that can be used
        to access that object. The URL will expire after `seconds` seconds.

        The only methods supported are GET and PUT. Anything else will raise
        an `InvalidTemporaryURLMethod` exception.

        If you have your Temporary URL key, you can pass it in directly and
        potentially save an API call to retrieve it. If you don't pass in the
        key, and don't wish to use any cached value, pass `cached=False`.
        """
        return self._manager.get_temp_url(container, obj, seconds,
                method=method, key=key, cached=cached)

Response: Given a storage object in a container returns a temporary URL that can be used to access that object.


Instruction:
Can you generate the documentation for the following Python 3 function
def list(self, limit=None, marker=None, end_marker=None, prefix=None):
        return self._manager.list(limit=limit, marker=marker,
                end_marker=end_marker, prefix=prefix)

Response:
List the containers in this account using the parameters to control
        pagination


Instruction:
Make a summary of the following Python 3 code
def make_container_public(self, container, ttl=None):
        return self._manager.make_public(container, ttl=ttl)

Response: Enables CDN access for the specified container.


Instruction:
Implement a Python 3 function for
returning a list of info on Containers.

Response:
def list_containers_info(self, limit=None, marker=None):
        """Returns a list of info on Containers.

        For each container, a dict containing the following keys is returned:
        \code
            name - the name of the container
            count - the number of objects in the container
            bytes - the total bytes in the container
        """
        return self._manager.list_containers_info(limit=limit, marker=marker)


Instruction:
Write a Python 3 script for
listing all of the directories in a container.

Response:
def list_container_subdirs(self, container, limit=None, marker=None,
            prefix=None, delimiter=None, full_listing=False):
        """
        Although you cannot nest directories, you can simulate a hierarchical
        structure within a single container by adding forward slash characters
        (/) in the object name. This method returns a list of all of these
        pseudo-subdirectories in the specified container.
        """
        return self._manager.list_subdirs(container, limit=limit,
                marker=marker, prefix=prefix, delimiter=delimiter,
                full_listing=full_listing)


Instruction:
How would you explain what the following Python 3 function does
def list_container_object_names(self, container, limit=None, marker=None,
            prefix=None, delimiter=None, full_listing=False):
        """
        Returns the names of all the objects in the specified container,
        optionally limited by the pagination parameters.
        """
        return self._manager.list_object_names(container, marker=marker,
                limit=limit, prefix=prefix, delimiter=delimiter,
                full_listing=full_listing)

Response: Returns the names of all the objects in the specified container optionally limited by the pagination parameters.


Instruction:
How would you code a function in Python 3 to
return a dictionary containing the metadata for the container.

Response:
def get_container_metadata(self, container, prefix=None):
        """
        Returns a dictionary containing the metadata for the container.
        """
        return self._manager.get_metadata(container, prefix=prefix)


Instruction:
Write a Python 3 function that can
set the metadata for a container.

Response:
def set_container_metadata(self, container, metadata, clear=False,
            prefix=None):
        """
        Accepts a dictionary of metadata key/value pairs and updates the
        specified container metadata with them.

        If 'clear' is True, any existing metadata is deleted and only the
        passed metadata is retained. Otherwise, the values passed here update
        the container's metadata.

        By default, the standard container metadata prefix
        ('X-Container-Meta-') is prepended to the header name if it isn't
        present. For non-standard headers, you must include a non-None prefix,
        such as an empty string.
        """
        return self._manager.set_metadata(container, metadata, clear=clear,
                prefix=prefix)


Instruction:
How would you code a function in Python 3 to
remove all of the metadata of a container.

Response:
def delete_container_metadata(self, container, prefix=None):
        """
        Removes all of thethe container's metadata.

        By default, all metadata beginning with the standard container metadata
        prefix ('X-Container-Meta-') is removed. If you wish to remove all
        metadata beginning with a different prefix, you must specify that
        prefix.
        """
        return self._manager.delete_metadata(container, prefix=prefix)


Instruction:
Can you tell what is the following Python 3 function doing
def get_object_metadata(self, container, obj, prefix=None):
        return self._manager.get_object_metadata(container, obj, prefix=prefix)

Response: Returns the metadata for the specified object as a dict.


Instruction:
How would you implement a function in Python 3 that
removes the specified key from the storage object s metadata.

Response:
def remove_object_metadata_key(self, container, obj, key, prefix=None):
        """
        Removes the specified key from the storage object's metadata. If the key
        does not exist in the metadata, nothing is done.
        """
        self.set_object_metadata(container, obj, {key: ""}, prefix=prefix)


Instruction:
Can you tell what is the following Python 3 function doing
def list_container_objects(self, container, limit=None, marker=None,
            prefix=None, delimiter=None, end_marker=None, full_listing=False):
        """
        Return a list of StorageObjects representing the objects in the
        container. You can use the marker, end_marker, and limit params to
        handle pagination, and the prefix and delimiter params to filter the
        objects returned.  Also, by default only the first 10,000 objects are
        returned; if you set full_listing to True, an iterator to return all
        the objects in the container is returned. In this case, only the
        'prefix' parameter is used; if you specify any others, they are
        ignored.
        """
        if full_listing:
            return self._manager.object_listing_iterator(container,
                    prefix=prefix)
        return self._manager.list_objects(container, limit=limit,
                marker=marker, prefix=prefix, delimiter=delimiter,
                end_marker=end_marker)

Response: List the objects in a container.


Instruction:
Implement a function in Python 3 to
delete the specified object in the specified container in the specified number of seconds.

Response:
def delete_object_in_seconds(self, cont, obj, seconds, extra_info=None):
        """
        Sets the object in the specified container to be deleted after the
        specified number of seconds.

        The 'extra_info' parameter is included for backwards compatibility. It
        is no longer used at all, and will not be modified with swiftclient
        info, since swiftclient is not used any more.
        """
        return self._manager.delete_object_in_seconds(cont, obj, seconds)


Instruction:
Write a Python 3 script for
storing an object in a container.

Response:
def store_object(self, container, obj_name, data, content_type=None,
            etag=None, content_encoding=None, ttl=None, return_none=False,
            chunk_size=None, headers=None, metadata=None, extra_info=None):
        """
        Creates a new object in the specified container, and populates it with
        the given data. A StorageObject reference to the uploaded file
        will be returned, unless 'return_none' is set to True.

        The 'extra_info' parameter is included for backwards compatibility. It
        is no longer used at all, and will not be modified with swiftclient
        info, since swiftclient is not used any more.
        """
        return self.create_object(container, obj_name=obj_name, data=data,
                content_type=content_type, etag=etag,
                content_encoding=content_encoding, ttl=ttl,
                return_none=return_none, chunk_size=chunk_size,
                headers=headers, metadata=metadata)


Instruction:
Write a Python 3 script for
uploading a file to a container.

Response:
def upload_file(self, container, file_or_path, obj_name=None,
            content_type=None, etag=None, content_encoding=None, ttl=None,
            content_length=None, return_none=False, headers=None,
            metadata=None, extra_info=None):
        """
        Uploads the specified file to the container. If no name is supplied,
        the file's name will be used. Either a file path or an open file-like
        object may be supplied. A StorageObject reference to the uploaded file
        will be returned, unless 'return_none' is set to True.

        You may optionally set the `content_type` and `content_encoding`
        parameters; pyrax will create the appropriate headers when the object
        is stored.

        If the size of the file is known, it can be passed as `content_length`.

        If you wish for the object to be temporary, specify the time it should
        be stored in seconds in the `ttl` parameter. If this is specified, the
        object will be deleted after that number of seconds.

        The 'extra_info' parameter is included for backwards compatibility. It
        is no longer used at all, and will not be modified with swiftclient
        info, since swiftclient is not used any more.
        """
        return self.create_object(container, file_or_path=file_or_path,
                obj_name=obj_name, content_type=content_type, etag=etag,
                content_encoding=content_encoding, ttl=ttl, headers=headers,
                metadata=metadata, return_none=return_none)


Instruction:
Explain what the following Python 3 code does
def fetch_object(self, container, obj, include_meta=False,
            chunk_size=None, size=None, extra_info=None):
        """
        Fetches the object from storage.

        If 'include_meta' is False, only the bytes representing the
        stored object are returned.

        Note: if 'chunk_size' is defined, you must fully read the object's
        contents before making another request.

        If 'size' is specified, only the first 'size' bytes of the object will
        be returned. If the object if smaller than 'size', the entire object is
        returned.

        When 'include_meta' is True, what is returned from this method is a
        2-tuple:
            Element 0: a dictionary containing metadata about the file.
            Element 1: a stream of bytes representing the object's contents.

        The 'extra_info' parameter is included for backwards compatibility. It
        is no longer used at all, and will not be modified with swiftclient
        info, since swiftclient is not used any more.
        """
        return self._manager.fetch_object(container, obj,
                include_meta=include_meta, chunk_size=chunk_size, size=size)

Response: Fetches the object from storage.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def fetch_partial(self, container, obj, size):
        return self._manager.fetch_partial(container, obj, size)

Response: Fetch a partial version of the object.


Instruction:
Make a summary of the following Python 3 code
def fetch_dlo(self, container, name, chunk_size=None, verbose=False):
        if chunk_size is None:
            chunk_size = DEFAULT_CHUNKSIZE

        class FetchChunker(object):
            """
            Class that takes the generator objects returned by a chunked
            fetch_object() call and wraps them to behave as file-like objects
            for uploading.
            """
            def __init__(self, gen, verbose=False):
                self.gen = gen
                self.verbose = verbose
                self.processed = 0
                self.count = 0
                self.interval = 100

            def read(self, size=None):
                self.count += 1
                if self.verbose:
                    if self.count > self.interval:
                        self.count = 0
                        print(".")
                ret = next(self.gen)
                self.processed += len(ret)
                return ret

        parts = self.get_container_objects(container, prefix=name)
        fetches = [(part.name, self.fetch_object(container, part.name,
                    chunk_size=chunk_size))
                for part in parts
                if part.name != name]
        job = [(fetch[0], FetchChunker(fetch[1], verbose=verbose))
                for fetch in fetches]
        return job

Response: Fetch a single - part DLO from a container.


Instruction:
Make a summary of the following Python 3 code
def download_object(self, container, obj, directory, structure=True):
        return self._manager.download_object(container, obj, directory,
                structure=structure)

Response: Downloads the specified object from storage and writes it to the specified directory.


Instruction:
Here you have a function in Python 3, explain what it does
def delete(self, container, del_objects=False):
        return self._manager.delete(container, del_objects=del_objects)

Response: Deletes the specified container.


Instruction:
Make a summary of the following Python 3 code
def copy_object(self, container, obj, new_container, new_obj_name=None,
            content_type=None, extra_info=None):
        """
        Copies the object to the new container, optionally giving it a new name.
        If you copy to the same container, you must supply a different name.

        You can optionally change the content_type of the object by supplying
        that in the 'content_type' parameter.

        The 'extra_info' parameter is included for backwards compatibility. It
        is no longer used at all, and will not be modified with swiftclient
        info, since swiftclient is not used any more.
        """
        return self._manager.copy_object(container, obj, new_container,
                new_obj_name=new_obj_name, content_type=content_type)

Response: Copies the object to a new container optionally giving it a new name.


Instruction:
Here you have a function in Python 3, explain what it does
def move_object(self, container, obj, new_container, new_obj_name=None,
            new_reference=False, content_type=None, extra_info=None):
        """
        Works just like copy_object, except that the source object is deleted
        after a successful copy.

        You can optionally change the content_type of the object by supplying
        that in the 'content_type' parameter.

        NOTE: any references to the original object will no longer be valid;
        you will have to get a reference to the new object by passing True for
        the 'new_reference' parameter. When this is True, a reference to the
        newly moved object is returned. Otherwise, the etag for the moved
        object is returned.

        The 'extra_info' parameter is included for backwards compatibility. It
        is no longer used at all, and will not be modified with swiftclient
        info, since swiftclient is not used any more.
        """
        return self._manager.move_object(container, obj, new_container,
                new_obj_name=new_obj_name, new_reference=new_reference,
                content_type=content_type)

Response: Moves an object from one container to another.


Instruction:
Write a Python 3 function for
copying an object to itself but applies a new content - type.

Response:
def change_object_content_type(self, container, obj, new_ctype,
            guess=False, extra_info=None):
        """
        Copies object to itself, but applies a new content-type. The guess
        feature requires the container to be CDN-enabled. If not then the
        content-type must be supplied. If using guess with a CDN-enabled
        container, new_ctype can be set to None. Failure during the put will
        result in a swift exception.

        The 'extra_info' parameter is included for backwards compatibility. It
        is no longer used at all, and will not be modified with swiftclient
        info, since swiftclient is not used any more.
        """
        return self._manager.change_object_content_type(container, obj,
                new_ctype, guess=guess)


Instruction:
Make a summary of the following Python 3 code
def _upload_folder_in_background(self, folder_path, container, ignore,
            upload_key, ttl=None):
        """Runs the folder upload in the background."""
        uploader = FolderUploader(folder_path, container, ignore, upload_key,
                self, ttl=ttl)
        uploader.start()

Response: Runs the folder upload in the background.


Instruction:
Can you generate the documentation for the following Python 3 function
def sync_folder_to_container(self, folder_path, container, delete=False,
            include_hidden=False, ignore=None, ignore_timestamps=False,
            object_prefix="", verbose=False):
        """
        Compares the contents of the specified folder, and checks to make sure
        that the corresponding object is present in the specified container. If
        there is no remote object matching the local file, it is created. If a
        matching object exists, the etag is examined to determine if the object
        in the container matches the local file; if they differ, the container
        is updated with the local file if the local file is newer when
        `ignore_timestamps' is False (default). If `ignore_timestamps` is True,
        the object is overwritten with the local file contents whenever the
        etags differ. NOTE: the timestamp of a remote object is the time it was
        uploaded, not the original modification time of the file stored in that
        object.  Unless 'include_hidden' is True, files beginning with an
        initial period are ignored.

        If the 'delete' option is True, any objects in the container that do
        not have corresponding files in the local folder are deleted.

        You can selectively ignore files by passing either a single pattern or
        a list of patterns; these will be applied to the individual folder and
        file names, and any names that match any of the 'ignore' patterns will
        not be uploaded. The patterns should be standard *nix-style shell
        patterns; e.g., '*pyc' will ignore all files ending in 'pyc', such as
        'program.pyc' and 'abcpyc'.

        If `object_prefix` is set it will be appended to the object name when
        it is checked and uploaded to the container. For example, if you use
        sync_folder_to_container("folderToSync/", myContainer,
            object_prefix="imgFolder") it will upload the files to the
        container/imgFolder/... instead of just container/...

        Set `verbose` to True to make it print what is going on. It will
        show which files are being uploaded and which ones are not and why.
        """
        cont = self.get_container(container)
        self._local_files = []
        # Load a list of all the remote objects so we don't have to keep
        # hitting the service
        if verbose:
            log = logging.getLogger("pyrax")
            log.info("Loading remote object list (prefix=%s)", object_prefix)
        data = cont.get_objects(prefix=object_prefix, full_listing=True)
        self._remote_files = dict((d.name, d) for d in data)
        self._sync_summary = {"total": 0,
                "uploaded": 0,
                "ignored": 0,
                "older": 0,
                "duplicate": 0,
                "failed": 0,
                "failure_reasons": [],
                "deleted": 0,
                }
        self._sync_folder_to_container(folder_path, cont, prefix="",
                delete=delete, include_hidden=include_hidden, ignore=ignore,
                ignore_timestamps=ignore_timestamps,
                object_prefix=object_prefix, verbose=verbose)
        # Unset the _remote_files
        self._remote_files = None
        if verbose:
            # Log the summary
            summary = self._sync_summary
            log.info("Folder sync completed at %s" % time.ctime())
            log.info("  Total files processed: %s" % summary["total"])
            log.info("  Number Uploaded: %s" % summary["uploaded"])
            log.info("  Number Ignored: %s" % summary["ignored"])
            log.info("  Number Skipped (older): %s" % summary["older"])
            log.info("  Number Skipped (dupe): %s" % summary["duplicate"])
            log.info("  Number Deleted: %s" % summary["deleted"])
            log.info("  Number Failed: %s" % summary["failed"])
            if summary["failed"]:
                for reason in summary["failure_reasons"]:
                    log.info("  Reason: %s" % reason)

Response: Syncs the contents of the specified folder to the specified container.


Instruction:
Can you create a Python 3 function that
deletes all the objects that are not present in the specified container.

Response:
def _delete_objects_not_in_list(self, cont, object_prefix=""):
        """
        Finds all the objects in the specified container that are not present
        in the self._local_files list, and deletes them.
        """
        objnames = set(cont.get_object_names(prefix=object_prefix,
                full_listing=True))
        localnames = set(self._local_files)
        to_delete = list(objnames.difference(localnames))
        self._sync_summary["deleted"] += len(to_delete)
        # We don't need to wait around for this to complete. Store the thread
        # reference in case it is needed at some point.
        self._thread = self.bulk_delete(cont, to_delete, async_=True)


Instruction:
Write a Python 3 function for
bulking deletes multiple objects from a container in a single call.

Response:
def bulk_delete(self, container, object_names, async_=False):
        """
        Deletes multiple objects from a container in a single call.

        The bulk deletion call does not return until all of the specified
        objects have been processed. For large numbers of objects, this can
        take quite a while, so there is an 'async_' parameter to give you the
        option to have this call return immediately. If 'async_' is True, an
        object is returned with a 'completed' attribute that will be set to
        True as soon as the bulk deletion is complete, and a 'results'
        attribute that will contain a dictionary (described below) with the
        results of the bulk deletion.

        When deletion is complete the bulk deletion object's 'results'
        attribute will be populated with the information returned from the API
        call. In synchronous mode this is the value that is returned when the
        call completes. It is a dictionary with the following keys:

            deleted - the number of objects deleted
            not_found - the number of objects not found
            status - the HTTP return status code. '200 OK' indicates success
            errors - a list of any errors returned by the bulk delete call

        This isn't available in swiftclient yet, so it's using code patterned
        after the client code in that library.
        """
        deleter = BulkDeleter(self, container, object_names)
        deleter.start()
        if async_:
            return deleter
        while not deleter.completed:
            time.sleep(self.bulk_delete_interval)
        return deleter.results


Instruction:
Can you tell what is the following Python 3 function doing
def upload_files_in_folder(self, dirname, fnames):
        if utils.match_pattern(dirname, self.ignore):
            return False
        good_names = (nm for nm in fnames
                if not utils.match_pattern(nm, self.ignore))
        for fname in good_names:
            if self.client._should_abort_folder_upload(self.upload_key):
                return
            full_path = os.path.join(dirname, fname)
            obj_name = os.path.relpath(full_path, self.root_folder)
            obj_size = os.stat(full_path).st_size
            self.client.upload_file(self.container, full_path,
                    obj_name=obj_name, return_none=True, ttl=self.ttl)
            self.client._update_progress(self.upload_key, obj_size)

Response: Handles the iteration across files within a folder.


Instruction:
Can you implement a function in Python 3 that
starts the uploading thread.

Response:
def run(self):
        """Starts the uploading thread."""
        root_path, folder_name = os.path.split(self.root_folder)
        self.root_folder = os.path.join(root_path, folder_name)
        for dirname, _, fnames in os.walk(self.root_folder):
            self.upload_files_in_folder(dirname, fnames)


Instruction:
Write a Python 3 function for
giving an iterable enumerate its contents for a user to choose from.

Response:
def option_chooser(options, attr=None):
    """Given an iterable, enumerate its contents for a user to choose from.
    If the optional `attr` is not None, that attribute in each iterated
    object will be printed.

    This function will exit the program if the user chooses the escape option.
    """
    for num, option in enumerate(options):
        if attr:
            print("%s: %s" % (num, getattr(option, attr)))
        else:
            print("%s: %s" % (num, option))
    # Add an escape option
    escape_opt = num + 1
    print("%s: I want to exit!" % escape_opt)
    choice = six.moves.input("Selection: ")
    try:
        ichoice = int(choice)
        if ichoice > escape_opt:
            raise ValueError
    except ValueError:
        print("Valid entries are the numbers 0-%s. Received '%s'." % (escape_opt,
                choice))
        sys.exit()

    if ichoice == escape_opt:
        print("Bye!")
        sys.exit()

    return ichoice


Instruction:
Can you implement a function in Python 3 that
assures that a queue ID or name is passed as the queue parameter.

Response:
def assure_queue(fnc):
    """
    Converts a queue ID or name passed as the 'queue' parameter to a Queue
    object.
    """
    @wraps(fnc)
    def _wrapped(self, queue, *args, **kwargs):
        if not isinstance(queue, Queue):
            # Must be the ID
            queue = self._manager.get(queue)
        return fnc(self, queue, *args, **kwargs)
    return _wrapped


Instruction:
Create a Python 3 function for
deleting the message with the supplied ID from the message manager.

Response:
def delete_message(self, msg_id, claim_id=None):
        """
        Deletes the message whose ID matches the supplied msg_id from the
        specified queue. If the message has been claimed, the ID of that claim
        must be passed as the 'claim_id' parameter.
        """
        return self._message_manager.delete(msg_id, claim_id=claim_id)


Instruction:
Given the following Python 3 function, write the documentation
def list(self, include_claimed=False, echo=False, marker=None, limit=None):
        return self._message_manager.list(include_claimed=include_claimed,
                echo=echo, marker=marker, limit=limit)

Response: Returns a list of all messages for this queue.


Instruction:
Here you have a function in Python 3, explain what it does
def list_by_claim(self, claim):
        if not isinstance(claim, QueueClaim):
            claim = self._claim_manager.get(claim)
        return claim.messages

Response: Returns a list of all the messages that have been claimed by the specified claim.


Instruction:
Implement a Python 3 function for
returning a new QueueClaim object that contains the messages that have been claimed for the given time period and the count unclaimed messages.

Response:
def claim_messages(self, ttl, grace, count=None):
        """
        Claims up to `count` unclaimed messages from this queue. If count is
        not specified, the default is to claim 10 messages.

        The `ttl` parameter specifies how long the server should wait before
        releasing the claim. The ttl value MUST be between 60 and 43200 seconds.

        The `grace` parameter is the message grace period in seconds. The value
        of grace MUST be between 60 and 43200 seconds. The server extends the
        lifetime of claimed messages to be at least as long as the lifetime of
        the claim itself, plus a specified grace period to deal with crashed
        workers (up to 1209600 or 14 days including claim lifetime). If a
        claimed message would normally live longer than the grace period, its
        expiration will not be adjusted.

        Returns a QueueClaim object, whose 'messages' attribute contains the
        list of QueueMessage objects representing the claimed messages.
        """
        return self._claim_manager.claim(ttl, grace, count=count)


Instruction:
Write a Python 3 script to
update the specified claim with either a new TTL or a new grace period.

Response:
def update_claim(self, claim, ttl=None, grace=None):
        """
        Updates the specified claim with either a new TTL or grace period, or
        both.
        """
        return self._claim_manager.update(claim, ttl=ttl, grace=grace)


Instruction:
Make a summary of the following Python 3 code
def _add_details(self, info):
        super(QueueMessage, self)._add_details(info)
        if self.href is None:
            return
        parsed = urllib.parse.urlparse(self.href)
        self.id = parsed.path.rsplit("/", 1)[-1]
        query = parsed.query
        if query:
            self.claim_id = query.split("claim_id=")[-1]

Response: Add details to the object.


Instruction:
Can you implement a function in Python 3 that
adds details to the object.

Response:
def _add_details(self, info):
        """
        The 'id' attribute is not supplied directly, but included as part of
        the 'href' value. Also, convert the dicts for messages into
        QueueMessage objects.
        """
        msg_dicts = info.pop("messages", [])
        super(QueueClaim, self)._add_details(info)
        parsed = urllib.parse.urlparse(self.href)
        self.id = parsed.path.rsplit("/", 1)[-1]
        self.messages = [QueueMessage(self.manager._message_manager, item)
                for item in msg_dicts]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def list(self, include_claimed=False, echo=False, marker=None, limit=None):
        return self._iterate_list(include_claimed=include_claimed, echo=echo,
                marker=marker, limit=limit)

Response: List the available resource names.


Instruction:
How would you implement a function in Python 3 that
deletes the specified message from its queue.

Response:
def delete(self, msg, claim_id=None):
        """
        Deletes the specified message from its queue. If the message has been
        claimed, the ID of that claim must be passed as the 'claim_id'
        parameter.
        """
        msg_id = utils.get_id(msg)
        if claim_id:
            uri = "/%s/%s?claim_id=%s" % (self.uri_base, msg_id, claim_id)
        else:
            uri = "/%s/%s" % (self.uri_base, msg_id)
        return self._delete(uri)


Instruction:
How would you explain what the following Python 3 function does
def list_by_ids(self, ids):
        ids = utils.coerce_to_list(ids)
        uri = "/%s?ids=%s" % (self.uri_base, ",".join(ids))
        # The API is not consistent in how it returns message lists, so this
        # workaround is needed.
        curr_prkey = self.plural_response_key
        self.plural_response_key = ""
        # BROKEN: API returns a list, not a dict.
        ret = self._list(uri)
        self.plural_response_key = curr_prkey
        return ret

Response: This method returns a list of all the messages in this queue that match the given IDs.


Instruction:
Create a Python 3 function to
delete the messages whose IDs are passed in from this queue.

Response:
def delete_by_ids(self, ids):
        """
        Deletes the messages whose IDs are passed in from this queue.
        """
        ids = utils.coerce_to_list(ids)
        uri = "/%s?ids=%s" % (self.uri_base, ",".join(ids))
        return self.api.method_delete(uri)


Instruction:
Write a Python 3 function for
claiming up to `count` unclaimed messages from this queue. If count is not specified, the default is to claim 10 messages. The `ttl` parameter specifies how long the server should wait before releasing the claim. The ttl value MUST be between 60 and 43200 seconds. The `grace` parameter is the message grace period in seconds. The value of grace MUST be between 60 and 43200 seconds. The server extends the lifetime of claimed messages to be at least as long as the lifetime of the claim itself, plus a specified grace period to deal with crashed workers (up to 1209600 or 14 days including claim lifetime). If a claimed message would normally live longer than the grace period, its expiration will not be adjusted. bReturns a QueueClaim object, whose 'messages' attribute contains the list of QueueMessage objects representing the claimed messages.

Response:
def claim(self, ttl, grace, count=None):
        """
        Claims up to `count` unclaimed messages from this queue. If count is
        not specified, the default is to claim 10 messages.

        The `ttl` parameter specifies how long the server should wait before
        releasing the claim. The ttl value MUST be between 60 and 43200 seconds.

        The `grace` parameter is the message grace period in seconds. The value
        of grace MUST be between 60 and 43200 seconds. The server extends the
        lifetime of claimed messages to be at least as long as the lifetime of
        the claim itself, plus a specified grace period to deal with crashed
        workers (up to 1209600 or 14 days including claim lifetime). If a
        claimed message would normally live longer than the grace period, its
        expiration will not be adjusted.

        bReturns a QueueClaim object, whose 'messages' attribute contains the
        list of QueueMessage objects representing the claimed messages.
        """
        if count is None:
            qs = ""
        else:
            qs = "?limit=%s" % count
        uri = "/%s%s" % (self.uri_base, qs)
        body = {"ttl": ttl,
                "grace": grace,
                }
        resp, resp_body = self.api.method_post(uri, body=body)
        if resp.status_code == 204:
            # Nothing available to claim
            return None
        # Get the claim ID from the first message in the list.
        href = resp_body[0]["href"]
        claim_id = href.split("claim_id=")[-1]
        return self.get(claim_id)


Instruction:
Can you generate the documentation for the following Python 3 function
def update(self, claim, ttl=None, grace=None):
        body = {}
        if ttl is not None:
            body["ttl"] = ttl
        if grace is not None:
            body["grace"] = grace
        if not body:
            raise exc.MissingClaimParameters("You must supply a value for "
                    "'ttl' or 'grace' when calling 'update()'")
        uri = "/%s/%s" % (self.uri_base, utils.get_id(claim))
        resp, resp_body = self.api.method_patch(uri, body=body)

Response: Updates the specified resource in the specified resource store.


Instruction:
Can you generate the documentation for the following Python 3 function
def get(self, id_):
        if self.api.queue_exists(id_):
            return Queue(self, {"queue": {"name": id_, "id_": id_}}, key="queue")
        raise exc.NotFound("The queue '%s' does not exist." % id_)

Response: Get a specific queue by ID.


Instruction:
Explain what the following Python 3 code does
def get_stats(self, queue):
        uri = "/%s/%s/stats" % (self.uri_base, utils.get_id(queue))
        resp, resp_body = self.api.method_get(uri)
        return resp_body.get("messages")

Response: Returns the message stats for the specified queue.


Instruction:
Write a Python 3 function for
returning the metadata for the specified queue.

Response:
def get_metadata(self, queue):
        """
        Returns the metadata for the specified queue.
        """
        uri = "/%s/%s/metadata" % (self.uri_base, utils.get_id(queue))
        resp, resp_body = self.api.method_get(uri)
        return resp_body


Instruction:
Can you tell what is the following Python 3 function doing
def set_metadata(self, queue, metadata, clear=False):
        uri = "/%s/%s/metadata" % (self.uri_base, utils.get_id(queue))
        if clear:
            curr = {}
        else:
            curr = self.get_metadata(queue)
        curr.update(metadata)
        resp, resp_body = self.api.method_put(uri, body=curr)

Response: Sets the metadata for the specified queue.


Instruction:
Can you generate the documentation for the following Python 3 function
def _configure_manager(self):
        self._manager = QueueManager(self,
                resource_class=Queue, response_key="queue",
                uri_base="queues")

Response: Create the manager to handle queues.


Instruction:
How would you explain what the following Python 3 function does
def _add_custom_headers(self, dct):
        if self.client_id is None:
            self.client_id = os.environ.get("CLOUD_QUEUES_ID")
        if self.client_id:
            dct["Client-ID"] = self.client_id

Response: Add the Client - ID header required by Cloud Queues


Instruction:
Here you have a function in Python 3, explain what it does
def _api_request(self, uri, method, **kwargs):
        try:
            return super(QueueClient, self)._api_request(uri, method, **kwargs)
        except exc.BadRequest as e:
            if ((e.code == "400") and
                    (e.message == 'The "Client-ID" header is required.')):
                raise exc.QueueClientIDNotDefined("You must supply a client ID "
                        "to work with Queue messages.")
            else:
                raise

Response: This is the base method for handling the necessary exceptions.


Instruction:
Write a Python 3 script for
returning True if the named queue exists False otherwise.

Response:
def queue_exists(self, name):
        """
        Returns True or False, depending on the existence of the named queue.
        """
        try:
            queue = self._manager.head(name)
            return True
        except exc.NotFound:
            return False


Instruction:
How would you code a function in Python 3 to
create a new queue with the given name.

Response:
def create(self, name):
        """
        Cloud Queues works differently, in that they use the name as the ID for
        the resource. So for create(), we need to check if a queue by that name
        exists already, and raise an exception if it does. If not, create the
        queue and return a reference object for it.
        """
        if self.queue_exists(name):
            raise exc.DuplicateQueue("The queue '%s' already exists." % name)
        return self._manager.create(name)


Instruction:
Explain what the following Python 3 code does
def set_metadata(self, queue, metadata, clear=False):
        return self._manager.set_metadata(queue, metadata, clear=clear)

Response: Sets the metadata for the specified queue.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def delete_message(self, queue, msg_id, claim_id=None):
        return queue.delete_message(msg_id, claim_id=claim_id)

Response: Deletes the message with the supplied ID from the specified queue.


Instruction:
Can you generate the documentation for the following Python 3 function
def list_messages(self, queue, include_claimed=False, echo=False,
            marker=None, limit=None):
        """
        Returns a list of messages for the specified queue.

        By default only unclaimed messages are returned; if you want claimed
        messages included, pass `include_claimed=True`. Also, the requester's
        own messages are not returned by default; if you want them included,
        pass `echo=True`.

        The 'marker' and 'limit' parameters are used to control pagination of
        results. 'Marker' is the ID of the last message returned, while 'limit'
        controls the number of messages returned per reuqest (default=20).
        """
        return queue.list(include_claimed=include_claimed, echo=echo,
                marker=marker, limit=limit)

Response: Returns a list of all messages for the specified queue.


Instruction:
Can you tell what is the following Python 3 function doing
def claim_messages(self, queue, ttl, grace, count=None):
        return queue.claim_messages(ttl, grace, count=count)

Response: Returns a new QueueClaim object that contains the messages claimed by the server.


Instruction:
How would you explain what the following Python 3 function does
def update_claim(self, queue, claim, ttl=None, grace=None):
        return queue.update_claim(claim, ttl=ttl, grace=grace)

Response: Updates the specified claim in the specified queue.


Instruction:
Implement a function in Python 3 to
create the Manager instances to handle monitoring.

Response:
def _configure_manager(self):
        """
        Creates the Manager instances to handle monitoring.
        """
        self._flavor_manager = CloudCDNFlavorManager(self,
                uri_base="flavors", resource_class=CloudCDNFlavor,
                response_key=None, plural_response_key="flavors")
        self._services_manager = CloudCDNServiceManager(self,
                uri_base="services", resource_class=CloudCDNService,
                response_key=None, plural_response_key="services")


Instruction:
Make a summary of the following Python 3 code
def create_service(self, name, flavor_id, domains, origins,
                       restrictions=None, caching=None):
        """Create a new CDN service.

        Arguments:
        name: The name of the service.
        flavor_id: The ID of the flavor to use for this service.
        domains: A list of dictionaries, each of which has a required
                 key "domain" and optional key "protocol" (the default
                 protocol is http).
        origins: A list of dictionaries, each of which has a required
                 key "origin" which is the URL or IP address to pull
                 origin content from. Optional keys include "port" to
                 use a port other than the default of 80, and "ssl"
                 to enable SSL, which is disabled by default.
        caching: An optional

        """
        return self._services_manager.create(name, flavor_id, domains, origins,
                                             restrictions, caching)

Response: Create a new CDN service.


Instruction:
Here you have a function in Python 3, explain what it does
def delete_assets(self, service_id, url=None, all=False):
        self._services_manager.delete_assets(service_id, url, all)

Response: Delete CDN assets associated with a service_id.


Instruction:
How would you explain what the following Python 3 function does
def url_for(self, attr=None, filter_value=None,
            service_type=None, endpoint_type="publicURL",
            service_name=None, volume_service_name=None):
        """Fetches the public URL from the given service for
        a particular endpoint attribute. If none given, returns
        the first. See tests for sample service catalog."""
        matching_endpoints = []
        # We don't always get a service catalog back ...
        if "serviceCatalog" not in self.catalog["access"]:
            return None

        # Full catalog ...
        catalog = self.catalog["access"]["serviceCatalog"]
        for service in catalog:
            if service.get("type") != service_type:
                continue
            endpoints = service["endpoints"]
            for endpoint in endpoints:
                if not filter_value or endpoint.get(attr) == filter_value:
                    endpoint["serviceName"] = service.get("name")
                    matching_endpoints.append(endpoint)

        if not matching_endpoints:
            raise exc.EndpointNotFound()
        elif len(matching_endpoints) > 1:
            raise exc.AmbiguousEndpoints(endpoints=matching_endpoints)
        else:
            return matching_endpoints[0][endpoint_type]

Response: Fetches the public URL for a particular endpoint attribute. If none given returns the first endpoint. If none given returns the first endpoint.


Instruction:
Write a Python 3 function that can
get the usage records for this load balancer.

Response:
def get_usage(self, start=None, end=None):
        """
        Return the usage records for this load balancer. You may optionally
        include a start datetime or an end datetime, or both, which will limit
        the records to those on or after the start time, and those before or on
        the end time. These times should be Python datetime.datetime objects,
        Python datetime.date objects, or strings in the format:
        "YYYY-MM-DD HH:MM:SS" or "YYYY-MM-DD".
        """
        return self.manager.get_usage(self, start=start, end=end)


Instruction:
Make a summary of the following Python 3 code
def _add_details(self, info):
        for (key, val) in six.iteritems(info):
            if key == "nodes":
                val = [Node(parent=self, **nd) for nd in val]
            elif key == "sessionPersistence":
                val = val['persistenceType']
            elif key == "cluster":
                val = val['name']
            elif key == "virtualIps":
                key = "virtual_ips"
                val = [VirtualIP(parent=self, **vip) for vip in val]
            setattr(self, key, val)

Response: Override the base behavior to add Nodes VirtualIPs etc.


Instruction:
How would you explain what the following Python 3 function does
def update(self, name=None, algorithm=None, protocol=None, halfClosed=None,
            port=None, timeout=None, httpsRedirect=None):
        """
        Provides a way to modify the following attributes of a load balancer:
            - name
            - algorithm
            - protocol
            - halfClosed
            - port
            - timeout
            - httpsRedirect
        """
        return self.manager.update(self, name=name, algorithm=algorithm,
                protocol=protocol, halfClosed=halfClosed, port=port,
                timeout=timeout, httpsRedirect=httpsRedirect)

Response: Updates the attributes of the current load balancer.


Instruction:
Can you tell what is the following Python 3 function doing
def update_node(self, node, diff=None):
        return self.manager.update_node(node, diff=diff)

Response: Updates the attributes of a node.


Instruction:
Explain what the following Python 3 code does
def add_health_monitor(self, type, delay=10, timeout=10,
            attemptsBeforeDeactivation=3, path="/", statusRegex=None,
            bodyRegex=None, hostHeader=None):
        """
        Adds a health monitor to the load balancer. If a monitor already
        exists, it is updated with the supplied settings.
        """
        abd = attemptsBeforeDeactivation
        return self.manager.add_health_monitor(self, type=type, delay=delay,
                timeout=timeout, attemptsBeforeDeactivation=abd,
                path=path, statusRegex=statusRegex, bodyRegex=bodyRegex,
                hostHeader=hostHeader)

Response: Adds a health monitor to the load balancer.


Instruction:
How would you explain what the following Python 3 function does
def add_connection_throttle(self, maxConnectionRate=None,
            maxConnections=None, minConnections=None, rateInterval=None):
        """
        Updates the connection throttling information for the load balancer with
        the supplied values. At least one of the parameters must be supplied.
        """
        if not any((maxConnectionRate, maxConnections, minConnections,
                rateInterval)):
            # Pointless call
            return
        return self.manager.add_connection_throttle(self,
                maxConnectionRate=maxConnectionRate, maxConnections=maxConnections,
                minConnections=minConnections, rateInterval=rateInterval)

Response: Adds a connection throttling information to the load balancer with the supplied parameters.


Instruction:
Can you tell what is the following Python 3 function doing
def add_ssl_termination(self, securePort, privatekey, certificate,
            intermediateCertificate=None, enabled=True,
            secureTrafficOnly=False):
        """
        Adds SSL termination information to the load balancer. If SSL
        termination has already been configured, it is updated with the
        supplied settings.
        """
        return self.manager.add_ssl_termination(self, securePort=securePort,
                privatekey=privatekey, certificate=certificate,
                intermediateCertificate=intermediateCertificate,
                enabled=enabled, secureTrafficOnly=secureTrafficOnly)

Response: Adds SSL termination information to the load balancer.


Instruction:
How would you implement a function in Python 3 that
updates existing SSL termination information for the load balancer.

Response:
def update_ssl_termination(self, securePort=None, enabled=None,
            secureTrafficOnly=None):
        """
        Updates existing SSL termination information for the load balancer
        without affecting the existing certificates/keys.
        """
        return self.manager.update_ssl_termination(self, securePort=securePort,
                enabled=enabled, secureTrafficOnly=secureTrafficOnly)


Instruction:
Here you have a function in Python 3, explain what it does
def set_metadata_for_node(self, node, metadata):
        return self.manager.set_metadata(self, metadata, node=node)

Response: Sets the metadata for the specified node to the supplied dictionary containing the node s metadata.


Instruction:
How would you explain what the following Python 3 function does
def update_metadata_for_node(self, node, metadata):
        return self.manager.update_metadata(self, metadata, node=node)

Response: Updates the existing metadata for the specified node with the supplied dictionary.


Instruction:
Can you tell what is the following Python 3 function doing
def delete_metadata_for_node(self, node, keys=None):
        return self.manager.delete_metadata(self, keys=keys, node=node)

Response: Deletes metadata items for the specified node.


Instruction:
Create a Python 3 function for
updating the attributes of a load balancer.

Response:
def update(self, lb, name=None, algorithm=None, protocol=None,
            halfClosed=None, port=None, timeout=None, httpsRedirect=None):
        """
        Provides a way to modify the following attributes of a load balancer:
            - name
            - algorithm
            - protocol
            - halfClosed
            - port
            - timeout
            - httpsRedirect
        """
        body = {}
        if name is not None:
            body["name"] = name
        if algorithm is not None:
            body["algorithm"] = algorithm
        if protocol is not None:
            body["protocol"] = protocol
        if halfClosed is not None:
            body["halfClosed"] = halfClosed
        if port is not None:
            body["port"] = port
        if timeout is not None:
            body["timeout"] = timeout
        if httpsRedirect is not None:
            body["httpsRedirect"] = httpsRedirect
        if not body:
            # Nothing passed
            return
        body = {"loadBalancer": body}
        uri = "/loadbalancers/%s" % utils.get_id(lb)
        try:
            resp, resp_body = self.api.method_put(uri, body=body)
        except exc.ClientException as e:
            message = e.message
            details = e.details
            if message and details:
                errmsg = "%s - %s" % (message, details)
            else:
                errmsg = message
            raise exc.InvalidLoadBalancerParameters(errmsg)
        return resp, resp_body


Instruction:
Can you tell what is the following Python 3 function doing
def _create_body(self, name, port=None, protocol=None, nodes=None,
            virtual_ips=None, algorithm=None, halfClosed=None, accessList=None,
            connectionLogging=None, connectionThrottle=None, healthMonitor=None,
            metadata=None, timeout=None, sessionPersistence=None,
            httpsRedirect=None):
        """
        Used to create the dict required to create a load balancer instance.
        """
        required = (virtual_ips, port, protocol)
        if not all(required):
            raise exc.MissingLoadBalancerParameters("Load Balancer creation "
                "requires at least one virtual IP, a protocol, and a port.")
        nodes = utils.coerce_to_list(nodes)
        virtual_ips = utils.coerce_to_list(virtual_ips)
        bad_conditions = [node.condition for node in nodes
                if node.condition.upper() not in ("ENABLED", "DISABLED")]
        if bad_conditions:
            raise exc.InvalidNodeCondition("Nodes for new load balancer must be "
                    "created in either 'ENABLED' or 'DISABLED' condition; "
                    "received the following invalid conditions: %s" %
                    ", ".join(set(bad_conditions)))
        node_dicts = [nd.to_dict() for nd in nodes]
        vip_dicts = [vip.to_dict() for vip in virtual_ips]
        body = {"loadBalancer": {
                "name": name,
                "port": port,
                "protocol": protocol,
                "nodes": node_dicts,
                "virtualIps": vip_dicts,
                "algorithm": algorithm or "RANDOM",
                "halfClosed": halfClosed,
                "accessList": accessList,
                "connectionLogging": connectionLogging,
                "connectionThrottle": connectionThrottle,
                "healthMonitor": healthMonitor,
                "metadata": metadata,
                "timeout": timeout,
                "sessionPersistence": sessionPersistence,
                "httpsRedirect": httpsRedirect,
                }}
        return body

Response: Create the dict required to create a load balancer instance.


Instruction:
Here you have a function in Python 3, explain what it does
def add_nodes(self, lb, nodes):
        if not isinstance(nodes, (list, tuple)):
            nodes = [nodes]
        node_dicts = [nd.to_dict() for nd in nodes]
        resp, body = self.api.method_post("/loadbalancers/%s/nodes" % lb.id,
                body={"nodes": node_dicts})
        return resp, body

Response: Adds the list of nodes to the specified load balancer.


Instruction:
Write a Python 3 script to
remove the node from its load balancer.

Response:
def delete_node(self, loadbalancer, node):
        """Removes the node from its load balancer."""
        lb = node.parent
        if not lb:
            raise exc.UnattachedNode("No parent Load Balancer for this node "
                    "could be determined.")
        resp, body = self.api.method_delete("/loadbalancers/%s/nodes/%s" %
                (lb.id, node.id))
        return resp, body


Instruction:
Here you have a function in Python 3, explain what it does
def update_node(self, node, diff=None):
        lb = node.parent
        if not lb:
            raise exc.UnattachedNode("No parent Load Balancer for this node "
                    "could be determined.")
        if diff is None:
            diff = node._diff()
        req_body = {"node": diff}
        resp, body = self.api.method_put("/loadbalancers/%s/nodes/%s" %
                (lb.id, node.id), body=req_body)
        return resp, body

Response: Updates the attributes of a node.


Instruction:
Can you create a Python 3 function that
adds the VirtualIP to the specified load balancer.

Response:
def add_virtualip(self, lb, vip):
        """Adds the VirtualIP to the specified load balancer."""
        resp, body = self.api.method_post("/loadbalancers/%s/virtualips" % lb.id,
                body=vip.to_dict())
        return resp, body


Instruction:
Can you generate the documentation for the following Python 3 function
def delete_virtualip(self, loadbalancer, vip):
        lb = vip.parent
        if not lb:
            raise exc.UnattachedVirtualIP("No parent Load Balancer for this "
                    "VirtualIP could be determined.")
        resp, body = self.api.method_delete("/loadbalancers/%s/virtualips/%s" %
                (lb.id, vip.id))
        return resp, body

Response: Deletes the VirtualIP from its load balancer.


Instruction:
Explain what the following Python 3 code does
def add_access_list(self, loadbalancer, access_list):
        req_body = {"accessList": access_list}
        uri = "/loadbalancers/%s/accesslist" % utils.get_id(loadbalancer)
        resp, body = self.api.method_post(uri, body=req_body)
        return body

Response: Adds the provided list to the load balancer.


Instruction:
How would you code a function in Python 3 to
remove the access list from the load balancer.

Response:
def delete_access_list(self, loadbalancer):
        """
        Removes the access list from this load balancer.
        """
        uri = "/loadbalancers/%s/accesslist" % utils.get_id(loadbalancer)
        resp, body = self.api.method_delete(uri)
        return body


Instruction:
Make a summary of the following Python 3 code
def delete_access_list_items(self, loadbalancer, item_ids):
        if not isinstance(item_ids, (list, tuple)):
            item_ids = [item_ids]
        valid_ids = [itm["id"] for itm in self.get_access_list(loadbalancer)]
        bad_ids = [str(itm) for itm in item_ids if itm not in valid_ids]
        if bad_ids:
            raise exc.AccessListIDNotFound("The following ID(s) are not valid "
                    "Access List items: %s" % ", ".join(bad_ids))
        items = "&".join(["id=%s" % item_id for item_id in item_ids])
        uri = "/loadbalancers/%s/accesslist?%s" % (
                utils.get_id(loadbalancer), items)
        # TODO: add the item ids
        resp, body = self.api.method_delete(uri)
        return body

Response: Removes the items from the load balancer s access list that match the provided IDs.


Instruction:
Explain what the following Python 3 code does
def get_health_monitor(self, loadbalancer):
        uri = "/loadbalancers/%s/healthmonitor" % utils.get_id(loadbalancer)
        resp, body = self.api.method_get(uri)
        return body.get("healthMonitor", {})

Response: Returns the health monitor configuration for the load balancer.


Instruction:
Here you have a function in Python 3, explain what it does
def add_health_monitor(self, loadbalancer, type, delay=10, timeout=10,
            attemptsBeforeDeactivation=3, path="/", statusRegex=None,
            bodyRegex=None, hostHeader=None):
        """
        Adds a health monitor to the load balancer. If a monitor already
        exists, it is updated with the supplied settings.
        """
        uri = "/loadbalancers/%s/healthmonitor" % utils.get_id(loadbalancer)
        req_body = {"healthMonitor": {
                "type": type,
                "delay": delay,
                "timeout": timeout,
                "attemptsBeforeDeactivation": attemptsBeforeDeactivation,
                }}
        uptype = type.upper()
        if uptype.startswith("HTTP"):
            lb = self._get_lb(loadbalancer)
            if uptype != lb.protocol:
                raise exc.ProtocolMismatch("Cannot set the Health Monitor type "
                        "to '%s' when the Load Balancer's protocol is '%s'." %
                        (type, lb.protocol))
            if not all((path, statusRegex, bodyRegex)):
                raise exc.MissingHealthMonitorSettings("When creating an HTTP(S) "
                        "monitor, you must provide the 'path', 'statusRegex' and "
                        "'bodyRegex' parameters.")
            body_hm = req_body["healthMonitor"]
            body_hm["path"] = path
            body_hm["statusRegex"] = statusRegex
            body_hm["bodyRegex"] = bodyRegex
            if hostHeader:
                body_hm["hostHeader"] = hostHeader
        resp, body = self.api.method_put(uri, body=req_body)
        return body

Response: Adds a health monitor to the load balancer.


Instruction:
Make a summary of the following Python 3 code
def add_connection_throttle(self, loadbalancer, maxConnectionRate=None,
            maxConnections=None, minConnections=None, rateInterval=None):
        """
        Creates or updates the connection throttling information for the load
        balancer. When first creating the connection throttle, all 4 parameters
        must be supplied. When updating an existing connection throttle, at
        least one of the parameters must be supplied.
        """
        settings = {}
        if maxConnectionRate:
            settings["maxConnectionRate"] = maxConnectionRate
        if maxConnections:
            settings["maxConnections"] = maxConnections
        if minConnections:
            settings["minConnections"] = minConnections
        if rateInterval:
            settings["rateInterval"] = rateInterval
        req_body = {"connectionThrottle": settings}
        uri = "/loadbalancers/%s/connectionthrottle" % utils.get_id(loadbalancer)
        resp, body = self.api.method_put(uri, body=req_body)
        return body

Response: Adds or updates the connection throttling information for the load balancer.


Instruction:
Given the following Python 3 function, write the documentation
def get_ssl_termination(self, loadbalancer):
        uri = "/loadbalancers/%s/ssltermination" % utils.get_id(loadbalancer)
        try:
            resp, body = self.api.method_get(uri)
        except exc.NotFound:
            # For some reason, instead of returning an empty dict like the
            # other API GET calls, this raises a 404.
            return {}
        return body.get("sslTermination", {})

Response: Returns a dictionary representing the SSL termination configuration for the load balancer.


Instruction:
Explain what the following Python 3 code does
def add_ssl_termination(self, loadbalancer, securePort, privatekey, certificate,
            intermediateCertificate, enabled=True, secureTrafficOnly=False):
        """
        Adds SSL termination information to the load balancer. If SSL termination
        has already been configured, it is updated with the supplied settings.
        """
        uri = "/loadbalancers/%s/ssltermination" % utils.get_id(loadbalancer)
        req_body = {"sslTermination": {
                "certificate": certificate,
                "enabled": enabled,
                "secureTrafficOnly": secureTrafficOnly,
                "privatekey": privatekey,
                "intermediateCertificate": intermediateCertificate,
                "securePort": securePort,
                }}
        resp, body = self.api.method_put(uri, body=req_body)
        return body

Response: Adds SSL termination information to the load balancer.


Instruction:
How would you explain what the following Python 3 function does
def update_ssl_termination(self, loadbalancer, securePort=None, enabled=None,
            secureTrafficOnly=None):
        """
        Updates existing SSL termination information for the load balancer
        without affecting the existing certificates/keys.
        """
        ssl_info = self.get_ssl_termination(loadbalancer)
        if not ssl_info:
            raise exc.NoSSLTerminationConfiguration("You must configure SSL "
                    "termination on this load balancer before attempting "
                    "to update it.")
        if securePort is None:
            securePort = ssl_info["securePort"]
        if enabled is None:
            enabled = ssl_info["enabled"]
        if secureTrafficOnly is None:
            secureTrafficOnly = ssl_info["secureTrafficOnly"]
        uri = "/loadbalancers/%s/ssltermination" % utils.get_id(loadbalancer)
        req_body = {"sslTermination": {
                "enabled": enabled,
                "secureTrafficOnly": secureTrafficOnly,
                "securePort": securePort,
                }}
        resp, body = self.api.method_put(uri, body=req_body)
        return body

Response: Updates the SSL termination information for the load balancer.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_metadata(self, loadbalancer, node=None, raw=False):
        if node:
            uri = "/loadbalancers/%s/nodes/%s/metadata" % (
                    utils.get_id(loadbalancer), utils.get_id(node))
        else:
            uri = "/loadbalancers/%s/metadata" % utils.get_id(loadbalancer)
        resp, body = self.api.method_get(uri)
        meta = body.get("metadata", [])
        if raw:
            return meta
        ret = dict([(itm["key"], itm["value"]) for itm in meta])
        return ret

Response: Returns the current metadata for the load balancer. If node is provided returns the current metadata for that node. If raw is True returns the current metadata for the load balancer.