Instruction:
How would you explain what the following Python 3 function does
def line_plot(data, atts=None, percent=100.0, seed=1, title=None, outfile=None, wait=True):
    if not plot.matplotlib_available:
        logger.error("Matplotlib is not installed, plotting unavailable!")
        return

    # create subsample
    data = plot.create_subsample(data, percent=percent, seed=seed)

    fig = plt.figure()

    if atts is None:
        x = []
        for i in range(data.num_attributes):
            x.append(i)
    else:
        x = atts

    ax = fig.add_subplot(111)
    ax.set_xlabel("attributes")
    ax.set_ylabel("value")
    ax.grid(True)
    for index_y in range(data.num_instances):
        y = []
        for index_x in x:
            y.append(data.get_instance(index_y).get_value(index_x))
        ax.plot(x, y, "o-", alpha=0.5)
    if title is None:
        title = data.relationname
    if percent != 100:
        title += " (%0.1f%%)" % percent
    fig.canvas.set_window_title(title)
    plt.draw()
    if outfile is not None:
        plt.savefig(outfile)
    if wait:
        plt.show()

Response: Plots the dataset in one line per instance.


Instruction:
How would you explain what the following Python 3 function does
def filter(self, data):
        if isinstance(data, list):
            result = []
            for d in data:
                result.append(Instances(javabridge.static_call(
                    "Lweka/filters/Filter;", "useFilter",
                    "(Lweka/core/Instances;Lweka/filters/Filter;)Lweka/core/Instances;",
                    d.jobject, self.jobject)))
            return result
        else:
            return Instances(javabridge.static_call(
                "Lweka/filters/Filter;", "useFilter",
                "(Lweka/core/Instances;Lweka/filters/Filter;)Lweka/core/Instances;",
                data.jobject, self.jobject))

Response: Filters the dataset. When providing a list returns a list of Instances objects. When providing a list returns a list of Instances objects.


Instruction:
Make a summary of the following Python 3 code
def filters(self):
        objects = javabridge.get_env().get_object_array_elements(
            javabridge.call(self.jobject, "getFilters", "()[Lweka/filters/Filter;"))
        result = []
        for obj in objects:
            result.append(Filter(jobject=obj))
        return result

Response: Returns the list of base filters.


Instruction:
Given the following Python 3 function, write the documentation
def filters(self, filters):
        obj = []
        for fltr in filters:
            obj.append(fltr.jobject)
        javabridge.call(self.jobject, "setFilters", "([Lweka/filters/Filter;)V", obj)

Response: Sets the base filters.


Instruction:
Write a Python 3 script for
generating a help string for this container.

Response:
def generate_help(self):
        """
        Generates a help string for this container.

        :return: the help string
        :rtype: str
        """
        result = []
        result.append(self.__class__.__name__)
        result.append(re.sub(r'.', '=', self.__class__.__name__))
        result.append("")
        result.append("Supported value names:")
        for a in self.allowed:
            result.append(a)
        return '\n'.join(result)


Instruction:
How would you code a function in Python 3 to
call after the actual execution of the transformer.

Response:
def post_execute(self):
        """
        Gets executed after the actual execution.

        :return: None if successful, otherwise error message
        :rtype: str
        """
        result = super(Transformer, self).post_execute()
        if result is None:
            self._input = None
        return result


Instruction:
Make a summary of the following Python 3 code
def quickinfo(self):
        return "incremental: " + str(self.config["incremental"]) \
               + ", custom: " + str(self.config["use_custom_loader"]) \
               + ", loader: " + base.to_commandline(self.config["custom_loader"])

Response: Returns a short string describing some of the options of the actor.


Instruction:
Can you generate the documentation for the following Python 3 function
def fix_config(self, options):
        opt = "incremental"
        if opt not in options:
            options[opt] = False
        if opt not in self.help:
            self.help[opt] = "Whether to load the dataset incrementally (bool)."

        opt = "use_custom_loader"
        if opt not in options:
            options[opt] = False
        if opt not in self.help:
            self.help[opt] = "Whether to use a custom loader."

        opt = "custom_loader"
        if opt not in options:
            options[opt] = converters.Loader(classname="weka.core.converters.ArffLoader")
        if opt not in self.help:
            self.help[opt] = "The custom loader to use (Loader)."

        return super(LoadDataset, self).fix_config(options)

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
Write a Python 3 function for
checking the input token for unsupported classes. Raises an exception if unsupported.

Response:
def check_input(self, token):
        """
        Performs checks on the input token. Raises an exception if unsupported.

        :param token: the token to check
        :type token: Token
        """
        if token is None:
            raise Exception(self.full_name + ": No token provided!")
        if isinstance(token.payload, str):
            return
        raise Exception(self.full_name + ": Unhandled class: " + classes.get_classname(token.payload))


Instruction:
Can you tell what is the following Python 3 function doing
def do_execute(self):
        fname = str(self.input.payload)
        if not os.path.exists(fname):
            return "File '" + fname + "' does not exist!"
        if not os.path.isfile(fname):
            return "Location '" + fname + "' is not a file!"
        if self.resolve_option("use_custom_loader"):
            self._loader = self.resolve_option("custom_loader")
        else:
            self._loader = converters.loader_for_file(fname)
        dataset = self._loader.load_file(fname, incremental=bool(self.resolve_option("incremental")))
        if not self.resolve_option("incremental"):
            self._output.append(Token(dataset))
        else:
            self._iterator = self._loader.__iter__()
        return None

Response:
The actual execution of the actor.

        :return: None if successful, otherwise error message
        :rtype: str


Instruction:
Create a Python 3 function to
return the next available output token.

Response:
def output(self):
        """
        Returns the next available output token.

        :return: the next token, None if none available
        :rtype: Token
        """
        if self._iterator is not None:
            try:
                inst = self._iterator.next()
                result = Token(inst)
            except Exception as e:
                self._iterator = None
                result = None
        else:
            result = super(LoadDataset, self).output()
        return result


Instruction:
Can you write a function in Python 3 where it
stops execution of the object.

Response:
def stop_execution(self):
        """
        Triggers the stopping of the object.
        """
        super(LoadDataset, self).stop_execution()
        self._loader = None
        self._iterator = None


Instruction:
Can you generate the documentation for the following Python 3 function
def wrapup(self):
        self._loader = None
        self._iterator = None
        super(LoadDataset, self).wrapup()

Response: Removes any graphical output from the loader and iterator.


Instruction:
Make a summary of the following Python 3 code
def fix_config(self, options):
        options = super(SetStorageValue, self).fix_config(options)

        opt = "storage_name"
        if opt not in options:
            options[opt] = "unknown"
        if opt not in self.help:
            self.help[opt] = "The storage value name for storing the payload under (string)."

        return options

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
Explain what the following Python 3 code does
def do_execute(self):
        if self.storagehandler is None:
            return "No storage handler available!"
        self.storagehandler.storage[self.resolve_option("storage_name")] = self.input.payload
        self._output.append(self.input)
        return None

Response: The actual execution of the actor.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def fix_config(self, options):
        options = super(DeleteStorageValue, self).fix_config(options)

        opt = "storage_name"
        if opt not in options:
            options[opt] = "unknown"
        if opt not in self.help:
            self.help[opt] = "The name of the storage value to delete (string)."

        return options

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
Write a Python 3 script to
fix the options if necessary. I. e. it adds all required elements to the dictionary.

Response:
def fix_config(self, options):
        """
        Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.

        :param options: the options to fix
        :type options: dict
        :return: the (potentially) fixed options
        :rtype: dict
        """
        options = super(InitStorageValue, self).fix_config(options)

        opt = "storage_name"
        if opt not in options:
            options[opt] = "unknown"
        if opt not in self.help:
            self.help[opt] = "The name of the storage value to delete (string)."

        opt = "value"
        if opt not in options:
            options[opt] = "1"
        if opt not in self.help:
            self.help[opt] = "The initial value (string)."

        return options


Instruction:
Can you tell what is the following Python 3 function doing
def fix_config(self, options):
        options = super(UpdateStorageValue, self).fix_config(options)

        opt = "storage_name"
        if opt not in options:
            options[opt] = "unknown"
        if opt not in self.help:
            self.help[opt] = "The name of the storage value to update (string)."

        opt = "expression"
        if opt not in options:
            options[opt] = "int({X} + 1)"
        if opt not in self.help:
            self.help[opt] = "The expression for updating the storage value; use {X} for current value (string)."

        return options

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
Can you generate the documentation for the following Python 3 function
def do_execute(self):
        if self.storagehandler is None:
            return "No storage handler available!"
        expr = str(self.resolve_option("expression")).replace(
            "{X}", str(self.storagehandler.storage[str(self.resolve_option("storage_name"))]))
        expr = self.storagehandler.expand(expr)
        self.storagehandler.storage[self.resolve_option("storage_name")] = eval(expr)
        self._output.append(self.input)
        return None

Response: Execute the actor s execution.


Instruction:
Create a Python 3 function for
fixing the options if necessary. I. e. it adds all required elements to the dictionary.

Response:
def fix_config(self, options):
        """
        Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.

        :param options: the options to fix
        :type options: dict
        :return: the (potentially) fixed options
        :rtype: dict
        """
        options = super(MathExpression, self).fix_config(options)

        opt = "expression"
        if opt not in options:
            options[opt] = "{X}"
        if opt not in self.help:
            self.help[opt] = "The mathematical expression to evaluate (string)."

        return options


Instruction:
Write a Python 3 function for
executing the actor s execution.

Response:
def do_execute(self):
        """
        The actual execution of the actor.

        :return: None if successful, otherwise error message
        :rtype: str
        """
        expr = str(self.resolve_option("expression"))
        expr = expr.replace("{X}", str(self.input.payload))
        self._output.append(Token(eval(expr)))
        return None


Instruction:
Implement a Python 3 function for
fixing the options if necessary. I. e. it adds all required elements to the dictionary.

