Instruction:
Write a Python 3 script to
create a subset of entries from the current choice set.

Response:
def extract_subset(self, *constants):
        """Create a subset of entries

        This subset is a new ``Choices`` instance, with only the wanted constants from the
        main ``Choices`` (each "choice entry" in the subset is shared from the main ``Choices``)

        Parameters
        ----------
        *constants: list
            The constants names of this ``Choices`` object to make available in the subset.

        Returns
        -------
        Choices
            The newly created subset, which is a ``Choices`` object

        Example
        -------

        >>> STATES = Choices(
        ...     ('ONLINE',  1, 'Online'),
        ...     ('DRAFT',   2, 'Draft'),
        ...     ('OFFLINE', 3, 'Offline'),
        ... )
        >>> STATES
        [('ONLINE', 1, 'Online'), ('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
        >>> subset = STATES.extract_subset('DRAFT', 'OFFLINE')
        >>> subset
        [('DRAFT', 2, 'Draft'), ('OFFLINE', 3, 'Offline')]
        >>> subset.DRAFT
        2
        >>> subset.for_constant('DRAFT') is STATES.for_constant('DRAFT')
        True
        >>> subset.ONLINE
        Traceback (most recent call last):
        ...
        AttributeError: 'Choices' object has no attribute 'ONLINE'

        Raises
        ------
        ValueError
            If a constant is not defined as a constant in the ``Choices`` instance.

        """

        # Ensure that all passed constants exists as such in the list of available constants.
        bad_constants = set(constants).difference(self.constants)
        if bad_constants:
            raise ValueError("All constants in subsets should be in parent choice. "
                             "Missing constants: %s." % list(bad_constants))

        # Keep only entries we asked for.
        choice_entries = [self.constants[c] for c in constants]

        # Create a new ``Choices`` instance with the limited set of entries, and pass the other
        # configuration attributes to share the same behavior as the current ``Choices``.
        # Also we set ``mutable`` to False to disable the possibility to add new choices to the
        # subset.
        subset = self.__class__(
            *choice_entries,
            **{
                'dict_class': self.dict_class,
                'mutable': False,
            }
        )

        return subset


Instruction:
Can you generate the documentation for the following Python 3 function
def add_subset(self, name, constants):

        # Ensure that the name is not already used as an attribute.
        if hasattr(self, name):
            raise ValueError("Cannot use '%s' as a subset name. "
                             "It's already an attribute." % name)

        subset = self.extract_subset(*constants)

        # Make the subset accessible via an attribute.
        setattr(self, name, subset)
        self.subsets.append(name)

Response: Add a subset of entries under a defined name.


Instruction:
Write a Python 3 script for
converting the list of choices into a list of display values.

Response:
def _convert_choices(self, choices):
        """Auto create display values then call super method"""

        final_choices = []
        for choice in choices:

            if isinstance(choice, ChoiceEntry):
                final_choices.append(choice)
                continue

            original_choice = choice
            choice = list(choice)
            length = len(choice)

            assert 2 <= length <= 4, 'Invalid number of entries in %s' % (original_choice,)

            final_choice = []

            # do we have attributes?
            if length > 2 and isinstance(choice[-1], Mapping):
                final_choice.append(choice.pop())
            elif length == 4:
                attributes = choice.pop()
                assert attributes is None or isinstance(attributes, Mapping), 'Last argument must be a dict-like object in %s' % (original_choice,)
                if attributes:
                    final_choice.append(attributes)

            # the constant
            final_choice.insert(0, choice.pop(0))

            # the db value
            final_choice.insert(1, choice.pop(0))

            if len(choice):
                # we were given a display value
                final_choice.insert(2, choice.pop(0))
            else:
                # no display value, we compute it from the constant
                final_choice.insert(2, self.display_transform(final_choice[0]))

            final_choices.append(final_choice)

        return super(AutoDisplayChoices, self)._convert_choices(final_choices)


Instruction:
Make a summary of the following Python 3 code
def add_choices(self, *choices, **kwargs):
        return super(AutoChoices, self).add_choices(_NO_SUBSET_NAME_, *choices, **kwargs)

Response: Disallow super method to thing the first argument is a subset name


Instruction:
Can you implement a function in Python 3 that
converts the choices to the correct format

Response:
def _convert_choices(self, choices):
        """Auto create db values then call super method"""

        final_choices = []
        for choice in choices:

            if isinstance(choice, ChoiceEntry):
                final_choices.append(choice)
                continue

            original_choice = choice
            if isinstance(choice, six.string_types):
                if choice == _NO_SUBSET_NAME_:
                    continue
                choice = [choice, ]
            else:
                choice = list(choice)

            length = len(choice)

            assert 1 <= length <= 4, 'Invalid number of entries in %s' % (original_choice,)

            final_choice = []

            # do we have attributes?
            if length > 1 and isinstance(choice[-1], Mapping):
                final_choice.append(choice.pop())
            elif length == 4:
                attributes = choice.pop()
                assert attributes is None or isinstance(attributes, Mapping), 'Last argument must be a dict-like object in %s' % (original_choice,)
                if attributes:
                    final_choice.append(attributes)

            # the constant
            final_choice.insert(0, choice.pop(0))

            if len(choice):
                # we were given a db value
                final_choice.insert(1, choice.pop(0))
                if len(choice):
                    # we were given a display value
                    final_choice.insert(2, choice.pop(0))
            else:
                # set None to compute it later
                final_choice.insert(1, None)

            if final_choice[1] is None:
                # no db value, we compute it from the constant
                final_choice[1] = self.value_transform(final_choice[0])

            final_choices.append(final_choice)

        return super(AutoChoices, self)._convert_choices(final_choices)


Instruction:
Create a Python 3 function for
converting the constant to the real choice value.

Response:
def to_python(self, value):
        """Convert the constant to the real choice value."""

        # ``is_required`` is already checked in ``validate``.
        if value is None:
            return None

        # Validate the type.
        if not isinstance(value, six.string_types):
            raise forms.ValidationError(
                "Invalid value type (should be a string).",
                code='invalid-choice-type',
            )

        # Get the constant from the choices object, raising if it doesn't exist.
        try:
            final = getattr(self.choices, value)
        except AttributeError:
            available = '[%s]' % ', '.join(self.choices.constants)
            raise forms.ValidationError(
                "Invalid value (not in available choices. Available ones are: %s" % available,
                code='non-existing-choice',
            )

        return final


Instruction:
How would you code a function in Python 3 to
create an instance of a subclass of ChoiceAttributeMixin for the given value.

Response:
def create_choice_attribute(creator_type, value, choice_entry):
    """Create an instance of a subclass of ChoiceAttributeMixin for the given value.

    Parameters
    ----------
    creator_type : type
        ``ChoiceAttributeMixin`` or a subclass, from which we'll call the ``get_class_for_value``
        class-method.
    value : ?
        The value for which we want to create an instance of a new subclass of ``creator_type``.
    choice_entry: ChoiceEntry
        The ``ChoiceEntry`` instance that hold the current value, used to access its constant,
        value and display name.

    Returns
    -------
    ChoiceAttributeMixin
        An instance of a subclass of ``creator_type`` for the given value

    """

    klass = creator_type.get_class_for_value(value)
    return klass(value, choice_entry)


Instruction:
Can you implement a function in Python 3 that
classes method to construct a new class based on this mixin and the type of the given value.

Response:
def get_class_for_value(cls, value):
        """Class method to construct a class based on this mixin and the type of the given value.

        Parameters
        ----------
        value: ?
            The value from which to extract the type to create the new class.

        Notes
        -----
        The  create classes are cached (in ``cls.__classes_by_type``) to avoid recreating already
        created classes.
        """
        type_ = value.__class__

        # Check if the type is already a ``ChoiceAttribute``
        if issubclass(type_, ChoiceAttributeMixin):
            # In this case we can return this type
            return type_

        # Create a new class only if it wasn't already created for this type.
        if type_ not in cls._classes_by_type:
            # Compute the name of the class with the name of the type.
            class_name = str('%sChoiceAttribute' % type_.__name__.capitalize())
            # Create a new class and save it in the cache.
            cls._classes_by_type[type_] = type(class_name, (cls, type_), {
                'creator_type': cls,
            })

        # Return the class from the cache based on the type.
        return cls._classes_by_type[type_]


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

        if value is None:
            raise ValueError('Using `None` in a `Choices` object is not supported. You may '
                             'use an empty string.')

        return create_choice_attribute(self.ChoiceAttributeMixin, value, self)

Response: Returns a choice attribute for the given value.


Instruction:
Can you implement a function in Python 3 that
joins given arguments into a url. Trailing but not leading slashes are stripped for each argument.

Response:
def urljoin(*args):
        """
        Joins given arguments into a url. Trailing but not leading slashes are
        stripped for each argument.
        """
        return "/".join(map(lambda x: str(x).rstrip('/'), args)).rstrip('/')


Instruction:
Can you generate the documentation for the following Python 3 function
def server_version(self):
        if self.__server_version is None:
            from yagocd.resources.info import InfoManager
            self.__server_version = InfoManager(self).version

        return self.__server_version

Response: Get the server version of the resource.


Instruction:
Can you generate the documentation for the following Python 3 function
def pipeline_name(self):
        if 'pipeline_name' in self.data and self.data.pipeline_name:
            return self.data.get('pipeline_name')
        elif self.stage.pipeline is not None:
            return self.stage.pipeline.data.name
        else:
            return self.stage.data.pipeline_name

Response: Get pipeline name of current job instance.


Instruction:
Can you write a function in Python 3 where it
gets pipeline counter of current job instance.

Response:
def pipeline_counter(self):
        """
        Get pipeline counter of current job instance.

        Because instantiating job instance could be performed in different ways and those return different results,
        we have to check where from to get counter of the pipeline.

        :return: pipeline counter.
        """
        if 'pipeline_counter' in self.data and self.data.pipeline_counter:
            return self.data.get('pipeline_counter')
        elif self.stage.pipeline is not None:
            return self.stage.pipeline.data.counter
        else:
            return self.stage.data.pipeline_counter


Instruction:
Create a Python 3 function for
getting stage name of current job instance.

Response:
def stage_name(self):
        """
        Get stage name of current job instance.

        Because instantiating job instance could be performed in different ways and those return different results,
        we have to check where from to get name of the stage.

        :return: stage name.
        """
        if 'stage_name' in self.data and self.data.stage_name:
            return self.data.get('stage_name')
        else:
            return self.stage.data.name


