Instruction:
Implement a function in Python 3 to
find the files in the app directories and return the list of matches.

Response:
def find(self, path, all=False):
        """
        Looks for files in the app directories.
        """
        matches = []
        for app in self.apps:
            app_location = self.storages[app].location
            if app_location not in searched_locations:
                searched_locations.append(app_location)
            match = self.find_in_app(app, path)
            if match:
                if not all:
                    return match
                matches.append(match)
        return matches


Instruction:
Can you tell what is the following Python 3 function doing
def find_in_app(self, app, path):
        storage = self.storages.get(app, None)
        if storage:
            # only try to find a file if the source dir actually exists
            if storage.exists(path):
                matched_path = storage.path(path)
                if matched_path:
                    return matched_path

Response: Find a requested media file in an app s media fixtures locations.


Instruction:
Given the following Python 3 function, write the documentation
def set_options(self, **options):
        self.interactive = options['interactive']
        self.verbosity = options['verbosity']
        self.symlink = options['link']
        self.clear = options['clear']
        self.dry_run = options['dry_run']
        ignore_patterns = options['ignore_patterns']
        if options['use_default_ignore_patterns']:
            ignore_patterns += ['CVS', '.*', '*~']
        self.ignore_patterns = list(set(ignore_patterns))
        self.post_process = options['post_process']

Response: Set instance variables based on an options dict


Instruction:
How would you code a function in Python 3 to
collect the media files and store them in a dictionary.

Response:
def collect(self):
        """
        Perform the bulk of the work of collectmedia.

        Split off from handle() to facilitate testing.
        """
        if self.symlink and not self.local:
            raise CommandError("Can't symlink to a remote destination.")

        if self.clear:
            self.clear_dir('')

        if self.symlink:
            handler = self.link_file
        else:
            handler = self.copy_file

        found_files = OrderedDict()
        for finder in get_finders():
            for path, storage in finder.list(self.ignore_patterns):
                # Prefix the relative path if the source storage contains it
                if getattr(storage, 'prefix', None):
                    prefixed_path = os.path.join(storage.prefix, path)
                else:
                    prefixed_path = path

                if prefixed_path not in found_files:
                    found_files[prefixed_path] = (storage, path)
                    handler(path, prefixed_path, storage)

        # Here we check if the storage backend has a post_process
        # method and pass it the list of modified files.
        if self.post_process and hasattr(self.storage, 'post_process'):
            processor = self.storage.post_process(found_files,
                                                  dry_run=self.dry_run)
            for original_path, processed_path, processed in processor:
                if isinstance(processed, Exception):
                    self.stderr.write("Post-processing '%s' failed!" % original_path)
                    # Add a blank line before the traceback, otherwise it's
                    # too easy to miss the relevant part of the error message.
                    self.stderr.write("")
                    raise processed
                if processed:
                    self.log("Post-processed '%s' as '%s'" %
                             (original_path, processed_path), level=1)
                    self.post_processed_files.append(original_path)
                else:
                    self.log("Skipped post-processing '%s'" % original_path)

        return {
            'modified': self.copied_files + self.symlinked_files,
            'unmodified': self.unmodified_files,
            'post_processed': self.post_processed_files,
        }


Instruction:
Can you create a Python 3 function that
deletes the given relative path using the destination storage backend.

Response:
def clear_dir(self, path):
        """
        Deletes the given relative path using the destination storage backend.
        """
        dirs, files = self.storage.listdir(path)
        for f in files:
            fpath = os.path.join(path, f)
            if self.dry_run:
                self.log("Pretending to delete '%s'" %
                         smart_text(fpath), level=1)
            else:
                self.log("Deleting '%s'" % smart_text(fpath), level=1)
                self.storage.delete(fpath)
        for d in dirs:
            self.clear_dir(os.path.join(path, d))


Instruction:
How would you explain what the following Python 3 function does
def delete_file(self, path, prefixed_path, source_storage):
        if self.storage.exists(prefixed_path):
            try:
                # When was the target file modified last time?
                target_last_modified = \
                    self.storage.modified_time(prefixed_path)
            except (OSError, NotImplementedError, AttributeError):
                # The storage doesn't support ``modified_time`` or failed
                pass
            else:
                try:
                    # When was the source file modified last time?
                    source_last_modified = source_storage.modified_time(path)
                except (OSError, NotImplementedError, AttributeError):
                    pass
                else:
                    # The full path of the target file
                    if self.local:
                        full_path = self.storage.path(prefixed_path)
                    else:
                        full_path = None
                    # Skip the file if the source file is younger
                    # Avoid sub-second precision (see #14665, #19540)
                    if (target_last_modified.replace(microsecond=0)
                            >= source_last_modified.replace(microsecond=0)):
                        if not ((self.symlink and full_path
                                 and not os.path.islink(full_path)) or
                                (not self.symlink and full_path
                                 and os.path.islink(full_path))):
                            if prefixed_path not in self.unmodified_files:
                                self.unmodified_files.append(prefixed_path)
                            self.log("Skipping '%s' (not modified)" % path)
                            return False
            # Then delete the existing file if really needed
            if self.dry_run:
                self.log("Pretending to delete '%s'" % path)
            else:
                self.log("Deleting '%s'" % path)
                self.storage.delete(prefixed_path)
        return True

Response: Checks if the target file should be deleted if it exists and if it should be deleted if it should be deleted if it already exists and if it should be deleted if it should be deleted if it should be deleted if it already exists and if it should be deleted if it should be deleted if it should be deleted if it already exists.


Instruction:
Make a summary of the following Python 3 code
def link_file(self, path, prefixed_path, source_storage):
        # Skip this file if it was already copied earlier
        if prefixed_path in self.symlinked_files:
            return self.log("Skipping '%s' (already linked earlier)" % path)
        # Delete the target file if needed or break
        if not self.delete_file(path, prefixed_path, source_storage):
            return
        # The full path of the source file
        source_path = source_storage.path(path)
        # Finally link the file
        if self.dry_run:
            self.log("Pretending to link '%s'" % source_path, level=1)
        else:
            self.log("Linking '%s'" % source_path, level=1)
            full_path = self.storage.path(prefixed_path)
            try:
                os.makedirs(os.path.dirname(full_path))
            except OSError:
                pass
            try:
                if os.path.lexists(full_path):
                    os.unlink(full_path)
                os.symlink(source_path, full_path)
            except AttributeError:
                import platform
                raise CommandError("Symlinking is not supported by Python %s." %
                                   platform.python_version())
            except NotImplementedError:
                import platform
                raise CommandError("Symlinking is not supported in this "
                                   "platform (%s)." % platform.platform())
            except OSError as e:
                raise CommandError(e)
        if prefixed_path not in self.symlinked_files:
            self.symlinked_files.append(prefixed_path)

Response: Link the file at the given path to the source file at the given prefixed_path.


Instruction:
Can you create a Python 3 function that
copies a file from source_storage to the target storage.

Response:
def copy_file(self, path, prefixed_path, source_storage):
        """
        Attempt to copy ``path`` with storage
        """
        # Skip this file if it was already copied earlier
        if prefixed_path in self.copied_files:
            return self.log("Skipping '%s' (already copied earlier)" % path)
        # Delete the target file if needed or break
        if not self.delete_file(path, prefixed_path, source_storage):
            return
        # The full path of the source file
        source_path = source_storage.path(path)
        # Finally start copying
        if self.dry_run:
            self.log("Pretending to copy '%s'" % source_path, level=1)
        else:
            self.log("Copying '%s'" % source_path, level=1)
            with source_storage.open(path) as source_file:
                self.storage.save(prefixed_path, source_file)
        self.copied_files.append(prefixed_path)


Instruction:
Can you tell what is the following Python 3 function doing
def reorderChild(self, parent, newitem):
        source = self.getItem(parent).childItems
        target = newitem.childItems

        i = 0
        while i < len(source):

            if source[i] == target[i]:
                i += 1
                continue
            else:
                i0 = i
                j0 = source.index(target[i0])
                j = j0 + 1
                while j < len(source):
                    if source[j] == target[j - j0 + i0]:
                        j += 1
                        continue
                    else:
                        break
                self.moveRows(parent, i0, j0, j - j0)
                i += j - j0

Response: Reorder a list to match target by moving a sequence at a time.


Instruction:
Make a summary of the following Python 3 code
def moveRows(self, parent, index_to, index_from, length):
        source = self.getItem(parent).childItems

        self.beginMoveRows(
            parent, index_from, index_from + length - 1, parent, index_to
        )

        sublist = [source.pop(index_from) for _ in range(length)]

        for _ in range(length):
            source.insert(index_to, sublist.pop())

        self.endMoveRows()

Response:
Move a sub sequence in a list
            parent to index_to.


Instruction:
Can you tell what is the following Python 3 function doing
def cur_space(self, name=None):
        if name is None:
            return self._impl.model.currentspace.interface
        else:
            self._impl.model.currentspace = self._impl.spaces[name]
            return self.cur_space()

Response: Set the current space to the space named name and return it.


Instruction:
Make a summary of the following Python 3 code
def new_space(self, name=None, bases=None, formula=None, refs=None):
        space = self._impl.model.currentspace = self._impl.new_space(
            name=name, bases=get_impls(bases), formula=formula, refs=refs
        )

        return space.interface

Response: Create a new child space.


Instruction:
Can you tell what is the following Python 3 function doing
def import_module(self, module=None, recursive=False, **params):
        if module is None:
            if "module_" in params:
                warnings.warn(
                    "Parameter 'module_' is deprecated. Use 'module' instead.")
                module = params.pop("module_")
            else:
                raise ValueError("no module specified")

        if "bases" in params:
            params["bases"] = get_impls(params["bases"])

        space = (
            self._impl.model.currentspace
        ) = self._impl.new_space_from_module(
            module, recursive=recursive, **params
        )
        return get_interfaces(space)

Response: Create a child space from a module object.