Response:
def fix_config(self, options):
        """
        Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.

        :param options: the options to fix
        :type options: dict
        :return: the (potentially) fixed options
        :rtype: dict
        """
        options = super(ClassSelector, self).fix_config(options)

        opt = "index"
        if opt not in options:
            options[opt] = "last"
        if opt not in self.help:
            self.help[opt] = "The class index (1-based number); 'first' and 'last' are accepted as well (string)."

        opt = "unset"
        if opt not in options:
            options[opt] = False
        if opt not in self.help:
            self.help[opt] = "Whether to unset the class index (bool)."

        return options


Instruction:
Can you generate the documentation for the following Python 3 function
def do_execute(self):
        if isinstance(self.input.payload, Instances):
            inst = None
            data = self.input.payload
        elif isinstance(self.input.payload, Instance):
            inst = self.input.payload
            data = inst.dataset

        index = str(self.resolve_option("index"))
        unset = bool(self.resolve_option("unset"))
        if unset:
            data.no_class()
        else:
            if index == "first":
                data.class_is_first()
            elif index == "last":
                data.class_is_last()
            else:
                data.class_index = int(index) - 1

        if inst is None:
            self._output.append(Token(data))
        else:
            self._output.append(Token(inst))

        return None

Response:
The actual execution of the actor.

        :return: None if successful, otherwise error message
        :rtype: str


Instruction:
Write a Python 3 script for
fixing the options if necessary. I. e. it adds all required elements to the dictionary.

Response:
def fix_config(self, options):
        """
        Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.

        :param options: the options to fix
        :type options: dict
        :return: the (potentially) fixed options
        :rtype: dict
        """
        options = super(Train, self).fix_config(options)

        opt = "setup"
        if opt not in options:
            options[opt] = Classifier(classname="weka.classifiers.rules.ZeroR")
        if opt not in self.help:
            self.help[opt] = "The classifier/clusterer/associator to train (Classifier/Clusterer/Associator)."

        return options


Instruction:
Can you generate the documentation for the following Python 3 function
def do_execute(self):
        if isinstance(self.input.payload, Instances):
            inst = None
            data = self.input.payload
        else:
            inst = self.input.payload
            data = inst.dataset

        retrain = False
        if (self._header is None) or (self._header.equal_headers(data) is not None) or (inst is None):
            retrain = True
            self._header = Instances.template_instances(data, 0)

        if retrain or (self._model is None):
            cls = self.resolve_option("setup")
            if isinstance(cls, Classifier):
                self._model = Classifier.make_copy(cls)
            elif isinstance(cls, Clusterer):
                self._model = Clusterer.make_copy(cls)
            elif isinstance(cls, Associator):
                self._model = Associator.make_copy(cls)
            else:
                return "Unhandled class: " + classes.get_classname(cls)

        if retrain:
            if inst is not None:
                data = Instances.template_instances(data, 1)
                data.add_instance(inst)
            if isinstance(self._model, Classifier):
                self._model.build_classifier(data)
            elif isinstance(self._model, Clusterer):
                self._model.build_clusterer(data)
            elif isinstance(self._model, Associator):
                self._model.build_associations(data)
        else:
            if isinstance(self._model, Classifier):
                self._model.update_classifier(inst)
            elif isinstance(self._model, Clusterer):
                self._model.update_clusterer(inst)
            else:
                return "Cannot train incrementally: " + classes.get_classname(self._model)

        cont = ModelContainer(model=self._model, header=self._header)
        self._output.append(Token(cont))
        return None

Response:
The actual execution of the actor.

        :return: None if successful, otherwise error message
        :rtype: str


Instruction:
Can you write a function in Python 3 where it
fixes the options if necessary. I. e. it adds all required elements to the dictionary.

Response:
def fix_config(self, options):
        """
        Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.

        :param options: the options to fix
        :type options: dict
        :return: the (potentially) fixed options
        :rtype: dict
        """
        opt = "setup"
        if opt not in options:
            options[opt] = filters.Filter(classname="weka.filters.AllFilter")
        if opt not in self.help:
            self.help[opt] = "The filter to apply to the dataset (Filter)."

        opt = "keep_relationname"
        if opt not in options:
            options[opt] = False
        if opt not in self.help:
            self.help[opt] = "Whether to keep the original relation name (bool)."

        return super(Filter, self).fix_config(options)


Instruction:
Here you have a function in Python 3, explain what it does
def check_input(self, token):
        if token is None:
            raise Exception(self.full_name + ": No token provided!")
        if isinstance(token.payload, Instances):
            return
        if isinstance(token.payload, Instance):
            return
        raise Exception(self.full_name + ": Unhandled class: " + classes.get_classname(token.payload))

Response: Checks the input token for unsupported classes. Raises an exception if unsupported.


Instruction:
How would you code a function in Python 3 to
execute the actor s action.

Response:
def do_execute(self):
        """
        The actual execution of the actor.

        :return: None if successful, otherwise error message
        :rtype: str
        """
        if isinstance(self.input.payload, Instance):
            inst = self.input.payload
            data = Instances.template_instances(inst.dataset, 1)
            data.add_instance(inst)
        else:
            inst = None
            data = self.input.payload
        relname = data.relationname
        keep = self.resolve_option("keep_relationname")

        if inst is None:
            if (self._filter is None) or self._header.equal_headers(data) is not None:
                self._header = Instances.template_instances(data)
                self._filter = filters.Filter.make_copy(self.resolve_option("setup"))
                self._filter.inputformat(data)
            filtered = self._filter.filter(data)
            if keep:
                filtered.relationname = relname
            self._output.append(Token(filtered))
        else:
            if (self._filter is None) or self._header.equal_headers(data) is not None:
                self._header = Instances.template_instances(data)
                self._filter = filters.Filter.make_copy(self.resolve_option("setup"))
                self._filter.inputformat(data)
                filtered = self._filter.filter(data)
                if keep:
                    filtered.relationname = relname
                self._output.append(Token(filtered.get_instance(0)))
            else:
                self._filter.input(inst)
                self._filter.batch_finished()
                filtered = self._filter.output()
                if keep:
                    filtered.dataset.relationname = relname
                self._output.append(Token(filtered))

        return None


Instruction:
Write a Python 3 function for
fixing the options if necessary. I. e. it adds all required elements to the dictionary.

Response:
def fix_config(self, options):
        """
        Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.

        :param options: the options to fix
        :type options: dict
        :return: the (potentially) fixed options
        :rtype: dict
        """
        options = super(DeleteFile, self).fix_config(options)

        opt = "regexp"
        if opt not in options:
            options[opt] = ".*"
        if opt not in self.help:
            self.help[opt] = "The regular expression that the files must match (string)."

        return options


Instruction:
Can you generate a brief explanation for the following Python 3 code
def fix_config(self, options):
        options = super(CrossValidate, self).fix_config(options)

        opt = "setup"
        if opt not in options:
            options[opt] = Classifier(classname="weka.classifiers.rules.ZeroR")
        if opt not in self.help:
            self.help[opt] = "The classifier/clusterer to train (Classifier/Clusterer)."

        opt = "folds"
        if opt not in options:
            options[opt] = 10
        if opt not in self.help:
            self.help[opt] = "The number of folds for CV (int)."

        opt = "seed"
        if opt not in options:
            options[opt] = 1
        if opt not in self.help:
            self.help[opt] = "The seed value for randomizing the data (int)."

        opt = "discard_predictions"
        if opt not in options:
            options[opt] = False
        if opt not in self.help:
            self.help[opt] = "Discard classifier predictions to save memory (bool)."

        opt = "output"
        if opt not in options:
            options[opt] = None
        if opt not in self.help:
            self.help[opt] = "For capturing the classifier's prediction output (PredictionOutput)."

        return options

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
Can you write a function in Python 3 where it
executes the actual execution of the actor.

Response:
def do_execute(self):
        """
        The actual execution of the actor.

        :return: None if successful, otherwise error message
        :rtype: str
        """
        data = self.input.payload
        cls = self.resolve_option("setup")
        if isinstance(cls, Classifier):
            cls = Classifier.make_copy(cls)
            evl = Evaluation(data)
            evl.discard_predictions = bool(self.resolve_option("discard_predictions"))
            evl.crossvalidate_model(
                cls,
                data,
                int(self.resolve_option("folds")),
                Random(int(self.resolve_option("seed"))),
                self.resolve_option("output"))
            self._output.append(Token(evl))
        elif isinstance(cls, Clusterer):
            cls = Clusterer.make_copy(cls)
            evl = ClusterEvaluation()
            llh = evl.crossvalidate_model(
                cls,
                data,
                int(self.resolve_option("folds")),
                Random(int(self.resolve_option("seed"))))
            self._output.append(Token(llh))
        else:
            return "Unhandled class: " + classes.get_classname(cls)
        return None


Instruction:
Here you have a function in Python 3, explain what it does
def fix_config(self, options):
        options = super(Evaluate, self).fix_config(options)

        opt = "storage_name"
        if opt not in options:
            options[opt] = "unknown"
        if opt not in self.help:
            self.help[opt] = "The name of the classifier model in storage (string)."

        opt = "discard_predictions"
        if opt not in options:
            options[opt] = False
        if opt not in self.help:
            self.help[opt] = "Discard classifier predictions to save memory (bool)."

        opt = "output"
        if opt not in options:
            options[opt] = None
        if opt not in self.help:
            self.help[opt] = "For capturing the classifier's prediction output (PredictionOutput)."

        return options

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
How would you explain what the following Python 3 function does
def do_execute(self):
        data = self.input.payload
        if self.storagehandler is None:
            return "No storage handler available!"
        sname = str(self.resolve_option("storage_name"))
        if sname not in self.storagehandler.storage:
            return "No storage item called '" + sname + "' present!"
        cls = self.storagehandler.storage[sname]
        if isinstance(cls, Classifier):
            evl = Evaluation(data)
            evl.discard_predictions = bool(self.resolve_option("discard_predictions"))
            evl.test_model(
                cls,
                data,
                self.resolve_option("output"))
        elif isinstance(cls, Clusterer):
            evl = ClusterEvaluation()
            evl.set_model(cls)
            evl.test_model(data)
        else:
            return "Unhandled class: " + classes.get_classname(cls)
        self._output.append(Token(evl))
        return None