Instruction:
Can you generate a brief explanation for the following Python 3 code
def stage_counter(self):
        if 'stage_counter' in self.data and self.data.stage_counter:
            return self.data.get('stage_counter')
        else:
            return self.stage.data.counter

Response: Get stage counter of current job instance.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def properties(self):
        return PropertyManager(
            session=self._session,
            pipeline_name=self.pipeline_name,
            pipeline_counter=self.pipeline_counter,
            stage_name=self.stage_name,
            stage_counter=self.stage_counter,
            job_name=self.data.name
        )

Response: Property for accessing the current job.


Instruction:
How would you implement a function in Python 3 that
returns url for accessing the current instance of this object.

Response:
def url(self):
        """
        Returns url for accessing stage instance.
        """
        return "{server_url}/go/pipelines/{pipeline_name}/{pipeline_counter}/{stage_name}/{stage_counter}".format(
            server_url=self._session.server_url,
            pipeline_name=self.pipeline_name,
            pipeline_counter=self.pipeline_counter,
            stage_name=self.data.name,
            stage_counter=self.data.counter,
        )


Instruction:
Can you implement a function in Python 3 that
gets pipeline name of current stage instance.

Response:
def pipeline_name(self):
        """
        Get pipeline name of current stage instance.

        Because instantiating stage instance could be performed in different ways and those return different results,
        we have to check where from to get name of the pipeline.

        :return: pipeline name.
        """
        if 'pipeline_name' in self.data:
            return self.data.get('pipeline_name')
        elif self.pipeline is not None:
            return self.pipeline.data.name


Instruction:
Can you tell what is the following Python 3 function doing
def pipeline_counter(self):
        if 'pipeline_counter' in self.data:
            return self.data.get('pipeline_counter')
        elif self.pipeline is not None:
            return self.pipeline.data.counter

Response: Get pipeline counter of current stage instance.


Instruction:
Create a Python 3 function for
canceling an active pipeline of a specified stage.

Response:
def cancel(self):
        """
        Cancel an active stage of a specified stage.

        :return: a text confirmation.
        """
        return self._manager.cancel(pipeline_name=self.pipeline_name, stage_name=self.stage_name)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def jobs(self):
        jobs = list()
        for data in self.data.jobs:
            jobs.append(JobInstance(session=self._session, data=data, stage=self))

        return jobs

Response: Method for getting jobs from stage instance.


Instruction:
Make a summary of the following Python 3 code
def job(self, name):
        for job in self.jobs():
            if job.data.name == name:
                return job

Response: Method for searching specific job by it s name.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def agents(self):
        if self._agent_manager is None:
            self._agent_manager = AgentManager(session=self._session)
        return self._agent_manager

Response: Property for accessing AgentManager instance which is used to manage agents.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def configurations(self):
        if self._configuration_manager is None:
            self._configuration_manager = ConfigurationManager(session=self._session)
        return self._configuration_manager

Response: Property for accessing configuration manager instance which is used to manage configurations.


Instruction:
Can you generate the documentation for the following Python 3 function
def encryption(self):
        if self._encryption_manager is None:
            self._encryption_manager = EncryptionManager(session=self._session)
        return self._encryption_manager

Response: Property for accessing encryption manager instance


Instruction:
Here you have a function in Python 3, explain what it does
def elastic_profiles(self):
        if self._elastic_agent_profile_manager is None:
            self._elastic_agent_profile_manager = ElasticAgentProfileManager(session=self._session)
        return self._elastic_agent_profile_manager

Response: Property for accessing ElasticAgentProfileManager instance


Instruction:
Explain what the following Python 3 code does
def environments(self):
        if self._environment_manager is None:
            self._environment_manager = EnvironmentManager(session=self._session)
        return self._environment_manager

Response: Property for accessing environment manager instance which is used to manage environments.


Instruction:
Can you tell what is the following Python 3 function doing
def feeds(self):
        if self._feed_manager is None:
            self._feed_manager = FeedManager(session=self._session)
        return self._feed_manager

Response: Property for accessing the FeedManager instance which is used to manage feeds.


Instruction:
How would you explain what the following Python 3 function does
def jobs(self):
        if self._job_manager is None:
            self._job_manager = JobManager(session=self._session)
        return self._job_manager

Response: Property for accessing the JobManager instance which is used to manage feeds.


Instruction:
Given the following Python 3 function, write the documentation
def pipeline_configs(self):
        if self._pipeline_config_manager is None:
            self._pipeline_config_manager = PipelineConfigManager(session=self._session)
        return self._pipeline_config_manager

Response: Property for accessing PipelineConfigManager instance which is used to manage pipeline configurations.


Instruction:
Given the following Python 3 function, write the documentation
def plugin_info(self):
        if self._plugin_info_manager is None:
            self._plugin_info_manager = PluginInfoManager(session=self._session)
        return self._plugin_info_manager

Response: Property for accessing the PluginInfoManager instance which is used to manage pipeline configurations.


Instruction:
Here you have a function in Python 3, explain what it does
def scms(self):
        if self._scm_manager is None:
            self._scm_manager = SCMManager(session=self._session)
        return self._scm_manager

Response: Property for accessing the SCM manager instance which is used to manage pluggable SCM materials.


Instruction:
Given the following Python 3 function, write the documentation
def templates(self):
        if self._template_manager is None:
            self._template_manager = TemplateManager(session=self._session)
        return self._template_manager

Response: Property for accessing the TemplateManager instance which is used to manage templates.


Instruction:
How would you explain what the following Python 3 function does
def versions(self):
        if self._version_manager is None:
            self._version_manager = VersionManager(session=self._session)
        return self._version_manager

Response: Property for accessing version. VersionManager instance which is used to get server info.


Instruction:
Can you generate the documentation for the following Python 3 function
def url(self):
        return self.get_url(server_url=self._session.server_url, pipeline_name=self.data.name)

Response: Returns the url for accessing the current pipeline entity.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def config(self):
        return PipelineConfigManager(session=self._session, pipeline_name=self.data.name)

Response: Property for accessing pipeline configuration.


Instruction:
Write a Python 3 function for
returning the pipeline history for this pipeline.

Response:
def history(self, offset=0):
        """
        The pipeline history allows users to list pipeline instances.

        :param offset: number of pipeline instances to be skipped.
        :return: an array of pipeline instances :class:`yagocd.resources.pipeline.PipelineInstance`.
        :rtype: list of yagocd.resources.pipeline.PipelineInstance
        """
        return self._pipeline.history(name=self.data.name, offset=offset)


Instruction:
Make a summary of the following Python 3 code
def get(self, counter):
        return self._pipeline.get(name=self.data.name, counter=counter)

Response: Gets pipeline instance object.


Instruction:
Can you generate the documentation for the following Python 3 function
def pause(self, cause):
        self._pipeline.pause(name=self.data.name, cause=cause)

Response: Pause the current pipeline.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def schedule(self, materials=None, variables=None, secure_variables=None):
        return self._pipeline.schedule(
            name=self.data.name,
            materials=materials,
            variables=variables,
            secure_variables=secure_variables
        )

Response: Schedules a specific pipeline for the current user to set the environment variables.


Instruction:
How would you code a function in Python 3 to
schedule a new instance of the current object and return it.

Response:
def schedule_with_instance(
        self,
        materials=None,
        variables=None,
        secure_variables=None,
        backoff=0.5,
        max_tries=20
    ):
        """
        Schedule pipeline and return instance.
        Credits of implementation comes to `gaqzi`:
        https://github.com/gaqzi/py-gocd/blob/master/gocd/api/pipeline.py#L122

        :warning: Replace this with whatever is the official way as soon as gocd#990 is fixed. \
        https://github.com/gocd/gocd/issues/990

        :param materials: material revisions to use.
        :param variables: environment variables to set.
        :param secure_variables: secure environment variables to set.
        :param backoff: time to wait before checking for new instance.
        :param max_tries: maximum tries to do.
        :return: possible triggered instance of pipeline.
        :rtype: yagocd.resources.pipeline.PipelineInstance
        """
        return self._pipeline.schedule_with_instance(
            name=self.data.name,
            materials=materials,
            variables=variables,
            secure_variables=secure_variables,
            backoff=backoff,
            max_tries=max_tries
        )


Instruction:
Can you tell what is the following Python 3 function doing
def pipeline_url(self):
        return PipelineEntity.get_url(server_url=self._session.server_url, pipeline_name=self.data.name)

Response: Returns the url for accessing the pipeline entity.


Instruction:
Here you have a function in Python 3, explain what it does
def _accept_header(self):
        if not self.VERSION_TO_ACCEPT_HEADER:
            return self.ACCEPT_HEADER

        return YagocdUtil.choose_option(
            version_to_options=self.VERSION_TO_ACCEPT_HEADER,
            default=self.ACCEPT_HEADER,
            server_version=self._session.server_version
        )

Response: Method for determining correct Accept header.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_predecessors(self, transitive=False):
        result = self._predecessors
        if transitive:
            return YagocdUtil.graph_depth_walk(result, lambda v: v.predecessors)
        return result

Response: Property for getting predecessors of current pipeline.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_descendants(self, transitive=False):
        result = self._descendants
        if transitive:
            return YagocdUtil.graph_depth_walk(result, lambda v: v.descendants)
        return result

Response: Property for getting descendants of current pipeline.


Instruction:
Create a Python 3 function to
validate a given launch request.