Instruction:
Here you have a function in Python 3, explain what it does
def new_space_from_module(self, module, recursive=False, **params):
        if "bases" in params:
            params["bases"] = get_impls(params["bases"])

        space = (
            self._impl.model.currentspace
        ) = self._impl.new_space_from_module(
            module, recursive=recursive, **params
        )
        return get_interfaces(space)

Response: Create a new child space from a module object.


Instruction:
Implement a Python 3 function for
creating a new child space from an Excel file.

Response:
def new_space_from_excel(
        self,
        book,
        range_,
        sheet=None,
        name=None,
        names_row=None,
        param_cols=None,
        space_param_order=None,
        cells_param_order=None,
        transpose=False,
        names_col=None,
        param_rows=None,
    ):
        """Create a child space from an Excel range.

        To use this method, ``openpyxl`` package must be installed.

        Args:
            book (str): Path to an Excel file.
            range_ (str): Range expression, such as "A1", "$G4:$K10",
                or named range "NamedRange1".
            sheet (str): Sheet name (case ignored).
            name (str, optional): Name of the space. Defaults to ``SpaceN``,
                where ``N`` is a number determined automatically.
            names_row (optional): an index number indicating
                what row contains the names of cells and parameters.
                Defaults to the top row (0).
            param_cols (optional): a sequence of index numbers
                indicating parameter columns.
                Defaults to only the leftmost column ([0]).
            names_col (optional): an index number, starting from 0,
                indicating what column contains additional parameters.
            param_rows (optional): a sequence of index numbers, starting from
                0, indicating rows of additional parameters, in case cells are
                defined in two dimensions.
            transpose (optional): Defaults to ``False``.
                If set to ``True``, "row(s)" and "col(s)" in the parameter
                names are interpreted inversely, i.e.
                all indexes passed to "row(s)" parameters are interpreted
                as column indexes,
                and all indexes passed to "col(s)" parameters as row indexes.
            space_param_order: a sequence to specify space parameters and
                their orders. The elements of the sequence denote the indexes
                of ``param_cols`` elements, and optionally the index of
                ``param_rows`` elements shifted by the length of
                ``param_cols``. The elements of this parameter and
                ``cell_param_order`` must not overlap.
            cell_param_order (optional): a sequence to reorder the parameters.
                The elements of the sequence denote the indexes of
                ``param_cols`` elements, and optionally the index of
                ``param_rows`` elements shifted by the length of
                ``param_cols``. The elements of this parameter and
                ``cell_space_order`` must not overlap.

        Returns:
            The new child space created from the Excel range.
        """

        space = self._impl.new_space_from_excel(
            book,
            range_,
            sheet,
            name,
            names_row,
            param_cols,
            space_param_order,
            cells_param_order,
            transpose,
            names_col,
            param_rows,
        )

        return get_interfaces(space)


Instruction:
Can you generate the documentation for the following Python 3 function
def restore_state(self, system):

        for space in self._spaces.values():
            space.restore_state(system)

Response: Called after unpickling to restore some attributes manually.


Instruction:
How would you explain what the following Python 3 function does
def new_space(
        self,
        name=None,
        bases=None,
        formula=None,
        *,
        refs=None,
        source=None,
        is_derived=False,
        prefix=""
    ):
        """Create a new child space.

        Args:
            name (str): Name of the space. If omitted, the space is
                created automatically.
            bases: If specified, the new space becomes a derived space of
                the `base` space.
            formula: Function whose parameters used to set space parameters.
            refs: a mapping of refs to be added.
            arguments: ordered dict of space parameter names to their values.
            source: A source module from which cell definitions are read.
            prefix: Prefix to the autogenerated name when name is None.
        """
        from modelx.core.space import StaticSpaceImpl

        if name is None:
            name = self.spacenamer.get_next(self.namespace, prefix)

        if name in self.namespace:
            raise ValueError("Name '%s' already exists." % name)

        if not prefix and not is_valid_name(name):
            raise ValueError("Invalid name '%s'." % name)

        space = self._new_space(
            name=name,
            formula=formula,
            refs=refs,
            source=source,
            is_derived=is_derived,
        )
        self._set_space(space)

        self.model.spacegraph.add_space(space)

        # Set up direct base spaces and mro
        if bases is not None:
            if isinstance(bases, StaticSpaceImpl):
                bases = [bases]

            space.add_bases(bases)

        return space

Response: Create a new child space.


Instruction:
Implement a function in Python 3 to
create a node from arguments and return it

Response:
def get_node(obj, args, kwargs):
    """Create a node from arguments and return it"""

    if args is None and kwargs is None:
        return (obj,)

    if kwargs is None:
        kwargs = {}
    return obj, _bind_args(obj, args, kwargs)


Instruction:
Here you have a function in Python 3, explain what it does
def node_get_args(node):
    obj = node[OBJ]
    key = node[KEY]
    boundargs = obj.formula.signature.bind(*key)
    boundargs.apply_defaults()
    return boundargs.arguments

Response: Return an ordered mapping from params to args


Instruction:
Create a Python 3 function to
get a modelx object from its full name.

Response:
def get_object(name: str):
    """Get a modelx object from its full name."""
    # TODO: Duplicate of system.get_object
    elms = name.split(".")
    parent = get_models()[elms.pop(0)]
    while len(elms) > 0:
        obj = elms.pop(0)
        parent = getattr(parent, obj)

    return parent


Instruction:
Make a summary of the following Python 3 code
def _get_node(name: str, args: str):
    obj = get_object(name)
    args = ast.literal_eval(args)
    if not isinstance(args, tuple):
        args = (args,)

    return obj.node(*args)

Response:
Get node from object name and arg string

    Not Used. Left for future reference purpose.


Instruction:
Can you tell what is the following Python 3 function doing
def cur_model(model=None):
    if model is None:
        if _system.currentmodel is not None:
            return _system.currentmodel.interface
        else:
            return None
    else:
        if isinstance(model, _Model):
            _system.currentmodel = model._impl
        else:
            _system.currentmodel = _system.models[model]

        return _system.currentmodel.interface

Response: Get and or set the current model.


Instruction:
Write a Python 3 function for
getting and / or set the current space of the current model.

Response:
def cur_space(space=None):
    """Get and/or set the current space of the current model.

    If ``name`` is given, the current space of the current model is
    set to ``name`` and return it.
    If ``name`` is not given, the current space of the current model
    is returned.
    """
    if space is None:
        if _system.currentmodel is not None:
            if _system.currentmodel.currentspace is not None:
                return _system.currentmodel.currentspace.interface
            else:
                return None
        else:
            return None
    else:
        if isinstance(space, _Space):
            cur_model(space.model)
            _system.currentmodel.currentspace = space._impl
        else:
            _system.currentmodel.currentspace = _system.currentmodel.spaces[
                space
            ]

        return cur_space()


Instruction:
Implement a function in Python 3 to
hook to override default showwarning.

Response:
def custom_showwarning(
    message, category, filename="", lineno=-1, file=None, line=None
):
    """Hook to override default showwarning.

    https://stackoverflow.com/questions/2187269/python-print-only-the-message-on-warnings
    """

    if file is None:
        file = sys.stderr
        if file is None:
            # sys.stderr is None when run with pythonw.exe:
            # warnings get lost
            return
    text = "%s: %s\n" % (category.__name__, message)
    try:
        file.write(text)
    except OSError:
        # the file (probably stderr) is invalid - this warning gets lost.
        pass


Instruction:
Can you generate the documentation for the following Python 3 function
def excepthook(self, except_type, exception, traceback):
    if except_type is DeepReferenceError:
        print(exception.msg)
    else:
        self.default_excepthook(except_type, exception, traceback)

Response: Custom exception hook to replace sys. excepthook


Instruction:
How would you explain what the following Python 3 function does
def tracemessage(self, maxlen=6):
        result = ""
        for i, value in enumerate(self):
            result += "{0}: {1}\n".format(i, get_node_repr(value))

        result = result.strip("\n")
        lines = result.split("\n")

        if maxlen and len(lines) > maxlen:
            i = int(maxlen / 2)
            lines = lines[:i] + ["..."] + lines[-(maxlen - i) :]
            result = "\n".join(lines)

        return result

Response: Returns a string representation of the log entry.


Instruction:
How would you explain what the following Python 3 function does
def setup_ipython(self):
        if self.is_ipysetup:
            return

        from ipykernel.kernelapp import IPKernelApp

        self.shell = IPKernelApp.instance().shell  # None in PyCharm console

        if not self.shell and is_ipython():
            self.shell = get_ipython()

        if self.shell:
            shell_class = type(self.shell)
            shell_class.default_showtraceback = shell_class.showtraceback
            shell_class.showtraceback = custom_showtraceback
            self.is_ipysetup = True
        else:
            raise RuntimeError("IPython shell not found.")

Response: Monkey patch shell s error handler to include the custom showtraceback method of the IPython kernel.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def restore_ipython(self):
        if not self.is_ipysetup:
            return

        shell_class = type(self.shell)
        shell_class.showtraceback = shell_class.default_showtraceback
        del shell_class.default_showtraceback

        self.is_ipysetup = False

Response: Restore default IPython showtraceback


Instruction:
Can you create a Python 3 function that
restores Python settings to the original states

Response:
def restore_python(self):
        """Restore Python settings to the original states"""
        orig = self.orig_settings
        sys.setrecursionlimit(orig["sys.recursionlimit"])

        if "sys.tracebacklimit" in orig:
            sys.tracebacklimit = orig["sys.tracebacklimit"]
        else:
            if hasattr(sys, "tracebacklimit"):
                del sys.tracebacklimit

        if "showwarning" in orig:
            warnings.showwarning = orig["showwarning"]

        orig.clear()
        threading.stack_size()


Instruction:
Given the following Python 3 function, write the documentation
def get_object(self, name):

        parts = name.split(".")

        model_name = parts.pop(0)
        return self.models[model_name].get_object(".".join(parts))

Response: Retrieve an object by its absolute name.


