Instruction:
Implement a Python 3 function for
returning the total bytes for the specified path optionally ignoring any files which match the ignore parameter.

Response:
def folder_size(pth, ignore=None):
    """
    Returns the total bytes for the specified path, optionally ignoring
    any files which match the 'ignore' parameter. 'ignore' can either be
    a single string pattern, or a list of such patterns.
    """
    if not os.path.isdir(pth):
        raise exc.FolderNotFound

    ignore = coerce_to_list(ignore)

    total = 0
    for root, _, names in os.walk(pth):
        paths = [os.path.realpath(os.path.join(root, nm)) for nm in names]
        for pth in paths[::-1]:
            if not os.path.exists(pth):
                paths.remove(pth)
            elif match_pattern(pth, ignore):
                paths.remove(pth)
        total += sum(os.stat(pth).st_size for pth in paths)

    return total


Instruction:
Can you generate the documentation for the following Python 3 function
def add_method(obj, func, name=None):
    if name is None:
        name = func.__name__
    if sys.version_info < (3,):
        method = types.MethodType(func, obj, obj.__class__)
    else:
        method = types.MethodType(func, obj)
    setattr(obj, name, method)

Response: Adds an instance method to an object.


Instruction:
Explain what the following Python 3 code does
def wait_until(obj, att, desired, callback=None, interval=5, attempts=0,
        verbose=False, verbose_atts=None):
    """
    When changing the state of an object, it will commonly be in a transitional
    state until the change is complete. This will reload the object every
    `interval` seconds, and check its `att` attribute until the `desired` value
    is reached, or until the maximum number of attempts is reached. The updated
    object is returned. It is up to the calling program to check the returned
    object to make sure that it successfully reached the desired state.

    Once the desired value of the attribute is reached, the method returns. If
    not, it will re-try until the attribute's value matches one of the
    `desired` values. By default (attempts=0) it will loop infinitely until the
    attribute reaches the desired value. You can optionally limit the number of
    times that the object is reloaded by passing a positive value to
    `attempts`. If the attribute has not reached the desired value by then, the
    method will exit.

    If `verbose` is True, each attempt will print out the current value of the
    watched attribute and the time that has elapsed since the original request.
    Also, if `verbose_atts` is specified, the values of those attributes will
    also be output. If `verbose` is False, then `verbose_atts` has no effect.

    Note that `desired` can be a list of values; if the attribute becomes equal
    to any of those values, this will succeed. For example, when creating a new
    cloud server, it will initially have a status of 'BUILD', and you can't
    work with it until its status is 'ACTIVE'. However, there might be a
    problem with the build process, and the server will change to a status of
    'ERROR'. So for this case you need to set the `desired` parameter to
    `['ACTIVE', 'ERROR']`. If you simply pass 'ACTIVE' as the desired state,
    this will loop indefinitely if a build fails, as the server will never
    reach a status of 'ACTIVE'.

    Since this process of waiting can take a potentially long time, and will
    block your program's execution until the desired state of the object is
    reached, you may specify a callback function. The callback can be any
    callable that accepts a single parameter; the parameter it receives will be
    either the updated object (success), or None (failure). If a callback is
    specified, the program will return immediately after spawning the wait
    process in a separate thread.
    """
    if callback:
        waiter = _WaitThread(obj=obj, att=att, desired=desired, callback=callback,
                interval=interval, attempts=attempts, verbose=verbose,
                verbose_atts=verbose_atts)
        waiter.start()
        return waiter
    else:
        return _wait_until(obj=obj, att=att, desired=desired, callback=None,
                interval=interval, attempts=attempts, verbose=verbose,
                verbose_atts=verbose_atts)

Response: Waits until the state of an object is in the desired state.


Instruction:
Write a Python 3 function for
waiting until the desired value of the attribute is reached.

Response:
def _wait_until(obj, att, desired, callback, interval, attempts, verbose,
        verbose_atts):
    """
    Loops until either the desired value of the attribute is reached, or the
    number of attempts is exceeded.
    """
    if not isinstance(desired, (list, tuple)):
        desired = [desired]
    if verbose_atts is None:
        verbose_atts = []
    if not isinstance(verbose_atts, (list, tuple)):
        verbose_atts = [verbose_atts]
    infinite = (attempts == 0)
    attempt = 0
    start = time.time()
    while infinite or (attempt < attempts):
        try:
            # For servers:
            obj.get()
        except AttributeError:
            try:
                # For other objects that don't support .get()
                obj = obj.manager.get(obj.id)
            except AttributeError:
                # punt
                raise exc.NoReloadError("The 'wait_until' method is not "
                        "supported for '%s' objects." % obj.__class__)
        attval = getattr(obj, att)
        if verbose:
            elapsed = time.time() - start
            msgs = ["Current value of %s: %s (elapsed: %4.1f seconds)" % (
                    att, attval, elapsed)]
            for vatt in verbose_atts:
                vattval = getattr(obj, vatt, None)
                msgs.append("%s=%s" % (vatt, vattval))
            print(" ".join(msgs))
        if attval in desired:
            return obj
        time.sleep(interval)
        attempt += 1
    return obj


Instruction:
Given the following Python 3 function, write the documentation
def wait_for_build(obj, att=None, desired=None, callback=None, interval=None,
        attempts=None, verbose=None, verbose_atts=None):
    """
    Designed to handle the most common use case for wait_until: an object whose
    'status' attribute will end up in either 'ACTIVE' or 'ERROR' state. Since
    builds don't happen very quickly, the interval will default to 20 seconds
    to avoid excess polling.
    """
    att = att or "status"
    desired = desired or ["ACTIVE", "ERROR", "available", "COMPLETED"]
    interval = interval or 20
    attempts = attempts or 0
    verbose_atts = verbose_atts or "progress"
    return wait_until(obj, att, desired, callback=callback, interval=interval,
            attempts=attempts, verbose=verbose, verbose_atts=verbose_atts)

Response: This function is used to wait until a build is complete.


Instruction:
Can you tell what is the following Python 3 function doing
def _parse_datetime_string(val):
    dt = None
    lenval = len(val)
    fmt = {19: "%Y-%m-%d %H:%M:%S", 10: "%Y-%m-%d"}.get(lenval)
    if fmt is None:
        # Invalid date
        raise exc.InvalidDateTimeString("The supplied value '%s' does not "
              "match either of the formats 'YYYY-MM-DD HH:MM:SS' or "
              "'YYYY-MM-DD'." % val)
    return datetime.datetime.strptime(val, fmt)

Response: Attempts to parse a string representation of a date or datetime value and returns a datetime. datetime object.


Instruction:
Make a summary of the following Python 3 code
def iso_time_string(val, show_tzinfo=False):
    if not val:
        return ""
    if isinstance(val, six.string_types):
        dt = _parse_datetime_string(val)
    else:
        dt = val
    if not isinstance(dt, datetime.datetime):
        dt = datetime.datetime.fromordinal(dt.toordinal())
    has_tz = (dt.tzinfo is not None)
    if show_tzinfo and has_tz:
        # Need to remove the colon in the TZ portion
        ret = "".join(dt.isoformat().rsplit(":", 1))
    elif show_tzinfo and not has_tz:
        ret = "%s+0000" % dt.isoformat().split(".")[0]
    elif not show_tzinfo and has_tz:
        ret = dt.isoformat()[:-6]
    elif not show_tzinfo and not has_tz:
        ret = dt.isoformat().split(".")[0]
    return ret

Response:
Takes either a date datetime or a string and returns the ISO
    formatted string for that date or time.


Instruction:
Here you have a function in Python 3, explain what it does
def rfc2822_format(val):
    if isinstance(val, six.string_types):
        return val
    elif isinstance(val, (datetime.datetime, datetime.date)):
        # Convert to a timestamp
        val = time.mktime(val.timetuple())
    if isinstance(val, numbers.Number):
        return email.utils.formatdate(val)
    else:
        # Bail
        return val

Response: Takes either a date a datetime or a string and returns a string that represents the value in RFC 2822 format.


Instruction:
Make a summary of the following Python 3 code
def to_timestamp(val):
    # If we're given a number, give it right back - it's already a timestamp.
    if isinstance(val, numbers.Number):
        return val
    elif isinstance(val, six.string_types):
        dt = _parse_datetime_string(val)
    else:
        dt = val
    return time.mktime(dt.timetuple())

Response:
Converts a value that is either a Python date datetime or a string
    representation of a date or datetime value. Returns a standard Unix timestamp
    corresponding to that value.


Instruction:
Write a Python 3 script for
returning the id attribute of id_or_obj.

Response:
def get_id(id_or_obj):
    """
    Returns the 'id' attribute of 'id_or_obj' if present; if not,
    returns 'id_or_obj'.
    """
    if isinstance(id_or_obj, six.string_types + (int,)):
        # It's an ID
        return id_or_obj
    try:
        return id_or_obj.id
    except AttributeError:
        return id_or_obj


Instruction:
Here you have a function in Python 3, explain what it does
def get_name(name_or_obj):
    if isinstance(name_or_obj, six.string_types):
        # It's a name
        return name_or_obj
    try:
        return name_or_obj.name
    except AttributeError:
        raise exc.MissingName(name_or_obj)

Response: Returns the name attribute of name_or_obj.


