Instruction:
Write a Python 3 script to
open all contained L { sxbasic. Import } children to import all of their referenced schemas.

Response:
def open_imports(self, options, loaded_schemata):
        """
        Instruct all contained L{sxbasic.Import} children to import all of
        their referenced schemas. The imported schema contents are I{merged}
        in.

        @param options: An options dictionary.
        @type options: L{options.Options}
        @param loaded_schemata: Already loaded schemata cache (URL --> Schema).
        @type loaded_schemata: dict

        """
        for imp in self.imports:
            imported = imp.open(options, loaded_schemata)
            if imported is None:
                continue
            imported.open_imports(options, loaded_schemata)
            log.debug("imported:\n%s", imported)
            self.merge(imported)


Instruction:
Implement a function in Python 3 to
instruct all children to perform dereferencing.

Response:
def dereference(self):
        """Instruct all children to perform dereferencing."""
        all = []
        indexes = {}
        for child in self.children:
            child.content(all)
        dependencies = {}
        for x in all:
            x.qualify()
            midx, deps = x.dependencies()
            dependencies[x] = deps
            indexes[x] = midx
        for x, deps in dependency_sort(dependencies):
            midx = indexes.get(x)
            if midx is None:
                continue
            d = deps[midx]
            log.debug("(%s) merging %s <== %s", self.tns[1], Repr(x), Repr(d))
            x.merge(d)


Instruction:
How would you code a function in Python 3 to
create and return a new schema object using the specified root and base URL.

Response:
def instance(self, root, baseurl, loaded_schemata, options):
        """
        Create and return an new schema object using the specified I{root} and
        I{URL}.

        @param root: A schema root node.
        @type root: L{sax.element.Element}
        @param baseurl: A base URL.
        @type baseurl: str
        @param loaded_schemata: Already loaded schemata cache (URL --> Schema).
        @type loaded_schemata: dict
        @param options: An options dictionary.
        @type options: L{options.Options}
        @return: The newly created schema object.
        @rtype: L{Schema}
        @note: This is only used by Import children.

        """
        return Schema(root, baseurl, options, loaded_schemata)


Instruction:
Can you tell what is the following Python 3 function doing
def create_sqs_policy(self, topic_name, topic_arn, topic_subs):
        t = self.template

        arn_endpoints = []
        url_endpoints = []
        for sub in topic_subs:
            arn_endpoints.append(sub["Endpoint"])
            split_endpoint = sub["Endpoint"].split(":")
            queue_url = "https://%s.%s.amazonaws.com/%s/%s" % (
                split_endpoint[2],  # literally "sqs"
                split_endpoint[3],  # AWS region
                split_endpoint[4],  # AWS ID
                split_endpoint[5],  # Queue name
            )
            url_endpoints.append(queue_url)

        policy_doc = queue_policy(topic_arn, arn_endpoints)

        t.add_resource(
            sqs.QueuePolicy(
                topic_name + "SubPolicy",
                PolicyDocument=policy_doc,
                Queues=url_endpoints,
            )
        )

Response: This method creates the SQS policy needed for an SNS subscription. It creates the SQS policy needed for an SNS queue.


Instruction:
Here you have a function in Python 3, explain what it does
def create_topic(self, topic_name, topic_config):
        topic_subs = []
        t = self.template

        if "Subscription" in topic_config:
            topic_subs = topic_config["Subscription"]

        t.add_resource(
            sns.Topic.from_dict(
                topic_name,
                topic_config
            )
        )

        topic_arn = Ref(topic_name)

        t.add_output(
            Output(topic_name + "Name", Value=GetAtt(topic_name, "TopicName"))
        )
        t.add_output(Output(topic_name + "Arn", Value=topic_arn))

        sqs_subs = [sub for sub in topic_subs if sub["Protocol"] == "sqs"]
        if sqs_subs:
            self.create_sqs_policy(topic_name, topic_arn, sqs_subs)

Response: Creates the SNS topic along with any subscriptions requested.


Instruction:
Given the following Python 3 function, write the documentation
def get_stream_action_type(stream_arn):

    stream_type_map = {
        "kinesis": awacs.kinesis.Action,
        "dynamodb": awacs.dynamodb.Action,
    }

    stream_type = stream_arn.split(":")[2]
    try:
        return stream_type_map[stream_type]
    except KeyError:
        raise ValueError(
            "Invalid stream type '%s' in arn '%s'" % (stream_type, stream_arn)
        )

Response: Returns the awacs Action for a given stream type


Instruction:
Here you have a function in Python 3, explain what it does
def stream_reader_statements(stream_arn):
    action_type = get_stream_action_type(stream_arn)
    arn_parts = stream_arn.split("/")
    # Cut off the last bit and replace it with a wildcard
    wildcard_arn_parts = arn_parts[:-1]
    wildcard_arn_parts.append("*")
    wildcard_arn = "/".join(wildcard_arn_parts)

    return [
        Statement(
            Effect=Allow,
            Resource=[stream_arn],
            Action=[
                action_type("DescribeStream"),
                action_type("GetRecords"),
                action_type("GetShardIterator"),
            ]
        ),
        Statement(
            Effect=Allow,
            Resource=[wildcard_arn],
            Action=[action_type("ListStreams")]
        )
    ]

Response: Returns a list of statements to allow Lambda to read from a stream.


Instruction:
Write a Python 3 function that can
add statements to the policy.

Response:
def add_policy_statements(self, statements):
        """Adds statements to the policy.

        Args:
            statements (:class:`awacs.aws.Statement` or list): Either a single
                Statment, or a list of statements.
        """
        if isinstance(statements, Statement):
            statements = [statements]
        self._policy_statements.extend(statements)


Instruction:
Make a summary of the following Python 3 code
def generate_policy_statements(self):
        statements = self._policy_statements
        statements.extend(
            lambda_basic_execution_statements(
                self.function.Ref()
            )
        )
        extended_statements = self.extended_policy_statements()
        if extended_statements:
            statements.extend(extended_statements)
        return statements

Response: Generates the policy statements for the function used by the function.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def snake_to_camel_case(name):
    name = name.replace("-", "_")
    return "".join(word.capitalize() for word in name.split("_"))

Response: Convert a snake_case string to a CamelCase string.


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

    statements = []
    statements.extend(kms_key_root_statements())

    return Policy(
        Version="2012-10-17",
        Id="root-account-access",
        Statement=statements
    )

Response: Returns a new policy that can be used to access a KMS Key.


Instruction:
Explain what the following Python 3 code does
def check_properties(properties, allowed_properties, resource):
    for key in properties.keys():
        if key not in allowed_properties:
            raise ValueError(
                "%s is not a valid property of %s" % (key, resource)
            )

Response: Checks the list of properties in the properties variable against the allowed_properties variable.


Instruction:
Can you write a function in Python 3 where it
merges two sets of tags into a new troposphere object.

Response:
def merge_tags(left, right, factory=Tags):
    """
    Merge two sets of tags into a new troposphere object

    Args:
        left (Union[dict, troposphere.Tags]): dictionary or Tags object to be
            merged with lower priority
        right (Union[dict, troposphere.Tags]): dictionary or Tags object to be
            merged with higher priority
        factory (type): Type of object to create. Defaults to the troposphere
            Tags class.
    """

    if isinstance(left, Mapping):
        tags = dict(left)
    elif hasattr(left, 'tags'):
        tags = _tags_to_dict(left.tags)
    else:
        tags = _tags_to_dict(left)

    if isinstance(right, Mapping):
        tags.update(right)
    elif hasattr(left, 'tags'):
        tags.update(_tags_to_dict(right.tags))
    else:
        tags.update(_tags_to_dict(right))

    return factory(**tags)


Instruction:
Write a Python 3 script for
accepting record_set Name and Type. Return MD5 sum of these values.

Response:
def get_record_set_md5(rs_name, rs_type):
    """Accept record_set Name and Type. Return MD5 sum of these values."""
    rs_name = rs_name.lower()
    rs_type = rs_type.upper()
    # Make A and CNAME records hash to same sum to support updates.
    rs_type = "ACNAME" if rs_type in ["A", "CNAME"] else rs_type
    return md5(rs_name + rs_type).hexdigest()


Instruction:
Explain what the following Python 3 code does
def add_hosted_zone_id_for_alias_target_if_missing(self, rs):
        alias_target = getattr(rs, "AliasTarget", None)
        if alias_target:
            hosted_zone_id = getattr(alias_target, "HostedZoneId", None)
            if not hosted_zone_id:
                dns_name = alias_target.DNSName
                if dns_name.endswith(CF_DOMAIN):
                    alias_target.HostedZoneId = CLOUDFRONT_ZONE_ID
                elif dns_name.endswith(ELB_DOMAIN):
                    region = dns_name.split('.')[-5]
                    alias_target.HostedZoneId = ELB_ZONE_IDS[region]
                elif dns_name in S3_WEBSITE_ZONE_IDS:
                    alias_target.HostedZoneId = S3_WEBSITE_ZONE_IDS[dns_name]
                else:
                    alias_target.HostedZoneId = self.hosted_zone_id
        return rs

Response: Add proper hosted zone id to record set alias target if missing.


Instruction:
How would you explain what the following Python 3 function does
def create_record_set(self, rs_dict):
        record_set_md5 = get_record_set_md5(rs_dict["Name"], rs_dict["Type"])
        rs = route53.RecordSetType.from_dict(record_set_md5, rs_dict)
        rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id)
        rs = self.add_hosted_zone_id_for_alias_target_if_missing(rs)
        return self.template.add_resource(rs)

Response: Accept a record_set dict. Return a Troposphere record_set object.


Instruction:
Here you have a function in Python 3, explain what it does
def create_record_set_group(self, name, g_dict):
        rs = route53.RecordSetGroup.from_dict(name, g_dict)
        rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id)
        rs = self.add_hosted_zone_id_for_alias_target_if_missing(rs)
        return self.template.add_resource(rs)

Response: Accept a record_set dict. Return a Troposphere record_set object.


Instruction:
Write a Python 3 script for
accepting list of record_set dicts. returns list of record_set objects.

Response:
def create_record_sets(self, record_set_dicts):
        """Accept list of record_set dicts.
        Return list of record_set objects."""
        record_set_objects = []
        for record_set_dict in record_set_dicts:
            # pop removes the 'Enabled' key and tests if True.
            if record_set_dict.pop('Enabled', True):
                record_set_objects.append(
                    self.create_record_set(record_set_dict)
                )
        return record_set_objects


Instruction:
Given the following Python 3 function, write the documentation
def create_record_set_groups(self, record_set_group_dicts):
        record_set_groups = []
        for name, group in record_set_group_dicts.iteritems():
            # pop removes the 'Enabled' key and tests if True.
            if group.pop('Enabled', True):
                record_set_groups.append(
                    self.create_record_set_group(name, group)
                )
        return record_set_groups

Response:
Accept list of record_set_group dicts.
        Return list of record_set_group objects.


Instruction:
Create a Python 3 function to
return a list of statements that can be used to create a read - only policy an s3 bucket.