Instruction:
How would you explain what the following Python 3 function does
def get_modeltree(model=None):
    if model is None:
        model = mx.cur_model()
    treemodel = ModelTreeModel(model._baseattrs)
    view = QTreeView()
    view.setModel(treemodel)
    view.setWindowTitle("Model %s" % model.name)
    view.setAlternatingRowColors(True)
    return view

Response: Alias to : func : get_tree.


Instruction:
Can you generate the documentation for the following Python 3 function
def show_tree(model=None):
    if model is None:
        model = mx.cur_model()
    view = get_modeltree(model)
    app = QApplication.instance()
    if not app:
        raise RuntimeError("QApplication does not exist.")
    view.show()
    app.exec_()

Response: Display the model tree window.


Instruction:
Create a Python 3 function to
get interfaces from their implementations.

Response:
def get_interfaces(impls):
    """Get interfaces from their implementations."""
    if impls is None:
        return None

    elif isinstance(impls, OrderMixin):
        result = OrderedDict()
        for name in impls.order:
            result[name] = impls[name].interface
        return result

    elif isinstance(impls, Mapping):
        return {name: impls[name].interface for name in impls}

    elif isinstance(impls, Sequence):
        return [impl.interface for impl in impls]

    else:
        return impls.interface


Instruction:
Can you generate the documentation for the following Python 3 function
def get_impls(interfaces):
    if interfaces is None:
        return None

    elif isinstance(interfaces, Mapping):
        return {name: interfaces[name]._impl for name in interfaces}

    elif isinstance(interfaces, Sequence):
        return [interfaces._impl for interfaces in interfaces]

    else:
        return interfaces._impl

Response: Get impls from their interfaces.


Instruction:
Write a Python 3 function for
updating all LazyEvals in self. lzy_evals enough to update all owned LazyEvals.

Response:
def update_lazyevals(self):
        """Update all LazyEvals in self

        self.lzy_evals must be set to LazyEval object(s) enough to
        update all owned LazyEval objects.
        """
        if self.lazy_evals is None:
            return
        elif isinstance(self.lazy_evals, LazyEval):
            self.lazy_evals.get_updated()
        else:
            for lz in self.lazy_evals:
                lz.get_updated()


Instruction:
Here you have a function in Python 3, explain what it does
def _baseattrs(self):

        result = {
            "type": type(self).__name__,
            "id": id(self),
            "name": self.name,
            "fullname": self.fullname,
            "repr": self._get_repr(),
        }

        return result

Response: A dict of members expressed in literals


Instruction:
How would you explain what the following Python 3 function does
def _to_attrdict(self, attrs=None):
        result = self._baseattrs

        for attr in attrs:
            if hasattr(self, attr):
                result[attr] = getattr(self, attr)._to_attrdict(attrs)

        return result

Response: Convert the attribute list to a dictionary of attributes.


Instruction:
Given the following Python 3 function, write the documentation
def _update_data(self):

        func = self.owner.formula.func
        codeobj = func.__code__
        name = func.__name__  # self.cells.name   # func.__name__
        namespace_impl = self.owner._namespace_impl.get_updated()
        namespace = namespace_impl.interfaces
        selfnode = get_node(self.owner, None, None)

        for name in self.owner.formula.srcnames:
            if name in namespace_impl and isinstance(
                namespace_impl[name], ReferenceImpl
            ):
                refnode = get_node(namespace_impl[name], None, None)
                self.owner.model.lexdep.add_path([selfnode, refnode])

        closure = func.__closure__  # None normally.
        if closure is not None:  # pytest fails without this.
            closure = create_closure(self.owner.interface)

        self.altfunc = FunctionType(
            codeobj, namespace, name=name, closure=closure
        )

Response: Update altfunc with new data


Instruction:
Explain what the following Python 3 code does
def convert_args(args, kwargs):

    found = False
    for arg in args:
        if isinstance(arg, Cells):
            found = True
            break

    if found:
        args = tuple(
            arg.value if isinstance(arg, Cells) else arg for arg in args
        )

    if kwargs is not None:
        for key, arg in kwargs.items():
            if isinstance(arg, Cells):
                kwargs[key] = arg.value

    return args, kwargs

Response: If args and kwargs contains Cells convert them to their values.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def shareable_parameters(cells):
    result = []
    for c in cells.values():
        params = c.formula.parameters

        for i in range(min(len(result), len(params))):
            if params[i] != result[i]:
                return None

        for i in range(len(result), len(params)):
            result.append(params[i])

    return result

Response: Returns a list of parameters that are shareable among multiple cells.


Instruction:
How would you code a function in Python 3 to
make a copy of itself and return it.

Response:
def copy(self, space=None, name=None):
        """Make a copy of itself and return it."""
        return Cells(space=space, name=name, formula=self.formula)


Instruction:
Write a Python 3 script to
return a CellNode object for the given arguments.

Response:
def node(self, *args, **kwargs):
        """Return a :class:`CellNode` object for the given arguments."""
        return CellNode(get_node(self._impl, *convert_args(args, kwargs)))


Instruction:
Here you have a function in Python 3, explain what it does
def _baseattrs(self):

        result = super()._baseattrs
        result["params"] = ", ".join(self.parameters)
        return result

Response: A dict of members expressed in literals


Instruction:
Given the following Python 3 function, write the documentation
def value(self):
        if self.has_value:
            return self._impl[OBJ].get_value(self._impl[KEY])
        else:
            raise ValueError("Value not found")

Response: Return the value of the cells.


Instruction:
Make a summary of the following Python 3 code
def _baseattrs(self):

        result = {
            "type": type(self).__name__,
            "obj": self.cells._baseattrs,
            "args": self.args,
            "value": self.value if self.has_value else None,
            "predslen": len(self.preds),
            "succslen": len(self.succs),
            "repr_parent": self.cells._impl.repr_parent(),
            "repr": self.cells._get_repr(),
        }

        return result

Response: A dict of members expressed in literals


Instruction:
Write a Python 3 script for
reordering a list to match target by moving a sequence at a time.

Response:
def reorder_list(source, targetorder):
    """Reorder a list to match target by moving a sequence at a time.

    Written for QtAbstractItemModel.moveRows.
    """
    i = 0
    while i < len(source):

        if source[i] == targetorder[i]:
            i += 1
            continue
        else:
            i0 = i
            j0 = source.index(targetorder[i0])
            j = j0 + 1
            while j < len(source):
                if source[j] == targetorder[j - j0 + i0]:
                    j += 1
                    continue
                else:
                    break
            move_elements(source, i0, j0, j - j0)
            i += j - j0


Instruction:
Can you implement a function in Python 3 that
moves a sub sequence in a list

Response:
def move_elements(source, index_to, index_from, length):
    """Move a sub sequence in a list"""

    sublist = [source.pop(index_from) for _ in range(length)]

    for _ in range(length):
        source.insert(index_to, sublist.pop())


Instruction:
Implement a function in Python 3 to
convert column name to index.

Response:
def _get_col_index(name):
    """Convert column name to index."""

    index = string.ascii_uppercase.index
    col = 0
    for c in name.upper():
        col = col * 26 + index(c) + 1
    return col


Instruction:
How would you explain what the following Python 3 function does
def _get_range(book, range_, sheet):

    filename = None
    if isinstance(book, str):
        filename = book
        book = opxl.load_workbook(book, data_only=True)
    elif isinstance(book, opxl.Workbook):
        pass
    else:
        raise TypeError

    if _is_range_address(range_):
        sheet_names = [name.upper() for name in book.sheetnames]
        index = sheet_names.index(sheet.upper())
        data = book.worksheets[index][range_]
    else:
        data = _get_namedrange(book, range_, sheet)
        if data is None:
            raise ValueError(
                "Named range '%s' not found in %s" % (range_, filename or book)
            )

    return data

Response: Return a range as nested dict of openpyxl cells.


Instruction:
Here you have a function in Python 3, explain what it does
def read_range(filepath, range_expr, sheet=None, dict_generator=None):

    def default_generator(cells):
        for row_ind, row in enumerate(cells):
            for col_ind, cell in enumerate(row):
                yield (row_ind, col_ind), cell.value

    book = opxl.load_workbook(filepath, data_only=True)

    if _is_range_address(range_expr):
        sheet_names = [name.upper() for name in book.sheetnames]
        index = sheet_names.index(sheet.upper())
        cells = book.worksheets[index][range_expr]
    else:
        cells = _get_namedrange(book, range_expr, sheet)

    # In case of a single cell, return its value.
    if isinstance(cells, opxl.cell.Cell):
        return cells.value

    if dict_generator is None:
        dict_generator = default_generator

    gen = dict_generator(cells)
    return {keyval[0]: keyval[1] for keyval in gen}

Response: Read values from an Excel file into a nested list containing the values of the specified range.


Instruction:
Here you have a function in Python 3, explain what it does
def _get_namedrange(book, rangename, sheetname=None):

    def cond(namedef):

        if namedef.type.upper() == "RANGE":
            if namedef.name.upper() == rangename.upper():

                if sheetname is None:
                    if not namedef.localSheetId:
                        return True

                else:  # sheet local name
                    sheet_id = [sht.upper() for sht in book.sheetnames].index(
                        sheetname.upper()
                    )

                    if namedef.localSheetId == sheet_id:
                        return True

        return False

    def get_destinations(name_def):
        """Workaround for the bug in DefinedName.destinations"""

        from openpyxl.formula import Tokenizer
        from openpyxl.utils.cell import SHEETRANGE_RE

        if name_def.type == "RANGE":
            tok = Tokenizer("=" + name_def.value)
            for part in tok.items:
                if part.subtype == "RANGE":
                    m = SHEETRANGE_RE.match(part.value)
                    if m.group("quoted"):
                        sheet_name = m.group("quoted")
                    else:
                        sheet_name = m.group("notquoted")

                    yield sheet_name, m.group("cells")

    namedef = next(
        (item for item in book.defined_names.definedName if cond(item)), None
    )

    if namedef is None:
        return None

    dests = get_destinations(namedef)
    xlranges = []

    sheetnames_upper = [name.upper() for name in book.sheetnames]

    for sht, addr in dests:
        if sheetname:
            sht = sheetname
        index = sheetnames_upper.index(sht.upper())
        xlranges.append(book.worksheets[index][addr])

    if len(xlranges) == 1:
        return xlranges[0]
    else:
        return xlranges