Response:
def validate_launch_request(
            self,
            launch_url,
            headers,
            args
    ):
        """
        Validate a given launch request

        launch_url: Full URL that the launch request was POSTed to
        headers: k/v pair of HTTP headers coming in with the POST
        args: dictionary of body arguments passed to the launch_url
            Must have the following keys to be valid:
                oauth_consumer_key, oauth_timestamp, oauth_nonce,
                oauth_signature
        """

        # Validate args!
        if 'oauth_consumer_key' not in args:
            raise web.HTTPError(401, "oauth_consumer_key missing")
        if args['oauth_consumer_key'] not in self.consumers:
            raise web.HTTPError(401, "oauth_consumer_key not known")

        if 'oauth_signature' not in args:
            raise web.HTTPError(401, "oauth_signature missing")
        if 'oauth_timestamp' not in args:
            raise web.HTTPError(401, 'oauth_timestamp missing')

        # Allow 30s clock skew between LTI Consumer and Provider
        # Also don't accept timestamps from before our process started, since that could be
        # a replay attack - we won't have nonce lists from back then. This would allow users
        # who can control / know when our process restarts to trivially do replay attacks.
        oauth_timestamp = int(float(args['oauth_timestamp']))
        if (
                int(time.time()) - oauth_timestamp > 30
                or oauth_timestamp < LTILaunchValidator.PROCESS_START_TIME
        ):
            raise web.HTTPError(401, "oauth_timestamp too old")

        if 'oauth_nonce' not in args:
            raise web.HTTPError(401, 'oauth_nonce missing')
        if (
                oauth_timestamp in LTILaunchValidator.nonces
                and args['oauth_nonce'] in LTILaunchValidator.nonces[oauth_timestamp]
        ):
            raise web.HTTPError(401, "oauth_nonce + oauth_timestamp already used")
        LTILaunchValidator.nonces.setdefault(oauth_timestamp, set()).add(args['oauth_nonce'])

        args_list = []
        for key, values in args.items():
            if type(values) is list:
                args_list += [(key, value) for value in values]
            else:
                args_list.append((key, values))

        base_string = signature.construct_base_string(
            'POST',
            signature.normalize_base_string_uri(launch_url),
            signature.normalize_parameters(
                signature.collect_parameters(body=args_list, headers=headers)
            )
        )

        consumer_secret = self.consumers[args['oauth_consumer_key']]

        sign = signature.sign_hmac_sha1(base_string, consumer_secret, None)
        is_valid = signature.safe_string_equals(sign, args['oauth_signature'])

        if not is_valid:
            raise web.HTTPError(401, "Invalid oauth_signature")

        return True


Instruction:
Write a Python 3 script to
enable plotting in the iPython notebook.

Response:
def enable_ipython(self, **kwargs):
        """
        Enable plotting in the iPython notebook.

        Once enabled, all lightning plots will be automatically produced
        within the iPython notebook. They will also be available on
        your lightning server within the current session.
        """

        # inspired by code powering similar functionality in mpld3
        # https://github.com/jakevdp/mpld3/blob/master/mpld3/_display.py#L357

        from IPython.core.getipython import get_ipython
        from IPython.display import display, Javascript, HTML

        self.ipython_enabled = True
        self.set_size('medium')

        ip = get_ipython()
        formatter = ip.display_formatter.formatters['text/html']

        if self.local_enabled:
            from lightning.visualization import VisualizationLocal
            js = VisualizationLocal.load_embed()
            display(HTML("<script>" + js + "</script>"))
            if not self.quiet:
                print('Running local mode, some functionality limited.\n')
            formatter.for_type(VisualizationLocal, lambda viz, kwds=kwargs: viz.get_html())
        else:
            formatter.for_type(Visualization, lambda viz, kwds=kwargs: viz.get_html())
            r = requests.get(self.get_ipython_markup_link(), auth=self.auth)
            display(Javascript(r.text))


Instruction:
Can you implement a function in Python 3 that
disables plotting in the iPython notebook.

Response:
def disable_ipython(self):
        """
        Disable plotting in the iPython notebook.

        After disabling, lightning plots will be produced in your lightning server,
        but will not appear in the notebook.
        """
        from IPython.core.getipython import get_ipython

        self.ipython_enabled = False
        ip = get_ipython()
        formatter = ip.display_formatter.formatters['text/html']
        formatter.type_printers.pop(Visualization, None)
        formatter.type_printers.pop(VisualizationLocal, None)


Instruction:
Make a summary of the following Python 3 code
def create_session(self, name=None):
        self.session = Session.create(self, name=name)
        return self.session

Response: Create a lightning session.


Instruction:
Explain what the following Python 3 code does
def use_session(self, session_id):
        self.session = Session(lgn=self, id=session_id)
        return self.session

Response: Use the specified lightning session.


Instruction:
Write a Python 3 script for
setting the host for a lightning server.

Response:
def set_host(self, host):
        """
        Set the host for a lightning server.

        Host can be local (e.g. http://localhost:3000), a heroku
        instance (e.g. http://lightning-test.herokuapp.com), or
        a independently hosted lightning server.
        """
        if host[-1] == '/':
            host = host[:-1]

        self.host = host
        return self


Instruction:
Here you have a function in Python 3, explain what it does
def check_status(self):
        try:
            r = requests.get(self.host + '/status', auth=self.auth,
                             timeout=(10.0, 10.0))
            if not r.status_code == requests.codes.ok:
                print("Problem connecting to server at %s" % self.host)
                print("status code: %s" % r.status_code)
                return False
            else:
                print("Connected to server at %s" % self.host)
                return True
        except (requests.exceptions.ConnectionError,
                requests.exceptions.MissingSchema,
                requests.exceptions.InvalidSchema) as e:
            print("Problem connecting to server at %s" % self.host)
            print("error: %s" % e)
            return False

Response: Check the server for status


Instruction:
Can you tell what is the following Python 3 function doing
def _clean_data(cls, *args, **kwargs):

        datadict = cls.clean(*args, **kwargs)

        if 'data' in datadict:
            data = datadict['data']
            data = cls._ensure_dict_or_list(data)
        else:
            data = {}
            for key in datadict:
                if key == 'images':
                    data[key] = datadict[key]
                else:
                    d = cls._ensure_dict_or_list(datadict[key])
                    data[key] = cls._check_unkeyed_arrays(key, d)

        return data

Response: Convert raw data into a dictionary with plot - type specific methods.


Instruction:
Here you have a function in Python 3, explain what it does
def _baseplot(cls, session, type, *args, **kwargs):

        if not type:
            raise Exception("Must provide a plot type")

        options, description = cls._clean_options(**kwargs)
        data = cls._clean_data(*args)

        if 'images' in data and len(data) > 1:
            images = data['images']
            del data['images']
            viz = cls._create(session, data=data, type=type, options=options, description=description)
            first_image, remaining_images = images[0], images[1:]
            viz._append_image(first_image)
            for image in remaining_images:
                viz._append_image(image)

        elif 'images' in data:
            images = data['images']
            viz = cls._create(session, images=images, type=type, options=options, description=description)

        else:
            viz = cls._create(session, data=data, type=type, options=options, description=description)

        return viz

Response: Base method for plotting data and images.


Instruction:
Can you create a Python 3 function that
updates the data of the object with the given args and kwargs.

Response:
def update(self, *args, **kwargs):
        """
        Base method for updating data.

        Applies a plot-type specific cleaning operation, then
        updates the data in the visualization.
        """

        data = self._clean_data(*args, **kwargs)
        if 'images' in data:
            images = data['images']
            for img in images:
                self._update_image(img)
        else:
            self._update_data(data=data)


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

        data = self._clean_data(*args, **kwargs)
        if 'images' in data:
            images = data['images']
            for img in images:
                self._append_image(img)
        else:
            self._append_data(data=data)

Response: Base method for appending data to the visualization.


Instruction:
Can you write a function in Python 3 where it
gets user data from a viz.

Response:
def _get_user_data(self):
        """
        Base method for retrieving user data from a viz.
        """

        url = self.session.host + '/sessions/' + str(self.session.id) + '/visualizations/' + str(self.id) + '/settings/'
        r = requests.get(url)
        if r.status_code == 200:
            content = r.json()
        else:
            raise Exception('Error retrieving user data from server')

        return content


Instruction:
How would you explain what the following Python 3 function does
def check_property(prop, name, **kwargs):

    checkers = {
        'color': check_color,
        'alpha': check_alpha,
        'size': check_size,
        'thickness': check_thickness,
        'index': check_index,
        'coordinates': check_coordinates,
        'colormap': check_colormap,
        'bins': check_bins,
        'spec': check_spec
    }

    if name in checkers:
        return checkers[name](prop, **kwargs)
    elif isinstance(prop, list) or isinstance(prop, ndarray) or isscalar(prop):
        return check_1d(prop, name)
    else:
        return prop

Response: Check and parse a property with a specific checking function or a generic parser


Instruction:
How would you explain what the following Python 3 function does
def check_coordinates(co, xy=None):
    if isinstance(co, ndarray):
        co = co.tolist()
    if not (isinstance(co[0][0], list) or isinstance(co[0][0], tuple)):
        co = [co]
    if xy is not True:
        co = map(lambda p: asarray(p)[:, ::-1].tolist(), co)
    return co

Response: Check and parse coordinates as either a single coordinate list or a sequence of coordinates for multiple regions.


Instruction:
Can you create a Python 3 function that
checks and parse color specs as either a single r g b or a list of tuples of r g b.

Response:
def check_color(c):
    """
    Check and parse color specs as either a single [r,g,b] or a list of
    [[r,g,b],[r,g,b]...]
    """

    c = asarray(c)
    if c.ndim == 1:
        c = c.flatten()
        c = c[newaxis, :]
        if c.shape[1] != 3:
            raise Exception("Color must have three values per point")
    elif c.ndim == 2:
        if c.shape[1] != 3:
            raise Exception("Color array must have three values per point")
    return c


Instruction:
How would you explain what the following Python 3 function does
def check_colormap(cmap):
    names = set(['BrBG', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
                 'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu',
                 'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd',
                 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'Lightning'])
    if cmap not in names:
        raise Exception("Invalid cmap '%s',  must be one of %s" % (cmap, names))
    else:
        return cmap

Response: Check if cmap is one of the colorbrewer maps


Instruction:
Given the following Python 3 function, write the documentation
def check_size(s):

    s = check_1d(s, "size")
    if any(map(lambda d: d <= 0, s)):
        raise Exception('Size cannot be 0 or negative')

    return s

Response: Check and parse size specs as either a single list or a list of [ s... ]


Instruction:
Can you tell what is the following Python 3 function doing
def check_thickness(s):

    s = check_1d(s, "thickness")
    if any(map(lambda d: d <= 0, s)):
        raise Exception('Thickness cannot be 0 or negative')

    return s

Response: Check and parse thickness specs as either a single string or a list of strings


Instruction:
How would you implement a function in Python 3 that
checks and parses an index spec

Response:
def check_index(i):
    """
    Checks and parses an index spec, must be a one-dimensional array [i0, i1, ...]
    """

    i = asarray(i)
    if (i.ndim > 1) or (size(i) < 1):
        raise Exception("Index must be one-dimensional and non-singleton")

    return i


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

    a = check_1d(a, "alpha")
    if any(map(lambda d: d <= 0, a)):
        raise Exception('Alpha cannot be 0 or negative')

    return a

Response: Check and parse alpha specs as either a single list or a list of [ a... ]