Response:
def read_only_s3_bucket_policy_statements(buckets, folder="*"):
    """ Read only policy an s3 bucket. """
    list_buckets = [s3_arn(b) for b in buckets]
    object_buckets = [s3_objects_arn(b, folder) for b in buckets]

    bucket_resources = list_buckets + object_buckets

    return [
        Statement(
            Effect=Allow,
            Resource=[s3_arn("*")],
            Action=[s3.ListAllMyBuckets]
        ),
        Statement(
            Effect=Allow,
            Resource=bucket_resources,
            Action=[Action('s3', 'Get*'), Action('s3', 'List*')]
        )
    ]


Instruction:
Implement a function in Python 3 to
return a policy that can be used to access a static website for a given bucket.

Response:
def static_website_bucket_policy(bucket):
    """
    Attach this policy directly to an S3 bucket to make it a static website.
    This policy grants read access to **all unauthenticated** users.
    """
    return Policy(
        Statement=[
            Statement(
                Effect=Allow,
                Principal=Principal("*"),
                Action=[s3.GetObject],
                Resource=[s3_objects_arn(bucket)],
            )
        ]
    )


Instruction:
Make a summary of the following Python 3 code
def lambda_vpc_execution_statements():
    return [
        Statement(
            Effect=Allow,
            Resource=['*'],
            Action=[
                ec2.CreateNetworkInterface,
                ec2.DescribeNetworkInterfaces,
                ec2.DeleteNetworkInterface,
            ]
        )
    ]

Response: Return a list of Lambda execution statements that can be used to create and delete EC2 ENIs for VPC support.


Instruction:
How would you explain what the following Python 3 function does
def dynamodb_autoscaling_policy(tables):
    return Policy(
        Statement=[
            Statement(
                Effect=Allow,
                Resource=dynamodb_arns(tables),
                Action=[
                    dynamodb.DescribeTable,
                    dynamodb.UpdateTable,
                ]
            ),
            Statement(
                Effect=Allow,
                Resource=['*'],
                Action=[
                    cloudwatch.PutMetricAlarm,
                    cloudwatch.DescribeAlarms,
                    cloudwatch.GetMetricStatistics,
                    cloudwatch.SetAlarmState,
                    cloudwatch.DeleteAlarms,
                ]
            ),
        ]
    )

Response: Policy to allow AutoScaling a list of DynamoDB tables.


Instruction:
Create a Python 3 function to
convert HEALPix indices to longitudes and latitudes.

Response:
def healpix_to_lonlat(self, healpix_index, dx=None, dy=None):
        """
        Convert HEALPix indices (optionally with offsets) to longitudes/latitudes

        Parameters
        ----------
        healpix_index : `~numpy.ndarray`
            1-D array of HEALPix indices
        dx, dy : `~numpy.ndarray`, optional
            1-D arrays of offsets inside the HEALPix pixel, which must be in
            the range [0:1] (0.5 is the center of the HEALPix pixels). If not
            specified, the position at the center of the pixel is used.

        Returns
        -------
        lon : :class:`~astropy.coordinates.Longitude`
            The longitude values
        lat : :class:`~astropy.coordinates.Latitude`
            The latitude values
        """
        return healpix_to_lonlat(healpix_index, self.nside, dx=dx, dy=dy, order=self.order)


Instruction:
Write a Python 3 function for
converting lon lat values to HEALPix indices.

Response:
def lonlat_to_healpix(self, lon, lat, return_offsets=False):
        """
        Convert longitudes/latitudes to HEALPix indices (optionally with offsets)

        Parameters
        ----------
        lon, lat : :class:`~astropy.units.Quantity`
            The longitude and latitude values as :class:`~astropy.units.Quantity` instances
            with angle units.
        return_offsets : bool
            If `True`, the returned values are the HEALPix pixel as well as
            ``dx`` and ``dy``, the fractional positions inside the pixel. If
            `False` (the default), only the HEALPix pixel is returned.

        Returns
        -------
        healpix_index : `~numpy.ndarray`
            1-D array of HEALPix indices
        dx, dy : `~numpy.ndarray`
            1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5
            is the center of the HEALPix pixels). This is returned if
            ``return_offsets`` is `True`.
        """
        return lonlat_to_healpix(lon, lat, self.nside,
                                 return_offsets=return_offsets, order=self.order)


Instruction:
Implement a function in Python 3 to
return the four neighbours for each ( lon lat ) position and the weight associated with each one for bilinear interpolation.

Response:
def bilinear_interpolation_weights(self, lon, lat):
        """
        Get the four neighbours for each (lon, lat) position and the weight
        associated with each one for bilinear interpolation.

        Parameters
        ----------
        lon, lat : :class:`~astropy.units.Quantity`
            The longitude and latitude values as
            :class:`~astropy.units.Quantity` instances with angle units.

        Returns
        -------
        indices : `~numpy.ndarray`
            2-D array with shape (4, N) giving the four indices to use for the
            interpolation
        weights : `~numpy.ndarray`
            2-D array with shape (4, N) giving the four weights to use for the
            interpolation
        """
        return bilinear_interpolation_weights(lon, lat, self.nside, order=self.order)


Instruction:
Make a summary of the following Python 3 code
def interpolate_bilinear_lonlat(self, lon, lat, values):
        if len(values) != self.npix:
            raise ValueError('values must be an array of length {0} (got {1})'.format(self.npix, len(values)))
        return interpolate_bilinear_lonlat(lon, lat, values, order=self.order)

Response: Interpolate values at specific longitudes and latitudes using bilinear interpolation.


Instruction:
Implement a function in Python 3 to
search for HEALPix pixels within a given radius of a longitude and latitude pair.

Response:
def cone_search_lonlat(self, lon, lat, radius):
        """
        Find all the HEALPix pixels within a given radius of a longitude/latitude.

        Note that this returns all pixels that overlap, including partially, with
        the search cone. This function can only be used for a single lon/lat pair at
        a time, since different calls to the function may result in a different
        number of matches.

        Parameters
        ----------
        lon, lat : :class:`~astropy.units.Quantity`
            The longitude and latitude to search around
        radius : :class:`~astropy.units.Quantity`
            The search radius

        Returns
        -------
        healpix_index : `~numpy.ndarray`
            1-D array with all the matching HEALPix pixel indices.
        """
        if not lon.isscalar or not lat.isscalar or not radius.isscalar:
            raise ValueError('The longitude, latitude and radius must be '
                             'scalar Quantity objects')
        return healpix_cone_search(lon, lat, radius, self.nside, order=self.order)


Instruction:
Create a Python 3 function for
returning the longitude and latitude of the edges of each HEALPix pixels.

Response:
def boundaries_lonlat(self, healpix_index, step):
        """
        Return the longitude and latitude of the edges of HEALPix pixels

        This returns the longitude and latitude of points along the edge of each
        HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
        so setting ``step`` to 1 returns just the corners.

        Parameters
        ----------
        healpix_index : `~numpy.ndarray`
            1-D array of HEALPix pixels
        step : int
            The number of steps to take along each edge.

        Returns
        -------
        lon, lat : :class:`~astropy.units.Quantity`
            The longitude and latitude, as 2-D arrays where the first dimension is
            the same as the ``healpix_index`` input, and the second dimension has
            size ``4 * step``.
        """
        return boundaries_lonlat(healpix_index, step, self.nside, order=self.order)


Instruction:
Given the following Python 3 function, write the documentation
def neighbours(self, healpix_index):
        return neighbours(healpix_index, self.nside, order=self.order)

Response: Return the array of neighbours of a HEALPix pixel.


Instruction:
Explain what the following Python 3 code does
def healpix_to_skycoord(self, healpix_index, dx=None, dy=None):
        if self.frame is None:
            raise NoFrameError("healpix_to_skycoord")
        lon, lat = self.healpix_to_lonlat(healpix_index, dx=dx, dy=dy)
        representation = UnitSphericalRepresentation(lon, lat, copy=False)
        return SkyCoord(self.frame.realize_frame(representation))

Response: Convert HEALPix indices to celestial coordinates.


Instruction:
Write a Python 3 function for
converting a SkyCoord object to a HEALPix pixel array.

Response:
def skycoord_to_healpix(self, skycoord, return_offsets=False):
        """
        Convert celestial coordinates to HEALPix indices (optionally with offsets).

        Note that this method requires that a celestial frame was specified when
        initializing HEALPix. If you don't know or need the celestial frame, you
        can instead use :meth:`~astropy_healpix.HEALPix.lonlat_to_healpix`.

        Parameters
        ----------
        skycoord : :class:`~astropy.coordinates.SkyCoord`
            The celestial coordinates to convert
        return_offsets : bool
            If `True`, the returned values are the HEALPix pixel as well as
            ``dx`` and ``dy``, the fractional positions inside the pixel. If
            `False` (the default), only the HEALPix pixel is returned.

        Returns
        -------
        healpix_index : `~numpy.ndarray`
            1-D array of HEALPix indices
        dx, dy : `~numpy.ndarray`
            1-D arrays of offsets inside the HEALPix pixel in the range [0:1] (0.5
            is the center of the HEALPix pixels). This is returned if
            ``return_offsets`` is `True`.
        """
        if self.frame is None:
            raise NoFrameError("skycoord_to_healpix")
        skycoord = skycoord.transform_to(self.frame)
        representation = skycoord.represent_as(UnitSphericalRepresentation)
        lon, lat = representation.lon, representation.lat
        return self.lonlat_to_healpix(lon, lat, return_offsets=return_offsets)


Instruction:
Can you generate the documentation for the following Python 3 function
def interpolate_bilinear_skycoord(self, skycoord, values):
        if self.frame is None:
            raise NoFrameError("interpolate_bilinear_skycoord")
        skycoord = skycoord.transform_to(self.frame)
        representation = skycoord.represent_as(UnitSphericalRepresentation)
        lon, lat = representation.lon, representation.lat
        return self.interpolate_bilinear_lonlat(lon, lat, values)

Response: Interpolate values at specific celestial coordinates using bilinear interpolation.


Instruction:
How would you explain what the following Python 3 function does
def cone_search_skycoord(self, skycoord, radius):
        if self.frame is None:
            raise NoFrameError("cone_search_skycoord")
        skycoord = skycoord.transform_to(self.frame)
        representation = skycoord.represent_as(UnitSphericalRepresentation)
        lon, lat = representation.lon, representation.lat
        return self.cone_search_lonlat(lon, lat, radius)

Response: Find all HEALPix pixels within a given radius of a given celestial position.


Instruction:
Write a Python 3 script to
return the celestial coordinates of the edges of each HEALPix pixel.