Response: Get a named range from a workbook.


Instruction:
Can you tell what is the following Python 3 function doing
def get_mro(self, space):
        seqs = [self.get_mro(base) for base
                in self.get_bases(space)] + [list(self.get_bases(space))]
        res = []
        while True:
            non_empty = list(filter(None, seqs))

            if not non_empty:
                # Nothing left to process, we're done.
                res.insert(0, space)
                return res

            for seq in non_empty:  # Find merge candidates among seq heads.
                candidate = seq[0]
                not_head = [s for s in non_empty if candidate in s[1:]]
                if not_head:
                    # Reject the candidate.
                    candidate = None
                else:
                    break

            if not candidate:
                raise TypeError(
                    "inconsistent hierarchy, no C3 MRO is possible")

            res.append(candidate)

            for seq in non_empty:
                # Remove candidate.
                if seq[0] == candidate:
                    del seq[0]

Response: Calculate the Method Resolution Order of bases using the C3 algorithm.


Instruction:
Create a Python 3 function for
creating a new code object by altering some of the attributes of the code object.

Response:
def _alter_code(code, **attrs):
    """Create a new code object by altering some of ``code`` attributes

    Args:
        code: code objcect
        attrs: a mapping of names of code object attrs to their values
    """

    PyCode_New = ctypes.pythonapi.PyCode_New

    PyCode_New.argtypes = (
        ctypes.c_int,
        ctypes.c_int,
        ctypes.c_int,
        ctypes.c_int,
        ctypes.c_int,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.py_object,
        ctypes.c_int,
        ctypes.py_object)

    PyCode_New.restype = ctypes.py_object

    args = [
        [code.co_argcount, 'co_argcount'],
        [code.co_kwonlyargcount, 'co_kwonlyargcount'],
        [code.co_nlocals, 'co_nlocals'],
        [code.co_stacksize, 'co_stacksize'],
        [code.co_flags, 'co_flags'],
        [code.co_code, 'co_code'],
        [code.co_consts, 'co_consts'],
        [code.co_names, 'co_names'],
        [code.co_varnames, 'co_varnames'],
        [code.co_freevars, 'co_freevars'],
        [code.co_cellvars, 'co_cellvars'],
        [code.co_filename, 'co_filename'],
        [code.co_name, 'co_name'],
        [code.co_firstlineno, 'co_firstlineno'],
        [code.co_lnotab, 'co_lnotab']]

    for arg in args:
        if arg[1] in attrs:
            arg[0] = attrs[arg[1]]

    return PyCode_New(
        args[0][0],  # code.co_argcount,
        args[1][0],  # code.co_kwonlyargcount,
        args[2][0],  # code.co_nlocals,
        args[3][0],  # code.co_stacksize,
        args[4][0],  # code.co_flags,
        args[5][0],  # code.co_code,
        args[6][0],  # code.co_consts,
        args[7][0],  # code.co_names,
        args[8][0],  # code.co_varnames,
        args[9][0],  # code.co_freevars,
        args[10][0],  # code.co_cellvars,
        args[11][0],  # code.co_filename,
        args[12][0],  # code.co_name,
        args[13][0],  # code.co_firstlineno,
        args[14][0])


Instruction:
How would you implement a function in Python 3 that
returns a new function with modified local variables.

Response:
def alter_freevars(func, globals_=None, **vars):
    """Replace local variables with free variables

    Warnings:
        This function does not work.
    """

    if globals_ is None:
        globals_ = func.__globals__

    frees = tuple(vars.keys())
    oldlocs = func.__code__.co_names
    newlocs = tuple(name for name in oldlocs if name not in frees)

    code = _alter_code(func.__code__,
                       co_freevars=frees,
                       co_names=newlocs,
                       co_flags=func.__code__.co_flags | inspect.CO_NESTED)
    closure = _create_closure(*vars.values())

    return FunctionType(code, globals_, closure=closure)


Instruction:
How would you implement a function in Python 3 that
fixes the lamdaline of a source string.

Response:
def fix_lamdaline(source):
    """Remove the last redundant token from lambda expression

    lambda x: return x)
                      ^
    Return string without irrelevant tokens
    returned from inspect.getsource on lamda expr returns
    """

    # Using undocumented generate_tokens due to a tokenize.tokenize bug
    # See https://bugs.python.org/issue23297
    strio = io.StringIO(source)
    gen = tokenize.generate_tokens(strio.readline)

    tkns = []
    try:
        for t in gen:
            tkns.append(t)
    except tokenize.TokenError:
        pass

    # Find the position of 'lambda'
    lambda_pos = [(t.type, t.string) for t in tkns].index(
        (tokenize.NAME, "lambda")
    )

    # Ignore tokes before 'lambda'
    tkns = tkns[lambda_pos:]

    # Find the position of th las OP
    lastop_pos = (
        len(tkns) - 1 - [t.type for t in tkns[::-1]].index(tokenize.OP)
    )
    lastop = tkns[lastop_pos]

    # Remove OP from the line
    fiedlineno = lastop.start[0]
    fixedline = lastop.line[: lastop.start[1]] + lastop.line[lastop.end[1] :]

    tkns = tkns[:lastop_pos]

    fixedlines = ""
    last_lineno = 0
    for t in tkns:
        if last_lineno == t.start[0]:
            continue
        elif t.start[0] == fiedlineno:
            fixedlines += fixedline
            last_lineno = t.start[0]
        else:
            fixedlines += t.line
            last_lineno = t.start[0]

    return fixedlines


Instruction:
Create a Python 3 function for
finding the first FuncDef ast object in source

Response:
def find_funcdef(source):
    """Find the first FuncDef ast object in source"""

    try:
        module_node = compile(
            source, "<string>", mode="exec", flags=ast.PyCF_ONLY_AST
        )
    except SyntaxError:
        return find_funcdef(fix_lamdaline(source))

    for node in ast.walk(module_node):
        if isinstance(node, ast.FunctionDef) or isinstance(node, ast.Lambda):
            return node

    raise ValueError("function definition not found")


Instruction:
Explain what the following Python 3 code does
def extract_params(source):

    funcdef = find_funcdef(source)
    params = []
    for node in ast.walk(funcdef.args):
        if isinstance(node, ast.arg):
            if node.arg not in params:
                params.append(node.arg)

    return params

Response: Extract parameters from a function definition


Instruction:
Explain what the following Python 3 code does
def extract_names(source):
    if source is None:
        return None

    source = dedent(source)
    funcdef = find_funcdef(source)
    params = extract_params(source)
    names = []

    if isinstance(funcdef, ast.FunctionDef):
        stmts = funcdef.body
    elif isinstance(funcdef, ast.Lambda):
        stmts = [funcdef.body]
    else:
        raise ValueError("must not happen")

    for stmt in stmts:
        for node in ast.walk(stmt):
            if isinstance(node, ast.Name):
                if node.id not in names and node.id not in params:
                    names.append(node.id)

    return names

Response: Extract names from a function definition in the source.


Instruction:
Create a Python 3 function for
truing if src is a function definition

Response:
def is_funcdef(src):
    """True if src is a function definition"""

    module_node = ast.parse(dedent(src))

    if len(module_node.body) == 1 and isinstance(
            module_node.body[0], ast.FunctionDef
    ):
        return True
    else:
        return False


Instruction:
Write a Python 3 script for
removing decorators from function definition

Response:
def remove_decorator(source: str):
    """Remove decorators from function definition"""
    lines = source.splitlines()
    atok = asttokens.ASTTokens(source, parse=True)

    for node in ast.walk(atok.tree):
        if isinstance(node, ast.FunctionDef):
            break

    if node.decorator_list:
        deco_first = node.decorator_list[0]
        deco_last = node.decorator_list[-1]
        line_first = atok.tokens[deco_first.first_token.index - 1].start[0]
        line_last = atok.tokens[deco_last.last_token.index + 1].start[0]

        lines = lines[:line_first - 1] + lines[line_last:]

    return "\n".join(lines) + "\n"


Instruction:
Given the following Python 3 function, write the documentation
def replace_funcname(source: str, name: str):

    lines = source.splitlines()
    atok = asttokens.ASTTokens(source, parse=True)

    for node in ast.walk(atok.tree):
        if isinstance(node, ast.FunctionDef):
            break

    i = node.first_token.index
    for i in range(node.first_token.index, node.last_token.index):
        if (atok.tokens[i].type == token.NAME
                and atok.tokens[i].string == "def"):
            break

    lineno, col_begin = atok.tokens[i + 1].start
    lineno_end, col_end = atok.tokens[i + 1].end

    assert lineno == lineno_end

    lines[lineno-1] = (
            lines[lineno-1][:col_begin] + name + lines[lineno-1][col_end:]
    )

    return "\n".join(lines) + "\n"

Response: Replace function name in source with name


Instruction:
Create a Python 3 function for
truing if only one lambda expression is included

Response:
def has_lambda(src):
    """True if only one lambda expression is included"""

    module_node = ast.parse(dedent(src))
    lambdaexp = [node for node in ast.walk(module_node)
                 if isinstance(node, ast.Lambda)]

    return bool(lambdaexp)


Instruction:
Implement a function in Python 3 to
reload the source function from the source module.

Response:
def _reload(self, module=None):
        """Reload the source function from the source module.

        **Internal use only**
        Update the source function of the formula.
        This method is used to updated the underlying formula
        when the source code of the module in which the source function
        is read from is modified.

        If the formula was not created from a module, an error is raised.
        If ``module_`` is not given, the source module of the formula is
        reloaded. If ``module_`` is given and matches the source module,
        then the module_ is used without being reloaded.
        If ``module_`` is given and does not match the source module of
        the formula, an error is raised.

        Args:
            module_: A ``ModuleSource`` object

        Returns:
            self
        """
        if self.module is None:
            raise RuntimeError
        elif module is None:
            import importlib

            module = ModuleSource(importlib.reload(module))
        elif module.name != self.module:
            raise RuntimeError

        if self.name in module.funcs:
            func = module.funcs[self.name]
            self.__init__(func=func)
        else:
            self.__init__(func=NULL_FORMULA)

        return self