Instruction:
Here you have a function in Python 3, explain what it does
def params_to_dict(params, dct):
    for param, val in params.items():
        if val is None:
            continue
        dct[param] = val
    return dct

Response: Updates the dct dictionary with the params dictionary.


Instruction:
Implement a Python 3 function for
taking a dictionary and uses it to create a query string.

Response:
def dict_to_qs(dct):
    """
    Takes a dictionary and uses it to create a query string.
    """
    itms = ["%s=%s" % (key, val) for key, val in list(dct.items())
            if val is not None]
    return "&".join(itms)


Instruction:
Write a Python 3 script for
comparing nm with the supplied patterns and returns True if it matches at least one.

Response:
def match_pattern(nm, patterns):
    """
    Compares `nm` with the supplied patterns, and returns True if it matches
    at least one.

    Patterns are standard file-name wildcard strings, as defined in the
    `fnmatch` module. For example, the pattern "*.py" will match the names
    of all Python scripts.
    """
    patterns = coerce_to_list(patterns)
    for pat in patterns:
        if fnmatch.fnmatch(nm, pat):
            return True
    return False


Instruction:
Can you generate the documentation for the following Python 3 function
def update_exc(exc, msg, before=True, separator="\n"):
    emsg = exc.message
    if before:
        parts = (msg, separator, emsg)
    else:
        parts = (emsg, separator, msg)
    new_msg = "%s%s%s" % parts
    new_args = (new_msg, ) + exc.args[1:]
    exc.message = new_msg
    exc.args = new_args
    return exc

Response: Update an exception s error message with the given message.


Instruction:
Can you generate the documentation for the following Python 3 function
def case_insensitive_update(dct1, dct2):
    lowkeys = dict([(key.lower(), key) for key in dct1])
    for key, val in dct2.items():
        d1_key = lowkeys.get(key.lower(), key)
        dct1[d1_key] = val

Response: Updates the first dict with the second dict.


Instruction:
Make a summary of the following Python 3 code
def env(*args, **kwargs):
    for arg in args:
        value = os.environ.get(arg, None)
        if value:
            return value
    return kwargs.get("default", "")

Response:
Returns the first environment variable set
            if none are non - empty defaults to ""


Instruction:
Make a summary of the following Python 3 code
def import_class(import_str):
    mod_str, _sep, class_str = import_str.rpartition(".")
    __import__(mod_str)
    return getattr(sys.modules[mod_str], class_str)

Response: Returns a class from a string including module and class.


Instruction:
Write a Python 3 script for
decoding incoming text using incoming if they re not already unicode.

Response:
def safe_decode(text, incoming=None, errors='strict'):
    """Decodes incoming text/bytes string using `incoming` if they're not
       already unicode.

    This function was copied from novaclient.openstack.strutils

    :param incoming: Text's current encoding
    :param errors: Errors handling policy. See here for valid
        values http://docs.python.org/2/library/codecs.html
    :returns: text or a unicode `incoming` encoded
                representation of it.
    :raises TypeError: If text is not an instance of str
    """
    if not isinstance(text, (six.string_types, six.binary_type)):
        raise TypeError("%s can't be decoded" % type(text))

    if isinstance(text, six.text_type):
        return text

    if not incoming:
        incoming = (sys.stdin.encoding or
                    sys.getdefaultencoding())

    try:
        return text.decode(incoming, errors)
    except UnicodeDecodeError:
        # Note(flaper87) If we get here, it means that
        # sys.stdin.encoding / sys.getdefaultencoding
        # didn't return a suitable encoding to decode
        # text. This happens mostly when global LANG
        # var is not set correctly and there's no
        # default encoding. In this case, most likely
        # python will use ASCII or ANSI encoders as
        # default encodings but they won't be capable
        # of decoding non-ASCII characters.
        #
        # Also, UTF-8 is being used since it's an ASCII
        # extension.
        return text.decode('utf-8', errors)


Instruction:
How would you code a function in Python 3 to
normalize string. Convert to lowercase, remove non-word characters, and convert spaces to hyphens. This function was copied from novaclient.openstack.strutils Inspired by Django's `slugify` filter. :param value: Text to slugify :param incoming: Text's current encoding :param errors: Errors handling policy. See here for valid values http://docs.python.org/2/library/codecs.html :returns: slugified unicode representation of `value` :raises TypeError: If text is not an instance of str

Response:
def to_slug(value, incoming=None, errors="strict"):
    """Normalize string.

    Convert to lowercase, remove non-word characters, and convert spaces
    to hyphens.

    This function was copied from novaclient.openstack.strutils

    Inspired by Django's `slugify` filter.

    :param value: Text to slugify
    :param incoming: Text's current encoding
    :param errors: Errors handling policy. See here for valid
        values http://docs.python.org/2/library/codecs.html
    :returns: slugified unicode representation of `value`
    :raises TypeError: If text is not an instance of str
    """
    value = safe_decode(value, incoming, errors)
    # NOTE(aababilov): no need to use safe_(encode|decode) here:
    # encodings are always "ascii", error handling is always "ignore"
    # and types are always known (first: unicode; second: str)
    value = unicodedata.normalize("NFKD", value).encode(
        "ascii", "ignore").decode("ascii")
    value = SLUGIFY_STRIP_RE.sub("", value).strip().lower()
    return SLUGIFY_HYPHENATE_RE.sub("-", value)


Instruction:
Can you implement a function in Python 3 that
returns the next available item from the API.

Response:
def next(self):
        """
        Return the next available item. If there are no more items in the
        local 'results' list, check if there is a 'next_uri' value. If so,
        use that to get the next page of results from the API, and return
        the first item from that query.
        """
        try:
            return self.results.pop(0)
        except IndexError:
            if self.next_uri is None:
                raise StopIteration()
            else:
                if not self.next_uri:
                    self.results = self.list_method(marker=self.marker,
                            limit=self.limit, prefix=self.prefix)
                else:
                    args = self.extra_args
                    self.results = self._list_method(self.next_uri, *args)
                if self.results:
                    last_res = self.results[-1]
                    self.marker = getattr(last_res, self.marker_att)
        # We should have more results.
        try:
            return self.results.pop(0)
        except IndexError:
            raise StopIteration()


Instruction:
Can you implement a function in Python 3 that
converts a volumeID passed as the volume to a CloudBlockStorageVolume object.

Response:
def assure_volume(fnc):
    """
    Converts a volumeID passed as the volume to a CloudBlockStorageVolume object.
    """
    @wraps(fnc)
    def _wrapped(self, volume, *args, **kwargs):
        if not isinstance(volume, CloudBlockStorageVolume):
            # Must be the ID
            volume = self._manager.get(volume)
        return fnc(self, volume, *args, **kwargs)
    return _wrapped


Instruction:
Can you generate a brief explanation for the following Python 3 code
def assure_snapshot(fnc):
    @wraps(fnc)
    def _wrapped(self, snapshot, *args, **kwargs):
        if not isinstance(snapshot, CloudBlockStorageSnapshot):
            # Must be the ID
            snapshot = self._snapshot_manager.get(snapshot)
        return fnc(self, snapshot, *args, **kwargs)
    return _wrapped

Response: A decorator that ensures that a snapshot ID passed as the snapshot is passed as the snapshot.


Instruction:
Write a Python 3 function for
deleting the current snapshot.

Response:
def delete(self):
        """
        Adds a check to make sure that the snapshot is able to be deleted.
        """
        if self.status not in ("available", "error"):
            raise exc.SnapshotNotAvailable("Snapshot must be in 'available' "
                    "or 'error' status before deleting. Current status: %s" %
                    self.status)
        # When there are more thann one snapshot for a given volume, attempting to
        # delete them all will throw a 409 exception. This will help by retrying
        # such an error once after a RETRY_INTERVAL second delay.
        try:
            super(CloudBlockStorageSnapshot, self).delete()
        except exc.ClientException as e:
            if "Request conflicts with in-progress 'DELETE" in str(e):
                time.sleep(RETRY_INTERVAL)
                # Try again; if it fails, oh, well...
                super(CloudBlockStorageSnapshot, self).delete()


Instruction:
Write a Python 3 function for
updating the specified values on this snapshot.

Response:
def update(self, display_name=None, display_description=None):
        """
        Update the specified values on this snapshot. You may specify one or
        more values to update. If no values are specified as non-None, the call
        is a no-op; no exception will be raised.
        """
        return self.manager.update(self, display_name=display_name,
                display_description=display_description)


Instruction:
How would you implement a function in Python 3 that
attaches this volume to the cloud server instance at the specified mountpoint.

Response:
def attach_to_instance(self, instance, mountpoint):
        """
        Attaches this volume to the cloud server instance at the
        specified mountpoint. This requires a call to the cloud servers
        API; it cannot be done directly.
        """
        instance_id = _resolve_id(instance)
        try:
            resp = self._nova_volumes.create_server_volume(instance_id,
                    self.id, mountpoint)
        except Exception as e:
            raise exc.VolumeAttachmentFailed("%s" % e)


Instruction:
Write a Python 3 function for
detaching this volume from any device it may be attached to.

Response:
def detach(self):
        """
        Detaches this volume from any device it may be attached to. If it
        is not attached, nothing happens.
        """
        attachments = self.attachments
        if not attachments:
            # Not attached; no error needed, just return
            return
        # A volume can only be attached to one device at a time, but for some
        # reason this is a list instead of a singular value
        att = attachments[0]
        instance_id = att["server_id"]
        attachment_id = att["id"]
        try:
            self._nova_volumes.delete_server_volume(instance_id, attachment_id)
        except Exception as e:
            raise exc.VolumeDetachmentFailed("%s" % e)