Response:
def boundaries_skycoord(self, healpix_index, step):
        """
        Return the celestial coordinates of the edges of HEALPix pixels

        This returns the celestial coordinates of points along the edge of each
        HEALPIX pixel. The number of points returned for each pixel is ``4 * step``,
        so setting ``step`` to 1 returns just the corners.

        This method requires that a celestial frame was specified when
        initializing HEALPix.  If you don't know or need the celestial frame,
        you can instead use :meth:`~astropy_healpix.HEALPix.boundaries_lonlat`.

        Parameters
        ----------
        healpix_index : `~numpy.ndarray`
            1-D array of HEALPix pixels
        step : int
            The number of steps to take along each edge.

        Returns
        -------
        skycoord : :class:`~astropy.coordinates.SkyCoord`
            The celestial coordinates of the HEALPix pixel boundaries
        """
        if self.frame is None:
            raise NoFrameError("boundaries_skycoord")
        lon, lat = self.boundaries_lonlat(healpix_index, step)
        representation = UnitSphericalRepresentation(lon, lat, copy=False)
        return SkyCoord(self.frame.realize_frame(representation))


Instruction:
Explain what the following Python 3 code does
def level_to_nside(level):
    level = np.asarray(level, dtype=np.int64)

    _validate_level(level)
    return 2 ** level

Response: This function returns the number of pixels on the side of the HEALPix tiles at a given level.


Instruction:
Can you tell what is the following Python 3 function doing
def nside_to_level(nside):
    nside = np.asarray(nside, dtype=np.int64)

    _validate_nside(nside)
    return np.log2(nside).astype(np.int64)

Response: Find the HEALPix level for a given HEALPix tile.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def uniq_to_level_ipix(uniq):
    uniq = np.asarray(uniq, dtype=np.int64)

    level = (np.log2(uniq//4)) // 2
    level = level.astype(np.int64)
    _validate_level(level)

    ipix = uniq - (1 << 2*(level + 1))
    _validate_npix(level, ipix)

    return level, ipix

Response: Convert a HEALPix cell uniq number to its level and index equivalent.


Instruction:
Can you generate the documentation for the following Python 3 function
def level_ipix_to_uniq(level, ipix):
    level = np.asarray(level, dtype=np.int64)
    ipix = np.asarray(ipix, dtype=np.int64)

    _validate_level(level)
    _validate_npix(level, ipix)

    return ipix + (1 << 2*(level + 1))

Response: Convert a level and HEALPix index into a uniq number representing the cell.


Instruction:
Here you have a function in Python 3, explain what it does
def nside_to_pixel_area(nside):
    nside = np.asanyarray(nside, dtype=np.int64)
    _validate_nside(nside)
    npix = 12 * nside * nside
    pixel_area = 4 * math.pi / npix * u.sr
    return pixel_area

Response: Find the area of HEALPix pixels given the pixel dimensions of one of the 12 top - level HEALPix tiles.


Instruction:
How would you implement a function in Python 3 that
finds the resolution of HEALPix pixels given the pixel dimensions of one of the HEALPix tiles.

Response:
def nside_to_pixel_resolution(nside):
    """
    Find the resolution of HEALPix pixels given the pixel dimensions of one of
    the 12 'top-level' HEALPix tiles.

    Parameters
    ----------
    nside : int
        The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.

    Returns
    -------
    resolution : :class:`~astropy.units.Quantity`
        The resolution of the HEALPix pixels

    See also
    --------
    pixel_resolution_to_nside
    """
    nside = np.asanyarray(nside, dtype=np.int64)
    _validate_nside(nside)
    return (nside_to_pixel_area(nside) ** 0.5).to(u.arcmin)


Instruction:
Write a Python 3 script to
find the HEALPix tiles on the given angular resolution.

Response:
def pixel_resolution_to_nside(resolution, round='nearest'):
    """Find closest HEALPix nside for a given angular resolution.

    This function is the inverse of `nside_to_pixel_resolution`,
    for the default rounding scheme of ``round='nearest'``.

    If you choose ``round='up'``, you'll get HEALPix pixels that
    have at least the requested resolution (usually a bit better
    due to rounding).

    Pixel resolution is defined as square root of pixel area.

    Parameters
    ----------
    resolution : `~astropy.units.Quantity`
        Angular resolution
    round : {'up', 'nearest', 'down'}
        Which way to round

    Returns
    -------
    nside : int
        The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
        Always a power of 2.

    Examples
    --------
    >>> from astropy import units as u
    >>> from astropy_healpix import pixel_resolution_to_nside
    >>> pixel_resolution_to_nside(13 * u.arcmin)
    256
    >>> pixel_resolution_to_nside(13 * u.arcmin, round='up')
    512
    """
    resolution = resolution.to(u.rad).value
    pixel_area = resolution * resolution
    npix = 4 * math.pi / pixel_area
    nside = np.sqrt(npix / 12)

    # Now we have to round to the closest ``nside``
    # Since ``nside`` must be a power of two,
    # we first compute the corresponding ``level = log2(nside)`
    # round the level and then go back to nside
    level = np.log2(nside)

    if round == 'up':
        level = np.ceil(level)
    elif round == 'nearest':
        level = np.round(level)
    elif round == 'down':
        level = np.floor(level)
    else:
        raise ValueError('Invalid value for round: {!r}'.format(round))

    # For very low requested resolution (i.e. large angle values), we
    # return ``level=0``, i.e. ``nside=1``, i.e. the lowest resolution
    # that exists with HEALPix
    level = np.clip(level.astype(int), 0, None)

    return level_to_nside(level)


Instruction:
How would you explain what the following Python 3 function does
def nside_to_npix(nside):
    nside = np.asanyarray(nside, dtype=np.int64)
    _validate_nside(nside)
    return 12 * nside ** 2

Response: Find the number of pixels corresponding to a HEALPix resolution.


Instruction:
How would you explain what the following Python 3 function does
def npix_to_nside(npix):

    npix = np.asanyarray(npix, dtype=np.int64)

    if not np.all(npix % 12 == 0):
        raise ValueError('Number of pixels must be divisible by 12')

    square_root = np.sqrt(npix / 12)
    if not np.all(square_root ** 2 == npix / 12):
        raise ValueError('Number of pixels is not of the form 12 * nside ** 2')

    return np.round(square_root).astype(int)

Response: This function returns the number of pixels on the top of a HEALPix map given a total number of pixels.


Instruction:
Here you have a function in Python 3, explain what it does
def healpix_to_lonlat(healpix_index, nside, dx=None, dy=None, order='ring'):

    _validate_nside(nside)

    if _validate_order(order) == 'ring':
        func = _core.healpix_ring_to_lonlat
    else:  # _validate_order(order) == 'nested'
        func = _core.healpix_nested_to_lonlat

    if dx is None:
        dx = 0.5
    else:
        _validate_offset('x', dx)
    if dy is None:
        dy = 0.5
    else:
        _validate_offset('y', dy)

    nside = np.asarray(nside, dtype=np.intc)

    lon, lat = func(healpix_index, nside, dx, dy)

    lon = Longitude(lon, unit=u.rad, copy=False)
    lat = Latitude(lat, unit=u.rad, copy=False)

    return lon, lat

Response: Convert HEALPix indices to longitudes and latitudes.


Instruction:
Make a summary of the following Python 3 code
def lonlat_to_healpix(lon, lat, nside, return_offsets=False, order='ring'):

    if _validate_order(order) == 'ring':
        func = _core.lonlat_to_healpix_ring
    else:  # _validate_order(order) == 'nested'
        func = _core.lonlat_to_healpix_nested

    nside = np.asarray(nside, dtype=np.intc)

    lon = lon.to_value(u.rad)
    lat = lat.to_value(u.rad)

    healpix_index, dx, dy = func(lon, lat, nside)

    if return_offsets:
        return healpix_index, dx, dy
    else:
        return healpix_index

Response: Convert a longitude and latitude values into HEALPix indices.


Instruction:
Here you have a function in Python 3, explain what it does
def nested_to_ring(nested_index, nside):

    nside = np.asarray(nside, dtype=np.intc)

    return _core.nested_to_ring(nested_index, nside)

Response: Convert a HEALPix nested index to a HEALPix ring index.


Instruction:
Given the following Python 3 function, write the documentation
def ring_to_nested(ring_index, nside):

    nside = np.asarray(nside, dtype=np.intc)

    return _core.ring_to_nested(ring_index, nside)

Response: Convert a HEALPix ring index to a HEALPix nested index.


Instruction:
Explain what the following Python 3 code does
def bilinear_interpolation_weights(lon, lat, nside, order='ring'):

    lon = lon.to_value(u.rad)
    lat = lat.to_value(u.rad)

    _validate_nside(nside)

    nside = np.asarray(nside, dtype=np.intc)

    result = _core.bilinear_interpolation_weights(lon, lat, nside)
    indices = np.stack(result[:4])
    weights = np.stack(result[4:])

    if _validate_order(order) == 'nested':
        indices = ring_to_nested(indices, nside)

    return indices, weights

Response:
Get the four neighbours for each longitude and latitude of a HEALPix tile and the weight
    associated with each one for bilinear interpolation.


Instruction:
Given the following Python 3 function, write the documentation
def interpolate_bilinear_lonlat(lon, lat, values, order='ring'):
    nside = npix_to_nside(values.shape[0])
    indices, weights = bilinear_interpolation_weights(lon, lat, nside, order=order)
    values = values[indices]
    # At this point values has shape (N, M) where both N and M might be several
    # dimensions, and weights has shape (N,), so we need to transpose in order
    # to benefit from broadcasting, then transpose back so that the dimension
    # with length 4 is at the start again, ready for summing.
    result = (values.T * weights.T).T
    return result.sum(axis=0)

Response: Interpolate values at specific longitudes and latitudes using bilinear interpolation.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def neighbours(healpix_index, nside, order='ring'):

    _validate_nside(nside)

    nside = np.asarray(nside, dtype=np.intc)

    if _validate_order(order) == 'ring':
        func = _core.neighbours_ring
    else:  # _validate_order(order) == 'nested'
        func = _core.neighbours_nested

    return np.stack(func(healpix_index, nside))

Response: Find all the HEALPix pixels that are the neighbours of a HEALPix pixel.


Instruction:
How would you code a function in Python 3 to
search for HEALPix pixels within a given radius of a longitude and latitude pair.

Response:
def healpix_cone_search(lon, lat, radius, nside, order='ring'):
    """
    Find all the HEALPix pixels within a given radius of a longitude/latitude.

    Note that this returns all pixels that overlap, including partially, with
    the search cone. This function can only be used for a single lon/lat pair at
    a time, since different calls to the function may result in a different
    number of matches.

    Parameters
    ----------
    lon, lat : :class:`~astropy.units.Quantity`
        The longitude and latitude to search around
    radius : :class:`~astropy.units.Quantity`
        The search radius
    nside : int
        Number of pixels along the side of each of the 12 top-level HEALPix tiles
    order : { 'nested' | 'ring' }
        Order of HEALPix pixels

    Returns
    -------
    healpix_index : `~numpy.ndarray`
        1-D array with all the matching HEALPix pixel indices.
    """

    lon = lon.to_value(u.deg)
    lat = lat.to_value(u.deg)
    radius = radius.to_value(u.deg)

    _validate_nside(nside)
    order = _validate_order(order)

    return _core.healpix_cone_search(lon, lat, radius, nside, order)


Instruction:
Explain what the following Python 3 code does
def boundaries_lonlat(healpix_index, step, nside, order='ring'):

    healpix_index = np.asarray(healpix_index, dtype=np.int64)
    step = int(step)

    if step < 1:
        raise ValueError('step must be at least 1')

    # PERF: this could be optimized by writing a Cython routine to do this to
    # avoid allocating temporary arrays

    frac = np.linspace(0., 1., step + 1)[:-1]
    dx = np.hstack([1 - frac, np.repeat(0, step), frac, np.repeat(1, step)])
    dy = np.hstack([np.repeat(1, step), 1 - frac, np.repeat(0, step), frac])

    healpix_index, dx, dy = np.broadcast_arrays(healpix_index.reshape(-1, 1), dx, dy)

    lon, lat = healpix_to_lonlat(healpix_index.ravel(), nside, dx.ravel(), dy.ravel(), order=order)

    lon = lon.reshape(-1, 4 * step)
    lat = lat.reshape(-1, 4 * step)

    return lon, lat

Response: Returns the longitude and latitude of the edges of each HEALPix pixel in the order specified by order.


Instruction:
Implement a function in Python 3 to
drop - in replacement for healpy ~healpy. pixelfunc. nside2resol.

Response:
def nside2resol(nside, arcmin=False):
    """Drop-in replacement for healpy `~healpy.pixelfunc.nside2resol`."""
    resolution = nside_to_pixel_resolution(nside)
    if arcmin:
        return resolution.to(u.arcmin).value
    else:
        return resolution.to(u.rad).value


Instruction:
How would you implement a function in Python 3 that
drops - in replacement for healpy ~healpy. pixelfunc. nside2pixarea.

Response:
def nside2pixarea(nside, degrees=False):
    """Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`."""
    area = nside_to_pixel_area(nside)
    if degrees:
        return area.to(u.deg ** 2).value
    else:
        return area.to(u.sr).value


Instruction:
Make a summary of the following Python 3 code
def pix2ang(nside, ipix, nest=False, lonlat=False):
    lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')
    return _lonlat_to_healpy(lon, lat, lonlat=lonlat)

Response: Convert pixel indices into a healpy. HealPix object.


Instruction:
Explain what the following Python 3 code does
def ang2pix(nside, theta, phi, nest=False, lonlat=False):
    lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat)
    return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring')

Response: Convert an angle in HEALPix pixels to HEALPix pixels.


Instruction:
How would you explain what the following Python 3 function does
def pix2vec(nside, ipix, nest=False):
    lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring')
    return ang2vec(*_lonlat_to_healpy(lon, lat))

Response: Drop - in replacement for healpy ~healpy. pixelfunc. pix2vec.


Instruction:
Can you tell what is the following Python 3 function doing
def vec2pix(nside, x, y, z, nest=False):
    theta, phi = vec2ang(np.transpose([x, y, z]))
    # hp.vec2ang() returns raveled arrays, which are 1D.
    if np.isscalar(x):
        theta = theta.item()
        phi = phi.item()
    else:
        shape = np.shape(x)
        theta = theta.reshape(shape)
        phi = phi.reshape(shape)
    lon, lat = _healpy_to_lonlat(theta, phi)
    return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring')

Response: Convert a vector of lon lat coordinates to HEALPix pixels.


Instruction:
Write a Python 3 script to
drop - in replacement for healpy. pixelfunc. nest2ring.

Response:
def nest2ring(nside, ipix):
    """Drop-in replacement for healpy `~healpy.pixelfunc.nest2ring`."""
    ipix = np.atleast_1d(ipix).astype(np.int64, copy=False)
    return nested_to_ring(ipix, nside)


Instruction:
Write a Python 3 script for
dropping - in replacement for healpy. pixelfunc. ring2nest.

Response:
def ring2nest(nside, ipix):
    """Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`."""
    ipix = np.atleast_1d(ipix).astype(np.int64, copy=False)
    return ring_to_nested(ipix, nside)


Instruction:
Write a Python 3 script to
drop - in replacement for healpy ~healpy. boundaries.

Response:
def boundaries(nside, pix, step=1, nest=False):
    """Drop-in replacement for healpy `~healpy.boundaries`."""
    pix = np.asarray(pix)
    if pix.ndim > 1:
        # For consistency with healpy we only support scalars or 1D arrays
        raise ValueError("Array has to be one dimensional")
    lon, lat = boundaries_lonlat(pix, step, nside, order='nested' if nest else 'ring')
    rep_sph = UnitSphericalRepresentation(lon, lat)
    rep_car = rep_sph.to_cartesian().xyz.value.swapaxes(0, 1)
    if rep_car.shape[0] == 1:
        return rep_car[0]
    else:
        return rep_car


Instruction:
Can you generate the documentation for the following Python 3 function
def vec2ang(vectors, lonlat=False):
    x, y, z = vectors.transpose()
    rep_car = CartesianRepresentation(x, y, z)
    rep_sph = rep_car.represent_as(UnitSphericalRepresentation)
    return _lonlat_to_healpy(rep_sph.lon.ravel(), rep_sph.lat.ravel(), lonlat=lonlat)

Response: Drop - in replacement for healpy ~healpy. pixelfunc. vec2ang.


Instruction:
Implement a Python 3 function for
dropping - in replacement for healpy ~healpy. pixelfunc. ang2vec.

Response:
def ang2vec(theta, phi, lonlat=False):
    """Drop-in replacement for healpy `~healpy.pixelfunc.ang2vec`."""
    lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat)
    rep_sph = UnitSphericalRepresentation(lon, lat)
    rep_car = rep_sph.represent_as(CartesianRepresentation)
    return rep_car.xyz.value