Instruction:
Can you write a function in Python 3 where it
gets long description from README. rst

Response:
def get_description():
    """Get long description from README."""
    with open(path.join(here, 'README.rst'), 'r') as f:
        data = f.read()
    return data


Instruction:
How would you code a function in Python 3 to
convert the cells in the view into a DataFrame object.

Response:
def to_frame(self, *args):
        """Convert the cells in the view into a DataFrame object.

        If ``args`` is not given, this method returns a DataFrame that
        has an Index or a MultiIndex depending of the number of
        cells parameters and columns each of which corresponds to each
        cells included in the view.

        ``args`` can be given to calculate cells values and limit the
        DataFrame indexes to the given arguments.

        The cells in this view may have different number of parameters,
        but parameters shared among multiple cells
        must appear in the same position in all the parameter lists.
        For example,
        Having ``foo()``, ``bar(x)`` and ``baz(x, y=1)`` is okay
        because the shared parameter ``x`` is always the first parameter,
        but this method does not work if the view has ``quz(x, z=2, y=1)``
        cells in addition to the first three cells, because ``y`` appears
        in different positions.

        Args:
            args(optional): multiple arguments,
               or an iterator of arguments to the cells.
        """
        if sys.version_info < (3, 6, 0):
            from collections import OrderedDict

            impls = OrderedDict()
            for name, obj in self.items():
                impls[name] = obj._impl
        else:
            impls = get_impls(self)

        return _to_frame_inner(impls, args)


Instruction:
Can you generate the documentation for the following Python 3 function
def new_cells(self, name=None, formula=None):
        # Outside formulas only
        return self._impl.new_cells(name, formula).interface

Response: Create a new cells in the space.


Instruction:
Implement a Python 3 function for
creating a cells from a module.

Response:
def import_funcs(self, module):
        """Create a cells from a module."""
        # Outside formulas only
        newcells = self._impl.new_cells_from_module(module)
        return get_interfaces(newcells)


Instruction:
Can you create a Python 3 function that
creates multiple cells from an Excel file.

Response:
def new_cells_from_excel(
        self,
        book,
        range_,
        sheet=None,
        names_row=None,
        param_cols=None,
        param_order=None,
        transpose=False,
        names_col=None,
        param_rows=None,
    ):
        """Create multiple cells from an Excel range.

        This method reads values from a range in an Excel file,
        create cells and populate them with the values in the range.
        To use this method, ``openpyxl`` package must be installed.

        The Excel file to read data from is specified by ``book``
        parameters. The ``range_`` can be a range address, such as "$G4:$K10",
        or a named range. In case a range address is given,
        ``sheet`` must also be given.

        By default, cells data are interpreted as being laid out side-by-side.
        ``names_row`` is a row index (starting from 0) to specify the
        row that contains the names of cells and parameters.
        Cells and parameter names must be contained in a single row.
        ``param_cols`` accepts a sequence (such as list or tuple) of
        column indexes (starting from 0) that indicate columns that
        contain cells arguments.

        **2-dimensional cells definitions**

        The optional ``names_col`` and ``param_rows`` parameters are used,
        when data for one cells spans more than one column.
        In such cases, the cells data is 2-dimensional, and
        there must be parameter row(s) across the columns
        that contain arguments of the parameters.
        A sequence of row indexes that indicate parameter rows
        is passed to ``param_rows``.
        The names of those parameters must be contained in the
        same rows as parameter values (arguments), and
        ``names_col`` is to indicate the column position at which
        the parameter names are defined.

        **Horizontal arrangement**

        By default, cells data are interpreted as being placed
        side-by-side, regardless of whether one cells corresponds
        to a single column or multiple columns.
        ``transpose`` parameter is used to alter this orientation,
        and if it is set to ``True``, cells values are
        interpreted as being placed one above the other.
        "row(s)" and "col(s)" in the parameter
        names are interpreted inversely, i.e.
        all indexes passed to "row(s)" parameters are interpreted
        as column indexes,
        and all indexes passed to "col(s)" parameters as row indexes.

        Args:
            book (str): Path to an Excel file.
            range_ (str): Range expression, such as "A1", "$G4:$K10",
                or named range "NamedRange1".
            sheet (str): Sheet name (case ignored).
            names_row (optional): an index number indicating
                what row contains the names of cells and parameters.
                Defaults to the top row (0).
            param_cols (optional): a sequence of index numbers
                indicating parameter columns.
                Defaults to only the leftmost column ([0]).
            names_col (optional): an index number, starting from 0,
                indicating what column contains additional parameters.
            param_rows (optional): a sequence of index numbers, starting from
                0, indicating rows of additional parameters, in case cells are
                defined in two dimensions.
            transpose (optional): Defaults to ``False``.
                If set to ``True``, "row(s)" and "col(s)" in the parameter
                names are interpreted inversely, i.e.
                all indexes passed to "row(s)" parameters are interpreted
                as column indexes,
                and all indexes passed to "col(s)" parameters as row indexes.
            param_order (optional): a sequence to reorder the parameters.
                The elements of the sequence are the indexes of ``param_cols``
                elements, and optionally the index of ``param_rows`` elements
                shifted by the length of ``param_cols``.
        """
        return self._impl.new_cells_from_excel(
            book,
            range_,
            sheet,
            names_row,
            param_cols,
            param_order,
            transpose,
            names_col,
            param_rows,
        )


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_object(self, name):

        parts = name.split(".")
        child = parts.pop(0)

        if parts:
            return self.spaces[child].get_object(".".join(parts))
        else:
            return self._namespace_impl[child]

Response: Retrieve an object by a dotted name relative to the space.


Instruction:
Here you have a function in Python 3, explain what it does
def _get_dynamic_base(self, bases_):
        bases = tuple(
            base.bases[0] if base.is_dynamic() else base for base in bases_
        )

        if len(bases) == 1:
            return bases[0]

        elif len(bases) > 1:
            return self.model.get_dynamic_base(bases)

        else:
            RuntimeError("must not happen")

Response: Create or get the base space from a list of spaces


Instruction:
How would you code a function in Python 3 to
create a new dynamic root space.

Response:
def _new_dynspace(
        self,
        name=None,
        bases=None,
        formula=None,
        refs=None,
        arguments=None,
        source=None,
    ):
        """Create a new dynamic root space."""

        if name is None:
            name = self.spacenamer.get_next(self.namespace)

        if name in self.namespace:
            raise ValueError("Name '%s' already exists." % name)

        if not is_valid_name(name):
            raise ValueError("Invalid name '%s'." % name)

        space = RootDynamicSpaceImpl(
            parent=self,
            name=name,
            formula=formula,
            refs=refs,
            source=source,
            arguments=arguments,
        )
        space.is_derived = False
        self._set_space(space)

        if bases:  # i.e. not []
            dynbase = self._get_dynamic_base(bases)
            space._dynbase = dynbase
            dynbase._dynamic_subs.append(space)

        return space


Instruction:
Can you tell what is the following Python 3 function doing
def get_dynspace(self, args, kwargs=None):

        node = get_node(self, *convert_args(args, kwargs))
        key = node[KEY]

        if key in self.param_spaces:
            return self.param_spaces[key]

        else:
            last_self = self.system.self
            self.system.self = self

            try:
                space_args = self.eval_formula(node)

            finally:
                self.system.self = last_self

            if space_args is None:
                space_args = {"bases": [self]}  # Default
            else:
                if "bases" in space_args:
                    bases = get_impls(space_args["bases"])
                    if isinstance(bases, StaticSpaceImpl):
                        space_args["bases"] = [bases]
                    elif bases is None:
                        space_args["bases"] = [self]  # Default
                    else:
                        space_args["bases"] = bases
                else:
                    space_args["bases"] = [self]

            space_args["arguments"] = node_get_args(node)
            space = self._new_dynspace(**space_args)
            self.param_spaces[key] = space
            space.inherit(clear_value=False)
            return space

Response: Create a dynamic root space with the given arguments.


Instruction:
How would you implement a function in Python 3 that
calls after unpickling to restore some attributes manually.

Response:
def restore_state(self, system):
        """Called after unpickling to restore some attributes manually."""
        super().restore_state(system)
        BaseSpaceContainerImpl.restore_state(self, system)

        for cells in self._cells.values():
            cells.restore_state(system)


Instruction:
How would you explain what the following Python 3 function does
def new_cells_from_excel(
        self,
        book,
        range_,
        sheet=None,
        names_row=None,
        param_cols=None,
        param_order=None,
        transpose=False,
        names_col=None,
        param_rows=None,
    ):
        """Create multiple cells from an Excel range.

        Args:
            book (str): Path to an Excel file.
            range_ (str): Range expression, such as "A1", "$G4:$K10",
                or named range "NamedRange1".
            sheet (str): Sheet name (case ignored).
            names_row: Cells names in a sequence, or an integer number, or
              a string expression indicating row (or column depending on
              ```orientation```) to read cells names from.
            param_cols: a sequence of them
                indicating parameter columns (or rows depending on ```
                orientation```)
            param_order: a sequence of integers representing
                the order of params and extra_params.
            transpose: in which direction 'vertical' or 'horizontal'
            names_col: a string or a list of names of the extra params.
            param_rows: integer or string expression, or a sequence of them
                indicating row (or column) to be interpreted as parameters.
        """
        import modelx.io.excel as xl

        cellstable = xl.CellsTable(
            book,
            range_,
            sheet,
            names_row,
            param_cols,
            param_order,
            transpose,
            names_col,
            param_rows,
        )

        if cellstable.param_names:
            sig = "=None, ".join(cellstable.param_names) + "=None"
        else:
            sig = ""

        blank_func = "def _blank_func(" + sig + "): pass"

        for cellsdata in cellstable.items():
            cells = self.new_cells(name=cellsdata.name, formula=blank_func)
            for args, value in cellsdata.items():
                cells.set_value(args, value)