Instruction:
Here you have a function in Python 3, explain what it does
def delete(self, force=False):
        if force:
            self.detach()
            self.delete_all_snapshots()
        try:
            super(CloudBlockStorageVolume, self).delete()
        except exc.VolumeNotAvailable:
            # Notify the user? Record it somewhere?
            # For now, just re-raise
            raise

Response: Delete the Cloud Block Storage Volume.


Instruction:
Can you tell what is the following Python 3 function doing
def create_snapshot(self, name=None, description=None, force=False):
        name = name or ""
        description = description or ""
        # Note that passing in non-None values is required for the _create_body
        # method to distinguish between this and the request to create and
        # instance.
        return self.manager.create_snapshot(volume=self, name=name,
                    description=description, force=force)

Response: Creates a snapshot of this volume with an optional name and description.


Instruction:
Here you have a function in Python 3, explain what it does
def list_snapshots(self):
        return [snap for snap in self.manager.list_snapshots()
                if snap.volume_id == self.id]

Response: Returns a list of all snapshots of this volume.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _create_body(self, name, size=None, volume_type=None, description=None,
             metadata=None, snapshot_id=None, clone_id=None,
             availability_zone=None, image=None):
        """
        Used to create the dict required to create a new volume
        """
        if not isinstance(size, six.integer_types):
            raise exc.InvalidSize("Volume sizes must be integers")

        if volume_type is None:
            volume_type = "SATA"
        if description is None:
            description = ""
        if metadata is None:
            metadata = {}
        if image is not None:
            image = utils.get_id(image)
        body = {"volume": {
                "size": size,
                "snapshot_id": snapshot_id,
                "source_volid": clone_id,
                "display_name": name,
                "display_description": description,
                "volume_type": volume_type,
                "metadata": metadata,
                "availability_zone": availability_zone,
                "imageRef": image,
                }}
        return body

Response: Create the dict required to create a new volume


Instruction:
How would you explain what the following Python 3 function does
def create(self, *args, **kwargs):
        try:
            return super(CloudBlockStorageManager, self).create(*args,
                    **kwargs)
        except exc.BadRequest as e:
            msg = e.message
            if "Clones currently must be >= original volume size" in msg:
                raise exc.VolumeCloneTooSmall(msg)
            else:
                raise

Response: Creates a new object of the specified class.


Instruction:
Explain what the following Python 3 code does
def update(self, volume, display_name=None, display_description=None):
        uri = "/%s/%s" % (self.uri_base, utils.get_id(volume))
        param_dict = {}
        if display_name:
            param_dict["display_name"] = display_name
        if display_description:
            param_dict["display_description"] = display_description
        if not param_dict:
            # Nothing to do!
            return
        body = {"volume": param_dict}
        resp, resp_body = self.api.method_put(uri, body=body)

Response: Updates the display name and display description of the specified volume.


Instruction:
Create a Python 3 function to
create a snapshot of a specific node.

Response:
def create_snapshot(self, volume, name, description=None, force=False):
        """
        Pass-through method to allow the create_snapshot() call to be made
        directly on a volume.
        """
        return self.api.create_snapshot(volume, name, description=description,
                force=force)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _create_body(self, name, description=None, volume=None, force=False):
        body = {"snapshot": {
                "display_name": name,
                "display_description": description,
                "volume_id": volume.id,
                "force": str(force).lower(),
                }}
        return body

Response: Create the dict required to create a new snapshot


Instruction:
Can you write a function in Python 3 where it
creates a new snapshot.

Response:
def create(self, name, volume, description=None, force=False):
        """
        Adds exception handling to the default create() call.
        """
        try:
            snap = super(CloudBlockStorageSnapshotManager, self).create(
                    name=name, volume=volume, description=description,
                    force=force)
        except exc.BadRequest as e:
            msg = str(e)
            if "Invalid volume: must be available" in msg:
                # The volume for the snapshot was attached.
                raise exc.VolumeNotAvailable("Cannot create a snapshot from an "
                        "attached volume. Detach the volume before trying "
                        "again, or pass 'force=True' to the create_snapshot() "
                        "call.")
            else:
                # Some other error
                raise
        except exc.ClientException as e:
            if e.code == 409:
                if "Request conflicts with in-progress" in str(e):
                    txt = ("The volume is current creating a snapshot. You "
                            "must wait until that completes before attempting "
                            "to create an additional snapshot.")
                    raise exc.VolumeNotAvailable(txt)
                else:
                    raise
            else:
                raise
        return snap


Instruction:
Write a Python 3 function that can
create the manager to handle the instances and the flavors.

Response:
def _configure_manager(self):
        """
        Create the manager to handle the instances, and also another
        to handle flavors.
        """
        self._manager = CloudBlockStorageManager(self,
                resource_class=CloudBlockStorageVolume, response_key="volume",
                uri_base="volumes")
        self._types_manager = BaseManager(self,
                resource_class=CloudBlockStorageVolumeType,
                response_key="volume_type", uri_base="types")
        self._snapshot_manager = CloudBlockStorageSnapshotManager(self,
                resource_class=CloudBlockStorageSnapshot,
                response_key="snapshot", uri_base="snapshots")


Instruction:
Can you generate the documentation for the following Python 3 function
def update(self, volume, display_name=None, display_description=None):
        return volume.update(display_name=display_name,
                display_description=display_description)

Response: Update the specified values on the specified volume.


Instruction:
Can you implement a function in Python 3 that
creates a snapshot of the specified volume.

Response:
def create_snapshot(self, volume, name=None, description=None, force=False):
        """
        Creates a snapshot of the volume, with an optional name and description.

        Normally snapshots will not happen if the volume is attached. To
        override this default behavior, pass force=True.
        """
        return self._snapshot_manager.create(volume=volume, name=name,
                description=description, force=force)


Instruction:
Write a Python 3 script for
updating the specified values on the specified snapshot.

Response:
def update_snapshot(self, snapshot, display_name=None,
            display_description=None):
        """
        Update the specified values on the specified snapshot. You may specify
        one or more values to update.
        """
        return snapshot.update(display_name=display_name,
                display_description=display_description)


Instruction:
Can you write a function in Python 3 where it
converts an checkID passed as the check to a CloudMonitorCheck object.

Response:
def assure_check(fnc):
    """
    Converts an checkID passed as the check to a CloudMonitorCheck object.
    """
    @wraps(fnc)
    def _wrapped(self, check, *args, **kwargs):
        if not isinstance(check, CloudMonitorCheck):
            # Must be the ID
            check = self._check_manager.get(check)
        return fnc(self, check, *args, **kwargs)
    return _wrapped


Instruction:
Can you generate the documentation for the following Python 3 function
def assure_entity(fnc):
    @wraps(fnc)
    def _wrapped(self, entity, *args, **kwargs):
        if not isinstance(entity, CloudMonitorEntity):
            # Must be the ID
            entity = self._entity_manager.get(entity)
        return fnc(self, entity, *args, **kwargs)
    return _wrapped

Response: A decorator that ensures that an entityID passed as the entity is passed as the entity.


Instruction:
Here you have a function in Python 3, explain what it does
def update(self, agent=None, metadata=None):
        self.manager.update_entity(self, agent=agent, metadata=metadata)

Response: Update the agent_id and metadata of this resource.


Instruction:
Make a summary of the following Python 3 code
def get_check(self, check):
        chk = self._check_manager.get(check)
        chk.set_entity(self)
        return chk

Response: Returns an instance of the specified check.


Instruction:
Given the following Python 3 function, write the documentation
def list_checks(self, limit=None, marker=None, return_next=False):
        checks = self._check_manager.list(limit=limit, marker=marker,
                return_next=return_next)
        for check in checks:
            check.set_entity(self)
        return checks

Response: Returns a list of the checks defined for this account.


Instruction:
Make a summary of the following Python 3 code
def find_all_checks(self, **kwargs):
        checks = self._check_manager.find_all_checks(**kwargs)
        for check in checks:
            check.set_entity(self)
        return checks

Response: Find all checks for this entity with attributes matching kwargs.


Instruction:
Can you tell what is the following Python 3 function doing
def create_check(self, label=None, name=None, check_type=None,
            disabled=False, metadata=None, details=None,
            monitoring_zones_poll=None, timeout=None, period=None,
            target_alias=None, target_hostname=None, target_receiver=None,
            test_only=False, include_debug=False):
        """
        Creates a check on this entity with the specified attributes. The
        'details' parameter should be a dict with the keys as the option name,
        and the value as the desired setting.
        """
        return self._check_manager.create_check(label=label, name=name,
                check_type=check_type, disabled=disabled, metadata=metadata,
                details=details, monitoring_zones_poll=monitoring_zones_poll,
                timeout=timeout, period=period, target_alias=target_alias,
                target_hostname=target_hostname,
                target_receiver=target_receiver, test_only=test_only,
                include_debug=include_debug)

Response: Creates a check on this entity with the specified attributes.


Instruction:
Write a Python 3 script to
create an alarm that binds the check on this entity with the notification plan.