Instruction:
Make a summary of the following Python 3 code
def check_1d(x, name):

    x = asarray(x)
    if size(x) == 1:
        x = asarray([x])
    if x.ndim == 2:
        raise Exception("Property: %s must be one-dimensional" % name)
    x = x.flatten()

    return x

Response: Check and parse a one - dimensional spec as either a single [ x x... ] or a list of [ x x... ]


Instruction:
How would you implement a function in Python 3 that
gives a list of pairs of points which define a polygon return a binary mask covering the interior of the polygon with dimensions dim

Response:
def polygon_to_mask(coords, dims, z=None):
    """
    Given a list of pairs of points which define a polygon, return a binary
    mask covering the interior of the polygon with dimensions dim
    """

    bounds = array(coords).astype('int')
    path = Path(bounds)

    grid = meshgrid(range(dims[1]), range(dims[0]))
    grid_flat = zip(grid[0].ravel(), grid[1].ravel())

    mask = path.contains_points(grid_flat).reshape(dims[0:2]).astype('int')

    if z is not None:
        if len(dims) < 3:
            raise Exception('Dims must have three-dimensions for embedding z-index')
        if z >= dims[2]:
            raise Exception('Z-index %g exceeds third dimension %g' % (z, dims[2]))
        tmp = zeros(dims)
        tmp[:, :, z] = mask
        mask = tmp

    return mask


Instruction:
Write a Python 3 function for
giving a list of pairs of points which define a polygon return a list of points interior to the polygon

Response:
def polygon_to_points(coords, z=None):
    """
    Given a list of pairs of points which define a polygon,
    return a list of points interior to the polygon
    """

    bounds = array(coords).astype('int')

    bmax = bounds.max(0)
    bmin = bounds.min(0)

    path = Path(bounds)

    grid = meshgrid(range(bmin[0], bmax[0]+1), range(bmin[1], bmax[1]+1))

    grid_flat = zip(grid[0].ravel(), grid[1].ravel())

    points = path.contains_points(grid_flat).reshape(grid[0].shape).astype('int')
    points = where(points)
    points = (vstack([points[0], points[1]]).T + bmin[-1::-1]).tolist()
    if z is not None:
        points = map(lambda p: [p[0], p[1], z], points)

    return points


Instruction:
Can you write a function in Python 3 where it
saves self - contained html to a file.

Response:
def save_html(self, filename=None, overwrite=False):
        """
        Save self-contained html to a file.

        Parameters
        ----------
        filename : str
            The filename to save to
        """

        if filename is None:
            raise ValueError('Please provide a filename, e.g. viz.save_html(filename="viz.html").')

        import os
        base = self._html
        js = self.load_embed()
        if os.path.exists(filename):
            if overwrite is False:
                raise ValueError("File '%s' exists. To ovewrite call save_html with overwrite=True."
                                 % os.path.abspath(filename))
            else:
                os.remove(filename)
        with open(filename, "wb") as f:
            f.write(base.encode('utf-8'))
            f.write('<script>' + js.encode('utf-8') + '</script>')


Instruction:
Create a Python 3 function for
defaulting 503 handler, which looks for the requested URL in the redirects table, redirects if found, and displays 404 page if not redirected. Templates: ``503.html`` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/')

Response:
def temporary_unavailable(request, template_name='503.html'):
    """
    Default 503 handler, which looks for the requested URL in the
    redirects table, redirects if found, and displays 404 page if not
    redirected.

    Templates: ``503.html``
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')

    """
    context = {
        'request_path': request.path,
    }
    return http.HttpResponseTemporaryUnavailable(
        render_to_string(template_name, context))


Instruction:
Can you implement a function in Python 3 that
tries to simplify a SpecifierSet by combining redundant specifiers.

Response:
def simplify_specifiers(spec):
    """Try to simplify a SpecifierSet by combining redundant specifiers."""

    def key(s):
        return (s.version, 1 if s.operator in ['>=', '<'] else 2)

    def in_bounds(v, lo, hi):
        if lo and v not in lo:
            return False
        if hi and v not in hi:
            return False
        return True

    def err(reason='inconsistent'):
        return ValueError('{} specifier set {}'.format(reason, spec))

    gt = None
    lt = None
    eq = None
    ne = []

    for i in spec:
        if i.operator == '==':
            if eq is None:
                eq = i
            elif eq != i:  # pragma: no branch
                raise err()
        elif i.operator == '!=':
            ne.append(i)
        elif i.operator in ['>', '>=']:
            gt = i if gt is None else max(gt, i, key=key)
        elif i.operator in ['<', '<=']:
            lt = i if lt is None else min(lt, i, key=key)
        else:
            raise err('invalid')

    ne = [i for i in ne if in_bounds(i.version, gt, lt)]
    if eq:
        if ( any(i.version in eq for i in ne) or
             not in_bounds(eq.version, gt, lt)):
            raise err()
        return SpecifierSet(str(eq))
    if lt and gt:
        if lt.version not in gt or gt.version not in lt:
            raise err()
        if ( gt.version == lt.version and gt.operator == '>=' and
             lt.operator == '<='):
            return SpecifierSet('=={}'.format(gt.version))

    return SpecifierSet(
        ','.join(str(i) for i in chain(iterate(gt), iterate(lt), ne))
    )


Instruction:
Can you tell what is the following Python 3 function doing
def make_node(cls, func_name, lineno, type_=None):
        entry = global_.SYMBOL_TABLE.declare_func(func_name, lineno, type_=type_)
        if entry is None:
            return None

        entry.declared = True
        return cls(entry, lineno)

Response: This will return a node with the symbol as a function.


Instruction:
Write a Python 3 function that can
check the function types

Response:
def check_type(*args, **kwargs):
    ''' Checks the function types
    '''
    args = tuple(x if isinstance(x, collections.Iterable) else (x,) for x in args)
    kwargs = {x: kwargs[x] if isinstance(kwargs[x], collections.Iterable) else (kwargs[x],) for x in kwargs}

    def decorate(func):
        types = args
        kwtypes = kwargs
        gi = "Got <{}> instead"
        errmsg1 = "to be of type <{}>. " + gi
        errmsg2 = "to be one of type ({}). " + gi
        errar = "{}:{} expected '{}' "
        errkw = "{}:{} expected {} "

        def check(*ar, **kw):
            line = inspect.getouterframes(inspect.currentframe())[1][2]
            fname = os.path.basename(inspect.getouterframes(inspect.currentframe())[1][1])

            for arg, type_ in zip(ar, types):
                if type(arg) not in type_:
                    if len(type_) == 1:
                        raise TypeError((errar + errmsg1).format(fname, line, arg, type_[0].__name__,
                                                                 type(arg).__name__))
                    else:
                        raise TypeError((errar + errmsg2).format(fname, line, arg,
                                                                 ', '.join('<%s>' % x.__name__ for x in type_),
                                                                 type(arg).__name__))
            for kwarg in kw:
                if kwtypes.get(kwarg, None) is None:
                    continue
                if type(kw[kwarg]) not in kwtypes[kwarg]:
                    if len(kwtypes[kwarg]) == 1:
                        raise TypeError((errkw + errmsg1).format(fname, line, kwarg, kwtypes[kwarg][0].__name__,
                                                                 type(kw[kwarg]).__name__))
                    else:
                        raise TypeError((errkw + errmsg2).format(
                            fname,
                            line,
                            kwarg,
                            ', '.join('<%s>' % x.__name__ for x in kwtypes[kwarg]),
                            type(kw[kwarg]).__name__)
                        )

            return func(*ar, **kw)

        return check

    return decorate


Instruction:
Write a Python 3 function for
mapping the given string into a unique label ID.

Response:
def add_string_label(self, str_):
        """ Maps ("folds") the given string, returning an unique label ID.
        This allows several constant labels to be initialized to the same address
        thus saving memory space.
        :param str_: the string to map
        :return: the unique label ID
        """
        if self.STRING_LABELS.get(str_, None) is None:
            self.STRING_LABELS[str_] = backend.tmp_label()

        return self.STRING_LABELS[str_]


Instruction:
Create a Python 3 function to
convert a backend type from api. constants to a SymbolTYPE object.

Response:
def TYPE(type_):
        """ Converts a backend type (from api.constants)
        to a SymbolTYPE object (taken from the SYMBOL_TABLE).
        If type_ is already a SymbolTYPE object, nothing
        is done.
        """
        if isinstance(type_, symbols.TYPE):
            return type_

        assert TYPE.is_valid(type_)
        return gl.SYMBOL_TABLE.basic_types[type_]


Instruction:
Write a Python 3 script for
converting the given args to a Quad and store it in the memory.

Response:
def emit(*args):
        """ Convert the given args to a Quad (3 address code) instruction
        """
        quad = Quad(*args)
        __DEBUG__('EMIT ' + str(quad))
        MEMORY.append(quad)


Instruction:
Explain what the following Python 3 code does
def traverse_const(node):
        if node.token == 'NUMBER':
            return node.t

        if node.token == 'UNARY':
            mid = node.operator
            if mid == 'MINUS':
                result = ' -' + Translator.traverse_const(node.operand)
            elif mid == 'ADDRESS':
                if node.operand.scope == SCOPE.global_ or node.operand.token in ('LABEL', 'FUNCTION'):
                    result = Translator.traverse_const(node.operand)
                else:
                    syntax_error_not_constant(node.operand.lineno)
                    return
            else:
                raise InvalidOperatorError(mid)
            return result

        if node.token == 'BINARY':
            mid = node.operator
            if mid == 'PLUS':
                mid = '+'
            elif mid == 'MINUS':
                mid = '-'
            elif mid == 'MUL':
                mid = '*'
            elif mid == 'DIV':
                mid = '/'
            elif mid == 'MOD':
                mid = '%'
            elif mid == 'POW':
                mid = '^'
            elif mid == 'SHL':
                mid = '>>'
            elif mid == 'SHR':
                mid = '<<'
            else:
                raise InvalidOperatorError(mid)

            return '(%s) %s (%s)' % (Translator.traverse_const(node.left), mid, Translator.traverse_const(node.right))

        if node.token == 'TYPECAST':
            if node.type_ in (Type.byte_, Type.ubyte):
                return '(' + Translator.traverse_const(node.operand) + ') & 0xFF'
            if node.type_ in (Type.integer, Type.uinteger):
                return '(' + Translator.traverse_const(node.operand) + ') & 0xFFFF'
            if node.type_ in (Type.long_, Type.ulong):
                return '(' + Translator.traverse_const(node.operand) + ') & 0xFFFFFFFF'
            if node.type_ == Type.fixed:
                return '((' + Translator.traverse_const(node.operand) + ') & 0xFFFF) << 16'
            syntax_error_cant_convert_to_type(node.lineno, str(node.operand), node.type_)
            return

        if node.token in ('VAR', 'VARARRAY', 'LABEL', 'FUNCTION'):
            # TODO: Check what happens with local vars and params
            return node.t

        if node.token == 'CONST':
            return Translator.traverse_const(node.expr)

        if node.token == 'ARRAYACCESS':
            return '({} + {})'.format(node.entry.mangled, node.offset)

        raise InvalidCONSTexpr(node)