Response: Executes the actual execution of the actor.


Instruction:
Can you generate the documentation for the following Python 3 function
def fix_config(self, options):
        options = super(EvaluationSummary, self).fix_config(options)

        opt = "title"
        if opt not in options:
            options[opt] = None
        if opt not in self.help:
            self.help[opt] = "The title for the output (string)."

        opt = "complexity"
        if opt not in options:
            options[opt] = False
        if opt not in self.help:
            self.help[opt] = "Whether to output classifier complexity information (bool)."

        opt = "matrix"
        if opt not in options:
            options[opt] = False
        if opt not in self.help:
            self.help[opt] = "Whether to output the classifier confusion matrix (bool)."

        return options

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
Can you create a Python 3 function that
checks if the input token is a supported Evaluation object. Raises an exception if unsupported.

Response:
def check_input(self, token):
        """
        Performs checks on the input token. Raises an exception if unsupported.

        :param token: the token to check
        :type token: Token
        """
        if isinstance(token.payload, Evaluation):
            return None
        if isinstance(token.payload, ClusterEvaluation):
            return None
        raise Exception(
            self.full_name + ": Input token is not a supported Evaluation object - "
            + classes.get_classname(token.payload))


Instruction:
Write a Python 3 script to
execute the actual execution of the actor.

Response:
def do_execute(self):
        """
        The actual execution of the actor.

        :return: None if successful, otherwise error message
        :rtype: str
        """
        evl = self.input.payload
        if isinstance(evl, Evaluation):
            summary = evl.summary(title=self.resolve_option("title"), complexity=bool(self.resolve_option("complexity")))
            if bool(self.resolve_option("matrix")):
                summary += "\n" + evl.matrix(title=self.resolve_option("title"))
        else:
            summary = evl.cluster_results
        self._output.append(Token(summary))
        return None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def do_execute(self):
        fname = self.input.payload
        data = serialization.read_all(fname)
        if len(data) == 1:
            if is_instance_of(data[0], "weka.classifiers.Classifier"):
                cont = ModelContainer(model=Classifier(jobject=data[0]))
            elif is_instance_of(data[0], "weka.clusterers.Clusterer"):
                cont = ModelContainer(model=Clusterer(jobject=data[0]))
            else:
                return "Unhandled class: " + classes.get_classname(data[0])
        elif len(data) == 2:
            if is_instance_of(data[0], "weka.classifiers.Classifier"):
                cont = ModelContainer(model=Classifier(jobject=data[0]), header=Instances(data[1]))
            elif is_instance_of(data[0], "weka.clusterers.Clusterer"):
                cont = ModelContainer(model=Clusterer(jobject=data[0]), header=Instances(data[1]))
            else:
                return "Unhandled class: " + classes.get_classname(data[0])
        else:
            return "Expected 1 or 2 objects, but got " + str(len(data)) + " instead reading: " + fname
        self._output.append(Token(cont))
        return None

Response: This method is called by the actor s do_execute method.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def fix_config(self, options):
        opt = "setup"
        if opt not in options:
            options[opt] = conversion.PassThrough()
        if opt not in self.help:
            self.help[opt] = "The conversion to apply to the input data (Conversion)."

        return super(Convert, self).fix_config(options)

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
Make a summary of the following Python 3 code
def check_input(self, token):
        if token is None:
            raise Exception(self.full_name + ": No token provided!")
        self.config["setup"].check_input(token.payload)

Response: Checks the input token for unsupported input. Raises an exception if unsupported.


Instruction:
Given the following Python 3 function, write the documentation
def do_execute(self):
        conv = self.config["setup"].shallow_copy()
        conv.input = self._input.payload
        result = conv.convert()
        if result is None:
            if conv.output is not None:
                self._output.append(Token(conv.output))
        return None

Response: Execute the actor s execution.


Instruction:
Here you have a function in Python 3, explain what it does
def quickinfo(self):
        return "search: " + base.to_commandline(self.config["search"]) + ", eval: " \
               + base.to_commandline(self.config["eval"])

Response: Returns a short string describing some of the options of the actor.


Instruction:
Given the following Python 3 function, write the documentation
def fix_config(self, options):
        opt = "search"
        if opt not in options:
            options[opt] = attsel.ASSearch(classname="weka.attributeSelection.BestFirst")
        if opt not in self.help:
            self.help[opt] = "The search algorithm to use (ASSearch)."

        opt = "eval"
        if opt not in options:
            options[opt] = attsel.ASEvaluation(classname="weka.attributeSelection.CfsSubsetEval")
        if opt not in self.help:
            self.help[opt] = "The evaluation algorithm to use (ASEvaluation)."

        return super(AttributeSelection, self).fix_config(options)

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
How would you explain what the following Python 3 function does
def check_input(self, token):
        if token is None:
            raise Exception(self.full_name + ": No token provided!")
        if not isinstance(token.payload, Instances):
            raise Exception(self.full_name + ": Not an Instances object!")

Response: Checks that the input token is a valid token. Raises an exception if unsupported.


Instruction:
Can you generate the documentation for the following Python 3 function
def do_execute(self):
        data = self.input.payload
        search = self.config["search"].shallow_copy()
        evl = self.config["eval"].shallow_copy()
        asel = attsel.AttributeSelection()
        asel.search(search)
        asel.evaluator(evl)
        asel.select_attributes(data)
        cont = AttributeSelectionContainer(
            original=data,
            reduced=asel.reduce_dimensionality(data),
            num_atts=asel.number_attributes_selected,
            selected=asel.selected_attributes,
            results=asel.results_string)
        self._output.append(Token(cont))
        return None

Response: The actual execution of the actor.


Instruction:
How would you explain what the following Python 3 function does
def fix_config(self, options):
        options = super(RenameRelation, self).fix_config(options)

        opt = "name"
        if opt not in options:
            options[opt] = "newname"
        if opt not in self.help:
            self.help[opt] = "The new relation name to use (string)."

        return options

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
Can you tell what is the following Python 3 function doing
def do_execute(self):
        relname = self.resolve_option("name")
        if isinstance(self.input.payload, Instance):
            self.input.payload.dataset.relationname = relname
        else:
            self.input.payload.relationname = relname
        self._output.append(self.input)
        return None

Response: The actual execution of the actor.


Instruction:
Make a summary of the following Python 3 code
def do_execute(self):
        if isinstance(self.input.payload, classes.JavaObject) and self.input.payload.is_serializable:
            copy = serialization.deepcopy(self.input.payload)
            if copy is not None:
                self._output.append(Token(copy))
        else:
            self._output.append(self.input)
        return None

Response: Executes the actual execution of the actor.


Instruction:
Write a Python 3 function for
fixing the options if necessary. I. e. it adds all required elements to the dictionary.

Response:
def fix_config(self, options):
        """
        Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.

        :param options: the options to fix
        :type options: dict
        :return: the (potentially) fixed options
        :rtype: dict
        """
        options = super(Predict, self).fix_config(options)

        opt = "model"
        if opt not in options:
            options[opt] = "."
        if opt not in self.help:
            self.help[opt] = "The serialized model to use for making predictions (string)."

        opt = "storage_name"
        if opt not in options:
            options[opt] = "unknown"
        if opt not in self.help:
            self.help[opt] = "The name of the model (or ModelContainer) in storage to use (string)."

        return options


Instruction:
Make a summary of the following Python 3 code
def check_input(self, token):
        if isinstance(token.payload, Instance):
            return
        raise Exception(self.full_name + ": Unhandled data type: " + str(token.payload.__class__.__name__))

Response: Checks the input token for unsupported data types. Raises an exception if unsupported.


Instruction:
Explain what the following Python 3 code does
def plot_dot_graph(graph, filename=None):
    if not plot.pygraphviz_available:
        logger.error("Pygraphviz is not installed, cannot generate graph plot!")
        return
    if not plot.PIL_available:
        logger.error("PIL is not installed, cannot display graph plot!")
        return

    agraph = AGraph(graph)
    agraph.layout(prog='dot')
    if filename is None:
        filename = tempfile.mktemp(suffix=".png")
    agraph.draw(filename)
    image = Image.open(filename)
    image.show()

Response: Plots a graph in graphviz dot notation.


Instruction:
Can you create a Python 3 function that
returns the stemmed version of the string s.

Response:
def stem(self, s):
        """
        Performs stemming on the string.

        :param s: the string to stem
        :type s: str
        :return: the stemmed string
        :rtype: str
        """
        return javabridge.get_env().get_string(self.__stem(javabridge.get_env().new_string_utf(s)))


Instruction:
Make a summary of the following Python 3 code
def create_instances_from_matrices(x, y=None, name="data"):
    if y is not None:
        if len(x) != len(y):
            raise Exception("Dimensions of x and y differ: " + str(len(x)) + " != " + str(len(y)))
    # create header
    atts = []
    for i in range(len(x[0])):
        atts.append(Attribute.create_numeric("x" + str(i+1)))
    if y is not None:
        atts.append(Attribute.create_numeric("y"))
    result = Instances.create_instances(name, atts, len(x))
    # add data
    for i in range(len(x)):
        values = list(x[i])
        if y is not None:
            values.append(y[i])
        result.add_instance(Instance.create_instance(values))
    return result

Response:
Allows the generation of an Instances object from a 2 - dimensional matrix for X and a
    1 - dimensional matrix for Y.


Instruction:
Write a Python 3 function that can
return the specified attribute or None if not found.

Response:
def attribute_by_name(self, name):
        """
        Returns the specified attribute, None if not found.

        :param name: the name of the attribute
        :type name: str
        :return: the attribute or None
        :rtype: Attribute
        """
        att = self.__attribute_by_name(javabridge.get_env().new_string(name))
        if att is None:
            return None
        else:
            return Attribute(att)