Response:
def create_alarm(self, check, notification_plan, criteria=None,
            disabled=False, label=None, name=None, metadata=None):
        """
        Creates an alarm that binds the check on this entity with a
        notification plan.
        """
        return self._alarm_manager.create(check, notification_plan,
                criteria=criteria, disabled=disabled, label=label, name=name,
                metadata=metadata)


Instruction:
How would you explain what the following Python 3 function does
def update_alarm(self, alarm, criteria=None, disabled=False,
            label=None, name=None, metadata=None):
        """
        Updates an existing alarm on this entity.
        """
        return self._alarm_manager.update(alarm, criteria=criteria,
                disabled=disabled, label=label, name=name, metadata=metadata)

Response: Updates an existing alarm on this entity.


Instruction:
Write a Python 3 function for
returning a list of all the alarms created on this entity.

Response:
def list_alarms(self, limit=None, marker=None, return_next=False):
        """
        Returns a list of all the alarms created on this entity.
        """
        return self._alarm_manager.list(limit=limit, marker=marker,
                return_next=return_next)


Instruction:
How would you implement a function in Python 3 that
lists the entries in the cache.

Response:
def list(self, limit=None, marker=None, return_next=False):
        """
        This is necessary to handle pagination correctly, as the Monitoring
        service defines 'marker' differently than most other services. For
        monitoring, 'marker' represents the first item in the next page,
        whereas other services define it as the ID of the last item in the
        current page.
        """
        kwargs = {}
        if return_next:
            kwargs["other_keys"] = "metadata"
        ret = super(_PaginationManager, self).list(limit=limit,
                marker=marker, **kwargs)
        if return_next:
            ents, meta = ret
            return (ents, meta[0].get("next_marker"))
        else:
            return ret


Instruction:
Create a Python 3 function for
creating a new alarm.

Response:
def create(self, notification_type, label=None, name=None, details=None):
        """
        Defines a notification for handling an alarm.
        """
        uri = "/%s" % self.uri_base
        body = {"label": label or name,
                "type": utils.get_id(notification_type),
                "details": details,
                }
        resp, resp_body = self.api.method_post(uri, body=body)
        return self.get(resp.headers["x-object-id"])


Instruction:
Can you write a function in Python 3 where it
updates the details of a specific CloudMonitorNotification.

Response:
def update_notification(self, notification, details):
        """
        Updates the specified notification with the supplied details.
        """
        if isinstance(notification, CloudMonitorNotification):
            nid = notification.id
            ntyp = notification.type
        else:
            # Supplied an ID
            nfcn = self.get(notification)
            nid = notification
            ntyp = nfcn.type
        uri = "/%s/%s" % (self.uri_base, nid)
        body = {"type": ntyp,
                "details": details}
        resp, resp_body = self.api.method_put(uri, body=body)


Instruction:
Create a Python 3 function to
return a list of all available notification types.

Response:
def list_types(self):
        """
        Returns a list of all available notification types.
        """
        uri = "/notification_types"
        resp, resp_body = self.api.method_get(uri)
        return [CloudMonitorNotificationType(self, info)
                for info in resp_body["values"]]


Instruction:
Write a Python 3 script to
return a CloudMonitorNotificationType object for the given ID.

Response:
def get_type(self, notification_type_id):
        """
        Returns a CloudMonitorNotificationType object for the given ID.
        """
        uri = "/notification_types/%s" % utils.get_id(notification_type_id)
        resp, resp_body = self.api.method_get(uri)
        return CloudMonitorNotificationType(self, resp_body)


Instruction:
Write a Python 3 function that can
create a new check taxonomy.

Response:
def create(self, label=None, name=None, critical_state=None, ok_state=None,
            warning_state=None):
        """
        Creates a notification plan to be executed when a monitoring check
        triggers an alarm. You can optionally label (or name) the plan.

        A plan consists of one or more notifications to be executed when an
        associated alarm is triggered. You can have different lists of actions
        for CRITICAL, WARNING or OK states.
        """
        uri = "/%s" % self.uri_base
        body = {"label": label or name}

        def make_list_of_ids(parameter):
            params = utils.coerce_to_list(parameter)
            return [utils.get_id(param) for param in params]

        if critical_state:
            critical_state = utils.coerce_to_list(critical_state)
            body["critical_state"] = make_list_of_ids(critical_state)
        if warning_state:
            warning_state = utils.coerce_to_list(warning_state)
            body["warning_state"] = make_list_of_ids(warning_state)
        if ok_state:
            ok_state = utils.coerce_to_list(ok_state)
            body["ok_state"] = make_list_of_ids(ok_state)
        resp, resp_body = self.api.method_post(uri, body=body)
        return self.get(resp.headers["x-object-id"])


Instruction:
Given the following Python 3 function, write the documentation
def get_metric_data_points(self, metric, start, end, points=None,
            resolution=None, stats=None):
        """
        Returns the data points for a given metric for the given period. The
        'start' and 'end' times must be specified; they can be be either Python
        date/datetime values, or a Unix timestamp.

        The 'points' parameter represents the number of points to return. The
        'resolution' parameter represents the granularity of the data. You must
        specify either 'points' or 'resolution'. The allowed values for
        resolution are:
            FULL
            MIN5
            MIN20
            MIN60
            MIN240
            MIN1440

        Finally, the 'stats' parameter specifies the stats you want returned.
        By default only the 'average' is returned. You omit this parameter,
        pass in a single value, or pass in a list of values. The allowed values
        are:
            average
            variance
            min
            max
        """
        allowed_resolutions = ("FULL", "MIN5", "MIN20", "MIN60", "MIN240",
                "MIN1440")
        if not (points or resolution):
            raise exc.MissingMonitoringCheckGranularity("You must specify "
                    "either the 'points' or 'resolution' parameter when "
                    "fetching metrics.")
        if resolution:
            if resolution.upper() not in allowed_resolutions:
                raise exc.InvalidMonitoringMetricsResolution("The specified "
                        "resolution '%s' is not valid. The valid values are: "
                        "%s." % (resolution, str(allowed_resolutions)))
        start_tm = utils.to_timestamp(start)
        end_tm = utils.to_timestamp(end)
        # NOTE: For some odd reason, the timestamps required for this must be
        # in milliseconds, instead of the UNIX standard for timestamps, which
        # is in seconds. So the values here are multiplied by 1000 to make it
        # work. If the API is ever corrected, the next two lines should be
        # removed. GitHub #176.
        start_tm *= 1000
        end_tm *= 1000
        qparms = []
        # Timestamps with fractional seconds currently cause a 408 (timeout)
        qparms.append("from=%s" % int(start_tm))
        qparms.append("to=%s" % int(end_tm))
        if points:
            qparms.append("points=%s" % points)
        if resolution:
            qparms.append("resolution=%s" % resolution.upper())
        if stats:
            stats = utils.coerce_to_list(stats)
            for stat in stats:
                qparms.append("select=%s" % stat)
        qparm = "&".join(qparms)
        uri = "/%s/%s/plot?%s" % (self.uri_base, metric, qparm)
        try:
            resp, resp_body = self.api.method_get(uri)
        except exc.BadRequest as e:
            msg = e.message
            dtls = e.details
            if msg.startswith("Validation error"):
                raise exc.InvalidMonitoringMetricsRequest("Your request was "
                        "invalid: '%s'" % dtls)
            else:
                raise
        return resp_body["values"]

Response: This method returns the data points for a given metric for a given period.


Instruction:
Write a Python 3 script for
creating an alarm that binds the check on the given entity with the given notification plan.

Response:
def create(self, check, notification_plan, criteria=None,
            disabled=False, label=None, name=None, metadata=None):
        """
        Creates an alarm that binds the check on the given entity with a
        notification plan.

        Note that the 'criteria' parameter, if supplied, should be a string
        representing the DSL for describing alerting conditions and their
        output states. Pyrax does not do any validation of these criteria
        statements; it is up to you as the developer to understand the language
        and correctly form the statement. This alarm language is documented
        online in the Cloud Monitoring section of http://docs.rackspace.com.
        """
        uri = "/%s" % self.uri_base
        body = {"check_id": utils.get_id(check),
                "notification_plan_id": utils.get_id(notification_plan),
                }
        if criteria:
            body["criteria"] = criteria
        if disabled is not None:
            body["disabled"] = disabled
        label_name = label or name
        if label_name:
            body["label"] = label_name
        if metadata:
            body["metadata"] = metadata
        resp, resp_body = self.api.method_post(uri, body=body)
        if resp.status_code == 201:
            alarm_id = resp.headers["x-object-id"]
            return self.get(alarm_id)


Instruction:
Create a Python 3 function for
updating an existing alarm.

Response:
def update(self, alarm, criteria=None, disabled=False, label=None,
            name=None, metadata=None):
        """
        Updates an existing alarm. See the comments on the 'create()' method
        regarding the criteria parameter.
        """
        uri = "/%s/%s" % (self.uri_base, utils.get_id(alarm))
        body = {}
        if criteria:
            body["criteria"] = criteria
        if disabled is not None:
            body["disabled"] = disabled
        label_name = label or name
        if label_name:
            body["label"] = label_name
        if metadata:
            body["metadata"] = metadata
        resp, resp_body = self.api.method_put(uri, body=body)


Instruction:
How would you code a function in Python 3 to
create a check on the specified entity.