Instruction:
Make a summary of the following Python 3 code
def get_interp_weights(nside, theta, phi=None, nest=False, lonlat=False):
    # if phi is not given, theta is interpreted as pixel number
    if phi is None:
        theta, phi = pix2ang(nside, ipix=theta, nest=nest)

    lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat)
    return bilinear_interpolation_weights(lon, lat, nside, order='nested' if nest else 'ring')

Response: Get the interpolated weights for a given HEALPix pixel.


Instruction:
Given the following Python 3 function, write the documentation
def get_interp_val(m, theta, phi, nest=False, lonlat=False):
    lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat)
    return interpolate_bilinear_lonlat(lon, lat, m, order='nested' if nest else 'ring')

Response: Get the value of a bilinear interpolation.


Instruction:
Write a Python 3 function for
running all benchmarks. Return results as a dict.

Response:
def bench_run(fast=False):
    """Run all benchmarks. Return results as a dict."""
    results = []

    if fast:
        SIZES = [10, 1e3, 1e5]
    else:
        SIZES = [10, 1e3, 1e6]

    for nest in [True, False]:
        for size in SIZES:
            for nside in [1, 128]:
                results.append(run_single('pix2ang', bench_pix2ang, fast=fast,
                                          size=int(size), nside=nside, nest=nest))

    for nest in [True, False]:
        for size in SIZES:
            for nside in [1, 128]:
                results.append(run_single('ang2pix', bench_ang2pix, fast=fast,
                                          size=int(size), nside=nside, nest=nest))

    for size in SIZES:
        for nside in [1, 128]:
            results.append(run_single('nest2ring', bench_nest2ring, fast=fast,
                                      size=int(size), nside=nside))

    for size in SIZES:
        for nside in [1, 128]:
            results.append(run_single('ring2nest', bench_ring2nest, fast=fast,
                                      size=int(size), nside=nside))

    for nest in [True, False]:
        for size in SIZES:
            for nside in [1, 128]:
                results.append(run_single('get_interp_weights', bench_get_interp_weights,
                                          fast=fast, size=int(size),
                                          nside=nside, nest=nest))

    return results


Instruction:
Can you generate the documentation for the following Python 3 function
def bench_report(results):

    table = Table(names=['function', 'nest', 'nside', 'size',
                         'time_healpy', 'time_self', 'ratio'],
                  dtype=['S20', bool, int, int, float, float, float], masked=True)
    for row in results:
        table.add_row(row)

    table['time_self'].format = '10.7f'

    if HEALPY_INSTALLED:
        table['ratio'] = table['time_self'] / table['time_healpy']
        table['time_healpy'].format = '10.7f'
        table['ratio'].format = '7.2f'

    table.pprint(max_lines=-1)

Response: Print a report for given benchmark results to the console.


Instruction:
Implement a function in Python 3 to
run all benchmarks and print report to the console.

Response:
def main(fast=False):
    """Run all benchmarks and print report to the console."""
    print('Running benchmarks...\n')
    results = bench_run(fast=fast)
    bench_report(results)


Instruction:
Make a summary of the following Python 3 code
def cached(f):

    cache = f.cache = {}

    @functools.wraps(f)
    def decorator(*args, **kwargs):
        key = str(args) + str(kwargs)
        if key not in cache:
            cache[key] = f(*args, **kwargs)
        return cache[key]
    return decorator

Response: A decorator for functions taking one or more arguments.


Instruction:
Implement a Python 3 function for
registering a Swagger UI application.

Response:
def register_swaggerui_app(app, swagger_uri, api_url, page_title='Swagger UI', favicon_url=None, config=None, uri_prefix=""):

    """:type app: falcon.API"""

    templates_folder = 'templates'
    static_folder = 'dist'

    default_config = {
        'client_realm': 'null',
        'client_id': 'null',
        'client_secret': 'null',
        'app_name': 'null',
        'docExpansion': "none",
        'jsonEditor': False,
        'defaultModelRendering': 'schema',
        'showRequestHeaders': False,
        'supportedSubmitMethods': ['get', 'post', 'put', 'delete', 'patch'],
    }

    if config:
        default_config.update(config)

    default_context = {
        'page_title': page_title,
        'favicon_url': favicon_url,
        'base_url': uri_prefix + swagger_uri,
        'api_url': api_url,
        'app_name': default_config.pop('app_name'),
        'client_realm': default_config.pop('client_realm'),
        'client_id': default_config.pop('client_id'),
        'client_secret': default_config.pop('client_secret'),
        # Rest are just serialized into json string
        # for inclusion in the .js file
        'config_json': json.dumps(default_config)
    }

    app.add_sink(
        StaticSinkAdapter(static_folder),
        r'%s/(?P<filepath>.*)\Z' % swagger_uri,
    )

    app.add_route(
        swagger_uri,
        SwaggerUiResource(templates_folder, default_context)
    )


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

        self.app = app

        self.dynamic_url = self.app.config.get('APIDOC_DYNAMIC_URL', self.dynamic_url)
        self.allow_absolute_url = self.app.config.get('APIDOC_ALLOW_ABSOLUTE_URL', self.allow_absolute_url)

        url = self.url_path

        if not self.url_path.endswith('/'):
            url += '/'

        app.add_url_rule(url, 'docs', self.__send_static_file, strict_slashes=True)
        app.add_url_rule(url + '<path:path>', 'docs', self.__send_static_file, strict_slashes=True)