Instruction:
Can you tell what is the following Python 3 function doing
def add_instance(self, inst, index=None):
        if index is None:
            self.__append_instance(inst.jobject)
        else:
            self.__insert_instance(index, inst.jobject)

Response: Adds the specified instance to the dataset.


Instruction:
Implement a function in Python 3 to
set the instance at the specified location in the dataset.

Response:
def set_instance(self, index, inst):
        """
        Sets the Instance at the specified location in the dataset.

        :param index: the 0-based index of the instance to replace
        :type index: int
        :param inst: the Instance to set
        :type inst: Instance
        :return: the instance
        :rtype: Instance
        """
        return Instance(
            self.__set_instance(index, inst.jobject))


Instruction:
Here you have a function in Python 3, explain what it does
def delete(self, index=None):
        if index is None:
            javabridge.call(self.jobject, "delete", "()V")
        else:
            javabridge.call(self.jobject, "delete", "(I)V", index)

Response: Removes either the specified Instance or all Instance objects.


Instruction:
Can you tell what is the following Python 3 function doing
def insert_attribute(self, att, index):
        javabridge.call(self.jobject, "insertAttributeAt", "(Lweka/core/Attribute;I)V", att.jobject, index)

Response: Inserts the specified attribute at the specified location.


Instruction:
Make a summary of the following Python 3 code
def train_cv(self, num_folds, fold, random=None):
        if random is None:
            return Instances(
                javabridge.call(self.jobject, "trainCV", "(II)Lweka/core/Instances;",
                                num_folds, fold))
        else:
            return Instances(
                javabridge.call(self.jobject, "trainCV", "(IILjava/util/Random;)Lweka/core/Instances;",
                                num_folds, fold, random.jobject))

Response: Generates a training fold for cross - validation.


Instruction:
Write a Python 3 script for
creating a copy of the Instances.

Response:
def copy_instances(cls, dataset, from_row=None, num_rows=None):
        """
        Creates a copy of the Instances. If either from_row or num_rows are None, then all of
        the data is being copied.

        :param dataset: the original dataset
        :type dataset: Instances
        :param from_row: the 0-based start index of the rows to copy
        :type from_row: int
        :param num_rows: the number of rows to copy
        :type num_rows: int
        :return: the copy of the data
        :rtype: Instances
        """
        if from_row is None or num_rows is None:
            return Instances(
                javabridge.make_instance(
                    "weka/core/Instances", "(Lweka/core/Instances;)V",
                    dataset.jobject))
        else:
            dataset = cls.copy_instances(dataset)
            return Instances(
                javabridge.make_instance(
                    "weka/core/Instances", "(Lweka/core/Instances;II)V",
                    dataset.jobject, from_row, num_rows))


Instruction:
How would you code a function in Python 3 to
use the Instances as template to create an empty dataset.

Response:
def template_instances(cls, dataset, capacity=0):
        """
        Uses the Instances as template to create an empty dataset.

        :param dataset: the original dataset
        :type dataset: Instances
        :param capacity: how many data rows to reserve initially (see compactify)
        :type capacity: int
        :return: the empty dataset
        :rtype: Instances
        """
        return Instances(
            javabridge.make_instance(
                "weka/core/Instances", "(Lweka/core/Instances;I)V", dataset.jobject, capacity))


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

Response:
def create_instances(cls, name, atts, capacity):
        """
        Creates a new Instances.

        :param name: the relation name
        :type name: str
        :param atts: the list of attributes to use for the dataset
        :type atts: list of Attribute
        :param capacity: how many data rows to reserve initially (see compactify)
        :type capacity: int
        :return: the dataset
        :rtype: Instances
        """
        attributes = []
        for att in atts:
            attributes.append(att.jobject)
        return Instances(
            javabridge.make_instance(
                "weka/core/Instances", "(Ljava/lang/String;Ljava/util/ArrayList;I)V",
                name, javabridge.make_list(attributes), capacity))


Instruction:
Here you have a function in Python 3, explain what it does
def merge_instances(cls, inst1, inst2):
        return Instances(javabridge.static_call(
            "weka/core/Instances", "mergeInstances",
            "(Lweka/core/Instances;Lweka/core/Instances;)Lweka/core/Instances;", inst1.jobject, inst2.jobject))

Response: Merges two Instances or str into one Instances.


Instruction:
Can you tell what is the following Python 3 function doing
def dataset(self):
        dataset = javabridge.call(self.jobject, "dataset", "()Lweka/core/Instances;")
        if dataset is None:
            return None
        else:
            return Instances(dataset)

Response: Returns the dataset that this instance belongs to.


Instruction:
Implement a function in Python 3 to
set the string value at the specified index.

Response:
def set_string_value(self, index, s):
        """
        Sets the string value at the specified position (0-based).

        :param index: the 0-based index of the inernal value
        :type index: int
        :param s: the string value
        :type s: str
        """
        return self.__set_string_value(index, javabridge.get_env().new_string(s))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_instance(cls, values, classname="weka.core.DenseInstance", weight=1.0):
        jni_classname = classname.replace(".", "/")
        if type(values) is list:
            for i in range(len(values)):
                values[i] = float(values[i])
            values = numpy.array(values)
        return Instance(
            javabridge.make_instance(
                jni_classname, "(D[D)V",
                weight, javabridge.get_env().make_double_array(values)))

Response: Creates a new instance of the class specified by classname and values.


Instruction:
Here you have a function in Python 3, explain what it does
def create_sparse_instance(cls, values, max_values, classname="weka.core.SparseInstance", weight=1.0):
        jni_classname = classname.replace(".", "/")
        indices = []
        vals = []
        for (i, v) in values:
            indices.append(i)
            vals.append(float(v))
        indices = numpy.array(indices, dtype=numpy.int32)
        vals = numpy.array(vals)
        return Instance(
            javabridge.make_instance(
                jni_classname, "(D[D[II)V",
                weight, javabridge.get_env().make_double_array(vals),
                javabridge.get_env().make_int_array(indices), max_values))

Response: Creates a new sparse instance.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def values(self):
        enm = javabridge.call(self.jobject, "enumerateValues", "()Ljava/util/Enumeration;")
        if enm is None:
            return None
        else:
            return typeconv.enumeration_to_list(enm)

Response: Returns the labels strings or relation - values.


Instruction:
How would you implement a function in Python 3 that
returns the type of the attribute as string.

Response:
def type_str(self, short=False):
        """
        Returns the type of the attribute as string.

        :return: the type
        :rtype: str
        """
        if short:
            return javabridge.static_call(
                "weka/core/Attribute", "typeToStringShort", "(Lweka/core/Attribute;)Ljava/lang/String;",
                self.jobject)
        else:
            return javabridge.static_call(
                "weka/core/Attribute", "typeToString", "(Lweka/core/Attribute;)Ljava/lang/String;",
                self.jobject)


Instruction:
Explain what the following Python 3 code does
def copy(self, name=None):
        if name is None:
            return Attribute(
                javabridge.call(self.jobject, "copy", "()Ljava/lang/Object;"))
        else:
            return Attribute(
                javabridge.call(self.jobject, "copy", "(Ljava/lang/String;)Lweka/core/Attribute;", name))

Response: Creates a copy of this attribute.


Instruction:
How would you explain what the following Python 3 function does
def create_nominal(cls, name, labels):
        return Attribute(
            javabridge.make_instance(
                "weka/core/Attribute", "(Ljava/lang/String;Ljava/util/List;)V", name, javabridge.make_list(labels)))

Response: Creates a nominal attribute.


Instruction:
Can you generate the documentation for the following Python 3 function
def create_relational(cls, name, inst):
        return Attribute(
            javabridge.make_instance(
                "weka/core/Attribute", "(Ljava/lang/String;Lweka/core/Instances;)V", name, inst.jobject))

Response: Creates a relational attribute.


Instruction:
Can you implement a function in Python 3 that
adds the bundled jars to the JVM s classpath.

Response:
def add_bundled_jars():
    """
    Adds the bundled jars to the JVM's classpath.
    """
    # determine lib directory with jars
    rootdir = os.path.split(os.path.dirname(__file__))[0]
    libdir = rootdir + os.sep + "lib"

    # add jars from lib directory
    for l in glob.glob(libdir + os.sep + "*.jar"):
        if l.lower().find("-src.") == -1:
            javabridge.JARS.append(str(l))


Instruction:
Can you generate the documentation for the following Python 3 function
def add_system_classpath():
    if 'CLASSPATH' in os.environ:
        parts = os.environ['CLASSPATH'].split(os.pathsep)
        for part in parts:
            javabridge.JARS.append(part)

Response: Adds the system s classpath to the JVM s classpath.


Instruction:
Implement a Python 3 function for
initializing the javabridge connection (starts up the JVM). :param class_path: the additional classpath elements to add :type class_path: list :param bundled: whether to add jars from the "lib" directory :type bundled: bool :param packages: whether to add jars from Weka packages as well (bool) or an alternative Weka home directory (str) :type packages: bool or str :param system_cp: whether to add the system classpath as well :type system_cp: bool :param max_heap_size: the maximum heap size (-Xmx parameter, eg 512m or 4g) :type max_heap_size: str