Response: Create multiple cells from an Excel file.


Instruction:
Can you tell what is the following Python 3 function doing
def set_attr(self, name, value):
        if not is_valid_name(name):
            raise ValueError("Invalid name '%s'" % name)

        if name in self.namespace:
            if name in self.refs:
                if name in self.self_refs:
                    self.new_ref(name, value)
                else:
                    raise KeyError("Ref '%s' cannot be changed" % name)

            elif name in self.cells:
                if self.cells[name].is_scalar():
                    self.cells[name].set_value((), value)
                else:
                    raise AttributeError("Cells '%s' is not a scalar." % name)
            else:
                raise ValueError
        else:
            self.new_ref(name, value)

Response: Implementation of attribute setting by user script


Instruction:
Here you have a function in Python 3, explain what it does
def del_attr(self, name):
        if name in self.namespace:
            if name in self.cells:
                self.del_cells(name)
            elif name in self.spaces:
                self.del_space(name)
            elif name in self.refs:
                self.del_ref(name)
            else:
                raise RuntimeError("Must not happen")
        else:
            raise KeyError("'%s' not found in Space '%s'" % (name, self.name))

Response:
Implementation of attribute deletion by user script
        Called by user script
       . name by user script
       .


Instruction:
Can you generate a brief explanation for the following Python 3 code
def del_cells(self, name):
        if name in self.cells:
            cells = self.cells[name]
            self.cells.del_item(name)
            self.inherit()
            self.model.spacegraph.update_subspaces(self)

        elif name in self.dynamic_spaces:
            cells = self.dynamic_spaces.pop(name)
            self.dynamic_spaces.set_update()

        else:
            raise KeyError("Cells '%s' does not exist" % name)

        NullImpl(cells)

Response: Implementation of cells deletion


Instruction:
Can you generate a brief explanation for the following Python 3 code
def cellsiter_to_dataframe(cellsiter, args, drop_allna=True):
    from modelx.core.cells import shareable_parameters

    if len(args):
        indexes = shareable_parameters(cellsiter)
    else:
        indexes = get_all_params(cellsiter.values())

    result = None

    for cells in cellsiter.values():
        df = cells_to_dataframe(cells, args)

        if drop_allna and df.isnull().all().all():
            continue  #  Ignore all NA or empty

        if df.index.names != [None]:
            if isinstance(df.index, pd.MultiIndex):
                if _pd_ver < (0, 20):
                    df = _reset_naindex(df)

            df = df.reset_index()

        missing_params = set(indexes) - set(df)

        for params in missing_params:
            df[params] = np.nan

        if result is None:
            result = df
        else:
            try:
                result = pd.merge(result, df, how="outer")
            except MergeError:
                # When no common column exists, i.e. all cells are scalars.
                result = pd.concat([result, df], axis=1)
            except ValueError:
                # When common columns are not coercible (numeric vs object),
                # Make the numeric column object type
                cols = set(result.columns) & set(df.columns)
                for col in cols:

                    # When only either of them has object dtype
                    if (
                        len(
                            [
                                str(frame[col].dtype)
                                for frame in (result, df)
                                if str(frame[col].dtype) == "object"
                            ]
                        )
                        == 1
                    ):

                        if str(result[col].dtype) == "object":
                            frame = df
                        else:
                            frame = result
                        frame[[col]] = frame[col].astype("object")

                # Try again
                result = pd.merge(result, df, how="outer")

    if result is None:
        return pd.DataFrame()
    else:
        return result.set_index(indexes) if indexes else result

Response: Convert multiple cells to a DataFrame.


Instruction:
Can you write a function in Python 3 where it
converts a CellImpl into a Series.

Response:
def cells_to_series(cells, args):
    """Convert a CellImpl into a Series.

    `args` must be a sequence of argkeys.

    `args` can be longer or shorter then the number of cell's parameters.
    If shorter, then defaults are filled if any, else raise error.
    If longer, then redundant args are ignored.
    """

    paramlen = len(cells.formula.parameters)
    is_multidx = paramlen > 1

    if len(cells.data) == 0:
        data = {}
        indexes = None

    elif paramlen == 0:  # Const Cells
        data = list(cells.data.values())
        indexes = [np.nan]

    else:

        if len(args) > 0:
            defaults = tuple(
                param.default
                for param in cells.formula.signature.parameters.values()
            )
            updated_args = []
            for arg in args:

                if len(arg) > paramlen:
                    arg = arg[:paramlen]
                elif len(arg) < paramlen:
                    arg += defaults[len(arg) :]

                updated_args.append(arg)

            items = [
                (arg, cells.data[arg])
                for arg in updated_args
                if arg in cells.data
            ]
        else:
            items = [(key, value) for key, value in cells.data.items()]

        if not is_multidx:  # Peel 1-element tuple
            items = [(key[0], value) for key, value in items]

        if len(items) == 0:
            indexes, data = None, {}
        else:
            indexes, data = zip(*items)
            if is_multidx:
                indexes = pd.MultiIndex.from_tuples(indexes)

    result = pd.Series(data=data, name=cells.name, index=indexes)

    if indexes is not None and any(i is not np.nan for i in indexes):
        result.index.names = list(cells.formula.parameters)

    return result


Instruction:
Write a Python 3 script to
remove all descendants of source.

Response:
def clear_descendants(self, source, clear_source=True):
        """Remove all descendants of(reachable from) `source`.

        Args:
            source: Node descendants
            clear_source(bool): Remove origin too if True.
        Returns:
            set: The removed nodes.
        """
        desc = nx.descendants(self, source)
        if clear_source:
            desc.add(source)
        self.remove_nodes_from(desc)
        return desc


Instruction:
Write a Python 3 function for
removing all nodes with obj and their descendants.

Response:
def clear_obj(self, obj):
        """"Remove all nodes with `obj` and their descendants."""
        obj_nodes = self.get_nodes_with(obj)
        removed = set()
        for node in obj_nodes:
            if self.has_node(node):
                removed.update(self.clear_descendants(node))
        return removed


Instruction:
Can you write a function in Python 3 where it
returns nodes with obj.

Response:
def get_nodes_with(self, obj):
        """Return nodes with `obj`."""
        result = set()

        if nx.__version__[0] == "1":
            nodes = self.nodes_iter()
        else:
            nodes = self.nodes

        for node in nodes:
            if node[OBJ] == obj:
                result.add(node)
        return result


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_path(self, nodes, **attr):
        if nx.__version__[0] == "1":
            return super().add_path(nodes, **attr)
        else:
            return nx.add_path(self, nodes, **attr)

Response: In replacement for deprecated add_path method


Instruction:
Create a Python 3 function for
renaming the model itself

Response:
def rename(self, name):
        """Rename the model itself"""
        self._impl.system.rename_model(new_name=name, old_name=self.name)


Instruction:
How would you code a function in Python 3 to
rename the current object.

Response:
def rename(self, name):
        """Rename self. Must be called only by its system."""
        if is_valid_name(name):
            if name not in self.system.models:
                self.name = name
                return True  # Rename success
            else:  # Model name already exists
                return False
        else:
            raise ValueError("Invalid name '%s'." % name)


Instruction:
How would you implement a function in Python 3 that
clears values and nodes calculated from source.

Response:
def clear_descendants(self, source, clear_source=True):
        """Clear values and nodes calculated from `source`."""
        removed = self.cellgraph.clear_descendants(source, clear_source)
        for node in removed:
            del node[OBJ].data[node[KEY]]


Instruction:
Here you have a function in Python 3, explain what it does
def clear_obj(self, obj):
        removed = self.cellgraph.clear_obj(obj)
        for node in removed:
            del node[OBJ].data[node[KEY]]

Response: Clear values and nodes of obj and their dependants.


Instruction:
Can you tell what is the following Python 3 function doing
def get_object(self, name):
        parts = name.split(".")
        space = self.spaces[parts.pop(0)]
        if parts:
            return space.get_object(".".join(parts))
        else:
            return space

Response: Retrieve an object by a dotted name relative to the model.


Instruction:
Implement a Python 3 function for
calling after unpickling to restore some attributes manually.

Response:
def restore_state(self, system):
        """Called after unpickling to restore some attributes manually."""
        Impl.restore_state(self, system)
        BaseSpaceContainerImpl.restore_state(self, system)
        mapping = {}
        for node in self.cellgraph:
            if isinstance(node, tuple):
                name, key = node
            else:
                name, key = node, None
            cells = self.get_object(name)
            mapping[node] = get_node(cells, key, None)

        self.cellgraph = nx.relabel_nodes(self.cellgraph, mapping)


Instruction:
How would you implement a function in Python 3 that
creates of get a base space for a tuple of bases

Response:
def get_dynamic_base(self, bases: tuple):
        """Create of get a base space for a tuple of bases"""

        try:
            return self._dynamic_bases_inverse[bases]
        except KeyError:
            name = self._dynamic_base_namer.get_next(self._dynamic_bases)
            base = self._new_space(name=name)
            self.spacegraph.add_space(base)
            self._dynamic_bases[name] = base
            self._dynamic_bases_inverse[bases] = base
            base.add_bases(bases)
            return base


Instruction:
Can you generate the documentation for the following Python 3 function
def check_mro(self, bases):

        try:
            self.add_node("temp")
            for base in bases:
                nx.DiGraph.add_edge(self, base, "temp")
            result = self.get_mro("temp")[1:]

        finally:
            self.remove_node("temp")

        return result

Response: Check if C3 MRO is possible with given bases


Instruction:
Create a Python 3 function to
return a list of command names supported by the current user.

Response:
def get_command_names():
    """
    Returns a list of command names supported
    """
    ret = []
    for f in os.listdir(COMMAND_MODULE_PATH):
        if os.path.isfile(os.path.join(COMMAND_MODULE_PATH, f)) and f.endswith(COMMAND_MODULE_SUFFIX):
            ret.append(f[:-len(COMMAND_MODULE_SUFFIX)])
    return ret