Response: Traverse a constant and returns an arithmetic expression that represents the constant.


Instruction:
How would you explain what the following Python 3 function does
def check_attr(node, n):
        if len(node.children) > n:
            return node.children[n]

Response:
Check if ATTR has to be normalized
            after this instruction has been translated
            to intermediate code.


Instruction:
How would you explain what the following Python 3 function does
def emit_var_assign(self, var, t):
        p = '*' if var.byref else ''  # Indirection prefix
        if self.O_LEVEL > 1 and not var.accessed:
            return

        if not var.type_.is_basic:
            raise NotImplementedError()

        if var.scope == SCOPE.global_:
            self.emit('store' + self.TSUFFIX(var.type_), var.mangled, t)
        elif var.scope == SCOPE.parameter:
            self.emit('pstore' + self.TSUFFIX(var.type_), p + str(var.offset), t)
        elif var.scope == SCOPE.local:
            if var.alias is not None and var.alias.class_ == CLASS.array:
                var.offset -= 1 + 2 * var.alias.count
            self.emit('pstore' + self.TSUFFIX(var.type_), p + str(-var.offset), t)

Response: Emits code for storing a value into a variable in a specific location.


Instruction:
Implement a function in Python 3 to
return the label for the loop type which is the loop exit.

Response:
def loop_exit_label(self, loop_type):
        """ Returns the label for the given loop type which
        exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO'
        """
        for i in range(len(self.LOOPS) - 1, -1, -1):
            if loop_type == self.LOOPS[i][0]:
                return self.LOOPS[i][1]

        raise InvalidLoopError(loop_type)


Instruction:
Implement a function in Python 3 to
return the label for the loop type which is the loop_type that continues the loop.

Response:
def loop_cont_label(self, loop_type):
        """ Returns the label for the given loop type which
        continues the loop. loop_type must be one of 'FOR', 'WHILE', 'DO'
        """
        for i in range(len(self.LOOPS) - 1, -1, -1):
            if loop_type == self.LOOPS[i][0]:
                return self.LOOPS[i][2]

        raise InvalidLoopError(loop_type)


Instruction:
How would you explain what the following Python 3 function does
def default_value(cls, type_, expr):  # TODO: This function must be moved to api.xx
        assert isinstance(type_, symbols.TYPE)
        assert type_.is_basic
        assert check.is_static(expr)

        if isinstance(expr, (symbols.CONST, symbols.VAR)):  # a constant expression like @label + 1
            if type_ in (cls.TYPE(TYPE.float_), cls.TYPE(TYPE.string)):
                syntax_error(expr.lineno, "Can't convert non-numeric value to {0} at compile time".format(type_.name))
                return ['<ERROR>']

            val = Translator.traverse_const(expr)
            if type_.size == 1:  # U/byte
                if expr.type_.size != 1:
                    return ['#({0}) & 0xFF'.format(val)]
                else:
                    return ['#{0}'.format(val)]

            if type_.size == 2:  # U/integer
                if expr.type_.size != 2:
                    return ['##({0}) & 0xFFFF'.format(val)]
                else:
                    return ['##{0}'.format(val)]

            if type_ == cls.TYPE(TYPE.fixed):
                return ['0000', '##({0}) & 0xFFFF'.format(val)]

            # U/Long
            return ['##({0}) & 0xFFFF'.format(val), '##(({0}) >> 16) & 0xFFFF'.format(val)]

        if type_ == cls.TYPE(TYPE.float_):
            C, DE, HL = _float(expr.value)
            C = C[:-1]  # Remove 'h' suffix
            if len(C) > 2:
                C = C[-2:]

            DE = DE[:-1]  # Remove 'h' suffix
            if len(DE) > 4:
                DE = DE[-4:]
            elif len(DE) < 3:
                DE = '00' + DE

            HL = HL[:-1]  # Remove 'h' suffix
            if len(HL) > 4:
                HL = HL[-4:]
            elif len(HL) < 3:
                HL = '00' + HL

            return [C, DE[-2:], DE[:-2], HL[-2:], HL[:-2]]

        if type_ == cls.TYPE(TYPE.fixed):
            value = 0xFFFFFFFF & int(expr.value * 2 ** 16)
        else:
            value = int(expr.value)

        result = [value, value >> 8, value >> 16, value >> 24]
        result = ['%02X' % (v & 0xFF) for v in result]
        return result[:type_.size]

Response: Returns a list of bytes for the current value of the given type.


Instruction:
Create a Python 3 function to
return a list of bytes which represents the array initial value.

Response:
def array_default_value(type_, values):
        """ Returns a list of bytes (as hexadecimal 2 char string)
        which represents the array initial value.
        """
        if not isinstance(values, list):
            return Translator.default_value(type_, values)

        l = []
        for row in values:
            l.extend(Translator.array_default_value(type_, row))

        return l


Instruction:
Here you have a function in Python 3, explain what it does
def has_control_chars(i):
        if not hasattr(i, 'type_'):
            return False

        if i.type_ != Type.string:
            return False

        if i.token in ('VAR', 'PARAMDECL'):
            return True  # We don't know what an alphanumeric variable will hold

        if i.token == 'STRING':
            for c in i.value:
                if 15 < ord(c) < 22:  # is it an attr char?
                    return True
            return False

        for j in i.children:
            if Translator.has_control_chars(j):
                return True

        return False

Response: Returns true if the passed token is an unknown string containing control chars.


Instruction:
Can you generate the documentation for the following Python 3 function
def visit_USR(self, node):
        self.emit('fparam' + self.TSUFFIX(gl.PTR_TYPE), node.children[0].t)
        self.emit('call', 'USR', node.type_.size)
        backend.REQUIRES.add('usr.asm')

Response: Emit a user call from basic


Instruction:
Can you create a Python 3 function that
copies all other attributes from the other object to this object.

Response:
def copy_attr(self, other):
        """ Copies all other attributes (not methods)
        from the other object to this instance.
        """
        if not isinstance(other, Symbol):
            return  # Nothing done if not a Symbol object

        tmp = re.compile('__.*__')
        for attr in (x for x in dir(other) if not tmp.match(x)):

            if (
                hasattr(self.__class__, attr) and
                str(type(getattr(self.__class__, attr)) in ('property', 'function', 'instancemethod'))
            ):
                continue

            val = getattr(other, attr)
            if isinstance(val, str) or str(val)[0] != '<':  # Not a value
                setattr(self, attr, val)


Instruction:
How would you implement a function in Python 3 that
defines the value of a macro. Issues a warning if the macro is already defined.

Response:
def define(self, id_, lineno, value='', fname=None, args=None):
        """ Defines the value of a macro.
        Issues a warning if the macro is already defined.
        """
        if fname is None:
            if CURRENT_FILE:
                fname = CURRENT_FILE[-1]
            else:  # If no files opened yet, use owns program fname
                fname = sys.argv[0]

        if self.defined(id_):
            i = self.table[id_]
            warning(lineno, '"%s" redefined (previous definition at %s:%i)' %
                    (i.name, i.fname, i.lineno))
        self.set(id_, lineno, value, fname, args)


Instruction:
Can you tell what is the following Python 3 function doing
def set(self, id_, lineno, value='', fname=None, args=None):
        if fname is None:
            if CURRENT_FILE:
                fname = CURRENT_FILE[-1]
            else:  # If no files opened yet, use owns program fname
                fname = sys.argv[0]
        self.table[id_] = ID(id_, args, value, lineno, fname)

Response: Set a new entry in the internal table.


Instruction:
How would you code a function in Python 3 to
return a list with two strings with two integers.

Response:
def _int_ops(op1, op2, swap=True):
    """ Receives a list with two strings (operands).
    If none of them contains integers, returns None.
    Otherwise, returns a t-uple with (op[0], op[1]),
    where op[1] is the integer one (the list is swapped)
    unless swap is False (e.g. sub and div used this
    because they're not commutative).

    The integer operand is always converted to int type.
    """
    if is_int(op1):
        if swap:
            return op2, int(op1)
        else:
            return int(op1), op2

    if is_int(op2):
        return op1, int(op2)

    return None


Instruction:
Make a summary of the following Python 3 code
def _f_ops(op1, op2, swap=True):
    if is_float(op1):
        if swap:
            return op2, float(op1)
        else:
            return float(op1), op2

    if is_float(op2):
        return op1, float(op2)

    return None

Response: Receives a list with two strings ( operands ). Returns None if there are no operands.


Instruction:
Make a summary of the following Python 3 code
def make_node(clss, node, *params):
        ''' This will return a node with a param_list
        (declared in a function declaration)
        Parameters:
            -node: A SymbolPARAMLIST instance or None
            -params: SymbolPARAMDECL insances
        '''
        if node is None:
            node = clss()

        if node.token != 'PARAMLIST':
            return clss.make_node(None, node, *params)

        for i in params:
            if i is not None:
                node.appendChild(i)

        return node

Response: This will return a node with a param_list


Instruction:
Given the following Python 3 function, write the documentation
def appendChild(self, param):
        ''' Overrides base class.
        '''
        Symbol.appendChild(self, param)
        if param.offset is None:
            param.offset = self.size
            self.size += param.size

Response: Adds a child to the end of the current object.


Instruction:
Create a Python 3 function to
create a binary node for a binary operation.