Response:
def create_check(self, label=None, name=None, check_type=None,
            details=None, disabled=False, metadata=None,
            monitoring_zones_poll=None, timeout=None, period=None,
            target_alias=None, target_hostname=None, target_receiver=None,
            test_only=False, include_debug=False):
        """
        Creates a check on the entity with the specified attributes. The
        'details' parameter should be a dict with the keys as the option name,
        and the value as the desired setting.

        If the 'test_only' parameter is True, then the check is not created;
        instead, the check is run and the results of the test run returned. If
        'include_debug' is True, additional debug information is returned.
        According to the current Cloud Monitoring docs:
            "Currently debug information is only available for the
            remote.http check and includes the response body."
        """
        if details is None:
            raise exc.MissingMonitoringCheckDetails("The required 'details' "
                    "parameter was not passed to the create_check() method.")
        ctype = utils.get_id(check_type)
        is_remote = ctype.startswith("remote")
        monitoring_zones_poll = utils.coerce_to_list(monitoring_zones_poll)
        monitoring_zones_poll = [utils.get_id(mzp)
                for mzp in monitoring_zones_poll]
        # only require monitoring_zones and targets for remote checks
        if is_remote:
            if not monitoring_zones_poll:
                raise exc.MonitoringZonesPollMissing("You must specify the "
                    "'monitoring_zones_poll' parameter for remote checks.")
            if not (target_alias or target_hostname):
                raise exc.MonitoringCheckTargetNotSpecified("You must "
                    "specify either the 'target_alias' or 'target_hostname' "
                    "when creating a remote check.")
        body = {"label": label or name,
                "details": details,
                "disabled": disabled,
                "type": utils.get_id(check_type),
                }
        params = ("monitoring_zones_poll", "timeout", "period",
                "target_alias", "target_hostname", "target_receiver")
        body = _params_to_dict(params, body, locals())
        if test_only:
            uri = "/%s/test-check" % self.uri_base
            if include_debug:
                uri = "%s?debug=true" % uri
        else:
            uri = "/%s" % self.uri_base
        try:
            resp = self.api.method_post(uri, body=body)[0]
        except exc.BadRequest as e:
            msg = e.message
            dtls = e.details
            match = _invalid_key_pat.match(msg)
            if match:
                missing = match.groups()[0].replace("details.", "")
                if missing in details:
                    errmsg = "".join(["The value passed for '%s' in the ",
                            "details parameter is not valid."]) % missing
                else:
                    errmsg = "".join(["The required value for the '%s' ",
                            "setting is missing from the 'details' ",
                            "parameter."]) % missing
                    utils.update_exc(e, errmsg)
                raise e
            else:
                if msg == "Validation error":
                    # Info is in the 'details'
                    raise exc.InvalidMonitoringCheckDetails("Validation "
                            "failed. Error: '%s'." % dtls)
            # its something other than validation error; probably
            # limits exceeded, but raise it instead of failing silently
            raise e
        else:
            if resp.status_code == 201:
                check_id = resp.headers["x-object-id"]
                return self.get(check_id)
            # don't fail silently here either; raise an error
            # if we get an unexpected response code
            raise exc.ClientException("Unknown response code creating check;"
                " expected 201, got %s" % resp.status_code)


Instruction:
Can you tell what is the following Python 3 function doing
def find_all_checks(self, **kwargs):
        found = []
        searches = kwargs.items()
        for obj in self.list():
            try:
                if all(getattr(obj, attr) == value
                        for (attr, value) in searches):
                    found.append(obj)
            except AttributeError:
                continue
        return found

Response:
Finds all checks for a given entity with attributes matching
       .


Instruction:
Write a Python 3 function that can
return a dictionary of data optionally filtered for a given entity.

Response:
def list(self, entity=None):
        """
        Returns a dictionary of data, optionally filtered for a given entity.
        """
        uri = "/%s" % self.uri_base
        if entity:
            uri = "%s?entityId=%s" % (uri, utils.get_id(entity))
        resp, resp_body = self._list(uri, return_raw=True)
        return resp_body


Instruction:
Create a Python 3 function to
create the dict required to create the resource.

Response:
def _create_body(self, name, label=None, agent=None, ip_addresses=None,
            metadata=None):
        """
        Used to create the dict required to create various resources. Accepts
        either 'label' or 'name' as the keyword parameter for the label
        attribute for entities.
        """
        label = label or name
        if ip_addresses is not None:
            body = {"label": label}
            if ip_addresses:
                body["ip_addresses"] = ip_addresses
            if agent:
                body["agent_id"] = utils.get_id(agent)
            if metadata:
                body["metadata"] = metadata
        return body


Instruction:
Explain what the following Python 3 code does
def update_entity(self, entity, agent=None, metadata=None):
        body = {}
        if agent:
            body["agent_id"] = utils.get_id(agent)
        if metadata:
            body["metadata"] = metadata
        if body:
            uri = "/%s/%s" % (self.uri_base, utils.get_id(entity))
            resp, body = self.api.method_put(uri, body=body)

Response: Updates the specified entity s attributes with the supplied parameters.


Instruction:
Implement a Python 3 function for
reloading the check with its current values.

Response:
def get(self):
        """Reloads the check with its current values."""
        new = self.manager.get(self)
        if new:
            self._add_details(new._info)


Instruction:
Can you generate the documentation for the following Python 3 function
def update(self, label=None, name=None, disabled=None, metadata=None,
            monitoring_zones_poll=None, timeout=None, period=None,
            target_alias=None, target_hostname=None, target_receiver=None):
        """
        Updates an existing check with any of the parameters.
        """
        self.manager.update(self, label=label, name=name,
                disabled=disabled, metadata=metadata,
                monitoring_zones_poll=monitoring_zones_poll, timeout=timeout,
                period=period, target_alias=target_alias,
                target_hostname=target_hostname,
                target_receiver=target_receiver)

Response: Updates the properties of the current check.


Instruction:
Explain what the following Python 3 code does
def list_metrics(self, limit=None, marker=None, return_next=False):
        return self._metrics_manager.list(limit=limit, marker=marker,
                return_next=return_next)

Response: Returns a list of all the metrics associated with this check.


Instruction:
Explain what the following Python 3 code does
def get_metric_data_points(self, metric, start, end, points=None,
            resolution=None, stats=None):
        """
        Returns the data points for a given metric for the given period. The
        'start' and 'end' times must be specified; they can be be either Python
        date/datetime values, or a Unix timestamp.

        The 'points' parameter represents the number of points to return. The
        'resolution' parameter represents the granularity of the data. You must
        specify either 'points' or 'resolution'. The allowed values for
        resolution are:
            FULL
            MIN5
            MIN20
            MIN60
            MIN240
            MIN1440

        Finally, the 'stats' parameter specifies the stats you want returned.
        By default only the 'average' is returned. You omit this parameter,
        pass in a single value, or pass in a list of values. The allowed values
        are:
            average
            variance
            min
            max
        """
        return self._metrics_manager.get_metric_data_points(metric, start, end,
                points=points, resolution=resolution, stats=stats)

Response: Returns the data points for a given metric for a given period.


Instruction:
Can you generate the documentation for the following Python 3 function
def create_alarm(self, notification_plan, criteria=None, disabled=False,
            label=None, name=None, metadata=None):
        """
        Creates an alarm that binds this check with a notification plan.
        """
        return self.manager.create_alarm(self.entity, self, notification_plan,
                criteria=criteria, disabled=disabled, label=label, name=name,
                metadata=metadata)

Response: Creates an alarm that binds this check with a notification plan.


Instruction:
Write a Python 3 function for
fetching the current state of the alarm from the API and updates the object with the new state.

Response:
def get(self):
        """
        Fetches the current state of the alarm from the API and updates the
        object.
        """
        new_alarm = self.entity.get_alarm(self)
        if new_alarm:
            self._add_details(new_alarm._info)


Instruction:
Write a Python 3 script to
create the Manager instances to handle monitoring.

Response:
def _configure_manager(self):
        """
        Creates the Manager instances to handle monitoring.
        """
        self._entity_manager = CloudMonitorEntityManager(self,
                uri_base="entities", resource_class=CloudMonitorEntity,
                response_key=None, plural_response_key=None)
        self._check_type_manager = _PaginationManager(self,
                uri_base="check_types", resource_class=CloudMonitorCheckType,
                response_key=None, plural_response_key=None)
        self._monitoring_zone_manager = BaseManager(self,
                uri_base="monitoring_zones", resource_class=CloudMonitorZone,
                response_key=None, plural_response_key=None)
        self._notification_manager = CloudMonitorNotificationManager(self,
                uri_base="notifications",
                resource_class=CloudMonitorNotification,
                response_key=None, plural_response_key=None)
        self._notification_plan_manager = CloudMonitorNotificationPlanManager(
                self, uri_base="notification_plans",
                resource_class=CloudMonitorNotificationPlan,
                response_key=None, plural_response_key=None)
        self._changelog_manager = _EntityFilteringManger(self,
                uri_base="changelogs/alarms", resource_class=None,
                response_key=None, plural_response_key=None)
        self._overview_manager = _EntityFilteringManger(self,
                uri_base="views/overview", resource_class=None,
                response_key="value", plural_response_key=None)
        self._token_manager = CloudMonitorTokenManager(self)


Instruction:
Create a Python 3 function for
updating the entity with the given entity.