Response: Initializes the flask application.


Instruction:
Explain what the following Python 3 code does
def __send_static_file(self, path=None):

        if not path:
            path = 'index.html'

        file_name = join(self.folder_path, path)

        # the api_project.js has the absolute url
        # hard coded so we replace them by the current url.
        if self.dynamic_url and path == 'api_project.js':
            return self.__send_api_file(file_name)

        if self.allow_absolute_url and path == 'main.js':
            return self.__send_main_file(file_name)

        # Any other apidoc file is treated as a normal static file
        return self.app.send_static_file(file_name)

Response: Send static files from the apidoc folder to the browser.


Instruction:
Make a summary of the following Python 3 code
def __send_api_file(self, file_name):

        file_name = join(self.app.static_folder, file_name)

        with codecs.open(file_name, 'r', 'utf-8') as file:
            data = file.read()

        # replaces the hard coded url by the current url.
        api_project = self.__read_api_project()

        old_url = api_project.get('url')

        # replaces the project's url only if it is present in the file.
        if old_url:
            new_url = request.url_root.strip('/')
            data = data.replace(old_url, new_url)

        # creates a flask response to send
        # the file to the browser

        headers = Headers()
        headers['Content-Length'] = getsize(file_name)

        response = self.app.response_class(data,
                                           mimetype=mimetypes.guess_type(file_name)[0],
                                           headers=headers,
                                           direct_passthrough=True)

        response.last_modified = int(getmtime(file_name))

        return response

Response: Send apidoc files from the apidoc folder to the browser.


Instruction:
How would you code a function in Python 3 to
send the apidoc files from the apidoc folder to the browser.

Response:
def __send_main_file(self, file_name):
        """
        Send apidoc files from the apidoc folder to the browser.
        This method replaces all absolute urls in the file by
        the current url.
        :param file_name: the apidoc file.
        """

        file_name = join(self.app.static_folder, file_name)

        with codecs.open(file_name, 'r', 'utf-8') as file:
            data = file.read()

        data = data.replace(
            'fields.article.url = apiProject.url + fields.article.url;',
            '''if (fields.article.url.substr(0, 4).toLowerCase() !== \'http\')
                        fields.article.url = apiProject.url + fields.article.url;''')

        headers = Headers()
        headers['Content-Length'] = getsize(file_name)

        response = self.app.response_class(data,
                                           mimetype=mimetypes.guess_type(file_name)[0],
                                           headers=headers,
                                           direct_passthrough=True)

        response.last_modified = int(getmtime(file_name))

        return response


Instruction:
Implement a function in Python 3 to
read the api_project. json file from apidoc folder as a json string.

Response:
def __read_api_project(self):
        """
        Reads the api_project.json file from apidoc folder as a json string.
        :return: a json string
        """

        file_name = join(self.app.static_folder, self.folder_path, 'api_project.json')

        with open(file_name, 'rt') as file:
            data = file.read()

        return json.loads(data)


Instruction:
How would you explain what the following Python 3 function does
def _raise_exception(cls, reason, data=None):
    text_dict = {
        "error": reason
    }

    if data is not None:
        text_dict["errors"] = data

    raise cls(
        text=json.dumps(text_dict),
        content_type="application/json"
    )

Response: Raise a aiohttp exception and pass payload / reason into it.


Instruction:
Can you write a function in Python 3 where it
validates the dict data against given schema.

Response:
def _validate_data(data, schema, validator_cls):
    """
    Validate the dict against given schema (using given validator class).
    """
    validator = validator_cls(schema)
    _errors = defaultdict(list)
    for err in validator.iter_errors(data):
        path = err.schema_path

        # Code courtesy: Ruslan Karalkin
        # Looking in error schema path for
        # property that failed validation
        # Schema example:
        # {
        #    "type": "object",
        #    "properties": {
        #        "foo": {"type": "number"},
        #        "bar": {"type": "string"}
        #     }
        #    "required": ["foo", "bar"]
        # }
        #
        # Related err.schema_path examples:
        # ['required'],
        # ['properties', 'foo', 'type']

        if "properties" in path:
            path.remove("properties")
        key = path.popleft()

        # If validation failed by missing property,
        # then parse err.message to find property name
        # as it always first word enclosed in quotes
        if key == "required":
            key = err.message.split("'")[1]

        _errors[key].append(str(err))

    if _errors:
        _raise_exception(
            web.HTTPBadRequest,
            "Request is invalid; There are validation errors.",
            _errors)


Instruction:
Implement a function in Python 3 to
decorate request handler to make it automagically validate it's request and response.

Response:
def validate(request_schema=None, response_schema=None):
    """
    Decorate request handler to make it automagically validate it's request
    and response.
    """
    def wrapper(func):
        # Validating the schemas itself.
        # Die with exception if they aren't valid
        if request_schema is not None:
            _request_schema_validator = validator_for(request_schema)
            _request_schema_validator.check_schema(request_schema)

        if response_schema is not None:
            _response_schema_validator = validator_for(response_schema)
            _response_schema_validator.check_schema(response_schema)

        @asyncio.coroutine
        @functools.wraps(func)
        def wrapped(*args):
            if asyncio.iscoroutinefunction(func):
                coro = func
            else:
                coro = asyncio.coroutine(func)

            # Supports class based views see web.View
            if isinstance(args[0], AbstractView):
                class_based = True
                request = args[0].request
            else:
                class_based = False
                request = args[-1]

            # Strictly expect json object here
            try:
                req_body = yield from request.json()
            except (json.decoder.JSONDecodeError, TypeError):
                _raise_exception(
                    web.HTTPBadRequest,
                    "Request is malformed; could not decode JSON object.")

            # Validate request data against request schema (if given)
            if request_schema is not None:
                _validate_data(req_body, request_schema,
                               _request_schema_validator)

            coro_args = req_body, request
            if class_based:
                coro_args = (args[0], ) + coro_args

            context = yield from coro(*coro_args)

            # No validation of response for websockets stream
            if isinstance(context, web.StreamResponse):
                return context

            # Validate response data against response schema (if given)
            if response_schema is not None:
                _validate_data(context, response_schema,
                               _response_schema_validator)

            try:
                return web.json_response(context)
            except (TypeError, ):
                _raise_exception(
                    web.HTTPInternalServerError,
                    "Response is malformed; could not encode JSON object.")

        # Store schemas in wrapped handlers, so it later can be reused
        setattr(wrapped, "_request_schema", request_schema)
        setattr(wrapped, "_response_schema", response_schema)
        return wrapped
    return wrapper


Instruction:
Create a Python 3 function for
generating JSON Schema representation of a biolink model

Response:
def cli(yamlfile, inline, format):
    """ Generate JSON Schema representation of a biolink model """
    print(JsonSchemaGenerator(yamlfile, format).serialize(inline=inline))


Instruction:
Make a summary of the following Python 3 code
def root_representer(dumper: yaml.Dumper, data: YAMLRoot):
    rval = dict()
    for k, v in data.__dict__.items():
        if not k.startswith('_') and v is not None and (not isinstance(v, (dict, list)) or v):
            rval[k] = v
    return dumper.represent_data(rval)

Response: YAML callback that dumps the root node of the object.


Instruction:
Write a Python 3 script for
generating a markdown documentation of a biolink model

Response:
def cli(yamlfile, format, dir, classes, img, noimages):
    """ Generate markdown documentation of a biolink model """
    MarkdownGenerator(yamlfile, format).serialize(classes=classes, directory=dir, image_dir=img, noimages=noimages)


Instruction:
Can you tell what is the following Python 3 function doing
def is_secondary_ref(self, en: str) -> bool:
        if not self.gen_classes:
            return True
        elif en in self.schema.classes:
            return en in self.gen_classes_neighborhood.classrefs
        elif en in self.schema.slots:
            return en in self.gen_classes_neighborhood.slotrefs
        elif en in self.schema.types:
            return en in self.gen_classes_neighborhood.typerefs
        else:
            return True

Response: Determine whether the element name en is the name of a secondary reference.


Instruction:
Write a Python 3 script to
return a description for the object if it is unique.

Response:
def desc_for(self, obj: Element, doing_descs: bool) -> str:
        """ Return a description for object if it is unique (different than its parent)

        @param obj: object to be described
        @param doing_descs: If false, always return an empty string
        @return: text or empty string
        """
        if obj.description and doing_descs:
            if isinstance(obj, SlotDefinition) and obj.is_a:
                parent = self.schema.slots[obj.is_a]
            elif isinstance(obj, ClassDefinition) and obj.is_a:
                parent = self.schema.classes[obj.is_a]
            else:
                parent = None
            return '' if parent and obj.description == parent.description else obj.description
        return ''


Instruction:
Here you have a function in Python 3, explain what it does
def link(self, ref: Optional[Union[str, Element]], *, after_link: str = None, use_desc: bool=False,
             add_subset: bool=True) -> str:
        """ Create a link to ref if appropriate.

        @param ref: the name or value of a class, slot, type or the name of a built in type.
        @param after_link: Text to put between link and description
        @param use_desc: True means append a description after the link if available
        @param add_subset: True means add any subset information that is available
        @return:
        """
        obj = self.obj_for(ref) if isinstance(ref, str) else ref
        nl = '\n'
        if isinstance(obj, str) or obj is None or not self.is_secondary_ref(obj.name):
            return self.bbin(ref)
        if isinstance(obj, SlotDefinition):
            link_name = ((be(obj.domain) + '.') if obj.alias else '') + self.aliased_slot_name(obj)
            link_ref = underscore(obj.name)
        else:
            link_name = self.obj_name(obj)
            link_ref = link_name
        desc = self.desc_for(obj, use_desc)
        return f'[{link_name}]' \
               f'({link_ref}.{self.format})' + \
                 (f' *subsets*: ({"| ".join(obj.in_subset)})' if add_subset and obj.in_subset else '') + \
                 (f' {after_link} ' if after_link else '') + (f' - {desc.split(nl)[0]}' if desc else '')

Response: Create a link to the name of a class slot type or a built in type.


Instruction:
Can you create a Python 3 function that
generates an OWL representation of a biolink model

Response:
def cli(yamlfile, format, output):
    """ Generate an OWL representation of a biolink model """
    print(OwlSchemaGenerator(yamlfile, format).serialize(output=output))