Response:
def start(class_path=None, bundled=True, packages=False, system_cp=False, max_heap_size=None):
    """
    Initializes the javabridge connection (starts up the JVM).

    :param class_path: the additional classpath elements to add
    :type class_path: list
    :param bundled: whether to add jars from the "lib" directory
    :type bundled: bool
    :param packages: whether to add jars from Weka packages as well (bool) or an alternative Weka home directory (str)
    :type packages: bool or str
    :param system_cp: whether to add the system classpath as well
    :type system_cp: bool
    :param max_heap_size: the maximum heap size (-Xmx parameter, eg 512m or 4g)
    :type max_heap_size: str
    """
    global started

    if started is not None:
        logger.info("JVM already running, call jvm.stop() first")
        return

    # add user-defined jars first
    if class_path is not None:
        for cp in class_path:
            logger.debug("Adding user-supplied classpath=" + cp)
            javabridge.JARS.append(cp)

    if bundled:
        logger.debug("Adding bundled jars")
        add_bundled_jars()

    if system_cp:
        logger.debug("Adding system classpath")
        add_system_classpath()

    logger.debug("Classpath=" + str(javabridge.JARS))
    logger.debug("MaxHeapSize=" + ("default" if (max_heap_size is None) else max_heap_size))

    args = []
    weka_home = None
    if packages is not None:
        if isinstance(packages, bool):
            if packages:
                logger.debug("Package support enabled")
            else:
                logger.debug("Package support disabled")
                args.append("-Dweka.packageManager.loadPackages=false")
        if isinstance(packages, str):
            if os.path.exists(packages) and os.path.isdir(packages):
                logger.debug("Using alternative Weka home directory: " + packages)
                weka_home = packages
            else:
                logger.warning("Invalid Weka home: " + packages)

    javabridge.start_vm(args=args, run_headless=True, max_heap_size=max_heap_size)
    javabridge.attach()
    started = True

    if weka_home is not None:
        from weka.core.classes import Environment
        env = Environment.system_wide()
        logger.debug("Using alternative Weka home directory: " + packages)
        env.add_variable("WEKA_HOME", weka_home)

    # initialize package manager
    javabridge.static_call(
        "Lweka/core/WekaPackageManager;", "loadPackages",
        "(Z)V",
        False)


Instruction:
Create a Python 3 function for
returning the class object associated with the dot - notation classname.

Response:
def get_class(classname):
    """
    Returns the class object associated with the dot-notation classname.

    Taken from here: http://stackoverflow.com/a/452981

    :param classname: the classname
    :type classname: str
    :return: the class object
    :rtype: object
    """
    parts = classname.split('.')
    module = ".".join(parts[:-1])
    m = __import__(module)
    for comp in parts[1:]:
        m = getattr(m, comp)
    return m


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_jclass(classname):
    try:
        return javabridge.class_for_name(classname)
    except:
        return javabridge.static_call(
            "Lweka/core/ClassHelper;", "forName",
            "(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Class;",
            javabridge.class_for_name("java.lang.Object"), classname)

Response: Returns the Java class object associated with the dot - notation classname.


Instruction:
Can you implement a function in Python 3 that
returns the Java object associated with the specified static field.

Response:
def get_static_field(classname, fieldname, signature):
    """
    Returns the Java object associated with the static field of the specified class.

    :param classname: the classname of the class to get the field from
    :type classname: str
    :param fieldname: the name of the field to retriev
    :type fieldname: str
    :return: the object
    :rtype: JB_Object
    """
    try:
        return javabridge.get_static_field(classname, fieldname, signature)
    except:
        return javabridge.static_call(
            "Lweka/core/ClassHelper;", "getStaticField",
            "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;",
            classname, fieldname)


Instruction:
Can you tell what is the following Python 3 function doing
def get_classname(obj):
    if isinstance(obj, javabridge.JB_Object):
        cls = javabridge.call(obj, "getClass", "()Ljava/lang/Class;")
        return javabridge.call(cls, "getName", "()Ljava/lang/String;")
    elif inspect.isclass(obj):
        return obj.__module__ + "." + obj.__name__
    else:
        return get_classname(obj.__class__)

Response: Returns the classname of the object.


Instruction:
Given the following Python 3 function, write the documentation
def is_instance_of(obj, class_or_intf_name):
    class_or_intf_name = class_or_intf_name.replace("/", ".")
    classname = get_classname(obj)
    # array? retrieve component type and check that
    if is_array(obj):
        jarray = JavaArray(jobject=obj)
        classname = jarray.component_type()
    result = javabridge.static_call(
        "Lweka/core/InheritanceUtils;", "isSubclass",
        "(Ljava/lang/String;Ljava/lang/String;)Z",
        class_or_intf_name, classname)
    if result:
        return True
    return javabridge.static_call(
        "Lweka/core/InheritanceUtils;", "hasInterface",
        "(Ljava/lang/String;Ljava/lang/String;)Z",
        class_or_intf_name, classname)

Response: Checks whether the object is an instance of the specified interface or is a subclass of the superclass.


Instruction:
Make a summary of the following Python 3 code
def from_commandline(cmdline, classname=None):
    params = split_options(cmdline)
    cls = params[0]
    params = params[1:]
    handler = OptionHandler(javabridge.static_call(
        "Lweka/core/Utils;", "forName",
        "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/Object;",
        javabridge.class_for_name("java.lang.Object"), cls, params))
    if classname is None:
        return handler
    else:
        c = get_class(classname)
        return c(jobject=handler.jobject)

Response: Creates an OptionHandler instance based on the provided commandline string.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def complete_classname(classname):

    result = javabridge.get_collection_wrapper(
        javabridge.static_call(
            "Lweka/Run;", "findSchemeMatch",
            "(Ljava/lang/String;Z)Ljava/util/List;",
            classname, True))
    if len(result) == 1:
        return str(result[0])
    elif len(result) == 0:
        raise Exception("No classname matches found for: " + classname)
    else:
        matches = []
        for i in range(len(result)):
            matches.append(str(result[i]))
        raise Exception("Found multiple matches for '" + classname + "':\n" + '\n'.join(matches))

Response: Attempts to complete a partial classname like. J48 and returns the full classname if a single match was found otherwise an exception is raised.


Instruction:
Can you generate the documentation for the following Python 3 function
def main():
    parser = argparse.ArgumentParser(
        description='Performs option handling operations from the command-line. Calls JVM start/stop automatically.')
    parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories")
    parser.add_argument("-action", metavar="action", dest="action", required=True,
                        help="The action to perform on the options: join=create single string, "\
                             "split=create array from quoted option, code=generate code from options")
    parser.add_argument("option", nargs=argparse.REMAINDER, help="The option(s) to process")
    parsed = parser.parse_args()
    jars = []
    if parsed.classpath is not None:
        jars = parsed.classpath.split(os.pathsep)

    jvm.start(jars, packages=True)

    try:
        if parsed.action == "join":
            output = "cmdline = \"" + backquote(join_options(parsed.option)) + "\""
        elif parsed.action == "split" and len(parsed.option) == 1:
            output = "options = [\n"
            opts = split_options(parsed.option[0])
            for idx, opt in enumerate(opts):
                if idx > 0:
                    output += ",\n"
                output += "    \"" + backquote(opt) + "\""
            output += "]"
        elif parsed.action == "code":
            options = parsed.option[:]
            cname = None
            # classname + options?
            if options[0].find(".") > -1:
                cname = options[0]
                options = options[1:]
            output = "options = [ \n"
            for idx, opt in enumerate(options):
                if idx > 0:
                    output += ",\n"
                output += "    \"" + backquote(opt) + "\""
            output += "]\n"
            if cname is not None:
                output += 'handler = OptionHandler(JavaObject.new_instance("' + cname + '"))\n'
                output += 'handler.options = options\n'
        else:
            raise Exception("Unsupported action: " + parsed.action)
        if output is not None:
            print(output)
    except Exception as e:
        print(e)
    finally:
        jvm.stop()

Response:
Main entry point for the
elf command - line interface.


Instruction:
Can you write a function in Python 3 where it
returns the options as JSON.

Response:
def to_json(self):
        """
        Returns the options as JSON.

        :return: the object as string
        :rtype: str
        """
        return json.dumps(self.to_dict(), sort_keys=True, indent=2, separators=(',', ': '))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def from_json(cls, s):
        d = json.loads(s)
        return get_dict_handler(d["type"])(d)

Response: Restores the object from the given JSON string.


Instruction:
Can you tell what is the following Python 3 function doing
def to_dict(self):
        result = {}
        result["type"] = "Configurable"
        result["class"] = get_classname(self)
        result["config"] = {}
        for k in self._config:
            v = self._config[k]
            if isinstance(v, JSONObject):
                result["config"][k] = v.to_dict()
            else:
                result["config"][k] = v
        return result

Response: Returns a dictionary that represents this object


Instruction:
Write a Python 3 script for
restoring its state from a dictionary used in de - JSONification.

Response:
def from_dict(cls, d):
        """
        Restores its state from a dictionary, used in de-JSONification.

        :param d: the object dictionary
        :type d: dict
        """
        conf = {}
        for k in d["config"]:
            v = d["config"][k]
            if isinstance(v, dict):
                conf[str(k)] = get_dict_handler(d["config"]["type"])(v)
            else:
                conf[str(k)] = v
        return get_class(str(d["class"]))(config=conf)


Instruction:
How would you implement a function in Python 3 that
returns the logger object.

Response:
def logger(self):
        """
        Returns the logger object.

        :return: the logger
        :rtype: logger
        """
        if self._logger is None:
            self._logger = self.new_logger()
        return self._logger


Instruction:
Implement a function in Python 3 to
generate a help string for this actor.

Response:
def generate_help(self):
        """
        Generates a help string for this actor.

        :return: the help string
        :rtype: str
        """
        result = []
        result.append(self.__class__.__name__)
        result.append(re.sub(r'.', '=', self.__class__.__name__))
        result.append("")
        result.append("DESCRIPTION")
        result.append(self.description())
        result.append("")
        result.append("OPTIONS")
        opts = sorted(self.config.keys())
        for opt in opts:
            result.append(opt)
            helpstr = self.help[opt]
            if helpstr is None:
                helpstr = "-missing help-"
            result.append("\t" + helpstr)
            result.append("")
        return '\n'.join(result)


Instruction:
Make a summary of the following Python 3 code
def classname(self):
        cls = javabridge.call(self.jobject, "getClass", "()Ljava/lang/Class;")
        return javabridge.call(cls, "getName", "()Ljava/lang/String;")

Response: Returns the Java classname in dot - notation.