Response:
def update_entity(self, entity, agent=None, metadata=None):
        """
        Only the agent_id and metadata are able to be updated via the API.
        """
        self._entity_manager.update_entity(entity, agent=agent,
                metadata=metadata)


Instruction:
Implement a function in Python 3 to
update an existing check in the given object.

Response:
def update_check(self, entity, check, label=None, name=None, disabled=None,
            metadata=None, monitoring_zones_poll=None, timeout=None,
            period=None, target_alias=None, target_hostname=None,
            target_receiver=None):
        """
        Updates an existing check with any of the parameters.
        """
        entity.update_check(check, label=label, name=name, disabled=disabled,
                metadata=metadata, monitoring_zones_poll=monitoring_zones_poll,
                timeout=timeout, period=period, target_alias=target_alias,
                target_hostname=target_hostname,
                target_receiver=target_receiver)


Instruction:
Explain what the following Python 3 code does
def list_metrics(self, entity, check, limit=None, marker=None,
            return_next=False):
        """
        Returns a list of all the metrics associated with the specified check.
        """
        return entity.list_metrics(check, limit=limit, marker=marker,
                return_next=return_next)

Response: Returns a list of all the metrics associated with the specified check.


Instruction:
Write a Python 3 function that can
create a new notification for handling an alarm.

Response:
def create_notification(self, notification_type, label=None, name=None,
            details=None):
        """
        Defines a notification for handling an alarm.
        """
        return self._notification_manager.create(notification_type,
                label=label, name=name, details=details)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_notification_plan(self, label=None, name=None,
            critical_state=None, ok_state=None, warning_state=None):
        """
        Creates a notification plan to be executed when a monitoring check
        triggers an alarm.
        """
        return self._notification_plan_manager.create(label=label, name=name,
                critical_state=critical_state, ok_state=ok_state,
                warning_state=warning_state)

Response:
Creates a notification plan for a check
       .


Instruction:
Can you write a function in Python 3 where it
updates an existing alarm on the given entity.

Response:
def update_alarm(self, entity, alarm, criteria=None, disabled=False,
            label=None, name=None, metadata=None):
        """
        Updates an existing alarm on the given entity.
        """
        return entity.update_alarm(alarm, criteria=criteria, disabled=disabled,
            label=label, name=name, metadata=metadata)


Instruction:
Write a Python 3 function that can
return a list of all the alarms created on the specified entity.

Response:
def list_alarms(self, entity, limit=None, marker=None, return_next=False):
        """
        Returns a list of all the alarms created on the specified entity.
        """
        return entity.list_alarms(limit=limit, marker=marker,
                return_next=return_next)


Instruction:
Can you create a Python 3 function that
handles all the common functionality required for API calls Returns the response object and the body that will be used to make the API call.

Response:
def request(method, uri, *args, **kwargs):
    """
    Handles all the common functionality required for API calls. Returns
    the resulting response object.

    Formats the request into a dict representing the headers
    and body that will be used to make the API call.
    """
    req_method = req_methods[method.upper()]
    raise_exception = kwargs.pop("raise_exception", True)
    raw_content = kwargs.pop("raw_content", False)
    kwargs["headers"] = kwargs.get("headers", {})
    http_log_req(method, uri, args, kwargs)
    data = None
    if "data" in kwargs:
        # The 'data' kwarg is used when you don't want json encoding.
        data = kwargs.pop("data")
    elif "body" in kwargs:
        if "Content-Type" not in kwargs["headers"]:
            kwargs["headers"]["Content-Type"] = "application/json"
        data = json.dumps(kwargs.pop("body"))
    if data:
        resp = req_method(uri, data=data, **kwargs)
    else:
        resp = req_method(uri, **kwargs)
    if raw_content:
        body = resp.content
    else:
        try:
            body = resp.json()
        except ValueError:
            # No JSON in response
            body = resp.content
    http_log_resp(resp, body)
    if resp.status_code >= 400 and raise_exception:
        raise exc.from_response(resp, body)
    return resp, body


Instruction:
Write a Python 3 function for
logging the HTTP request to the logger.

Response:
def http_log_req(method, uri, args, kwargs):
    """
    When pyrax.get_http_debug() is True, outputs the equivalent `curl`
    command for the API request being made.
    """
    if not pyrax.get_http_debug():
        return
    string_parts = ["curl -i -X %s" % method]
    for element in args:
        string_parts.append("%s" % element)
    for element in kwargs["headers"]:
        header = "-H '%s: %s'" % (element, kwargs["headers"][element])
        string_parts.append(header)
    string_parts.append(uri)
    log = logging.getLogger("pyrax")
    log.debug("\nREQ: %s\n" % " ".join(string_parts))
    if "body" in kwargs:
        pyrax._logger.debug("REQ BODY: %s\n" % (kwargs["body"]))
    if "data" in kwargs:
        pyrax._logger.debug("REQ DATA: %s\n" % (kwargs["data"]))


Instruction:
Write a Python 3 script for
logging the response to the log.

Response:
def http_log_resp(resp, body):
    """
    When pyrax.get_http_debug() is True, outputs the response received
    from the API request.
    """
    if not pyrax.get_http_debug():
        return
    log = logging.getLogger("pyrax")
    log.debug("RESP: %s\n%s", resp, resp.headers)
    if body:
        log.debug("RESP BODY: %s", body)


Instruction:
Can you implement a function in Python 3 that
assures that a Container or a name of a container is passed.

Response:
def assure_container(fnc):
    """
    Assures that whether a Container or a name of a container is passed, a
    Container object is available.
    """
    @wraps(fnc)
    def _wrapped(self, container, *args, **kwargs):
        if not isinstance(container, Container):
            # Must be the name
            container = self.get(container)
        return fnc(self, container, *args, **kwargs)
    return _wrapped


Instruction:
Create a Python 3 function for
returning a copy of the supplied dictionary with any keys that do not begin with the specified prefix accordingly.

Response:
def _massage_metakeys(dct, prfx):
    """
    Returns a copy of the supplied dictionary, prefixing any keys that do
    not begin with the specified prefix accordingly.
    """
    lowprefix = prfx.lower()
    ret = {}
    for k, v in list(dct.items()):
        if not k.lower().startswith(lowprefix):
            k = "%s%s" % (prfx, k)
        ret[k] = v
    return ret


Instruction:
Write a Python 3 function for
returning the size of a file - like object.

Response:
def get_file_size(fileobj):
    """
    Returns the size of a file-like object.
    """
    currpos = fileobj.tell()
    fileobj.seek(0, 2)
    total_size = fileobj.tell()
    fileobj.seek(currpos)
    return total_size


Instruction:
Make a summary of the following Python 3 code
def _set_cdn_defaults(self):
        if self._cdn_enabled is FAULT:
            self._cdn_enabled = False
        self._cdn_uri = None
        self._cdn_ttl = DEFAULT_CDN_TTL
        self._cdn_ssl_uri = None
        self._cdn_streaming_uri = None
        self._cdn_ios_uri = None
        self._cdn_log_retention = False

Response: Sets all the CDN - related attributes to default values.


Instruction:
Here you have a function in Python 3, explain what it does
def _fetch_cdn_data(self):
        if self._cdn_enabled is FAULT:
            headers = self.manager.fetch_cdn_data(self)
        else:
            headers = {}
        # Set defaults in case not all headers are present.
        self._set_cdn_defaults()
        if not headers:
            # Not CDN enabled; return
            return
        else:
            self._cdn_enabled = True
        for key, value in headers.items():
            low_key = key.lower()
            if low_key == "x-cdn-uri":
                self._cdn_uri = value
            elif low_key == "x-ttl":
                self._cdn_ttl = int(value)
            elif low_key == "x-cdn-ssl-uri":
                self._cdn_ssl_uri = value
            elif low_key == "x-cdn-streaming-uri":
                self._cdn_streaming_uri = value
            elif low_key == "x-cdn-ios-uri":
                self._cdn_ios_uri = value
            elif low_key == "x-log-retention":
                self._cdn_log_retention = (value == "True")

Response: Fetches the container s CDN data from the CDN service.


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

Response: Sets the container s metadata.


Instruction:
Here you have a function in Python 3, explain what it does
def purge_cdn_object(self, obj, email_addresses=None):
        return self.object_manager.purge(obj, email_addresses=email_addresses)

Response: Removes an object from public access before the TTL expires.


Instruction:
Here you have a function in Python 3, explain what it does
def get_object(self, item):
        if isinstance(item, six.string_types):
            item = self.object_manager.get(item)
        return item

Response: Returns a StorageObject matching the specified item.


Instruction:
Write a Python 3 script for
listing the objects in this container using the parameters to control the marker limit and delimiter end_marker and return_raw.

Response:
def list(self, marker=None, limit=None, prefix=None, delimiter=None,
            end_marker=None, full_listing=False, return_raw=False):
        """
        List the objects in this container, using the parameters to control the
        number and content of objects. Note that this is limited by the
        absolute request limits of Swift (currently 10,000 objects). If you
        need to list all objects in the container, use the `list_all()` method
        instead.
        """
        if full_listing:
            return self.list_all(prefix=prefix)
        else:
            return self.object_manager.list(marker=marker, limit=limit,
                    prefix=prefix, delimiter=delimiter, end_marker=end_marker,
                    return_raw=return_raw)