Response:
def make_node(cls, operator, left, right, lineno, func=None,
                  type_=None):
        """ Creates a binary node for a binary operation,
            e.g. A + 6 => '+' (A, 6) in prefix notation.

            Parameters:
            -operator: the binary operation token. e.g. 'PLUS' for A + 6
            -left: left operand
            -right: right operand
            -func: is a lambda function used when constant folding is applied
            -type_: resulting type (to enforce it).

            If no type_ is specified the resulting one will be guessed.
        """
        if left is None or right is None:
            return None

        a, b = left, right  # short form names
        # Check for constant non-numeric operations
        c_type = common_type(a, b)  # Resulting operation type or None
        if c_type:  # there must be a common type for a and b
            if is_numeric(a, b) and (is_const(a) or is_number(a)) and \
                    (is_const(b) or is_number(b)):
                if func is not None:
                    a = SymbolTYPECAST.make_node(c_type, a, lineno)  # ensure type
                    b = SymbolTYPECAST.make_node(c_type, b, lineno)  # ensure type
                    return SymbolNUMBER(func(a.value, b.value), type_=type_, lineno=lineno)

            if is_static(a, b):
                a = SymbolTYPECAST.make_node(c_type, a, lineno)  # ensure type
                b = SymbolTYPECAST.make_node(c_type, b, lineno)  # ensure type
                return SymbolCONST(cls(operator, a, b, lineno, type_=type_, func=func), lineno=lineno)

        if operator in ('BNOT', 'BAND', 'BOR', 'BXOR', 'NOT', 'AND', 'OR',
                        'XOR', 'MINUS', 'MULT', 'DIV', 'SHL', 'SHR') and \
                not is_numeric(a, b):
            syntax_error(lineno, 'Operator %s cannot be used with STRINGS' % operator)
            return None

        if is_string(a, b) and func is not None:  # Are they STRING Constants?
            if operator == 'PLUS':
                return SymbolSTRING(func(a.value, b.value), lineno)

            return SymbolNUMBER(int(func(a.text, b.text)), type_=TYPE.ubyte,
                                lineno=lineno)  # Convert to u8 (boolean)

        if operator in ('BNOT', 'BAND', 'BOR', 'BXOR'):
            if TYPE.is_decimal(c_type):
                c_type = TYPE.long_

        if a.type_ != b.type_ and TYPE.string in (a.type_, b.type_):
            c_type = a.type_  # Will give an error based on the fist operand

        if operator not in ('SHR', 'SHL'):
            a = SymbolTYPECAST.make_node(c_type, a, lineno)
            b = SymbolTYPECAST.make_node(c_type, b, lineno)

        if a is None or b is None:
            return None

        if type_ is None:
            if operator in ('LT', 'GT', 'EQ', 'LE', 'GE', 'NE', 'AND', 'OR',
                            'XOR', 'NOT'):
                type_ = TYPE.ubyte  # Boolean type
            else:
                type_ = c_type

        return cls(operator, a, b, type_=type_, lineno=lineno)


Instruction:
Given the following Python 3 function, write the documentation
def is_dynamic(self):
        if self is not self.final:
            return self.final.is_dynamic

        return any([x.is_dynamic for x in self.children])

Response: True if this type uses dynamic memory.


Instruction:
Write a Python 3 script to
return signed type or equivalent

Response:
def to_signed(cls, t):
        """ Return signed type or equivalent
        """
        assert isinstance(t, SymbolTYPE)
        t = t.final
        assert t.is_basic
        if cls.is_unsigned(t):
            return {cls.ubyte: cls.byte_,
                    cls.uinteger: cls.integer,
                    cls.ulong: cls.long_}[t]
        if cls.is_signed(t) or cls.is_decimal(t):
            return t
        return cls.unknown


Instruction:
Create a Python 3 function to
return the entry with the given ID in the given scope. Returns None if not found.

Response:
def get_entry(self, id_, scope=None):
        """ Returns the ID entry stored in self.table, starting
        by the first one. Returns None if not found.
        If scope is not None, only the given scope is searched.
        """
        if id_[-1] in DEPRECATED_SUFFIXES:
            id_ = id_[:-1]  # Remove it

        if scope is not None:
            assert len(self.table) > scope
            return self[scope][id_]

        for sc in self:
            if sc[id_] is not None:
                return sc[id_]

        return None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def declare(self, id_, lineno, entry):
        id2 = id_
        type_ = entry.type_

        if id2[-1] in DEPRECATED_SUFFIXES:
            id2 = id2[:-1]  # Remove it
            type_ = symbols.TYPEREF(self.basic_types[SUFFIX_TYPE[id_[-1]]], lineno)  # Overrides type_
            if entry.type_ is not None and not entry.type_.implicit and type_ != entry.type_:
                syntax_error(lineno, "expected type {2} for '{0}', got {1}".format(id_, entry.type_.name, type_.name))

        # Checks if already declared
        if self[self.current_scope][id2] is not None:
            return None

        entry.caseins = OPTIONS.case_insensitive.value
        self[self.current_scope][id2] = entry
        entry.name = id2  # Removes DEPRECATED SUFFIXES if any

        if isinstance(entry, symbols.TYPE):
            return entry  # If it's a type declaration, we're done

        # HINT: The following should be done by the respective callers!
        # entry.callable = None  # True if function, strings or arrays
        # entry.class_ = None  # TODO: important

        entry.forwarded = False  # True for a function header
        entry.mangled = '%s%s%s' % (self.mangle, global_.MANGLE_CHR, entry.name)  # Mangled name
        entry.type_ = type_  # type_ now reflects entry sigil (i.e. a$ => 'string' type) if any
        entry.scopeRef = self[self.current_scope]

        return entry

Response: Check that the id is already declared in the current scope and creates and returns it. If it is a type declaration and the caller function raises the syntax error.


Instruction:
Make a summary of the following Python 3 code
def check_is_declared(self, id_, lineno, classname='identifier',
                          scope=None, show_error=True):
        """ Checks if the given id is already defined in any scope
            or raises a Syntax Error.

            Note: classname is not the class attribute, but the name of
            the class as it would appear on compiler messages.
        """
        result = self.get_entry(id_, scope)
        if isinstance(result, symbols.TYPE):
            return True

        if result is None or not result.declared:
            if show_error:
                syntax_error(lineno, 'Undeclared %s "%s"' % (classname, id_))
            return False
        return True

Response: Checks if the given id is already declared in any scope.


Instruction:
Implement a function in Python 3 to
check if the given identifier is not already declared. Returns True if OK False otherwise.

Response:
def check_is_undeclared(self, id_, lineno, classname='identifier',
                            scope=None, show_error=False):
        """ The reverse of the above.

        Check the given identifier is not already declared. Returns True
        if OK, False otherwise.
        """
        result = self.get_entry(id_, scope)
        if result is None or not result.declared:
            return True

        if scope is None:
            scope = self.current_scope

        if show_error:
            syntax_error(lineno,
                         'Duplicated %s "%s" (previous one at %s:%i)' %
                         (classname, id_, self.table[scope][id_].filename,
                          self.table[scope][id_].lineno))
        return False


Instruction:
How would you explain what the following Python 3 function does
def check_class(self, id_, class_, lineno, scope=None, show_error=True):
        assert CLASS.is_valid(class_)
        entry = self.get_entry(id_, scope)
        if entry is None or entry.class_ == CLASS.unknown:  # Undeclared yet
            return True

        if entry.class_ != class_:
            if show_error:
                if entry.class_ == CLASS.array:
                    a1 = 'n'
                else:
                    a1 = ''
                if class_ == CLASS.array:
                    a2 = 'n'
                else:
                    a2 = ''
                syntax_error(lineno, "identifier '%s' is a%s %s, not a%s %s" %
                             (id_, a1, entry.class_, a2, class_))
            return False

        return True

Response: Check the class of the given identifier.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def enter_scope(self, funcname):
        old_mangle = self.mangle
        self.mangle = '%s%s%s' % (self.mangle, global_.MANGLE_CHR, funcname)
        self.table.append(SymbolTable.Scope(self.mangle, parent_mangle=old_mangle))
        global_.META_LOOPS.append(global_.LOOPS)  # saves current LOOPS state
        global_.LOOPS = []

Response: Enter a new variable scope.


Instruction:
Here you have a function in Python 3, explain what it does
def leave_scope(self):
        def entry_size(entry):
            """ For local variables and params, returns the real variable or
            local array size in bytes
            """
            if entry.scope == SCOPE.global_ or \
                    entry.is_aliased:  # aliases or global variables = 0
                return 0

            if entry.class_ != CLASS.array:
                return entry.size

            return entry.memsize

        for v in self.table[self.current_scope].values(filter_by_opt=False):
            if not v.accessed:
                if v.scope == SCOPE.parameter:
                    kind = 'Parameter'
                    v.accessed = True  # HINT: Parameters must always be present even if not used!
                    warning_not_used(v.lineno, v.name, kind=kind)

        entries = sorted(self.table[self.current_scope].values(filter_by_opt=True), key=entry_size)
        offset = 0

        for entry in entries:  # Symbols of the current level
            if entry.class_ is CLASS.unknown:
                self.move_to_global_scope(entry.name)

            if entry.class_ in (CLASS.function, CLASS.label, CLASS.type_):
                continue

            # Local variables offset
            if entry.class_ == CLASS.var and entry.scope == SCOPE.local:
                if entry.alias is not None:  # alias of another variable?
                    if entry.offset is None:
                        entry.offset = entry.alias.offset
                    else:
                        entry.offset = entry.alias.offset - entry.offset
                else:
                    offset += entry_size(entry)
                    entry.offset = offset

            if entry.class_ == CLASS.array and entry.scope == SCOPE.local:
                entry.offset = entry_size(entry) + offset
                offset = entry.offset

        self.mangle = self[self.current_scope].parent_mangle
        self.table.pop()
        global_.LOOPS = global_.META_LOOPS.pop()
        return offset

Response: Ends a function body and pops current scope out of the symbol table.


Instruction:
How would you explain what the following Python 3 function does
def move_to_global_scope(self, id_):
        # In the current scope and more than 1 scope?
        if id_ in self.table[self.current_scope].keys(filter_by_opt=False) and len(self.table) > 1:
            symbol = self.table[self.current_scope][id_]
            symbol.offset = None
            symbol.scope = SCOPE.global_
            if symbol.class_ != CLASS.label:
                symbol.mangled = "%s%s%s" % (self.table[self.global_scope].mangle, global_.MANGLE_CHR, id_)

            self.table[self.global_scope][id_] = symbol
            del self.table[self.current_scope][id_]  # Removes it from the current scope
            __DEBUG__("'{}' entry moved to global scope".format(id_))

Response: Move the given id to the global scope.


Instruction:
Make a summary of the following Python 3 code
def make_static(self, id_):
        entry = self.table[self.current_scope][id_]
        entry.scope = SCOPE.global_
        self.table[self.global_scope][entry.mangled] = entry

Response: Make a static variable in the current scope.