Instruction:
How would you explain what the following Python 3 function does
def visit_slot(self, slot_name: str, slot: SlotDefinition) -> None:
        # Note: We use the raw name in OWL and add a subProperty arc
        slot_uri = self.prop_uri(slot.name)

        # Parent slots
        if slot.is_a:
            self.graph.add((slot_uri, RDFS.subPropertyOf, self.prop_uri(slot.is_a)))
        for mixin in slot.mixins:
            self.graph.add((slot_uri, RDFS.subPropertyOf, self.prop_uri(mixin)))

        # Slot range
        if not slot.range or slot.range in builtin_names:
            self.graph.add((slot_uri, RDF.type,
                            OWL.DatatypeProperty if slot.object_property else OWL.AnnotationProperty))
            self.graph.add((slot_uri, RDFS.range, URIRef(builtin_uri(slot.range, expand=True))))
        elif slot.range in self.schema.types:
            self.graph.add((slot_uri, RDF.type,
                            OWL.DatatypeProperty if slot.object_property else OWL.AnnotationProperty))
            self.graph.add((slot_uri, RDFS.range, self.type_uri(slot.range)))
        else:
            self.graph.add((slot_uri, RDF.type, OWL.ObjectProperty if slot.object_property else OWL.AnnotationProperty))
            self.graph.add((slot_uri, RDFS.range, self.class_uri(slot.range)))

        # Slot domain
        if slot.domain:
            self.graph.add((slot_uri, RDFS.domain, self.class_uri(slot.domain)))

        # Annotations
        self.graph.add((slot_uri, RDFS.label, Literal(slot.name)))
        if slot.description:
            self.graph.add((slot_uri, OBO.IAO_0000115, Literal(slot.description)))

Response: Add a slot definition per slot_name.


Instruction:
Write a Python 3 function for
loading and flatten a schema from a file name URL or a block of text.

Response:
def load_raw_schema(data: Union[str, TextIO],
                    source_file: str=None,
                    source_file_date: str=None,
                    source_file_size: int=None,
                    base_dir: Optional[str]=None) -> SchemaDefinition:
    """ Load and flatten SchemaDefinition from a file name, a URL or a block of text

    @param data: URL, file name or block of text
    @param source_file: Source file name for the schema
    @param source_file_date: timestamp of source file
    @param source_file_size: size of source file
    @param base_dir: Working directory of sources
    @return: Map from schema name to SchemaDefinition
    """
    if isinstance(data, str):
        if '\n' in data:
            return load_raw_schema((cast(TextIO, StringIO(data))))  # Not sure why typing doesn't see StringIO as TextIO
        elif '://' in data:
            # TODO: complete and test URL access
            req = Request(data)
            req.add_header("Accept", "application/yaml, text/yaml;q=0.9")
            with urlopen(req) as response:
                return load_raw_schema(response)
        else:
            fname = os.path.join(base_dir if base_dir else '', data)
            with open(fname) as f:
                return load_raw_schema(f, data, time.ctime(os.path.getmtime(fname)), os.path.getsize(fname))
    else:
        schemadefs = yaml.load(data, DupCheckYamlLoader)
        # Some schemas don't have an outermost identifier.  Construct one if necessary
        if 'name' in schemadefs:
            schemadefs = {schemadefs.pop('name'): schemadefs}
        elif 'id' in schemadefs:
            schemadefs = {schemadefs['id']: schemadefs}
        elif len(schemadefs) > 1 or not isinstance(list(schemadefs.values())[0], dict):
            schemadefs = {'Unnamed Schema': schemadefs}
        schema: SchemaDefinition = None
        for sname, sdef in {k: SchemaDefinition(name=k, **v) for k, v in schemadefs.items()}.items():
            if schema is None:
                schema = sdef
                schema.source_file = os.path.basename(source_file) if source_file else None
                schema.source_file_date = source_file_date
                schema.source_file_size = source_file_size
                schema.generation_date =  datetime.now().strftime("%Y-%m-%d %H:%M")
                schema.metamodel_version = metamodel_version
            else:
                merge_schemas(schema, sdef)
        return schema


Instruction:
Implement a function in Python 3 to
construct a mapping from a node.

Response:
def map_constructor(self, loader,  node, deep=False):
        """ Walk the mapping, recording any duplicate keys.

        """
        mapping = {}
        for key_node, value_node in node.value:
            key = loader.construct_object(key_node, deep=deep)
            value = loader.construct_object(value_node, deep=deep)
            if key in mapping:
                raise ValueError(f"Duplicate key: \"{key}\"")
            mapping[key] = value

        return mapping


Instruction:
Can you create a Python 3 function that
compares two files using a filter

Response:
def cli(file1, file2, comments) -> int:
    """ Compare file1 to file2 using a filter """
    sys.exit(compare_files(file1, file2, comments))


Instruction:
Can you generate the documentation for the following Python 3 function
def cli(file, dir, format):
    print(GolrSchemaGenerator(file, format).serialize(dirname=dir))

Response: Generate GOLR representation of a biolink model


Instruction:
Make a summary of the following Python 3 code
def cli(yamlfile, directory, out, classname, format):
    DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)

Response: Generate graphviz representations of the biolink model


Instruction:
Write a Python 3 script to
generate JSONLD file from biolink schema

Response:
def cli(yamlfile, format, context):
    """ Generate JSONLD file from biolink schema """
    print(JSONLDGenerator(yamlfile, format).serialize(context=context))


Instruction:
Make a summary of the following Python 3 code
def cli(yamlfile, format, output, context):
    print(RDFGenerator(yamlfile, format).serialize(output=output, context=context))

Response: Generate an RDF representation of a biolink model


Instruction:
How would you implement a function in Python 3 that
returns the list of slots directly included in the class definition.

Response:
def cls_slots(self, cls: CLASS_OR_CLASSNAME) -> List[SlotDefinition]:
        """ Return the list of slots directly included in the class definition.  Includes slots whose
        domain is cls -- as declared in slot.domain or class.slots

        Does not include slots declared in mixins, apply_to or is_a links

        @param cls: class name or class definition name
        @return: all direct class slots
        """
        if not isinstance(cls, ClassDefinition):
            cls = self.schema.classes[cls]
        return [self.schema.slots[s] for s in cls.slots]


Instruction:
Write a Python 3 script for
returning all slots that are part of the class definition.

Response:
def all_slots(self, cls: CLASS_OR_CLASSNAME, *, cls_slots_first: bool = False) \
            -> List[SlotDefinition]:
        """ Return all slots that are part of the class definition.  This includes all is_a, mixin and apply_to slots
        but does NOT include slot_usage targets.  If class B has a slot_usage entry for slot "s", only the slot
        definition for the redefined slot will be included, not its base.  Slots are added in the order they appear
        in classes, with recursive is_a's being added first followed by mixins and finally apply_tos

        @param cls: class definition or class definition name
        @param cls_slots_first: True means return class slots at the top of the list
        @return: ordered list of slots in the class with slot usages removed
        """
        def merge_definitions(cls_name: Optional[ClassDefinitionName]) -> None:
            if cls_name:
                for slot in self.all_slots(cls_name):
                    aliased_name = self.aliased_slot_name(slot)
                    if aliased_name not in known_slots:
                        known_slots.add(aliased_name)
                        rval.append(slot)

        if not isinstance(cls, ClassDefinition):
            cls = self.schema.classes[cls]
        known_slots: Set[str] = self.aliased_slot_names(cls.slots)
        rval: List[SlotDefinition] = []

        if cls_slots_first:
            rval += self.cls_slots(cls)
            for mixin in cls.mixins:
                merge_definitions(mixin)
            merge_definitions(cls.is_a)
        else:
            merge_definitions(cls.is_a)
            for mixin in cls.mixins:
                merge_definitions(mixin)
            rval += self.cls_slots(cls)

        return rval


Instruction:
Can you generate a brief explanation for the following Python 3 code
def ancestors(self, definition: Union[SLOT_OR_SLOTNAME,
                                          CLASS_OR_CLASSNAME]) \
            -> List[Union[SlotDefinitionName, ClassDefinitionName]]:
        """ Return an ordered list of ancestor names for the supplied slot or class

        @param definition: Slot or class name or definition
        @return: List of ancestor names
        """
        definition = self.obj_for(definition)
        if definition is not None:
            return [definition.name] + self.ancestors(definition.is_a)
        else:
            return []

Response: Return an ordered list of ancestor names for the supplied slot or class name or class.


Instruction:
How would you code a function in Python 3 to
return a list of all slots classes and types that touch any element in elements including the element itself.

Response:
def neighborhood(self, elements: List[ELEMENT_NAME]) \
            -> References:
        """ Return a list of all slots, classes and types that touch any element in elements, including the element
        itself

        @param elements: Elements to do proximity with
        @return: All slots and classes that touch element
        """
        touches = References()
        for element in elements:
            if element in self.schema.classes:
                touches.classrefs.add(element)
                if None in touches.classrefs:
                    raise ValueError("1")
                cls = self.schema.classes[element]
                if cls.is_a:
                    touches.classrefs.add(cls.is_a)
                if None in touches.classrefs:
                    raise ValueError("1")
                # Mixins include apply_to's
                touches.classrefs.update(set(cls.mixins))
                for slotname in cls.slots:
                    slot = self.schema.slots[slotname]
                    if slot.range in self.schema.classes:
                        touches.classrefs.add(slot.range)
                    elif slot.range in self.schema.types:
                        touches.typerefs.add(slot.range)
                    if None in touches.classrefs:
                        raise ValueError("1")
                if element in self.synopsis.rangerefs:
                    for slotname in self.synopsis.rangerefs[element]:
                        touches.slotrefs.add(slotname)
                        if self.schema.slots[slotname].domain:
                            touches.classrefs.add(self.schema.slots[slotname].domain)
            elif element in self.schema.slots:
                touches.slotrefs.add(element)
                slot = self.schema.slots[element]
                touches.slotrefs.update(set(slot.mixins))
                if slot.is_a:
                    touches.slotrefs.add(slot.is_a)
                if element in self.synopsis.inverses:
                    touches.slotrefs.update(self.synopsis.inverses[element])
                if slot.domain:
                    touches.classrefs.add(slot.domain)
                if slot.range in self.schema.classes:
                    touches.classrefs.add(slot.range)
                elif slot.range in self.schema.types:
                    touches.typerefs.add(slot.range)
            elif element in self.schema.types:
                if element in self.synopsis.rangerefs:
                    touches.slotrefs.update(self.synopsis.rangerefs[element])

        return touches


Instruction:
Create a Python 3 function for
chasing the slot range to its final form

Response:
def grounded_slot_range(self, slot: Optional[Union[SlotDefinition, Optional[str]]]) -> str:
        """ Chase the slot range to its final form

        @param slot: slot to check
        @return: name of resolved range
        """
        if slot is not None and not isinstance(slot, str):
            slot = slot.range
        if slot is None:
            return DEFAULT_BUILTIN_TYPE_NAME         # Default type name
        elif slot in builtin_names:
            return slot
        elif slot in self.schema.types:
            return self.grounded_slot_range(self.schema.types[slot].typeof)
        else:
            return slot


Instruction:
Implement a Python 3 function for
returning the overloaded slot name if one exists otherwise the actual name

Response:
def aliased_slot_name(self, slot: SLOT_OR_SLOTNAME) -> str:
        """ Return the overloaded slot name -- the alias if one exists otherwise the actual name

        @param slot: either a slot name or a definition
        @return: overloaded name
        """
        if isinstance(slot, str):
            slot = self.schema.slots[slot]
        return slot.alias if slot.alias else slot.name


Instruction:
Create a Python 3 function to
return the aliased slot names for all members of the list .