Instruction:
How would you implement a function in Python 3 that
returns a list of the names of all the objects in this container.

Response:
def list_object_names(self, marker=None, limit=None, prefix=None,
            delimiter=None, end_marker=None, full_listing=False):
        """
        Returns a list of the names of all the objects in this container. The
        same pagination parameters apply as in self.list().
        """
        if full_listing:
            objects = self.list_all(prefix=prefix)
        else:
            objects = self.list(marker=marker, limit=limit, prefix=prefix,
                    delimiter=delimiter, end_marker=end_marker)
        return [obj.name for obj in objects]


Instruction:
Given the following Python 3 function, write the documentation
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.
        """
        return self.object_manager.create(file_or_path=file_or_path,
                data=data, obj_name=obj_name, content_type=content_type,
                etag=etag, content_encoding=content_encoding,
                content_length=content_length, ttl=ttl, chunked=chunked,
                metadata=metadata, chunk_size=chunk_size, headers=headers,
                return_none=return_none)

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


Instruction:
Can you generate a brief explanation for the following Python 3 code
def store_object(self, obj_name, data, content_type=None, etag=None,
            content_encoding=None, ttl=None, return_none=False,
            headers=None, extra_info=None):
        """
        Creates a new object in this 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(obj_name=obj_name, data=data,
                content_type=content_type, etag=etag,
                content_encoding=content_encoding, ttl=ttl,
                return_none=return_none, headers=headers)

Response: Stores an object in this container.


Instruction:
How would you explain what the following Python 3 function does
def upload_file(self, file_or_path, obj_name=None, content_type=None,
            etag=None, return_none=False, content_encoding=None, ttl=None,
            content_length=None, headers=None):
        """
        Uploads the specified file to this 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(file_or_path=file_or_path, obj_name=obj_name,
                content_type=content_type, etag=etag,
                content_encoding=content_encoding, headers=headers,
                content_length=content_length, ttl=ttl,
                return_none=return_none)

Response: Uploads a file to this container.


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

Response:
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, 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.object_manager.fetch(obj, include_meta=include_meta,
                chunk_size=chunk_size, size=size)


Instruction:
How would you code a function in Python 3 to
fetch a single object from the cache.

Response:
def fetch_object(self, obj_name, include_meta=False, chunk_size=None):
        """
        Alias for self.fetch(); included for backwards compatibility
        """
        return self.fetch(obj=obj_name, include_meta=include_meta,
                chunk_size=chunk_size)


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

Response:
def download(self, 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 self.object_manager.download(obj, directory, structure=structure)


Instruction:
Create a Python 3 function for
downloading an object from the cache.

Response:
def download_object(self, obj_name, directory, structure=True):
        """
        Alias for self.download(); included for backwards compatibility
        """
        return self.download(obj=obj_name, directory=directory,
                structure=structure)


Instruction:
How would you explain what the following Python 3 function does
def delete(self, del_objects=False):
        return self.manager.delete(self, del_objects=del_objects)

Response:
Deletes this Container. If the container contains objects, the
        command will fail unless 'del_objects' is passed as True. In that
        case, each object will be deleted first, and then the container.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def delete_object_in_seconds(self, obj, seconds, extra_info=None):
        return self.manager.delete_object_in_seconds(self, obj, seconds)

Response: Deletes the specified object in the specified number of seconds.


Instruction:
Write a Python 3 function for
deleting all objects from this container.

Response:
def delete_all_objects(self, 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
        """
        nms = self.list_object_names(full_listing=True)
        return self.object_manager.delete_all_objects(nms, async_=async_)