Instruction:
Can you create a Python 3 function that
accesses a symbol by its identifier and checks if it exists and if it is an implicit declared variable.

Response:
def access_id(self, id_, lineno, scope=None, default_type=None, default_class=CLASS.unknown):
        """ Access a symbol by its identifier and checks if it exists.
        If not, it's supposed to be an implicit declared variable.

        default_class is the class to use in case of an undeclared-implicit-accessed id
        """
        if isinstance(default_type, symbols.BASICTYPE):
            default_type = symbols.TYPEREF(default_type, lineno, implicit=False)
        assert default_type is None or isinstance(default_type, symbols.TYPEREF)

        if not check_is_declared_explicit(lineno, id_):
            return None

        result = self.get_entry(id_, scope)
        if result is None:
            if default_type is None:
                default_type = symbols.TYPEREF(self.basic_types[global_.DEFAULT_IMPLICIT_TYPE],
                                               lineno, implicit=True)

            result = self.declare_variable(id_, lineno, default_type)
            result.declared = False  # It was implicitly declared
            result.class_ = default_class
            return result

        # The entry was already declared. If it's type is auto and the default type is not None,
        # update its type.
        if default_type is not None and result.type_ == self.basic_types[TYPE.auto]:
            result.type_ = default_type
            warning_implicit_type(lineno, id_, default_type)

        return result


Instruction:
Here you have a function in Python 3, explain what it does
def access_var(self, id_, lineno, scope=None, default_type=None):
        result = self.access_id(id_, lineno, scope, default_type)
        if result is None:
            return None

        if not self.check_class(id_, CLASS.var, lineno, scope):
            return None

        assert isinstance(result, symbols.VAR)
        result.class_ = CLASS.var

        return result

Response: Access a variable in the current context.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def access_array(self, id_, lineno, scope=None, default_type=None):
        if not self.check_is_declared(id_, lineno, 'array', scope):
            return None

        if not self.check_class(id_, CLASS.array, lineno, scope):
            return None

        return self.access_id(id_, lineno, scope=scope, default_type=default_type)

Response: Called when an accessed variable is expected to be an array. Returns the object that is used to access the array.


Instruction:
Implement a function in Python 3 to
access a function in the current scope.

Response:
def access_func(self, id_, lineno, scope=None, default_type=None):
        """
        Since ZX BASIC allows access to undeclared functions, we must allow
        and *implicitly* declare them if they are not declared already.
        This function just checks if the id_ exists and returns its entry if so.
        Otherwise, creates an implicit declared variable entry and returns it.
        """
        assert default_type is None or isinstance(default_type, symbols.TYPEREF)

        result = self.get_entry(id_, scope)
        if result is None:
            if default_type is None:
                if global_.DEFAULT_IMPLICIT_TYPE == TYPE.auto:
                    default_type = symbols.TYPEREF(self.basic_types[TYPE.auto], lineno, implicit=True)
                else:
                    default_type = symbols.TYPEREF(self.basic_types[global_.DEFAULT_TYPE], lineno, implicit=True)

            return self.declare_func(id_, lineno, default_type)

        if not self.check_class(id_, CLASS.function, lineno, scope):
            return None

        return result


Instruction:
Write a Python 3 function for
creating a func array or string call. Checks if id is callable or not. Returns None if it is not callable.

Response:
def access_call(self, id_, lineno, scope=None, type_=None):
        """ Creates a func/array/string call. Checks if id is callable or not.
        An identifier is "callable" if it can be followed by a list of para-
        meters.
        This does not mean the id_ is a function, but that it allows the same
        syntax a function does:

        For example:
           - MyFunction(a, "hello", 5) is a Function so MyFuncion is callable
           - MyArray(5, 3.7, VAL("32")) makes MyArray identifier "callable".
           - MyString(5 TO 7) or MyString(5) is a "callable" string.
        """
        entry = self.access_id(id_, lineno, scope, default_type=type_)
        if entry is None:
            return self.access_func(id_, lineno)

        if entry.callable is False:  # Is it NOT callable?
            if entry.type_ != self.basic_types[TYPE.string]:
                syntax_error_not_array_nor_func(lineno, id_)
                return None
            else:  # Ok, it is a string slice if it has 0 or 1 parameters
                return entry

        if entry.callable is None and entry.type_ == self.basic_types[TYPE.string]:
            # Ok, it is a string slice if it has 0 or 1 parameters
            entry.callable = False
            return entry

        # Mangled name (functions always has _name as mangled)
        # entry.mangled = '_%s' % entry.name
        # entry.callable = True  # HINT: must be true already
        return entry


Instruction:
Make a summary of the following Python 3 code
def declare_variable(self, id_, lineno, type_, default_value=None):
        assert isinstance(type_, symbols.TYPEREF)
        if not self.check_is_undeclared(id_, lineno, scope=self.current_scope, show_error=False):
            entry = self.get_entry(id_)
            if entry.scope == SCOPE.parameter:
                syntax_error(lineno,
                             "Variable '%s' already declared as a parameter "
                             "at %s:%i" % (id_, entry.filename, entry.lineno))
            else:
                syntax_error(lineno, "Variable '%s' already declared at "
                                     "%s:%i" % (id_, entry.filename, entry.lineno))
            return None

        if not self.check_class(id_, CLASS.var, lineno, scope=self.current_scope):
            return None

        entry = (self.get_entry(id_, scope=self.current_scope) or
                 self.declare(id_, lineno, symbols.VAR(id_, lineno, class_=CLASS.var)))
        __DEBUG__("Entry %s declared with class %s at scope %i" % (entry.name, CLASS.to_string(entry.class_),
                                                                   self.current_scope))

        if entry.type_ is None or entry.type_ == self.basic_types[TYPE.unknown]:
            entry.type_ = type_

        if entry.type_ != type_:
            if not type_.implicit and entry.type_ is not None:
                syntax_error(lineno,
                             "'%s' suffix is for type '%s' but it was "
                             "declared as '%s'" %
                             (id_, entry.type_, type_))
                return None
                # type_ = entry.type_  # TODO: Unused??

        entry.scope = SCOPE.global_ if self.current_scope == self.global_scope else SCOPE.local
        entry.callable = False
        entry.class_ = CLASS.var  # HINT: class_ attribute could be erased if access_id was used.
        entry.declared = True  # marks it as declared

        if entry.type_.implicit and entry.type_ != self.basic_types[TYPE.unknown]:
            warning_implicit_type(lineno, id_, entry.type_.name)

        if default_value is not None and entry.type_ != default_value.type_:
            if is_number(default_value):
                default_value = symbols.TYPECAST.make_node(entry.type_, default_value,
                                                           lineno)
                if default_value is None:
                    return None
            else:
                syntax_error(lineno,
                             "Variable '%s' declared as '%s' but initialized "
                             "with a '%s' value" %
                             (id_, entry.type_, default_value.type_))
                return None

        entry.default_value = default_value
        return entry

Response: This method declares a variable in the database.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def declare_type(self, type_):
        assert isinstance(type_, symbols.TYPE)
        # Checks it's not a basic type
        if not type_.is_basic and type_.name.lower() in TYPE.TYPE_NAMES.values():
            syntax_error(type_.lineno, "'%s' is a basic type and cannot be redefined" %
                         type_.name)
            return None

        if not self.check_is_undeclared(type_.name, type_.lineno, scope=self.current_scope, show_error=True):
            return None

        entry = self.declare(type_.name, type_.lineno, type_)
        return entry

Response: Declares a type. Checks that the given type is not already declared in the current scope and that it s not a basic type. Returns the type_ Symbol or None on error.


Instruction:
Can you tell what is the following Python 3 function doing
def declare_label(self, id_, lineno):
        # TODO: consider to make labels private
        id1 = id_
        id_ = str(id_)

        if not self.check_is_undeclared(id_, lineno, 'label'):
            entry = self.get_entry(id_)
            syntax_error(lineno, "Label '%s' already used at %s:%i" %
                         (id_, entry.filename, entry.lineno))
            return entry

        entry = self.get_entry(id_)
        if entry is not None and entry.declared:
            if entry.is_line_number:
                syntax_error(lineno, "Duplicated line number '%s'. "
                                     "Previous was at %i" % (entry.name, entry.lineno))
            else:
                syntax_error(lineno, "Label '%s' already declared at line %i" %
                             (id_, entry.lineno))
            return None

        entry = (self.get_entry(id_, scope=self.current_scope) or
                 self.get_entry(id_, scope=self.global_scope) or
                 self.declare(id_, lineno, symbols.LABEL(id_, lineno)))
        if entry is None:
            return None

        if not isinstance(entry, symbols.LABEL):
            entry = symbols.VAR.to_label(entry)

        if id_[0] == '.':
            id_ = id_[1:]
            # HINT: ??? Mangled name. Just the label, 'cause it starts with '.'
            entry.mangled = '%s' % id_
        else:
            # HINT: Mangled name. Labels are __LABEL__
            entry.mangled = '__LABEL__%s' % entry.name

        entry.is_line_number = isinstance(id1, int)

        if global_.FUNCTION_LEVEL:
            entry.scope_owner = list(global_.FUNCTION_LEVEL)

        self.move_to_global_scope(id_)  # Labels are always global # TODO: not in the future
        entry.declared = True
        entry.type_ = self.basic_types[global_.PTR_TYPE]
        return entry

Response:
Declares a label (line numbers are also labels).
            Unlike variables, labels are always global.


Instruction:
How would you explain what the following Python 3 function does
def declare_param(self, id_, lineno, type_=None):
        if not self.check_is_undeclared(id_, lineno, classname='parameter',
                                        scope=self.current_scope, show_error=True):
            return None

        entry = self.declare(id_, lineno, symbols.PARAMDECL(id_, lineno, type_))
        if entry is None:
            return
        entry.declared = True
        if entry.type_.implicit:
            warning_implicit_type(lineno, id_, type_)
        return entry

Response:
Declares a parameter
        Check if entry.declared is False. Otherwise raises an error.


Instruction:
Implement a function in Python 3 to
declare an array in the symbol table. Error if already exists.