Instruction:
Make a summary of the following Python 3 code
def set_property(self, path, jobject):
        # unwrap?
        if isinstance(jobject, JavaObject):
            jobject = jobject.jobject

        javabridge.static_call(
            "Lweka/core/PropertyPath;", "setValue",
            "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)V",
            self.jobject, path, jobject)

Response: Sets the value of the property at the given path.


Instruction:
Write a Python 3 script to
raise an exception if the object does not implement the specified interface or is not a subclass of the specified class.

Response:
def enforce_type(cls, jobject, intf_or_class):
        """
        Raises an exception if the object does not implement the specified interface or is not a subclass.

        :param jobject: the Java object to check
        :type jobject: JB_Object
        :param intf_or_class: the classname in Java notation (eg "weka.core.DenseInstance")
        :type intf_or_class: str
        """
        if not cls.check_type(jobject, intf_or_class):
            raise TypeError("Object does not implement or subclass " + intf_or_class + ": " + get_classname(jobject))


Instruction:
How would you explain what the following Python 3 function does
def new_instance(cls, classname):
        try:
            return javabridge.static_call(
                "Lweka/core/Utils;", "forName",
                "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/Object;",
                javabridge.class_for_name("java.lang.Object"), classname, [])
        except JavaException as e:
            print("Failed to instantiate " + classname + ": " + str(e))
            return None

Response: Creates a new object from the given classname using the default constructor.


Instruction:
Make a summary of the following Python 3 code
def add_variable(self, key, value, system_wide=False):
        if system_wide:
            javabridge.call(self.jobject, "addVariableSystemWide", "(Ljava/lang/String;Ljava/lang/String;)V", key, value)
        else:
            javabridge.call(self.jobject, "addVariable", "(Ljava/lang/String;Ljava/lang/String;)V", key, value)

Response: Adds the environment variable.


Instruction:
Create a Python 3 function for
returning the names of all environment variables.

Response:
def variable_names(self):
        """
        Returns the names of all environment variables.

        :return: the names of the variables
        :rtype: list
        """
        result = []
        names = javabridge.call(self.jobject, "getVariableNames", "()Ljava/util/Set;")
        for name in javabridge.iterate_collection(names):
            result.append(javabridge.to_string(name))
        return result


Instruction:
Make a summary of the following Python 3 code
def component_type(self):
        cls = javabridge.call(self.jobject, "getClass", "()Ljava/lang/Class;")
        comptype = javabridge.call(cls, "getComponentType", "()Ljava/lang/Class;")
        return javabridge.call(comptype, "getName", "()Ljava/lang/String;")

Response: Returns the classname of the elements.


Instruction:
Can you generate the documentation for the following Python 3 function
def new_instance(cls, classname, length):
        return javabridge.static_call(
            "Ljava/lang/reflect/Array;",
            "newInstance",
            "(Ljava/lang/Class;I)Ljava/lang/Object;",
            get_jclass(classname=classname), length)

Response: Creates a new array with the given classname and length.


Instruction:
Make a summary of the following Python 3 code
def values(self):
        cls = javabridge.call(self.jobject, "getClass", "()Ljava/lang/Class;")
        clsname = javabridge.call(cls, "getName", "()Ljava/lang/String;")
        l = javabridge.static_call(clsname.replace(".", "/"), "values", "()[L" + clsname.replace(".", "/") + ";")
        l = javabridge.get_env().get_object_array_elements(l)
        result = []
        for item in l:
            result.append(Enum(jobject=item))
        return result

Response: Returns list of all enum members.


Instruction:
How would you implement a function in Python 3 that
returns the next random integer.

Response:
def next_int(self, n=None):
        """
        Next random integer. if n is provided, then between 0 and n-1.

        :param n: the upper limit (minus 1) for the random integer
        :type n: int
        :return: the next random integer
        :rtype: int
        """
        if n is None:
            return javabridge.call(self.jobject, "nextInt", "()I")
        else:
            return javabridge.call(self.jobject, "nextInt", "(I)I", n)


Instruction:
Explain what the following Python 3 code does
def options(self):
        if self.is_optionhandler:
            return typeconv.string_array_to_list(javabridge.call(self.jobject, "getOptions", "()[Ljava/lang/String;"))
        else:
            return []

Response: Gets the currently set options as list.


Instruction:
Explain what the following Python 3 code does
def options(self, options):
        if self.is_optionhandler:
            javabridge.call(self.jobject, "setOptions", "([Ljava/lang/String;)V", typeconv.string_list_to_array(options))

Response: Sets the command - line options.


Instruction:
Here you have a function in Python 3, explain what it does
def to_help(self):
        result = []
        result.append(self.classname)
        result.append("=" * len(self.classname))
        result.append("")
        result.append("DESCRIPTION")
        result.append("")
        result.append(self.global_info())
        result.append("")
        result.append("OPTIONS")
        result.append("")
        options = javabridge.call(self.jobject, "listOptions", "()Ljava/util/Enumeration;")
        enum = javabridge.get_enumeration_wrapper(options)
        while enum.hasMoreElements():
            opt = Option(enum.nextElement())
            result.append(opt.synopsis)
            result.append(opt.description)
            result.append("")
        return '\n'.join(result)

Response: Returns the generated help string for the current object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_dict(self):
        result = super(OptionHandler, self).to_dict()
        result["type"] = "OptionHandler"
        result["options"] = join_options(self.options)
        return result

Response: Returns a dictionary that represents this object to be used for JSONification.


Instruction:
Can you tell what is the following Python 3 function doing
def from_dict(cls, d):
        result = OptionHandler(cls.new_instance(d["class"]))
        result.options = split_options(d["options"])
        return result

Response: Restores an object state from a dictionary used in de - JSONification.


Instruction:
Can you implement a function in Python 3 that
returns the Tag that matches the name.

Response:
def find(self, name):
        """
        Returns the Tag that matches the name.

        :param name: the string representation of the tag
        :type name: str
        :return: the tag, None if not found
        :rtype: Tag
        """
        result = None
        for t in self.array:
            if str(t) == name:
                result = Tag(t.jobject)
                break
        return result


Instruction:
Can you implement a function in Python 3 that
returns the Tag array obtained from the object using the specified method name.

Response:
def get_object_tags(cls, javaobject, methodname):
        """
        Instantiates the Tag array obtained from the object using the specified method name.

        Example:
        cls = Classifier(classname="weka.classifiers.meta.MultiSearch")
        tags = Tags.get_object_tags(cls, "getMetricsTags")

        :param javaobject: the javaobject to obtain the tags from
        :type javaobject: JavaObject
        :param methodname: the method name returning the Tag array
        :type methodname: str
        :return: the Tags objects
        :rtype: Tags
        """
        return Tags(jobject=javabridge.call(javaobject.jobject, methodname, "()[Lweka/core/Tag;"))


Instruction:
Can you generate the documentation for the following Python 3 function
def tags(self):
        result = []
        a = javabridge.call(self.jobject, "getTags", "()Lweka/core/Tag;]")
        length = javabridge.get_env().get_array_length(a)
        wrapped = javabridge.get_env().get_object_array_elements(a)
        for i in range(length):
            result.append(Tag(javabridge.get_env().get_string(wrapped[i])))
        return result

Response: Returns the associated tags.


Instruction:
Can you generate the documentation for the following Python 3 function
def base_object(self):
        jobj = javabridge.call(self.jobject, "getBaseObject", "()Ljava/io/Serializable;")
        if OptionHandler.check_type(jobj, "weka.core.OptionHandler"):
            return OptionHandler(jobj)
        else:
            return JavaObject(jobj)

Response: Returns the base object to apply the setups to.


Instruction:
Explain what the following Python 3 code does
def base_object(self, obj):
        if not obj.is_serializable:
            raise Exception("Base object must be serializable: " + obj.classname)
        javabridge.call(self.jobject, "setBaseObject", "(Ljava/io/Serializable;)V", obj.jobject)

Response: Sets the base object to apply the setups to.


Instruction:
Make a summary of the following Python 3 code
def parameters(self):
        array = JavaArray(javabridge.call(self.jobject, "getParameters", "()[Lweka/core/setupgenerator/AbstractParameter;"))
        result = []
        for item in array:
            result.append(AbstractParameter(jobject=item.jobject))
        return result

Response: Returns the list of currently set search parameters.


Instruction:
Can you implement a function in Python 3 that
sets the list of search parameters to use.

Response:
def parameters(self, params):
        """
        Sets the list of search parameters to use.

        :param params: list of AbstractSearchParameter objects
        :type params: list
        """
        array = JavaArray(jobject=JavaArray.new_instance("weka.core.setupgenerator.AbstractParameter", len(params)))
        for idx, obj in enumerate(params):
            array[idx] = obj.jobject
        javabridge.call(self.jobject, "setParameters", "([Lweka/core/setupgenerator/AbstractParameter;)V", array.jobject)


Instruction:
How would you explain what the following Python 3 function does
def setups(self):
        result = []
        has_options = self.base_object.is_optionhandler
        enm = javabridge.get_enumeration_wrapper(javabridge.call(self.jobject, "setups", "()Ljava/util/Enumeration;"))
        while enm.hasMoreElements():
            if has_options:
                result.append(OptionHandler(enm.nextElement()))
            else:
                result.append(JavaObject(enm.nextElement()))
        return result

Response: Generates and returns all the setups according to the parameter search space.


Instruction:
Write a Python 3 function that can
convert the object into a commandline string.

Response:
def to_commandline(o):
    """
    Turns the object into a commandline string. However, first checks whether a string represents
    a internal value placeholder (@{...}).

    :param o: the object to turn into commandline
    :type o: object
    :return: the commandline
    :rtype: str
    """
    if isinstance(o, str) and o.startswith("@{") and o.endswith("}"):
        return o
    else:
        return classes.to_commandline(o)