Instruction:
Can you tell what is the following Python 3 function doing
def copy_object(self, 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.
        """
        return self.manager.copy_object(self, obj, new_container,
                new_obj_name=new_obj_name, content_type=content_type)

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


Instruction:
Implement a function in Python 3 to
move an object to a new container.

Response:
def move_object(self, 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(self, obj, new_container,
                new_obj_name=new_obj_name, new_reference=new_reference,
                content_type=content_type)


Instruction:
Can you generate the documentation for the following Python 3 function
def change_object_content_type(self, obj, new_ctype, guess=False):
        return self.manager.change_object_content_type(self, obj, new_ctype,
                guess=guess)

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


Instruction:
Can you implement a function in Python 3 that
gives a storage object in this container returns a temporary URL that can be used to access that object.

Response:
def get_temp_url(self, obj, seconds, method="GET", key=None, cached=True):
        """
        Given a storage object in this 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(self, obj, seconds, method=method,
                key=key, cached=cached)


Instruction:
Write a Python 3 function for
setting the object s metadata to the given dictionary.

Response:
def set_object_metadata(self, 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.

        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.

        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 self.object_manager.set_metadata(obj, metadata, clear=clear,
                prefix=prefix)


Instruction:
Can you tell what is the following Python 3 function doing
def list_subdirs(self, marker=None, limit=None, prefix=None, delimiter=None,
            full_listing=False):
        """
        Return a list of the namesrepresenting the pseudo-subdirectories in
        this container. You can use the marker and limit params to handle
        pagination, and the prefix param to filter the objects returned. The
        delimiter param is there for backwards compatibility only, as the call
        requires the delimiter to be '/'.
        """
        return self.manager.list_subdirs(self, marker=marker, limit=limit,
                prefix=prefix, delimiter=delimiter, full_listing=full_listing)

Response: Return a list of the pseudo - directories in the infrastructure.


Instruction:
Make a summary of the following Python 3 code
def list(self, limit=None, marker=None, end_marker=None, prefix=None):
        uri = "/%s" % self.uri_base
        qs = utils.dict_to_qs({"marker": marker, "limit": limit,
                "prefix": prefix, "end_marker": end_marker})
        if qs:
            uri = "%s?%s" % (uri, qs)
        resp, resp_body = self.api.method_get(uri)
        return [Container(self, res, loaded=False)
                for res in resp_body if res]

Response: Returns a list of all the available container resources.


Instruction:
Here you have a function in Python 3, explain what it does
def get(self, container):
        name = utils.get_name(container)
        uri = "/%s" % name
        resp, resp_body = self.api.method_head(uri)
        hdrs = resp.headers
        data = {"total_bytes": int(hdrs.get("x-container-bytes-used", "0")),
                "object_count": int(hdrs.get("x-container-object-count", "0")),
                "name": name}
        return Container(self, data, loaded=False)

Response: Returns a Container object matching the specified container name.


Instruction:
Can you write a function in Python 3 where it
creates a new container with the specified name and metadata.

Response:
def create(self, name, metadata=None, prefix=None, *args, **kwargs):
        """
        Creates a new container, and returns a Container object that represents
        that contianer. If a container by the same name already exists, no
        exception is raised; instead, a reference to that existing container is
        returned.
        """
        uri = "/%s" % name
        headers = {}
        if prefix is None:
            prefix = CONTAINER_META_PREFIX
        if metadata:
            metadata = _massage_metakeys(metadata, prefix)
            headers = metadata
        resp, resp_body = self.api.method_put(uri, headers=headers)
        if resp.status_code in (201, 202):
            hresp, hresp_body = self.api.method_head(uri)
            num_obj = int(hresp.headers.get("x-container-object-count", "0"))
            num_bytes = int(hresp.headers.get("x-container-bytes-used", "0"))
            cont_info = {"name": name, "object_count": num_obj,
                    "total_bytes": num_bytes}
            return Container(self, cont_info)
        elif resp.status_code == 400:
            raise exc.ClientException("Container creation failed: %s" %
                    resp_body)


Instruction:
Can you create a Python 3 function that
deletes the specified container.

Response:
def delete(self, container, del_objects=False):
        """
        Deletes the specified container. If the container contains objects, the
        command will fail unless 'del_objects' is passed as True. In that case,
        each object will be deleted first, and then the container.
        """
        if del_objects:
            nms = self.list_object_names(container, full_listing=True)
            self.api.bulk_delete(container, nms, async_=False)
        uri = "/%s" % utils.get_name(container)
        resp, resp_body = self.api.method_delete(uri)


Instruction:
Can you create a Python 3 function that
returns the CDN - enabled data for the specified container.

Response:
def fetch_cdn_data(self, container):
        """
        Returns a dict containing the CDN information for the specified
        container. If the container is not CDN-enabled, returns an empty dict.
        """
        name = utils.get_name(container)
        uri = "/%s" % name
        try:
            resp, resp_body = self.api.cdn_request(uri, "HEAD")
        except exc.NotCDNEnabled:
            return {}
        return resp.headers


Instruction:
Here you have a function in Python 3, explain what it does
def get_headers(self, container):
        uri = "/%s" % utils.get_name(container)
        resp, resp_body = self.api.method_head(uri)
        return resp.headers

Response: Returns the headers for the specified container.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_account_metadata(self, prefix=None):
        headers = self.get_account_headers()
        if prefix is None:
            prefix = ACCOUNT_META_PREFIX
        low_prefix = prefix.lower()
        ret = {}
        for hkey, hval in list(headers.items()):
            lowkey = hkey.lower()
            if lowkey.startswith(low_prefix):
                cleaned = hkey.replace(low_prefix, "").replace("-", "_")
                ret[cleaned] = hval
        return ret

Response: Returns a dictionary containing metadata about the account.


Instruction:
Can you create a Python 3 function that
sets the metadata for the specified account.

Response:
def set_account_metadata(self, metadata, clear=False, prefix=None):
        """
        Accepts a dictionary of metadata key/value pairs and updates the
        account 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.
        """
        # Add the metadata prefix, if needed.
        if prefix is None:
            prefix = ACCOUNT_META_PREFIX
        massaged = _massage_metakeys(metadata, prefix)
        new_meta = {}
        if clear:
            curr_meta = self.get_account_metadata(prefix=prefix)
            for ckey in curr_meta:
                new_meta[ckey] = ""
            new_meta = _massage_metakeys(new_meta, prefix)
        utils.case_insensitive_update(new_meta, massaged)
        uri = "/"
        resp, resp_body = self.api.method_post(uri, headers=new_meta)
        return 200 <= resp.status_code <= 299


Instruction:
Create a Python 3 function for
removing all metadata matching the specified prefix from the account.

Response:
def delete_account_metadata(self, prefix=None):
        """
        Removes all metadata matching the specified prefix from the account.

        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.
        """
        # Add the metadata prefix, if needed.
        if prefix is None:
            prefix = ACCOUNT_META_PREFIX
        curr_meta = self.get_account_metadata(prefix=prefix)
        for ckey in curr_meta:
            curr_meta[ckey] = ""
        new_meta = _massage_metakeys(curr_meta, prefix)
        uri = "/"
        resp, resp_body = self.api.method_post(uri, headers=new_meta)
        return 200 <= resp.status_code <= 299


Instruction:
Write a Python 3 script for
returning a dictionary containing the metadata for the container.

Response:
def get_metadata(self, container, prefix=None):
        """
        Returns a dictionary containing the metadata for the container.
        """
        headers = self.get_headers(container)
        if prefix is None:
            prefix = CONTAINER_META_PREFIX
        low_prefix = prefix.lower()
        ret = {}
        for hkey, hval in list(headers.items()):
            if hkey.lower().startswith(low_prefix):
                cleaned = hkey.replace(low_prefix, "").replace("-", "_")
                ret[cleaned] = hval
        return ret


Instruction:
Can you implement a function in Python 3 that
sets the metadata for the specified container.

Response:
def set_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.
        """
        # Add the metadata prefix, if needed.
        if prefix is None:
            prefix = CONTAINER_META_PREFIX
        massaged = _massage_metakeys(metadata, prefix)
        new_meta = {}
        if clear:
            curr_meta = self.api.get_container_metadata(container,
                    prefix=prefix)
            for ckey in curr_meta:
                new_meta[ckey] = ""
        utils.case_insensitive_update(new_meta, massaged)
        name = utils.get_name(container)
        uri = "/%s" % name
        resp, resp_body = self.api.method_post(uri, headers=new_meta)
        return 200 <= resp.status_code <= 299


Instruction:
Here you have a function in Python 3, explain what it does
def remove_metadata_key(self, container, key):
        meta_dict = {key: ""}
        return self.set_metadata(container, meta_dict)

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


Instruction:
Can you implement a function in Python 3 that
removes all of the metadata for the specified container.

Response:
def delete_metadata(self, container, prefix=None):
        """
        Removes all of the 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.
        """
        # Add the metadata prefix, if needed.
        if prefix is None:
            prefix = CONTAINER_META_PREFIX
        new_meta = {}
        curr_meta = self.get_metadata(container, prefix=prefix)
        for ckey in curr_meta:
            new_meta[ckey] = ""
        uri = "/%s" % utils.get_name(container)
        resp, resp_body = self.api.method_post(uri, headers=new_meta)
        return 200 <= resp.status_code <= 299


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

Response:
def get_cdn_metadata(self, container):
        """
        Returns a dictionary containing the CDN metadata for the container. If
        the container does not exist, a NotFound exception is raised. If the
        container exists, but is not CDN-enabled, a NotCDNEnabled exception is
        raised.
        """
        uri = "%s/%s" % (self.uri_base, utils.get_name(container))
        resp, resp_body = self.api.cdn_request(uri, "HEAD")
        ret = dict(resp.headers)
        # Remove non-CDN headers
        ret.pop("content-length", None)
        ret.pop("content-type", None)
        ret.pop("date", None)
        return ret


Instruction:
Can you create a Python 3 function that
sets the CDN metadata for the specified container.

Response:
def set_cdn_metadata(self, container, metadata):
        """
        Accepts a dictionary of metadata key/value pairs and updates
        the specified container metadata with them.

        NOTE: arbitrary metadata headers are not allowed. The only metadata
        you can update are: X-Log-Retention, X-CDN-enabled, and X-TTL.
        """
        allowed = ("x-log-retention", "x-cdn-enabled", "x-ttl")
        hdrs = {}
        bad = []
        for mkey, mval in six.iteritems(metadata):
            if mkey.lower() not in allowed:
                bad.append(mkey)
                continue
            hdrs[mkey] = str(mval)
        if bad:
            raise exc.InvalidCDNMetadata("The only CDN metadata you can "
                    "update are: X-Log-Retention, X-CDN-enabled, and X-TTL. "
                    "Received the following illegal item(s): %s" %
                    ", ".join(bad))
        uri = "%s/%s" % (self.uri_base, utils.get_name(container))
        resp, resp_body = self.api.cdn_request(uri, "POST", headers=hdrs)
        return resp


Instruction:
Can you create a Python 3 function that
gives a storage object in a container returns a temporary URL that can be used to access that object.

Response:
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`.
        """
        if not key:
            key = self.api.get_temp_url_key(cached=cached)
        if not key:
            raise exc.MissingTemporaryURLKey("You must set the key for "
                    "Temporary URLs before you can generate them. This is "
                    "done via the `set_temp_url_key()` method.")
        cname = utils.get_name(container)
        oname = utils.get_name(obj)
        mod_method = method.upper().strip()
        if mod_method not in ("GET", "PUT"):
            raise exc.InvalidTemporaryURLMethod("Method must be either 'GET' "
                    "or 'PUT'; received '%s'." % method)
        mgt_url = self.api.management_url
        mtch = re.search(r"/v\d/", mgt_url)
        start = mtch.start()
        base_url = mgt_url[:start]
        path_parts = (mgt_url[start:], cname, oname)
        cleaned = (part.strip("/\\") for part in path_parts)
        pth = "/%s" % "/".join(cleaned)
        expires = int(time.time() + int(seconds))
        try:
            key = key.encode("ascii")
            hmac_body = b'\n'.join([
                mod_method.encode("ascii"),
                six.text_type(expires).encode("ascii"),
                pth.encode("ascii")])
        except UnicodeEncodeError:
            raise exc.UnicodePathError("Due to a bug in Python, the TempURL "
                    "function only works with ASCII object paths.")
        sig = hmac.new(key, hmac_body, hashlib.sha1).hexdigest()
        temp_url = "%s%s?temp_url_sig=%s&temp_url_expires=%s" % (base_url, pth,
                sig, expires)
        return temp_url


Instruction:
Explain what the following Python 3 code does
def list_containers_info(self, limit=None, marker=None):
        uri = ""
        qs = utils.dict_to_qs({"limit": limit, "marker": marker})
        if qs:
            uri += "%s?%s" % (uri, qs)
        resp, resp_body = self.api.method_get(uri)
        return resp_body

Response: Returns a list of info on Containers.


Instruction:
Can you generate the documentation for the following Python 3 function
def list_public_containers(self):
        resp, resp_body = self.api.cdn_request("", "GET")
        return [cont["name"] for cont in resp_body]

Response: Returns a list of the names of all CDN - enabled containers.


Instruction:
Here you have a function in Python 3, explain what it does
def make_public(self, container, ttl=None):
        return self._set_cdn_access(container, public=True, ttl=ttl)

Response:
Enables CDN access for the specified container and optionally sets the
        TTL for the container.


Instruction:
Create a Python 3 function to
set the CDN access for the specified container.

Response:
def _set_cdn_access(self, container, public, ttl=None):
        """
        Enables or disables CDN access for the specified container, and
        optionally sets the TTL for the container when enabling access.
        """
        headers = {"X-Cdn-Enabled": "%s" % public}
        if public and ttl:
            headers["X-Ttl"] = ttl
        self.api.cdn_request("/%s" % utils.get_name(container), method="PUT",
                headers=headers)


Instruction:
Create a Python 3 function to
return the status of the CDN log retention for the specified container.

Response:
def get_cdn_log_retention(self, container):
        """
        Returns the status of the setting for CDN log retention for the
        specified container.
        """
        resp, resp_body = self.api.cdn_request("/%s" %
                utils.get_name(container), method="HEAD")
        return resp.headers.get("x-log-retention").lower() == "true"


Instruction:
Can you implement a function in Python 3 that
sets whether CDN access logs for the specified container are collected and stored on Cloud Files.

Response:
def set_cdn_log_retention(self, container, enabled):
        """
        Enables or disables whether CDN access logs for the specified container
        are collected and stored on Cloud Files.
        """
        headers = {"X-Log-Retention": "%s" % enabled}
        self.api.cdn_request("/%s" % utils.get_name(container), method="PUT",
                headers=headers)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_container_streaming_uri(self, container):
        resp, resp_body = self.api.cdn_request("/%s" %
                utils.get_name(container), method="HEAD")
        return resp.headers.get("x-cdn-streaming-uri")

Response: Returns the URI for streaming content for the given container.