Response:
def aliased_slot_names(self, slot_names: List[SlotDefinitionName]) -> Set[str]:
        """ Return the aliased slot names for all members of the list

        @param slot_names: actual slot names
        @return: aliases w/ duplicates removed
        """
        return {self.aliased_slot_name(sn) for sn in slot_names}


Instruction:
Implement a function in Python 3 to
return the class slot or type that represents name or name itself if it is a builtin type or None if not found.

Response:
def obj_for(self, obj_or_name: Union[str, Element]) -> Optional[Union[str, Element]]:
        """ Return the class, slot or type that represents name or name itself if it is a builtin

        @param obj_or_name: Object or name
        @return: Corresponding element or None if not found (most likely cause is that it is a builtin type)
        """
        name = obj_or_name.name if isinstance(obj_or_name, Element) else obj_or_name
        return self.schema.classes[name] if name in self.schema.classes \
            else self.schema.slots[name] if name in self.schema.slots \
            else self.schema.types[name] if name in self.schema.types else name if name in builtin_names \
            else None


Instruction:
Can you create a Python 3 function that
returns the formatted name used for the supplied object

Response:
def obj_name(self, obj: Union[str, Element]) -> str:
        """ Return the formatted name used for the supplied definition """
        if isinstance(obj, str):
            obj = self.obj_for(obj)
        if isinstance(obj, SlotDefinition):
            return underscore(self.aliased_slot_name(obj))
        else:
            return camelcase(obj if isinstance(obj, str) else obj.name)


Instruction:
Can you write a function in Python 3 where it
generates CSV file from biolink model

Response:
def cli(yamlfile, root, format):
    """ Generate CSV/TSV file from biolink model """
    print(CsvGenerator(yamlfile, format).serialize(classes=root))


Instruction:
Make a summary of the following Python 3 code
def gen_inherited(self) -> str:
        inherited_head = 'inherited_slots: List[str] = ['
        inherited_slots = ', '.join([f'"{underscore(slot.name)}"' for slot in self.schema.slots.values()
                                     if slot.inherited])
        is_rows = split_line(inherited_slots, 120 - len(inherited_head))
        return inherited_head + ('\n' + len(inherited_head) * ' ').join([r.strip() for r in is_rows]) + ']'

Response: Generate the list of slot properties that are inherited across slot usage or is_a paths


Instruction:
Can you generate a brief explanation for the following Python 3 code
def gen_references(self) -> str:
        rval = []
        for cls in self.schema.classes.values():
            pkeys = self.primary_keys_for(cls)
            for pk in pkeys:
                pk_slot = self.schema.slots[pk]
                classname = camelcase(cls.name) + camelcase(pk)
                if cls.is_a and getattr(self.schema.classes[cls.is_a], pk, None):
                    parent = self.range_type_name(pk_slot, cls.is_a)
                else:
                    parent = self.python_name_for(pk_slot.range)
                rval.append(f'class {classname}({parent}):\n\tpass')
        return '\n\n\n'.join(rval)

Response: Generate python type declarations for all identifiers


Instruction:
Create a Python 3 function to
generate python type declarations for all defined types

Response:
def gen_typedefs(self) -> str:
        """ Generate python type declarations for all defined types """
        rval = []
        for typ in self.schema.types.values():
            typname = self.python_name_for(typ.name)
            parent = self.python_name_for(typ.typeof)
            rval.append(f'class {typname}({parent}):\n\tpass')
        return '\n\n\n'.join(rval) + ('\n' if rval else '')


Instruction:
Make a summary of the following Python 3 code
def gen_classdefs(self) -> str:
        return '\n'.join([self.gen_classdef(k, v) for k, v in self.schema.classes.items() if not v.mixin])

Response: Generate class definitions for all non - mixin classes in the model


Instruction:
Implement a function in Python 3 to
generate python definition for class clsname

Response:
def gen_classdef(self, clsname: str,  cls: ClassDefinition) -> str:
        """ Generate python definition for class clsname """
        parentref = f'({self.python_name_for(cls.is_a) if cls.is_a else "YAMLRoot"})'
        slotdefs = self.gen_slot_variables(cls)
        postinits = self.gen_postinits(cls)
        if not slotdefs:
            slotdefs = 'pass'
        wrapped_description = f'''
    """
    {wrapped_annotation(be(cls.description))}
    """''' if be(cls.description) else ''
        return f'''
@dataclass
class {camelcase(clsname)}{parentref}:{wrapped_description}
    {slotdefs}
    {postinits}'''


Instruction:
How would you code a function in Python 3 to
generate python definition for class cls generating primary keys first followed by the rest of the slots

Response:
def gen_slot_variables(self, cls: ClassDefinition) -> str:
        """ Generate python definition for class cls, generating primary keys first followed by the rest of the slots
        """
        return '\n\t'.join([self.gen_slot_variable(cls, pk) for pk in self.primary_keys_for(cls)] +
                           [self.gen_slot_variable(cls, slot)
                            for slot in cls.slots
                            if not self.schema.slots[slot].primary_key and not self.schema.slots[slot].identifier])


Instruction:
Write a Python 3 script for
generating a slot variable for the given slotname as defined in class

Response:
def gen_slot_variable(self, cls: ClassDefinition, slotname: str) -> str:
        """ Generate a slot variable for slotname as defined in class
        """
        slot = self.schema.slots[slotname]

        # Alias allows re-use of slot names in different contexts
        if slot.alias:
            slotname = slot.alias

        range_type = self.range_type_name(slot, cls.name)
        # Python version < 3.7 -- forward references have to be quoted
        if slot.inlined and slot.range in self.schema.classes and self.forward_reference(slot.range, cls.name):
            range_type = f'"{range_type}"'
        slot_range, default_val = self.range_cardinality(range_type, slot, cls)
        default = f'= {default_val}' if default_val else ''
        return f'''{underscore(slotname)}: {slot_range} {default}'''


Instruction:
Make a summary of the following Python 3 code
def gen_postinits(self, cls: ClassDefinition) -> str:
        post_inits = []
        if not cls.abstract:
            pkeys = self.primary_keys_for(cls)
            for pkey in pkeys:
                post_inits.append(self.gen_postinit(cls, pkey))
        for slotname in cls.slots:
            slot = self.schema.slots[slotname]
            if not (slot.primary_key or slot.identifier):
                post_inits.append(self.gen_postinit(cls, slotname))
        post_inits_line = '\n\t\t'.join([p for p in post_inits if p])
        return (f'''
    def _fix_elements(self):
        super()._fix_elements()
        {post_inits_line}''' + '\n') if post_inits_line else ''

Response: Generate all the typing and existence checks post initialize


Instruction:
How would you explain what the following Python 3 function does
def gen_postinit(self, cls: ClassDefinition, slotname: str) -> Optional[str]:
        rlines: List[str] = []
        slot = self.schema.slots[slotname]
        if slot.alias:
            slotname = slot.alias
        slotname = self.python_name_for(slotname)
        range_type_name = self.range_type_name(slot, cls.name)

        # Generate existence check for required slots.  Note that inherited classes have to check post-init because
        # named variables can't be mixed in the class signature
        if slot.primary_key or slot.identifier or slot.required:
            if cls.is_a:
                rlines.append(f'if self.{slotname} is None:')
                rlines.append(f'\traise ValueError(f"{slotname} must be supplied")')
                rlines.append(f'if not isinstance(self.{slotname}, {range_type_name}):')
                rlines.append(f'\tself.{slotname} = {range_type_name}(self.{slotname})')
        elif slot.range in self.schema.classes or slot.range in self.schema.types:
            if not slot.multivalued:
                rlines.append(f'if self.{slotname} and not isinstance(self.{slotname}, {range_type_name}):')
                # Another really wierd case -- a class that has no properties
                if slot.range in self.schema.classes and not self.all_slots_for(self.schema.classes[slot.range]):
                    rlines.append(f'\tself.{slotname} = {range_type_name}()')
                else:
                    rlines.append(f'\tself.{slotname} = {range_type_name}(self.{slotname})')
            elif slot.inlined:
                slot_range_cls = self.schema.classes[slot.range]
                pkeys = self.primary_keys_for(slot_range_cls)
                if pkeys:
                    # Special situation -- if there are only two values: primary key and value,
                    # we load it is a list, not a dictionary
                    if len(self.all_slots_for(slot_range_cls)) - len(pkeys) == 1:
                        class_init = '(k, v)'
                    else:
                        pkey_name = self.python_name_for(pkeys[0])
                        class_init = f'({pkey_name}=k, **({{}} if v is None else v))'
                    rlines.append(f'for k, v in self.{slotname}.items():')
                    rlines.append(f'\tif not isinstance(v, {range_type_name}):')
                    rlines.append(f'\t\tself.{slotname}[k] = {range_type_name}{class_init}')
            else:
                rlines.append(f'self.{slotname} = [v if isinstance(v, {range_type_name})')
                indent = len(f'self.{slotname} = [') * ' '
                rlines.append(f'{indent}else {range_type_name}(v) for v in self.{slotname}]')
        return '\n\t\t'.join(rlines)

Response: Generate python post - init rules for a class.


Instruction:
Write a Python 3 function that can
return all primary keys for cls

Response:
def primary_keys_for(self, cls: ClassDefinition) -> List[SlotDefinitionName]:
        """ Return all primary keys / identifiers for cls

        @param cls: class to get keys for
        @return: List of primary keys
        """
        return [slot_name for slot_name in self.all_slots_for(cls)
                if self.schema.slots[slot_name].primary_key or self.schema.slots[slot_name].identifier]


Instruction:
How would you explain what the following Python 3 function does
def all_slots_for(self, cls: ClassDefinition) -> List[SlotDefinitionName]:
        if not cls.is_a:
            return cls.slots
        else:
            return [sn for sn in self.all_slots_for(self.schema.classes[cls.is_a]) if sn not in cls.slot_usage] \
                   + cls.slots

Response: Return all slots for the given class cls.


Instruction:
Can you tell what is the following Python 3 function doing
def range_type_name(self, slot: SlotDefinition, containing_class_name: ClassDefinitionName) -> str:
        if slot.primary_key or slot.identifier:
            return self.python_name_for(containing_class_name) + camelcase(slot.name)

        if slot.range in self.schema.classes and not slot.inlined:
            class_key = self.key_name_for(cast(ClassDefinitionName, slot.range))
            if class_key:
                return class_key
        return self.python_name_for(slot.range)

Response: Generate the type name for the given slot.


Instruction:
Can you generate the documentation for the following Python 3 function
def forward_reference(self, slot_range: str, owning_class: str) -> bool:
        for cname in self.schema.classes:
            if cname == owning_class:
                return True             # Occurs on or after
            elif cname == slot_range:
                return False            # Occurs before
        return True

Response: Determines whether the given slot_range is a forward reference.