Response:
def declare_array(self, id_, lineno, type_, bounds, default_value=None):
        """ Declares an array in the symbol table (VARARRAY). Error if already
        exists.
        """
        assert isinstance(type_, symbols.TYPEREF)
        assert isinstance(bounds, symbols.BOUNDLIST)

        if not self.check_class(id_, CLASS.array, lineno, scope=self.current_scope):
            return None

        entry = self.get_entry(id_, self.current_scope)
        if entry is None:
            entry = self.declare(id_, lineno, symbols.VARARRAY(id_, bounds, lineno, type_=type_))

        if not entry.declared:
            if entry.callable:
                syntax_error(lineno,
                             "Array '%s' must be declared before use. "
                             "First used at line %i" %
                             (id_, entry.lineno))
                return None
        else:
            if entry.scope == SCOPE.parameter:
                syntax_error(lineno, "variable '%s' already declared as a "
                                     "parameter at line %i" % (id_, entry.lineno))
            else:
                syntax_error(lineno, "variable '%s' already declared at "
                                     "line %i" % (id_, entry.lineno))
            return None

        if entry.type_ != self.basic_types[TYPE.unknown] and entry.type_ != type_:
            if not type_.implicit:
                syntax_error(lineno, "Array suffix for '%s' is for type '%s' "
                                     "but declared as '%s'" %
                             (entry.name, entry.type_, type_))
                return None

            type_.implicit = False
            type_ = entry.type_

        if type_.implicit:
            warning_implicit_type(lineno, id_, type_)

        if not isinstance(entry, symbols.VARARRAY):
            entry = symbols.VAR.to_vararray(entry, bounds)

        entry.declared = True
        entry.type_ = type_
        entry.scope = SCOPE.global_ if self.current_scope == self.global_scope else SCOPE.local
        entry.default_value = default_value
        entry.callable = True
        entry.class_ = CLASS.array
        entry.lbound_used = entry.ubound_used = False  # Flag to true when LBOUND/UBOUND used somewhere in the code

        __DEBUG__('Entry %s declared with class %s at scope %i' % (id_, CLASS.to_string(entry.class_),
                                                                   self.current_scope))
        return entry


Instruction:
Can you generate the documentation for the following Python 3 function
def declare_func(self, id_, lineno, type_=None):
        if not self.check_class(id_, 'function', lineno):
            entry = self.get_entry(id_)  # Must not exist or have _class = None or Function and declared = False
            an = 'an' if entry.class_.lower()[0] in 'aeio' else 'a'
            syntax_error(lineno, "'%s' already declared as %s %s at %i" % (id_, an, entry.class_, entry.lineno))
            return None

        entry = self.get_entry(id_)  # Must not exist or have _class = None or Function and declared = False
        if entry is not None:
            if entry.declared and not entry.forwarded:
                syntax_error(lineno, "Duplicate function name '%s', previously defined at %i" % (id_, entry.lineno))
                return None

            if entry.class_ != CLASS.unknown and entry.callable is False:  # HINT: Must use is False here.
                syntax_error_not_array_nor_func(lineno, id_)
                return None

            if id_[-1] in DEPRECATED_SUFFIXES and entry.type_ != self.basic_types[SUFFIX_TYPE[id_[-1]]]:
                syntax_error_func_type_mismatch(lineno, entry)

            if entry.token == 'VAR':  # This was a function used in advance
                symbols.VAR.to_function(entry, lineno=lineno)
            entry.mangled = '%s_%s' % (self.mangle, entry.name)  # HINT: mangle for nexted scopes
        else:
            entry = self.declare(id_, lineno, symbols.FUNCTION(id_, lineno, type_=type_))

        if entry.forwarded:
            entry.forwared = False  # No longer forwarded
            old_type = entry.type_  # Remembers the old type
            if entry.type_ is not None:
                if entry.type_ != old_type:
                    syntax_error_func_type_mismatch(lineno, entry)
            else:
                entry.type_ = old_type
        else:
            entry.params_size = 0  # Size of parameters

        entry.locals_size = 0  # Size of local variables
        return entry

Response: Declares a function in the current scope.


Instruction:
Create a Python 3 function to
check if all the labels have been declared

Response:
def check_labels(self):
        """ Checks if all the labels has been declared
        """
        for entry in self.labels:
            self.check_is_declared(entry.name, entry.lineno, CLASS.label)


Instruction:
Make a summary of the following Python 3 code
def check_classes(self, scope=-1):
        for entry in self[scope].values():
            if entry.class_ is None:
                syntax_error(entry.lineno, "Unknown identifier '%s'" % entry.name)

Response: Check if pending identifiers are defined or not.


Instruction:
Can you create a Python 3 function that
returns a list of symbol instances corresponding to variables in the current scope.

Response:
def vars_(self):
        """ Returns symbol instances corresponding to variables
        of the current scope.
        """
        return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var]


Instruction:
Can you generate the documentation for the following Python 3 function
def labels(self):
        return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label]

Response: Returns a list of symbol instances corresponding to labels in the current scope.


Instruction:
Can you create a Python 3 function that
returns a list of all types that are defined in the current scope.

Response:
def types(self):
        """ Returns symbol instances corresponding to type declarations
        within the current scope.
        """
        return [x for x in self[self.current_scope].values() if isinstance(x, symbols.TYPE)]


Instruction:
Can you generate the documentation for the following Python 3 function
def arrays(self):
        return [x for x in self[self.current_scope].values() if x.class_ == CLASS.array]

Response: Returns a list of symbol instances corresponding to arrays in the current scope.


Instruction:
Implement a function in Python 3 to
return a list of symbol instances corresponding to functions in the current scope.

Response:
def functions(self):
        """ Returns symbol instances corresponding to functions
        of the current scope.
        """
        return [x for x in self[self.current_scope].values() if x.class_ in
                (CLASS.function, CLASS.sub)]


Instruction:
Can you generate the documentation for the following Python 3 function
def aliases(self):
        return [x for x in self[self.current_scope].values() if x.is_aliased]

Response: Returns a list of symbol instances corresponding to aliased vars.


Instruction:
Write a Python 3 function for
checking arg s type is one in type_list otherwise raises an error.

Response:
def check_type(lineno, type_list, arg):
    """ Check arg's type is one in type_list, otherwise,
    raises an error.
    """
    if not isinstance(type_list, list):
        type_list = [type_list]

    if arg.type_ in type_list:
        return True

    if len(type_list) == 1:
        syntax_error(lineno, "Wrong expression type '%s'. Expected '%s'" %
                     (arg.type_, type_list[0]))
    else:
        syntax_error(lineno, "Wrong expression type '%s'. Expected one of '%s'"
                     % (arg.type_, tuple(type_list)))

    return False


Instruction:
Can you generate the documentation for the following Python 3 function
def check_is_declared_explicit(lineno, id_, classname='variable'):
    if not config.OPTIONS.explicit.value:
        return True

    entry = global_.SYMBOL_TABLE.check_is_declared(id_, lineno, classname)
    return entry is not None

Response: Check if the current ID is already declared.


Instruction:
Can you generate the documentation for the following Python 3 function
def check_call_arguments(lineno, id_, args):
    if not global_.SYMBOL_TABLE.check_is_declared(id_, lineno, 'function'):
        return False

    if not global_.SYMBOL_TABLE.check_class(id_, CLASS.function, lineno):
        return False

    entry = global_.SYMBOL_TABLE.get_entry(id_)

    if len(args) != len(entry.params):
        c = 's' if len(entry.params) != 1 else ''
        syntax_error(lineno, "Function '%s' takes %i parameter%s, not %i" %
                     (id_, len(entry.params), c, len(args)))
        return False

    for arg, param in zip(args, entry.params):
        if not arg.typecast(param.type_):
            return False

        if param.byref:
            from symbols.var import SymbolVAR
            if not isinstance(arg.value, SymbolVAR):
                syntax_error(lineno, "Expected a variable name, not an "
                                     "expression (parameter By Reference)")
                return False

            if arg.class_ not in (CLASS.var, CLASS.array):
                syntax_error(lineno, "Expected a variable or array name "
                                     "(parameter By Reference)")
                return False

            arg.byref = True

    if entry.forwarded:  # The function / sub was DECLARED but not implemented
        syntax_error(lineno, "%s '%s' declared but not implemented" % (CLASS.to_string(entry.class_), entry.name))
        return False

    return True

Response: Checks the arguments in a function call against a function signature. Returns True on success Returns False on error


Instruction:
Can you generate a brief explanation for the following Python 3 code
def check_pending_calls():
    result = True

    # Check for functions defined after calls (parametres, etc)
    for id_, params, lineno in global_.FUNCTION_CALLS:
        result = result and check_call_arguments(lineno, id_, params)

    return result

Response:
Checks if any pending calls are made to the current scope
   .


Instruction:
Write a Python 3 script to
check if the given AST has pending labels.

Response:
def check_pending_labels(ast):
    """ Iteratively traverses the node looking for ID with no class set,
    marks them as labels, and check they've been declared.

    This way we avoid stack overflow for high line-numbered listings.
    """
    result = True
    visited = set()
    pending = [ast]

    while pending:
        node = pending.pop()

        if node is None or node in visited:  # Avoid recursive infinite-loop
            continue

        visited.add(node)
        for x in node.children:
            pending.append(x)

        if node.token != 'VAR' or (node.token == 'VAR' and node.class_ is not CLASS.unknown):
            continue

        tmp = global_.SYMBOL_TABLE.get_entry(node.name)
        if tmp is None or tmp.class_ is CLASS.unknown:
            syntax_error(node.lineno, 'Undeclared identifier "%s"'
                         % node.name)
        else:
            assert tmp.class_ == CLASS.label
            node.to_label(node)

        result = result and tmp is not None

    return result


Instruction:
Can you write a function in Python 3 where it
checks if the given label is valid and returns a label object.

Response:
def check_and_make_label(lbl, lineno):
    """ Checks if the given label (or line number) is valid and, if so,
    returns a label object.
    :param lbl: Line number of label (string)
    :param lineno: Line number in the basic source code for error reporting
    :return: Label object or None if error.
    """
    if isinstance(lbl, float):
        if lbl == int(lbl):
            id_ = str(int(lbl))
        else:
            syntax_error(lineno, 'Line numbers must be integers.')
            return None
    else:
        id_ = lbl

    return global_.SYMBOL_TABLE.access_label(id_, lineno)


Instruction:
Can you tell what is the following Python 3 function doing
def is_null(*symbols):
    from symbols.symbol_ import Symbol

    for sym in symbols:
        if sym is None:
            continue
        if not isinstance(sym, Symbol):
            return False
        if sym.token == 'NOP':
            continue
        if sym.token == 'BLOCK':
            if not is_null(*sym.children):
                return False
            continue
        return False
    return True

Response: True if no nodes or all the given nodes are either NOP or empty blocks.