Instruction:
Can you create a Python 3 function that
returns a dictionary value for the specified key.

Response:
def get(vals, key, default_val=None):
    """
    Returns a dictionary value
    """
    val = vals
    for part in key.split('.'):
        if isinstance(val, dict):
            val = val.get(part, None)
            if val is None:
                return default_val
        else:
            return default_val
    return val


Instruction:
Given the following Python 3 function, write the documentation
def parse_option_settings(option_settings):
    ret = []
    for namespace, params in list(option_settings.items()):
        for key, value in list(params.items()):
            ret.append((namespace, key, value))
    return ret

Response: Parses option_settings as they are defined in the configuration file.


Instruction:
Implement a Python 3 function for
parsing an environment config into a single dict.

Response:
def parse_env_config(config, env_name):
    """
    Parses an environment config
    """
    all_env = get(config, 'app.all_environments', {})
    env = get(config, 'app.environments.' + str(env_name), {})
    return merge_dict(all_env, env)


Instruction:
Can you tell what is the following Python 3 function doing
def create_archive(directory, filename, config={}, ignore_predicate=None, ignored_files=['.git', '.svn']):
    with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as zip_file:
        root_len = len(os.path.abspath(directory))

        # create it
        out("Creating archive: " + str(filename))
        for root, dirs, files in os.walk(directory, followlinks=True):
            archive_root = os.path.abspath(root)[root_len + 1:]
            for f in files:
                fullpath = os.path.join(root, f)
                archive_name = os.path.join(archive_root, f)

                # ignore the file we're creating
                if filename in fullpath:
                    continue

                # ignored files
                if ignored_files is not None:
                    for name in ignored_files:
                        if fullpath.endswith(name):
                            out("Skipping: " + str(name))
                            continue

                # do predicate
                if ignore_predicate is not None:
                    if not ignore_predicate(archive_name):
                        out("Skipping: " + str(archive_name))
                        continue

                out("Adding: " + str(archive_name))
                zip_file.write(fullpath, archive_name, zipfile.ZIP_DEFLATED)

    return filename

Response: Creates an archive from a directory and returns the filename that was created.


Instruction:
Explain what the following Python 3 code does
def add_config_files_to_archive(directory, filename, config={}):
    with zipfile.ZipFile(filename, 'a') as zip_file:
        for conf in config:
            for conf, tree in list(conf.items()):
                if 'yaml' in tree:
                    content = yaml.dump(tree['yaml'], default_flow_style=False)
                else:
                    content = tree.get('content', '')
                out("Adding file " + str(conf) + " to archive " + str(filename))
                file_entry = zipfile.ZipInfo(conf)
                file_entry.external_attr = tree.get('permissions', 0o644) << 16
                zip_file.writestr(file_entry, content)

    return filename

Response: Adds configuration files to an existing archive


Instruction:
Make a summary of the following Python 3 code
def swap_environment_cnames(self, from_env_name, to_env_name):
        self.ebs.swap_environment_cnames(source_environment_name=from_env_name,
                                         destination_environment_name=to_env_name)

Response: Swaps the environment names of a specific environment.


Instruction:
Explain what the following Python 3 code does
def upload_archive(self, filename, key, auto_create_bucket=True):
        try:
            bucket = self.s3.get_bucket(self.aws.bucket)
            if ((
                  self.aws.region != 'us-east-1' and self.aws.region != 'eu-west-1') and bucket.get_location() != self.aws.region) or (
                  self.aws.region == 'us-east-1' and bucket.get_location() != '') or (
                  self.aws.region == 'eu-west-1' and bucket.get_location() != 'eu-west-1'):
                raise Exception("Existing bucket doesn't match region")
        except S3ResponseError:
            bucket = self.s3.create_bucket(self.aws.bucket, location=self.aws.region)

        def __report_upload_progress(sent, total):
            if not sent:
                sent = 0
            if not total:
                total = 0
            out("Uploaded " + str(sent) + " bytes of " + str(total) \
                + " (" + str(int(float(max(1, sent)) / float(total) * 100)) + "%)")

        # upload the new version
        k = Key(bucket)
        k.key = self.aws.bucket_path + key
        k.set_metadata('time', str(time()))
        k.set_contents_from_filename(filename, cb=__report_upload_progress, num_cb=10)

Response: Uploads an application archive version to s3


Instruction:
Explain what the following Python 3 code does
def create_application(self, description=None):
        out("Creating application " + str(self.app_name))
        self.ebs.create_application(self.app_name, description=description)

Response:
Creates an application and sets the helpers current
        app_name to the application created by this application.


Instruction:
Can you generate the documentation for the following Python 3 function
def delete_application(self):
        out("Deleting application " + str(self.app_name))
        self.ebs.delete_application(self.app_name, terminate_env_by_force=True)

Response: Delete the application from the ebs


Instruction:
Can you write a function in Python 3 where it
returns whether or not the given app_name exists.

Response:
def application_exists(self):
        """
        Returns whether or not the given app_name exists
        """
        response = self.ebs.describe_applications(application_names=[self.app_name])
        return len(response['DescribeApplicationsResponse']['DescribeApplicationsResult']['Applications']) > 0


Instruction:
Write a Python 3 function that can
create a new environment in the cluster.

Response:
def create_environment(self, env_name, version_label=None,
                           solution_stack_name=None, cname_prefix=None, description=None,
                           option_settings=None, tier_name='WebServer', tier_type='Standard', tier_version='1.1'):
        """
        Creates a new environment
        """
        out("Creating environment: " + str(env_name) + ", tier_name:" + str(tier_name) + ", tier_type:" + str(tier_type))
        self.ebs.create_environment(self.app_name, env_name,
                                    version_label=version_label,
                                    solution_stack_name=solution_stack_name,
                                    cname_prefix=cname_prefix,
                                    description=description,
                                    option_settings=option_settings,
                                    tier_type=tier_type,
                                    tier_name=tier_name,
                                    tier_version=tier_version)


Instruction:
How would you explain what the following Python 3 function does
def environment_exists(self, env_name):
        response = self.ebs.describe_environments(application_name=self.app_name, environment_names=[env_name],
                                                  include_deleted=False)
        return len(response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']) > 0 \
               and response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments'][0][
                       'Status'] != 'Terminated'

Response: Returns whether or not the given environment exists


Instruction:
How would you explain what the following Python 3 function does
def get_environments(self):
        response = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False)
        return response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']

Response: Returns the list of environments in the current environment


Instruction:
Create a Python 3 function to
update an application version of an environment.

Response:
def update_environment(self, environment_name, description=None, option_settings=[], tier_type=None, tier_name=None,
                           tier_version='1.0'):
        """
        Updates an application version
        """
        out("Updating environment: " + str(environment_name))
        messages = self.ebs.validate_configuration_settings(self.app_name, option_settings,
                                                            environment_name=environment_name)
        messages = messages['ValidateConfigurationSettingsResponse']['ValidateConfigurationSettingsResult']['Messages']
        ok = True
        for message in messages:
            if message['Severity'] == 'error':
                ok = False
            out("[" + message['Severity'] + "] " + str(environment_name) + " - '" \
                + message['Namespace'] + ":" + message['OptionName'] + "': " + message['Message'])
        self.ebs.update_environment(
            environment_name=environment_name,
            description=description,
            option_settings=option_settings,
            tier_type=tier_type,
            tier_name=tier_name,
            tier_version=tier_version)


Instruction:
Can you create a Python 3 function that
returns an environment name for the given cname

Response:
def environment_name_for_cname(self, env_cname):
        """
        Returns an environment name for the given cname
        """
        envs = self.get_environments()
        for env in envs:
            if env['Status'] != 'Terminated' \
                and 'CNAME' in env \
                and env['CNAME'] \
                and env['CNAME'].lower().startswith(env_cname.lower() + '.'):
                return env['EnvironmentName']
        return None


Instruction:
Can you create a Python 3 function that
deploys a version to an environment

Response:
def deploy_version(self, environment_name, version_label):
        """
        Deploys a version to an environment
        """
        out("Deploying " + str(version_label) + " to " + str(environment_name))
        self.ebs.update_environment(environment_name=environment_name, version_label=version_label)


Instruction:
Make a summary of the following Python 3 code
def get_versions(self):
        response = self.ebs.describe_application_versions(application_name=self.app_name)
        return response['DescribeApplicationVersionsResponse']['DescribeApplicationVersionsResult']['ApplicationVersions']

Response: Returns the available versions of the application


Instruction:
Here you have a function in Python 3, explain what it does
def create_application_version(self, version_label, key):
        out("Creating application version " + str(version_label) + " for " + str(key))
        self.ebs.create_application_version(self.app_name, version_label,
                                            s3_bucket=self.aws.bucket, s3_key=self.aws.bucket_path+key)

Response: Creates an application version


Instruction:
Make a summary of the following Python 3 code
def delete_unused_versions(self, versions_to_keep=10):

        # get versions in use
        environments = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False)
        environments = environments['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']
        versions_in_use = []
        for env in environments:
            versions_in_use.append(env['VersionLabel'])

        # get all versions
        versions = self.ebs.describe_application_versions(application_name=self.app_name)
        versions = versions['DescribeApplicationVersionsResponse']['DescribeApplicationVersionsResult'][
            'ApplicationVersions']
        versions = sorted(versions, reverse=True, key=functools.cmp_to_key(lambda x, y: (x['DateCreated'] > y['DateCreated']) - (x['DateCreated'] < y['DateCreated'])))

        # delete versions in use
        for version in versions[versions_to_keep:]:
            if version['VersionLabel'] in versions_in_use:
                out("Not deleting " + version["VersionLabel"] + " because it is in use")
            else:
                out("Deleting unused version: " + version["VersionLabel"])
                self.ebs.delete_application_version(application_name=self.app_name,
                                                    version_label=version['VersionLabel'])
                sleep(2)