Instruction:
Make a summary of the following Python 3 code
def resolve(self) -> SchemaDefinition:

        if not isinstance(self.schema.slots, dict):
            raise ValueError(f"File: {self.schema.source_file} Slots are not a dictionary")

        if not isinstance(self.schema.classes, dict):
            raise ValueError(f"File: {self.schema.source_file} Classes are not a dictionary")

        # Process imports
        for sname in self.schema.imports:
            if sname not in self.loaded:
                self.loaded.add(sname)
                merge_schemas(self.schema, load_raw_schema(sname + '.yaml', base_dir=self.base_dir))

        # slot.domain --> class.slots
        for slot in self.schema.slots.values():
            if slot.domain in self.schema.classes and slot.name not in self.schema.classes[slot.domain].slots:
                self.schema.classes[slot.domain].slots.append(slot.name)

        # class.slots --> slot.domain
        for cls in self.schema.classes.values():
            if not isinstance(cls, ClassDefinition):
                raise ValueError(
                    f'File: {self.schema.source_file} Class "{cls} (type: {type(cls)})" definition is peculiar')
            if isinstance(cls.slots, str):
                print(f"File: {self.schema.source_file} Class: {cls.name} Slots are not an array", file=sys.stderr)
                cls.slots = [cls.slots]
            for slotname in cls.slots:
                if slotname in self.schema.slots:
                    if self.schema.slots[slotname].domain is None:
                        self.schema.slots[slotname].domain = cls.name

        # apply to --> mixins
        for cls in self.schema.classes.values():
            if cls.apply_to in self.schema.classes:
                self.schema.classes[cls.apply_to].mixins.append(cls.name)

        # Override class slots with slot usage definitions
        for cls in self.schema.classes.values():
            for slot_name, slot_usage in cls.slot_usage.items():
                # Construct a new slot
                # Follow the ancestry of the class to get the most proximal parent
                parent_slot = self.slot_definition_for(slot_name, cls)
                if not parent_slot and slot_name in self.schema.slots:
                    parent_slot = self.schema.slots[slot_name]
                # If parent slot is still not defined, it means that we introduced a NEW slot in the slot usages
                child_name = SlotDefinitionName(cls.name + ' ' + slot_name) if parent_slot else slot_name
                new_slot = SlotDefinition(name=child_name, alias=slot_name, domain=cls.name)
                merge_slots(new_slot, slot_usage)

                # Copy the parent definition.  If there is no parent definition, the slot is being defined
                # locally as a slot_usage
                if parent_slot is not None:
                    new_slot.is_a = parent_slot.name
                    merge_slots(new_slot, parent_slot)

                # Add the slot usage overrides
                merge_slots(new_slot, slot_usage)
                self.schema.slots[child_name] = new_slot

                # Add or replace the slot in the class definition
                append = True
                for i, s in enumerate(cls.slots):
                    if s == slot_name:
                        cls.slots[i] = SlotDefinitionName(child_name)
                        append = False
                        break
                if append:
                    cls.slots.append(SlotDefinitionName(child_name))

        # Update slots with parental information
        merged_slots: List[SlotDefinition] = []
        for slot in self.schema.slots.values():
            self.merge_slot(slot, merged_slots)

        # Clean up the slot range defaults
        for slot in self.schema.slots.values():
            if not slot.range:
                slot.range = 'string'

        return self.schema

Response: Resolve the schema to a fully resolved version of the schema.


Instruction:
Write a Python 3 function that can
find the most proximal definition for the given slotname in the context of cls.

Response:
def slot_definition_for(self, slotname: SlotDefinitionName, cls: ClassDefinition) -> Optional[SlotDefinition]:
        """ Find the most proximal definition for slotname in the context of cls"""
        if cls.is_a:
            for sn in self.schema.classes[cls.is_a].slots:
                slot = self.schema.slots[sn]
                if slot.alias and slotname == slot.alias or slotname == slot.name:
                    return slot
        for mixin in cls.mixins:
            for sn in self.schema.classes[mixin].slots:
                slot = self.schema.slots[sn]
                if slot.alias and slotname == slot.alias or slotname == slot.name:
                    return slot
        if cls.is_a:
            defn = self.slot_definition_for(slotname, self.schema.classes[cls.is_a])
            if defn:
                return defn
        for mixin in cls.mixins:
            defn = self.slot_definition_for(slotname, self.schema.classes[mixin])
            if defn:
                return defn
        return None


Instruction:
Implement a Python 3 function for
generating a UML representation of a biolink model

Response:
def cli(yamlfile, format, classes, directory):
    """ Generate a UML representation of a biolink model """
    print(YumlGenerator(yamlfile, format).serialize(classes=classes, directory=directory), end="")


Instruction:
Explain what the following Python 3 code does
def class_box(self, cn: ClassDefinitionName) -> str:
        slot_defs: List[str] = []
        if cn not in self.box_generated and (not self.focus_classes or cn in self.focus_classes):
            cls = self.schema.classes[cn]
            for slotname in self.filtered_cls_slots(cn, all_slots=True):
                slot = self.schema.slots[slotname]
                if not slot.range or slot.range in builtin_names or slot.range in self.schema.types:
                    mod = self.prop_modifier(cls, slot)
                    slot_defs.append(underscore(self.aliased_slot_name(slot)) +
                                     mod + ':' +
                                     underscore(slot.range) + self.cardinality(slot))
            self.box_generated.add(cn)
        self.referenced.add(cn)
        return '[' + camelcase(cn) + ('|' + ';'.join(slot_defs) if slot_defs else '') + ']'

Response: Generates a box for the class.


Instruction:
How would you code a function in Python 3 to
emit all associations for a focus class.

Response:
def class_associations(self, cn: ClassDefinitionName, must_render: bool=False) -> str:
        """ Emit all associations for a focus class.  If none are specified, all classes are generated

        @param cn: Name of class to be emitted
        @param must_render: True means render even if this is a target (class is specifically requested)
        @return: YUML representation of the association
        """

        # NOTE: YUML diagrams draw in the opposite order in which they are created, so we work from bottom to top and
        # from right to left
        assocs: List[str] = []
        if cn not in self.associations_generated and (not self.focus_classes or cn in self.focus_classes):
            cls = self.schema.classes[cn]

            # Slots
            for slotname in self.filtered_cls_slots(cn, False)[::-1]:
                slot = self.schema.slots[slotname]
                if slot.range in self.schema.classes:
                    assocs.append(self.class_box(cn) + (yuml_inline if slot.inlined else yuml_ref) +
                                  self.aliased_slot_name(slot) + self.prop_modifier(cls, slot) +
                                  self.cardinality(slot) + '>' + self.class_box(slot.range))

            # Referencing slots
            if cn in self.synopsis.rangerefs:
                for slotname in sorted(self.synopsis.rangerefs[cn]):
                    slot = self.schema.slots[slotname]
                    if slot.domain in self.schema.classes and (slot.range != cls.name or must_render):
                        assocs.append(self.class_box(slot.domain) + (yuml_inline if slot.inlined else yuml_ref) +
                                      self.aliased_slot_name(slot) + self.prop_modifier(cls, slot) +
                                      self.cardinality(slot) + '>' + self.class_box(cn))

            # Mixins used in the class
            for mixin in cls.mixins:
                assocs.append(self.class_box(cn) + yuml_uses + self.class_box(mixin))

            # Classes that use the class as a mixin
            if cls.name in self.synopsis.mixinrefs:
                for mixin in sorted(self.synopsis.mixinrefs[cls.name].classrefs, reverse=True):
                    assocs.append(self.class_box(ClassDefinitionName(mixin)) + yuml_uses + self.class_box(cn))

            # Classes that inject information
            if cn in self.synopsis.applytos:
                for injector in sorted(self.synopsis.applytos[cn].classrefs, reverse=True):
                    assocs.append(self.class_box(cn) + yuml_injected + self.class_box(ClassDefinitionName(injector)))
            self.associations_generated.add(cn)

            # Children
            if cn in self.synopsis.isarefs:
                for is_a_cls in sorted(self.synopsis.isarefs[cn].classrefs, reverse=True):
                    assocs.append(self.class_box(cn) + yuml_is_a + self.class_box(ClassDefinitionName(is_a_cls)))

            # Parent
            if cls.is_a:
                assocs.append(self.class_box(cls.is_a) + yuml_is_a + self.class_box(cn))
        return ', '.join(assocs)


Instruction:
Write a Python 3 script to
return the set of slots associated with the class that meet the filter criteria.

Response:
def filtered_cls_slots(self, cn: ClassDefinitionName, all_slots: bool=True) \
            -> List[SlotDefinitionName]:
        """ Return the set of slots associated with the class that meet the filter criteria.  Slots will be returned
        in defining order, with class slots returned last

        @param cn: name of class to filter
        @param all_slots: True means include attributes
        @return: List of slot definitions
        """
        rval = []
        cls = self.schema.classes[cn]
        cls_slots = self.all_slots(cls, cls_slots_first=True)
        for slot in cls_slots:
            if all_slots or slot.range in self.schema.classes:
                rval.append(slot.name)

        return rval


Instruction:
Implement a Python 3 function for
returning the modifiers for the given slot.

Response:
def prop_modifier(self, cls: ClassDefinition, slot: SlotDefinition) -> str:
        """ Return the modifiers for the slot:
            (i) - inherited
            (m) - inherited through mixin
            (a) - injected
            (pk) - primary ckey

        @param cls:
        @param slot:
        @return:
        """
        pk = '(pk)' if slot.primary_key else ''
        inherited = slot.name not in cls.slots
        mixin = inherited and slot.name in \
                [mslot.name for mslot in [self.schema.classes[m] for m in cls.mixins]]
        injected = cls.name in self.synopsis.applytos and \
                   slot.name in [aslot.name for aslot in
                                 [self.schema.classes[a] for a in sorted(self.synopsis.applytos[cls.name].classrefs)]]
        return pk + '(a)' if injected else '(m)' if mixin else '(i)' if inherited else ''


Instruction:
Can you create a Python 3 function that
generates a ShEx Schema for a biolink model

Response:
def cli(yamlfile, format, output, collections):
    """ Generate a ShEx Schema for a  biolink model """
    print(ShExGenerator(yamlfile, format).serialize(output=output, collections=collections))


Instruction:
Write a Python 3 script to
generate a shape that represents an RDF list of target_type

Response:
def gen_multivalued_slot(self, target_name_base: str, target_type: IRIREF) -> IRIREF:
        """ Generate a shape that represents an RDF list of target_type

        @param target_name_base:
        @param target_type:
        @return:
        """
        list_shape_id = IRIREF(target_name_base + "__List")
        if list_shape_id not in self.list_shapes:
            list_shape = Shape(id=list_shape_id, closed=True)
            list_shape.expression = EachOf()
            expressions = [TripleConstraint(predicate=RDF.first, valueExpr=target_type, min=0, max=1)]
            targets = ShapeOr()
            targets.shapeExprs = [(NodeConstraint(values=[RDF.nil])), list_shape_id]
            expressions.append(TripleConstraint(predicate=RDF.rest, valueExpr=targets))
            list_shape.expression.expressions = expressions
            self.shapes.append(list_shape)
            self.list_shapes.append(list_shape_id)
        return list_shape_id