Instruction:
Make a summary of the following Python 3 code
def unique_name(self, name):
        result = name

        if self.parent is not None:
            index = self.index
            bname = re.sub(r'-[0-9]+$', '', name)
            names = []
            for idx, actor in enumerate(self.parent.actors):
                if idx != index:
                    names.append(actor.name)
            result = bname
            count = 0
            while result in names:
                count += 1
                result = bname + "-" + str(count)

        return result

Response: Generates a unique name for the current object.


Instruction:
Given the following Python 3 function, write the documentation
def parent(self, parent):
        self._name = self.unique_name(self._name)
        self._full_name = None
        self._logger = None
        self._parent = parent

Response: Sets the parent of the actor.


Instruction:
Explain what the following Python 3 code does
def full_name(self):
        if self._full_name is None:
            fn = self.name.replace(".", "\\.")
            parent = self._parent
            if parent is not None:
                fn = parent.full_name + "." + fn
            self._full_name = fn

        return self._full_name

Response: Gets the full name of the actor.


Instruction:
Write a Python 3 script for
fixing the options if necessary. I. e. it adds all required elements to the dictionary.

Response:
def fix_config(self, options):
        """
        Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.

        :param options: the options to fix
        :type options: dict
        :return: the (potentially) fixed options
        :rtype: dict
        """
        opt = "annotation"
        if opt not in options:
            options[opt] = None
        if opt not in self.help:
            self.help[opt] = "The (optional) annotation for this actor (string)."

        opt = "skip"
        if opt not in options:
            options[opt] = False
        if opt not in self.help:
            self.help[opt] = "Whether to skip (disable) this actor (bool)."

        return super(Actor, self).fix_config(options)


Instruction:
Create a Python 3 function for
returning a dictionary that represents this object to be used for JSONification.

Response:
def to_dict(self):
        """
        Returns a dictionary that represents this object, to be used for JSONification.

        :return: the object dictionary
        :rtype: dict
        """
        result = super(Actor, self).to_dict()
        result["type"] = "Actor"
        result["name"] = self.name
        return result


Instruction:
How would you implement a function in Python 3 that
restores an object state from a dictionary.

Response:
def from_dict(cls, d):
        """
        Restores an object state from a dictionary, used in de-JSONification.

        :param d: the object dictionary
        :type d: dict
        :return: the object
        :rtype: object
        """
        conf = {}
        for k in d["config"]:
            v = d["config"][k]
            if isinstance(v, dict):
                if u"type" in v:
                    typestr = v[u"type"]
                else:
                    typestr = v["type"]
                conf[str(k)] = classes.get_dict_handler(typestr)(v)
            else:
                conf[str(k)] = v
        return classes.get_class(d["class"])(name=d["name"], config=conf)


Instruction:
How would you implement a function in Python 3 that
resolves the option name in internal storage.

Response:
def resolve_option(self, name, default=None):
        """
        Resolves the option, i.e., interprets "@{...}" values and retrievs them instead from internal
        storage.

        :param name: the name of the option
        :type name: str
        :param default: the optional default value
        :type default: object
        :return: the resolved value
        :rtype: object
        """
        value = self.config[name]
        if value is None:
            return default
        elif isinstance(value, str) \
                and value.startswith("@{") \
                and value.endswith("}") \
                and (value.find("@{", 1) == -1):
            stname = value[2:len(value)-1]
            if (self.storagehandler is not None) and (stname in self.storagehandler.storage):
                return self.storagehandler.storage[stname]
            else:
                return default
        else:
            return value


Instruction:
Implement a function in Python 3 to
return the storage handler available to thise actor.

Response:
def storagehandler(self):
        """
        Returns the storage handler available to thise actor.

        :return: the storage handler, None if not available
        """
        if isinstance(self, StorageHandler):
            return self
        elif self.parent is not None:
            return self.parent.storagehandler
        else:
            return None


Instruction:
Create a Python 3 function for
executing the actor. :return: None if successful, otherwise error message :rtype: str

Response:
def execute(self):
        """
        Executes the actor.

        :return: None if successful, otherwise error message
        :rtype: str
        """
        if self.skip:
            return None

        result = self.pre_execute()
        if result is None:
            try:
                result = self.do_execute()
            except Exception as e:
                result = traceback.format_exc()
                print(self.full_name + "\n" + result)
        if result is None:
            result = self.post_execute()
        return result


Instruction:
Make a summary of the following Python 3 code
def output(self):
        if (self._output is None) or (len(self._output) == 0):
            result = None
        else:
            result = self._output.pop(0)
        return result

Response: Returns the next available output token.


Instruction:
Given the following Python 3 function, write the documentation
def expand(self, s):
        result = s
        while result.find("@{") > -1:
            start = result.index("@{")
            end = result.index("}", start)
            name = result[start + 2:end]
            value = self.storage[name]
            if value is None:
                raise("Storage value '" + name + "' not present, failed to expand string: " + s)
            else:
                result = result[0:start] + str(value) + result[end + 1:]
        return result

Response:
Expands all occurrences of "@{...}" within the string with the actual values currently stored
        in internal storage.


Instruction:
How would you explain what the following Python 3 function does
def extract(cls, padded):
        if padded.startswith("@{") and padded.endswith("}"):
            return padded[2:len(padded)-1]
        else:
            return padded

Response: Extracts the name from the padded string.


Instruction:
Implement a Python 3 function for
fixing the options if necessary. I. e. it adds all required elements to the dictionary.

Response:
def fix_config(self, options):
        """
        Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.

        :param options: the options to fix
        :type options: dict
        :return: the (potentially) fixed options
        :rtype: dict
        """
        options = super(ActorHandler, self).fix_config(options)

        opt = "actors"
        if opt not in options:
            options[opt] = self.default_actors()
        if opt not in self.help:
            self.help[opt] = "The list of sub-actors that this actor manages."

        return options


Instruction:
Can you create a Python 3 function that
returns a dictionary that represents this object to be used for JSONification.

Response:
def to_dict(self):
        """
        Returns a dictionary that represents this object, to be used for JSONification.

        :return: the object dictionary
        :rtype: dict
        """
        result = super(ActorHandler, self).to_dict()
        result["type"] = "ActorHandler"
        del result["config"]["actors"]
        result["actors"] = []
        for actor in self.actors:
            result["actors"].append(actor.to_dict())
        return result


Instruction:
Create a Python 3 function to
restore an object state from a dictionary.

Response:
def from_dict(cls, d):
        """
        Restores an object state from a dictionary, used in de-JSONification.

        :param d: the object dictionary
        :type d: dict
        :return: the object
        :rtype: object
        """
        result = super(ActorHandler, cls).from_dict(d)
        if "actors" in d:
            l = d["actors"]
            for e in l:
                if u"type" in e:
                    typestr = e[u"type"]
                else:
                    typestr = e["type"]
                result.actors.append(classes.get_dict_handler(typestr)(e))
        return result


Instruction:
Can you tell what is the following Python 3 function doing
def actors(self, actors):
        if actors is None:
            actors = self.default_actors()
        self.check_actors(actors)
        self.config["actors"] = actors

Response: Sets the sub - actors of the actor.


Instruction:
Write a Python 3 script for
returning the count of active actors.

Response:
def active(self):
        """
        Returns the count of non-skipped actors.

        :return: the count
        :rtype: int
        """
        result = 0
        for actor in self.actors:
            if not actor.skip:
                result += 1
        return result


Instruction:
Can you tell what is the following Python 3 function doing
def first_active(self):
        result = None
        for actor in self.actors:
            if not actor.skip:
                result = actor
                break
        return result

Response: Returns the first non - skipped actor.


Instruction:
Can you write a function in Python 3 where it
returns the last non - skipped actor.

Response:
def last_active(self):
        """
        Returns the last non-skipped actor.

        :return: the last active actor, None if not available
        :rtype: Actor
        """
        result = None
        for actor in reversed(self.actors):
            if not actor.skip:
                result = actor
                break
        return result


Instruction:
Make a summary of the following Python 3 code
def index_of(self, name):
        result = -1
        for index, actor in enumerate(self.actors):
            if actor.name == name:
                result = index
                break
        return result

Response: Returns the index of the actor with the given name.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def setup(self):
        result = super(ActorHandler, self).setup()
        if result is None:
            self.update_parent()
            try:
                self.check_actors(self.actors)
            except Exception as e:
                result = str(e)
        if result is None:
            for actor in self.actors:
                name = actor.name
                newname = actor.unique_name(actor.name)
                if name != newname:
                    actor.name = newname
        if result is None:
            for actor in self.actors:
                if actor.skip:
                    continue
                result = actor.setup()
                if result is not None:
                    break
        if result is None:
            result = self._director.setup()
        return result

Response: Sets up the actor before execution.


Instruction:
Can you write a function in Python 3 where it
wraps up the actor handler.

Response:
def wrapup(self):
        """
        Finishes up after execution finishes, does not remove any graphical output.
        """
        for actor in self.actors:
            if actor.skip:
                continue
            actor.wrapup()
        super(ActorHandler, self).wrapup()


Instruction:
Explain what the following Python 3 code does
def cleanup(self):
        for actor in self.actors:
            if actor.skip:
                continue
            actor.cleanup()
        super(ActorHandler, self).cleanup()

Response: Cleanup all resources that were created by the actor handler.


Instruction:
Write a Python 3 function that can
stop execution of the object.

Response:
def stop_execution(self):
        """
        Triggers the stopping of the object.
        """
        if not (self._stopping or self._stopped):
            for actor in self.owner.actors:
                actor.stop_execution()
            self._stopping = True


Instruction:
How would you explain what the following Python 3 function does
def check_actors(self, actors):
        super(Flow, self).check_actors(actors)
        actor = self.first_active
        if (actor is not None) and not base.is_source(actor):
            raise Exception("First active actor is not a source: " + actor.full_name)

Response: Checks that the given actors are valid. Raises an exception if invalid setup.


Instruction:
How would you code a function in Python 3 to
load the flow from a JSON file.

Response:
def load(cls, fname):
        """
        Loads the flow from a JSON file.

        :param fname: the file to load
        :type fname: str
        :return: the flow
        :rtype: Flow
        """
        with open(fname) as f:
            content = f.readlines()
        return Flow.from_json(''.join(content))