Response: Deletes unused versions in the specified list of versions_to_keep.


Instruction:
Create a Python 3 function for
describing the events from the given environment.

Response:
def describe_events(self, environment_name, next_token=None, start_time=None):
        """
        Describes events from the given environment
        """
        events = self.ebs.describe_events(
            application_name=self.app_name,
            environment_name=environment_name,
            next_token=next_token,
            start_time=start_time + 'Z')

        return (events['DescribeEventsResponse']['DescribeEventsResult']['Events'], events['DescribeEventsResponse']['DescribeEventsResult']['NextToken'])


Instruction:
How would you code a function in Python 3 to
wait for an environment to have the given version_label and to be in the green state.

Response:
def wait_for_environments(self, environment_names, health=None, status=None, version_label=None,
                              include_deleted=True, use_events=True):
        """
        Waits for an environment to have the given version_label
        and to be in the green state
        """

        # turn into a list
        if not isinstance(environment_names, (list, tuple)):
            environment_names = [environment_names]
        environment_names = environment_names[:]

        # print some stuff
        s = "Waiting for environment(s) " + (", ".join(environment_names)) + " to"
        if health is not None:
            s += " have health " + health
        else:
            s += " have any health"
        if version_label is not None:
            s += " and have version " + version_label
        if status is not None:
            s += " and have status " + status
        out(s)

        started = time()
        seen_events = list()

        for env_name in environment_names:
            (events, next_token) = self.describe_events(env_name, start_time=datetime.now().isoformat())
            for event in events:
                seen_events.append(event)

        while True:
            # bail if they're all good
            if len(environment_names) == 0:
                break

            # wait
            sleep(10)

            # # get the env
            environments = self.ebs.describe_environments(
                application_name=self.app_name,
                environment_names=environment_names,
                include_deleted=include_deleted)

            environments = environments['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']
            if len(environments) <= 0:
                raise Exception("Couldn't find any environments")

            # loop through and wait
            for env in environments[:]:
                env_name = env['EnvironmentName']

                # the message
                msg = "Environment " + env_name + " is " + str(env['Health'])
                if version_label is not None:
                    msg = msg + " and has version " + str(env['VersionLabel'])
                if status is not None:
                    msg = msg + " and has status " + str(env['Status'])

                # what we're doing
                good_to_go = True
                if health is not None:
                    good_to_go = good_to_go and str(env['Health']) == health
                if status is not None:
                    good_to_go = good_to_go and str(env['Status']) == status
                if version_label is not None:
                    good_to_go = good_to_go and str(env['VersionLabel']) == version_label

                # allow a certain number of Red samples before failing
                if env['Status'] == 'Ready' and env['Health'] == 'Red':
                    if 'RedCount' not in env:
                        env['RedCount'] = 0

                    env['RedCount'] += 1
                    if env['RedCount'] > MAX_RED_SAMPLES:
                        out('Deploy failed')
                        raise Exception('Ready and red')

                # log it
                if good_to_go:
                    out(msg + " ... done")
                    environment_names.remove(env_name)
                else:
                    out(msg + " ... waiting")

                # log events
                (events, next_token) = self.describe_events(env_name, start_time=datetime.now().isoformat())
                for event in events:
                    if event not in seen_events:
                        out("["+event['Severity']+"] "+event['Message'])
                        seen_events.append(event)

            # check the time
            elapsed = time() - started
            if elapsed > self.wait_time_secs:
                message = "Wait time for environment(s) {environments} to be {health} expired".format(
                    environments=" and ".join(environment_names), health=(health or "Green")
                )
                raise Exception(message)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_arguments(parser):
    parser.add_argument('-o', '--old-environment', help='Old environment name', required=True)
    parser.add_argument('-n', '--new-environment', help='New environment name', required=True)

Response: Adds arguments for the swap urls command


Instruction:
Write a Python 3 script to
swap old and new URLs.

Response:
def execute(helper, config, args):
    """
    Swaps old and new URLs.
    If old_environment was active, new_environment will become the active environment
    """
    old_env_name = args.old_environment
    new_env_name = args.new_environment

    # swap C-Names
    out("Assuming that {} is the currently active environment...".format(old_env_name))
    out("Swapping environment cnames: {} will become active, {} will become inactive.".format(new_env_name,
                                                                                old_env_name))
    helper.swap_environment_cnames(old_env_name, new_env_name)
    helper.wait_for_environments([old_env_name, new_env_name], status='Ready', include_deleted=False)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def execute(helper, config, args):
    env = parse_env_config(config, args.environment)
    option_settings = env.get('option_settings', {})
    settings = parse_option_settings(option_settings)
    for setting in settings:
        out(str(setting))

Response: dump command dumps things


Instruction:
Given the following Python 3 function, write the documentation
def cached_property(f):
    @property
    @functools.wraps(f)
    def wrapped(self, name=f.__name__):
        try:
            cache = self.__cache__
        except AttributeError:
            self.__cache__ = cache = {}
        try:
            return cache[name]
        except KeyError:
            cache[name] = rv = f(self)
            return rv
    return wrapped

Response: A property decorator that caches the result of a function.


Instruction:
How would you implement a function in Python 3 that
prints the current state of the current application.

Response:
def execute(helper, config, args):
    """
    Lists environments
    """
    envs = config.get('app', {}).get('environments', [])
    out("Parsed environments:")
    for name, conf in list(envs.items()):
        out('\t'+name)
    envs = helper.get_environments()
    out("Deployed environments:")
    for env in envs:
        if env['Status'] != 'Terminated':
            out('\t'+str(env['EnvironmentName'])+' ('+str(env['Status'])+', '+str(env['CNAME'])+')')


Instruction:
Write a Python 3 function that can
delete an application and wait for all environments to terminate

Response:
def execute(helper, config, args):
    """
    Deletes an environment
    """
    helper.delete_application()

    # wait
    if not args.dont_wait:

        # get environments
        environment_names = []
        for env in helper.get_environments():
            environment_names.append(env['EnvironmentName'])

        # wait for them
        helper.wait_for_environments(environment_names, status='Terminated')
    return 0


Instruction:
Here you have a function in Python 3, explain what it does
def execute(helper, config, args):

    env_config = parse_env_config(config, args.environment)
    environments_to_wait_for_term = []
    environments = helper.get_environments()

    for env in environments:
        if env['EnvironmentName'] == args.environment:
            if env['Status'] != 'Ready':
                out("Unable to delete " + env['EnvironmentName']
                    + " because it's not in status Ready ("
                    + env['Status'] + ")")
            else:
                out("Deleting environment: "+env['EnvironmentName'])
                helper.delete_environment(env['EnvironmentName'])
                environments_to_wait_for_term.append(env['EnvironmentName'])

    if not args.dont_wait:
        helper.wait_for_environments(environments_to_wait_for_term,
                                     status='Terminated',
                                     include_deleted=True)

    out("Environment deleted")
    return 0

Response: Deletes an environment and waits for the termination of the environment


Instruction:
Can you generate a brief explanation for the following Python 3 code
def execute(helper, config, args):
    version_label = args.version_label
    env_config = parse_env_config(config, args.environment)
    env_name = args.environment

    # upload or build an archive
    version_label = upload_application_archive(
        helper, env_config, archive=args.archive,
        directory=args.directory, version_label=version_label)

    import datetime
    start_time = datetime.datetime.utcnow().isoformat() + 'Z'
    # deploy it
    helper.deploy_version(env_name, version_label)

    # wait
    if not args.dont_wait:
        helper.wait_for_environments(env_name, status='Ready',
                                     version_label=version_label,
                                     include_deleted=False)

    # update it
    env = parse_env_config(config, env_name)
    option_settings = parse_option_settings(env.get('option_settings', {}))
    helper.update_environment(env_name,
                              description=env.get('description', None),
                              option_settings=option_settings,
                              tier_type=env.get('tier_type'),
                              tier_name=env.get('tier_name'),
                              tier_version=env.get('tier_version'))

    # wait
    if not args.dont_wait:
        helper.wait_for_environments(env_name, health='Green',
                                     status='Ready', version_label=version_label,
                                     include_deleted=False)

    events = helper.ebs.describe_events(start_time=start_time, environment_name=env_name)
    import json
    if args.log_events_to_file:
        with open('ebs_events.json', 'w+') as f:
            json.dump(events, f)

    # delete unused
    helper.delete_unused_versions(versions_to_keep=int(get(config, 'app.versions_to_keep', 10)))

Response: Deploy or upload an application to an environment


Instruction:
Write a Python 3 script to
add the arguments for the deploy command

Response:
def add_arguments(parser):
    """
    adds arguments for the deploy command
    """
    parser.add_argument('-e', '--environment',      help='Environment name', required=True)
    parser.add_argument('-w', '--dont-wait',        help='Skip waiting for the init to finish', action='store_true')
    parser.add_argument('-l', '--version-label',    help='Version label', required=False)


Instruction:
Write a Python 3 function for
deploying to an environment

Response:
def execute(helper, config, args):
    """
    Deploys to an environment
    """
    env_config = parse_env_config(config, args.environment)
    cname_prefix = env_config.get('cname_prefix', None)
    env_name = args.environment

    # change version
    if args.version_label:
        helper.deploy_version(env_name, args.version_label)
        if not args.dont_wait:
            helper.wait_for_environments(env_name, status='Ready', version_label=args.version_label)

    # update it
    env = parse_env_config(config, env_name)
    option_settings = parse_option_settings(env.get('option_settings', {}))
    helper.update_environment(env_name,
        description=env.get('description', None),
        option_settings=option_settings,
        tier_type=env.get('tier_type'),
        tier_name=env.get('tier_name'),
        tier_version=env.get('tier_version'))

    # wait
    if not args.dont_wait:
        helper.wait_for_environments(env_name, health='Green', status='Ready', version_label=args.version_label)

    # delete unused
    helper.delete_unused_versions(versions_to_keep=int( get(config, 'app.versions_to_keep', 10) ))