Instruction:
Implement a function in Python 3 to
create a new director instance for handling the sub - actors.

Response:
def new_director(self):
        """
        Creates the director to use for handling the sub-actors.

        :return: the director instance
        :rtype: Director
        """
        result = SequentialDirector(self)
        result.record_output = False
        result.allow_source = False
        return result


Instruction:
Implement a Python 3 function for
checking that the given list of actors are valid. Raises an exception if invalid setup.

Response:
def check_actors(self, actors):
        """
        Performs checks on the actors that are to be used. Raises an exception if invalid setup.

        :param actors: the actors to check
        :type actors: list
        """
        super(Sequence, self).check_actors(actors)
        actor = self.first_active
        if (actor is not None) and not isinstance(actor, InputConsumer):
            raise Exception("First active actor does not accept input: " + actor.full_name)


Instruction:
Make a summary of the following Python 3 code
def do_execute(self):
        self.first_active.input = self.input
        result = self._director.execute()
        if result is None:
            self._output.append(self.input)
        return result

Response: Execute the actor s director and return the result.


Instruction:
Can you tell what is the following Python 3 function doing
def fix_config(self, options):
        options = super(Tee, self).fix_config(options)

        opt = "condition"
        if opt not in options:
            options[opt] = "True"
        if opt not in self.help:
            self.help[opt] = "The (optional) condition for teeing off the tokens; uses the 'eval' method, "\
                             "ie the expression must evaluate to a boolean value; storage values placeholders "\
                             "'@{...}' get replaced with their string representations before evaluating the "\
                             "expression (string)."

        return options

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
Can you tell what is the following Python 3 function doing
def check_actors(self, actors):
        super(Tee, self).check_actors(actors)
        actor = self.first_active
        if actor is None:
            if self._requires_active_actors:
                raise Exception("No active actor!")
        elif not isinstance(actor, InputConsumer):
            raise Exception("First active actor does not accept input: " + actor.full_name)

Response: Checks that the given actors are valid. Raises an exception if invalid setup.


Instruction:
How would you implement a function in Python 3 that
fixes the options if necessary. I. e. it adds all required elements to the dictionary.

Response:
def fix_config(self, options):
        """
        Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.

        :param options: the options to fix
        :type options: dict
        :return: the (potentially) fixed options
        :rtype: dict
        """
        options = super(Trigger, self).fix_config(options)

        opt = "condition"
        if opt not in options:
            options[opt] = "True"
        if opt not in self.help:
            self.help[opt] = "The (optional) condition for teeing off the tokens; uses the 'eval' method, "\
                             "ie the expression must evaluate to a boolean value; storage values placeholders "\
                             "'@{...}' get replaced with their string representations before evaluating the "\
                             "expression (string)."

        return options


Instruction:
Can you generate a brief explanation for the following Python 3 code
def check_actors(self):
        actors = []
        for actor in self.owner.actors:
            if actor.skip:
                continue
            actors.append(actor)
        if len(actors) == 0:
            return
        for actor in actors:
            if not isinstance(actor, InputConsumer):
                raise Exception("Actor does not accept any input: " + actor.full_name)

Response: Checks the actors of the owner. Raises an exception if invalid.


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

        result = None
        self._stopped = False
        self._stopping = False

        for actor in self.owner.actors:
            if self.is_stopping() or self.is_stopped():
                break
            actor.input = self.owner.input
            result = actor.execute()
            if result is not None:
                break

        return result

Response:
Actual execution of the director.

        :return: None if successful, otherwise error message
        :rtype: str


Instruction:
Write a Python 3 script to
fix the options if necessary. I. e. it adds all required elements to the dictionary.

Response:
def fix_config(self, options):
        """
        Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.

        :param options: the options to fix
        :type options: dict
        :return: the (potentially) fixed options
        :rtype: dict
        """
        options = super(ContainerValuePicker, self).fix_config(options)

        opt = "value"
        if opt not in options:
            options[opt] = "Model"
        if opt not in self.help:
            self.help[opt] = "The name of the container value to pick from the container (string)."

        opt = "switch"
        if opt not in options:
            options[opt] = False
        if opt not in self.help:
            self.help[opt] = "Whether to switch the ouputs, i.e., forward the container to the sub-flow and the " \
                             + "container value to the following actor instead (bool)."

        return options


Instruction:
How would you explain what the following Python 3 function does
def fix_config(self, options):
        options = super(CommandlineToAny, self).fix_config(options)

        opt = "wrapper"
        if opt not in options:
            options[opt] = "weka.core.classes.OptionHandler"
        if opt not in self.help:
            self.help[opt] = "The name of the wrapper class to use (string)."

        return options

Response: Fixes the options if necessary. I. e. it adds all required elements to the dictionary.


Instruction:
Can you write a function in Python 3 where it
checks if the input object is a valid ISO 3166 - 1 version of the object. Raises an exception if unsupported.

Response:
def check_input(self, obj):
        """
        Performs checks on the input object. Raises an exception if unsupported.

        :param obj: the object to check
        :type obj: object
        """
        if isinstance(obj, str):
            return
        if isinstance(obj, unicode):
            return
        raise Exception("Unsupported class: " + self._input.__class__.__name__)


Instruction:
Make a summary of the following Python 3 code
def convert(self):
        cname = str(self.config["wrapper"])
        self._output = classes.from_commandline(self._input, classname=cname)
        return None

Response: Performs the actual conversion.


Instruction:
How would you explain what the following Python 3 function does
def plot_experiment(mat, title="Experiment", axes_swapped=False, measure="Statistic", show_stdev=False,
                    key_loc="lower right", outfile=None, wait=True):
    """
    Plots the results from an experiment.

    :param mat: the result matrix to plot
    :type mat: ResultMatrix
    :param title: the title for the experiment
    :type title: str
    :param axes_swapped: whether the axes whether swapped ("sets x cls" or "cls x sets")
    :type axes_swapped: bool
    :param measure: the measure that is being displayed
    :type measure: str
    :param show_stdev: whether to show the standard deviation as error bar
    :type show_stdev: bool
    :param key_loc: the location string for the key
    :type key_loc: str
    :param outfile: the output file, ignored if None
    :type outfile: str
    :param wait: whether to wait for the user to close the plot
    :type wait: bool
    """

    if not plot.matplotlib_available:
        logger.error("Matplotlib is not installed, plotting unavailable!")
        return

    if not isinstance(mat, ResultMatrix):
        logger.error("Need to supply a result matrix!")
        return

    fig, ax = plt.subplots()
    if axes_swapped:
        ax.set_xlabel(measure)
        ax.set_ylabel("Classifiers")
    else:
        ax.set_xlabel("Classifiers")
        ax.set_ylabel(measure)
    ax.set_title(title)
    fig.canvas.set_window_title(title)
    ax.grid(True)
    ticksx = []
    ticks = []
    inc = 1.0 / float(mat.columns)
    for i in range(mat.columns):
        ticksx.append((i + 0.5) * inc)
        ticks.append("[" + str(i+1) + "]")
    plt.xticks(ticksx, ticks)
    plt.xlim([0.0, 1.0])
    for r in range(mat.rows):
        x = []
        means = []
        stdevs = []
        for c in range(mat.columns):
            mean = mat.get_mean(c, r)
            stdev = mat.get_stdev(c, r)
            if not math.isnan(mean):
                x.append((c + 0.5) * inc)
                means.append(mean)
                if not math.isnan(stdev):
                    stdevs.append(stdev)
        plot_label = mat.get_row_name(r)
        if show_stdev:
            ax.errorbar(x, means, yerr=stdevs, fmt='-o', ls="-", label=plot_label)
        else:
            ax.plot(x, means, "o-", label=plot_label)
    plt.draw()
    plt.legend(loc=key_loc, shadow=True)
    if outfile is not None:
        plt.savefig(outfile)
    if wait:
        plt.show()

Response: Plots the results from an experiment.


Instruction:
Here you have a function in Python 3, explain what it does
def create_subsample(data, percent, seed=1):
    if percent <= 0 or percent >= 100:
        return data
    data = Instances.copy_instances(data)
    data.randomize(Random(seed))
    data = Instances.copy_instances(data, 0, int(round(data.num_instances * percent / 100.0)))
    return data

Response: Generates a subsample of the dataset.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def predictions_to_instances(data, preds):
    if len(preds) == 0:
        return None

    is_numeric = isinstance(preds[0], NumericPrediction)

    # create header
    atts = []
    if is_numeric:
        atts.append(Attribute.create_numeric("index"))
        atts.append(Attribute.create_numeric("weight"))
        atts.append(Attribute.create_numeric("actual"))
        atts.append(Attribute.create_numeric("predicted"))
        atts.append(Attribute.create_numeric("error"))
    else:
        atts.append(Attribute.create_numeric("index"))
        atts.append(Attribute.create_numeric("weight"))
        atts.append(data.class_attribute.copy(name="actual"))
        atts.append(data.class_attribute.copy(name="predicted"))
        atts.append(Attribute.create_nominal("error", ["no", "yes"]))
        atts.append(Attribute.create_numeric("classification"))
        for i in range(data.class_attribute.num_values):
            atts.append(Attribute.create_numeric("distribution-" + data.class_attribute.value(i)))

    result = Instances.create_instances("Predictions", atts, len(preds))

    count = 0
    for pred in preds:
        count += 1
        if is_numeric:
            values = array([count, pred.weight, pred.actual, pred.predicted, pred.error])
        else:
            if pred.actual == pred.predicted:
                error = 0.0
            else:
                error = 1.0
            l = [count, pred.weight, pred.actual, pred.predicted, error, max(pred.distribution)]
            for i in range(data.class_attribute.num_values):
                l.append(pred.distribution[i])
            values = array(l)
        inst = Instance.create_instance(values)
        result.add_instance(inst)

    return result

Response: Converts the predictions to Instances object.