Instruction:
How would you explain what the following Python 3 function does
def create_box(width=1, height=1, depth=1, width_segments=1, height_segments=1,
               depth_segments=1, planes=None):
    """ Generate vertices & indices for a filled and outlined box.

    Parameters
    ----------
    width : float
        Box width.
    height : float
        Box height.
    depth : float
        Box depth.
    width_segments : int
        Box segments count along the width.
    height_segments : float
        Box segments count along the height.
    depth_segments : float
        Box segments count along the depth.
    planes: array_like
        Any combination of ``{'-x', '+x', '-y', '+y', '-z', '+z'}``
        Included planes in the box construction.

    Returns
    -------
    vertices : array
        Array of vertices suitable for use as a VertexBuffer.
    faces : array
        Indices to use to produce a filled box.
    outline : array
        Indices to use to produce an outline of the box.
    """

    planes = (('+x', '-x', '+y', '-y', '+z', '-z')
              if planes is None else
              [d.lower() for d in planes])

    w_s, h_s, d_s = width_segments, height_segments, depth_segments

    planes_m = []
    if '-z' in planes:
        planes_m.append(create_plane(width, depth, w_s, d_s, '-z'))
        planes_m[-1][0]['position'][..., 2] -= height / 2
    if '+z' in planes:
        planes_m.append(create_plane(width, depth, w_s, d_s, '+z'))
        planes_m[-1][0]['position'][..., 2] += height / 2

    if '-y' in planes:
        planes_m.append(create_plane(height, width, h_s, w_s, '-y'))
        planes_m[-1][0]['position'][..., 1] -= depth / 2
    if '+y' in planes:
        planes_m.append(create_plane(height, width, h_s, w_s, '+y'))
        planes_m[-1][0]['position'][..., 1] += depth / 2

    if '-x' in planes:
        planes_m.append(create_plane(depth, height, d_s, h_s, '-x'))
        planes_m[-1][0]['position'][..., 0] -= width / 2
    if '+x' in planes:
        planes_m.append(create_plane(depth, height, d_s, h_s, '+x'))
        planes_m[-1][0]['position'][..., 0] += width / 2

    positions = np.zeros((0, 3), dtype=np.float32)
    texcoords = np.zeros((0, 2), dtype=np.float32)
    normals = np.zeros((0, 3), dtype=np.float32)

    faces = np.zeros((0, 3), dtype=np.uint32)
    outline = np.zeros((0, 2), dtype=np.uint32)

    offset = 0
    for vertices_p, faces_p, outline_p in planes_m:
        positions = np.vstack((positions, vertices_p['position']))
        texcoords = np.vstack((texcoords, vertices_p['texcoord']))
        normals = np.vstack((normals, vertices_p['normal']))

        faces = np.vstack((faces, faces_p + offset))
        outline = np.vstack((outline, outline_p + offset))
        offset += vertices_p['position'].shape[0]

    vertices = np.zeros(positions.shape[0],
                        [('position', np.float32, 3),
                         ('texcoord', np.float32, 2),
                         ('normal', np.float32, 3),
                         ('color', np.float32, 4)])

    colors = np.ravel(positions)
    colors = np.hstack((np.reshape(np.interp(colors,
                                             (np.min(colors),
                                              np.max(colors)),
                                             (0, 1)),
                                   positions.shape),
                        np.ones((positions.shape[0], 1))))

    vertices['position'] = positions
    vertices['texcoord'] = texcoords
    vertices['normal'] = normals
    vertices['color'] = colors

    return vertices, faces, outline

Response: Generates a new unfilled and outlined box.


Instruction:
Can you tell what is the following Python 3 function doing
def create_sphere(rows=10, cols=10, depth=10, radius=1.0, offset=True,
                  subdivisions=3, method='latitude'):
    """Create a sphere

    Parameters
    ----------
    rows : int
        Number of rows (for method='latitude' and 'cube').
    cols : int
        Number of columns (for method='latitude' and 'cube').
    depth : int
        Number of depth segments (for method='cube').
    radius : float
        Sphere radius.
    offset : bool
        Rotate each row by half a column (for method='latitude').
    subdivisions : int
        Number of subdivisions to perform (for method='ico')
    method : str
        Method for generating sphere. Accepts 'latitude' for latitude-
        longitude, 'ico' for icosahedron, and 'cube' for cube based
        tessellation.

    Returns
    -------
    sphere : MeshData
        Vertices and faces computed for a spherical surface.
    """
    if method == 'latitude':
        return _latitude(rows, cols, radius, offset)
    elif method == 'ico':
        return _ico(radius, subdivisions)
    elif method == 'cube':
        return _cube(rows, cols, depth, radius)
    else:
        raise Exception("Invalid method. Accepts: 'latitude', 'ico', 'cube'")

Response: Create a spherical sphere.


Instruction:
Here you have a function in Python 3, explain what it does
def create_cylinder(rows, cols, radius=[1.0, 1.0], length=1.0, offset=False):
    verts = np.empty((rows+1, cols, 3), dtype=np.float32)
    if isinstance(radius, int):
        radius = [radius, radius]  # convert to list
    # compute vertices
    th = np.linspace(2 * np.pi, 0, cols).reshape(1, cols)
    # radius as a function of z
    r = np.linspace(radius[0], radius[1], num=rows+1,
                    endpoint=True).reshape(rows+1, 1)
    verts[..., 2] = np.linspace(0, length, num=rows+1,
                                endpoint=True).reshape(rows+1, 1)  # z
    if offset:
        # rotate each row by 1/2 column
        th = th + ((np.pi / cols) * np.arange(rows+1).reshape(rows+1, 1))
    verts[..., 0] = r * np.cos(th)  # x = r cos(th)
    verts[..., 1] = r * np.sin(th)  # y = r sin(th)
    # just reshape: no redundant vertices...
    verts = verts.reshape((rows+1)*cols, 3)
    # compute faces
    faces = np.empty((rows*cols*2, 3), dtype=np.uint32)
    rowtemplate1 = (((np.arange(cols).reshape(cols, 1) +
                      np.array([[0, 1, 0]])) % cols) +
                    np.array([[0, 0, cols]]))
    rowtemplate2 = (((np.arange(cols).reshape(cols, 1) +
                      np.array([[0, 1, 1]])) % cols) +
                    np.array([[cols, 0, cols]]))
    for row in range(rows):
        start = row * cols * 2
        faces[start:start+cols] = rowtemplate1 + row * cols
        faces[start+cols:start+(cols*2)] = rowtemplate2 + row * cols

    return MeshData(vertices=verts, faces=faces)

Response: Create a new cylinder in the current system.


Instruction:
Write a Python 3 script for
creating a new cone in the current surface.

Response:
def create_cone(cols, radius=1.0, length=1.0):
    """Create a cone

    Parameters
    ----------
    cols : int
        Number of faces.
    radius : float
        Base cone radius.
    length : float
        Length of the cone.

    Returns
    -------
    cone : MeshData
        Vertices and faces computed for a cone surface.
    """
    verts = np.empty((cols+1, 3), dtype=np.float32)
    # compute vertexes
    th = np.linspace(2 * np.pi, 0, cols+1).reshape(1, cols+1)
    verts[:-1, 2] = 0.0
    verts[:-1, 0] = radius * np.cos(th[0, :-1])  # x = r cos(th)
    verts[:-1, 1] = radius * np.sin(th[0, :-1])  # y = r sin(th)
    # Add the extremity
    verts[-1, 0] = 0.0
    verts[-1, 1] = 0.0
    verts[-1, 2] = length
    verts = verts.reshape((cols+1), 3)  # just reshape: no redundant vertices
    # compute faces
    faces = np.empty((cols, 3), dtype=np.uint32)
    template = np.array([[0, 1]])
    for pos in range(cols):
        faces[pos, :-1] = template + pos
    faces[:, 2] = cols
    faces[-1, 1] = 0

    return MeshData(vertices=verts, faces=faces)


Instruction:
Implement a function in Python 3 to
create a 3D arrow using a cylinder plus a cone.

Response:
def create_arrow(rows, cols, radius=0.1, length=1.0,
                 cone_radius=None, cone_length=None):
    """Create a 3D arrow using a cylinder plus cone

    Parameters
    ----------
    rows : int
        Number of rows.
    cols : int
        Number of columns.
    radius : float
        Base cylinder radius.
    length : float
        Length of the arrow.
    cone_radius : float
        Radius of the cone base.
           If None, then this defaults to 2x the cylinder radius.
    cone_length : float
        Length of the cone.
           If None, then this defaults to 1/3 of the arrow length.

    Returns
    -------
    arrow : MeshData
        Vertices and faces computed for a cone surface.
    """
    # create the cylinder
    md_cyl = None
    if cone_radius is None:
        cone_radius = radius*2.0
    if cone_length is None:
        con_L = length/3.0
        cyl_L = length*2.0/3.0
    else:
        cyl_L = max(0, length - cone_length)
        con_L = min(cone_length, length)
    if cyl_L != 0:
        md_cyl = create_cylinder(rows, cols, radius=[radius, radius],
                                 length=cyl_L)
    # create the cone
    md_con = create_cone(cols, radius=cone_radius, length=con_L)
    verts = md_con.get_vertices()
    nbr_verts_con = verts.size//3
    faces = md_con.get_faces()
    if md_cyl is not None:
        trans = np.array([[0.0, 0.0, cyl_L]])
        verts = np.vstack((verts+trans, md_cyl.get_vertices()))
        faces = np.vstack((faces, md_cyl.get_faces()+nbr_verts_con))

    return MeshData(vertices=verts, faces=faces)


Instruction:
Explain what the following Python 3 code does
def create_grid_mesh(xs, ys, zs):
    '''Generate vertices and indices for an implicitly connected mesh.

    The intention is that this makes it simple to generate a mesh
    from meshgrid data.

    Parameters
    ----------
    xs : ndarray
        A 2d array of x coordinates for the vertices of the mesh. Must
        have the same dimensions as ys and zs.
    ys : ndarray
        A 2d array of y coordinates for the vertices of the mesh. Must
        have the same dimensions as xs and zs.
    zs : ndarray
        A 2d array of z coordinates for the vertices of the mesh. Must
        have the same dimensions as xs and ys.

    Returns
    -------
    vertices : ndarray
        The array of vertices in the mesh.
    indices : ndarray
        The array of indices for the mesh.
    '''

    shape = xs.shape
    length = shape[0] * shape[1]

    vertices = np.zeros((length, 3))

    vertices[:, 0] = xs.reshape(length)
    vertices[:, 1] = ys.reshape(length)
    vertices[:, 2] = zs.reshape(length)

    basic_indices = np.array([0, 1, 1 + shape[1], 0,
                              0 + shape[1], 1 + shape[1]],
                             dtype=np.uint32)

    inner_grid_length = (shape[0] - 1) * (shape[1] - 1)

    offsets = np.arange(inner_grid_length)
    offsets += np.repeat(np.arange(shape[0] - 1), shape[1] - 1)
    offsets = np.repeat(offsets, 6)
    indices = np.resize(basic_indices, len(offsets)) + offsets

    indices = indices.reshape((len(indices) // 3, 3))

    return vertices, indices

Response: Generate vertices and indices for an implicitly connected mesh.


Instruction:
How would you explain what the following Python 3 function does
def _straight_line_vertices(adjacency_mat, node_coords, directed=False):

    if not issparse(adjacency_mat):
        adjacency_mat = np.asarray(adjacency_mat, float)

    if (adjacency_mat.ndim != 2 or adjacency_mat.shape[0] !=
            adjacency_mat.shape[1]):
        raise ValueError("Adjacency matrix should be square.")

    arrow_vertices = np.array([])

    edges = _get_edges(adjacency_mat)
    line_vertices = node_coords[edges.ravel()]

    if directed:
        arrows = np.array(list(_get_directed_edges(adjacency_mat)))
        arrow_vertices = node_coords[arrows.ravel()]
        arrow_vertices = arrow_vertices.reshape((len(arrow_vertices)/2, 4))

    return line_vertices, arrow_vertices

Response: Generates the vertices for straight lines between nodes.


Instruction:
Explain what the following Python 3 code does
def _rescale_layout(pos, scale=1):

    pos -= pos.min(axis=0)
    pos *= scale / pos.max()

    return pos

Response: Rescale the given coordinate list to the range [ 0 scale ).


Instruction:
How would you code a function in Python 3 to
get unique FT_Library handle

Response:
def get_handle():
    '''
    Get unique FT_Library handle
    '''
    global __handle__
    if not __handle__:
        __handle__ = FT_Library()
        error = FT_Init_FreeType(byref(__handle__))
        if error:
            raise RuntimeError(hex(error))
    return __handle__


Instruction:
Create a Python 3 function to
create a new base camera object of the specified type.

Response:
def make_camera(cam_type, *args, **kwargs):
    """ Factory function for creating new cameras using a string name.

    Parameters
    ----------
    cam_type : str
        May be one of:

            * 'panzoom' : Creates :class:`PanZoomCamera`
            * 'turntable' : Creates :class:`TurntableCamera`
            * None : Creates :class:`Camera`

    Notes
    -----
    All extra arguments are passed to the __init__ method of the selected
    Camera class.
    """
    cam_types = {None: BaseCamera}
    for camType in (BaseCamera, PanZoomCamera, PerspectiveCamera,
                    TurntableCamera, FlyCamera, ArcballCamera):
        cam_types[camType.__name__[:-6].lower()] = camType

    try:
        return cam_types[cam_type](*args, **kwargs)
    except KeyError:
        raise KeyError('Unknown camera type "%s". Options are: %s' %
                       (cam_type, cam_types.keys()))


Instruction:
Write a Python 3 function for
setting the position of the datapoints in the log file

Response:
def set_data_values(self, label, x, y, z):
        """
        Set the position of the datapoints
        """
        # TODO: avoid re-allocating an array every time
        self.layers[label]['data'] = np.array([x, y, z]).transpose()
        self._update()


Instruction:
How would you explain what the following Python 3 function does
def SegmentCollection(mode="agg-fast", *args, **kwargs):

    if mode == "raw":
        return RawSegmentCollection(*args, **kwargs)
    return AggSegmentCollection(*args, **kwargs)

Response: A segment collection function.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def surface(func, umin=0, umax=2 * np.pi, ucount=64, urepeat=1.0,
            vmin=0, vmax=2 * np.pi, vcount=64, vrepeat=1.0):
    """
    Computes the parameterization of a parametric surface

    func: function(u,v)
        Parametric function used to build the surface
    """

    vtype = [('position', np.float32, 3),
             ('texcoord', np.float32, 2),
             ('normal',   np.float32, 3)]
    itype = np.uint32

    # umin, umax, ucount = 0, 2*np.pi, 64
    # vmin, vmax, vcount = 0, 2*np.pi, 64

    vcount += 1
    ucount += 1
    n = vcount * ucount

    Un = np.repeat(np.linspace(0, 1, ucount, endpoint=True), vcount)
    Vn = np.tile(np.linspace(0, 1, vcount, endpoint=True), ucount)
    U = umin + Un * (umax - umin)
    V = vmin + Vn * (vmax - vmin)

    vertices = np.zeros(n, dtype=vtype)
    for i, (u, v) in enumerate(zip(U, V)):
        vertices["position"][i] = func(u, v)

    vertices["texcoord"][:, 0] = Un * urepeat
    vertices["texcoord"][:, 1] = Vn * vrepeat

    indices = []
    for i in range(ucount - 1):
        for j in range(vcount - 1):
            indices.append(i * (vcount) + j)
            indices.append(i * (vcount) + j + 1)
            indices.append(i * (vcount) + j + vcount + 1)
            indices.append(i * (vcount) + j + vcount)
            indices.append(i * (vcount) + j + vcount + 1)
            indices.append(i * (vcount) + j)
    indices = np.array(indices, dtype=itype)
    vertices["normal"] = normals(vertices["position"],
                                 indices.reshape(len(indices) / 3, 3))

    return vertices, indices

Response:
Computes the parameterization of a parametric surface
 ArcGIS object.


Instruction:
Can you create a Python 3 function that
returns a point collection of the current page.

Response:
def PointCollection(mode="raw", *args, **kwargs):
    """
    mode: string
      - "raw"  (speed: fastest, size: small,   output: ugly)
      - "agg"  (speed: fast,    size: small,   output: beautiful)
    """

    if mode == "raw":
        return RawPointCollection(*args, **kwargs)
    return AggPointCollection(*args, **kwargs)


Instruction:
How would you code a function in Python 3 to
add new data to the right side of every line strip and remove as much data from the left.

Response:
def roll_data(self, data):
        """Append new data to the right side of every line strip and remove
        as much data from the left.

        Parameters
        ----------
        data : array-like
            A data array to append.
        """
        data = data.astype('float32')[..., np.newaxis]
        s1 = self._data_shape[1] - self._offset
        if data.shape[1] > s1:
            self._pos_tex[:, self._offset:] = data[:, :s1]
            self._pos_tex[:, :data.shape[1] - s1] = data[:, s1:]
            self._offset = (self._offset + data.shape[1]) % self._data_shape[1]
        else:
            self._pos_tex[:, self._offset:self._offset+data.shape[1]] = data
            self._offset += data.shape[1]
        self.shared_program['offset'] = self._offset
        self.update()


Instruction:
How would you explain what the following Python 3 function does
def set_data(self, index, data):
        self._pos_tex[index, :] = data
        self.update()

Response: Set the complete data for a single line strip.


Instruction:
Write a Python 3 script for
creating a program and add it to this MultiProgram.

Response:
def add_program(self, name=None):
        """Create a program and add it to this MultiProgram.

        It is the caller's responsibility to keep a reference to the returned
        program.

        The *name* must be unique, but is otherwise arbitrary and used for
        debugging purposes.
        """
        if name is None:
            name = 'program' + str(self._next_prog_id)
            self._next_prog_id += 1

        if name in self._programs:
            raise KeyError("Program named '%s' already exists." % name)

        # create a program and update it to look like the rest
        prog = ModularProgram(self._vcode, self._fcode)
        for key, val in self._set_items.items():
            prog[key] = val
        self.frag._new_program(prog)
        self.vert._new_program(prog)

        self._programs[name] = prog
        return prog


Instruction:
Can you generate the documentation for the following Python 3 function
def _new_program(self, p):
        for k, v in self._set_items.items():
            getattr(p, self._shader)[k] = v

Response: Update the items in the shader with the new items.


Instruction:
Make a summary of the following Python 3 code
def attach(self, canvas):
        self._canvas = canvas
        canvas.events.resize.connect(self.on_resize)
        canvas.events.mouse_wheel.connect(self.on_mouse_wheel)
        canvas.events.mouse_move.connect(self.on_mouse_move)

Response: Attach this tranform to a canvas.


Instruction:
Can you generate the documentation for the following Python 3 function
def on_mouse_move(self, event):
        if event.is_dragging:
            dxy = event.pos - event.last_event.pos
            button = event.press_event.button

            if button == 1:
                dxy = self.canvas_tr.map(dxy)
                o = self.canvas_tr.map([0, 0])
                t = dxy - o
                self.move(t)
            elif button == 2:
                center = self.canvas_tr.map(event.press_event.pos)
                if self._aspect is None:
                    self.zoom(np.exp(dxy * (0.01, -0.01)), center)
                else:
                    s = dxy[1] * -0.01
                    self.zoom(np.exp(np.array([s, s])), center)

            self.shader_map()

Response:
Mouse move handler

        Parameters
        ----------
        event : instance of Event
            The event.


Instruction:
Write a Python 3 function that can
calculate and returns the tangents normals and binormals for the tube.

Response:
def _frenet_frames(points, closed):
    '''Calculates and returns the tangents, normals and binormals for
    the tube.'''
    tangents = np.zeros((len(points), 3))
    normals = np.zeros((len(points), 3))

    epsilon = 0.0001

    # Compute tangent vectors for each segment
    tangents = np.roll(points, -1, axis=0) - np.roll(points, 1, axis=0)
    if not closed:
        tangents[0] = points[1] - points[0]
        tangents[-1] = points[-1] - points[-2]
    mags = np.sqrt(np.sum(tangents * tangents, axis=1))
    tangents /= mags[:, np.newaxis]

    # Get initial normal and binormal
    t = np.abs(tangents[0])

    smallest = np.argmin(t)
    normal = np.zeros(3)
    normal[smallest] = 1.

    vec = np.cross(tangents[0], normal)

    normals[0] = np.cross(tangents[0], vec)

    # Compute normal and binormal vectors along the path
    for i in range(1, len(points)):
        normals[i] = normals[i-1]

        vec = np.cross(tangents[i-1], tangents[i])
        if norm(vec) > epsilon:
            vec /= norm(vec)
            theta = np.arccos(np.clip(tangents[i-1].dot(tangents[i]), -1, 1))
            normals[i] = rotate(-np.degrees(theta),
                                vec)[:3, :3].dot(normals[i])

    if closed:
        theta = np.arccos(np.clip(normals[0].dot(normals[-1]), -1, 1))
        theta /= len(points) - 1

        if tangents[0].dot(np.cross(normals[0], normals[-1])) > 0:
            theta *= -1.

        for i in range(1, len(points)):
            normals[i] = rotate(-np.degrees(theta*i),
                                tangents[i])[:3, :3].dot(normals[i])

    binormals = np.cross(tangents, normals)

    return tangents, normals, binormals


Instruction:
Here you have a function in Python 3, explain what it does
def max_order(self):
        # TODO: cache value
        combo = int(0)
        for iv in self._interval_set._intervals:
            combo |= iv[0] | iv[1]

        ret = AbstractMOC.HPY_MAX_NORDER - (utils.number_trailing_zeros(combo) // 2)
        if ret < 0:
            ret = 0

        return ret

Response: Returns the maximum number of HEALPix cells in the MOC instance.


Instruction:
Can you create a Python 3 function that
returns the intersection of this MOC and another MOCs.

Response:
def intersection(self, another_moc, *args):
        """
        Intersection between the MOC instance and other MOCs.

        Parameters
        ----------
        another_moc : `~mocpy.moc.MOC`
            The MOC used for performing the intersection with self.
        args : `~mocpy.moc.MOC`
            Other additional MOCs to perform the intersection with.

        Returns
        -------
        result : `~mocpy.moc.MOC`/`~mocpy.tmoc.TimeMOC`
            The resulting MOC.
        """
        interval_set = self._interval_set.intersection(another_moc._interval_set)
        for moc in args:
            interval_set = interval_set.intersection(moc._interval_set)

        return self.__class__(interval_set)


Instruction:
Make a summary of the following Python 3 code
def union(self, another_moc, *args):
        interval_set = self._interval_set.union(another_moc._interval_set)
        for moc in args:
            interval_set = interval_set.union(moc._interval_set)

        return self.__class__(interval_set)

Response: Union between the MOC instance and another MOCs.


Instruction:
Can you tell what is the following Python 3 function doing
def difference(self, another_moc, *args):
        interval_set = self._interval_set.difference(another_moc._interval_set)
        for moc in args:
            interval_set = interval_set.difference(moc._interval_set)

        return self.__class__(interval_set)

Response: Difference between this MOC and another MOC.


Instruction:
Write a Python 3 function that can
return all the pixels neighbours of ipix

Response:
def _neighbour_pixels(hp, ipix):
        """
        Returns all the pixels neighbours of ``ipix``
        """
        neigh_ipix = np.unique(hp.neighbours(ipix).ravel())
        # Remove negative pixel values returned by `~astropy_healpix.HEALPix.neighbours`
        return neigh_ipix[np.where(neigh_ipix >= 0)]


Instruction:
Can you create a Python 3 function that
creates a MOC from a numpy array representing the HEALPix cells.

Response:
def from_cells(cls, cells):
        """
        Creates a MOC from a numpy array representing the HEALPix cells.

        Parameters
        ----------
        cells : `numpy.ndarray`
            Must be a numpy structured array (See https://docs.scipy.org/doc/numpy-1.15.0/user/basics.rec.html).
            The structure of a cell contains 3 attributes:

            - A `ipix` value being a np.uint64
            - A `depth` value being a np.uint32
            - A `fully_covered` flag bit stored in a np.uint8

        Returns
        -------
        moc : `~mocpy.moc.MOC`
            The MOC.
        """
        shift = (AbstractMOC.HPY_MAX_NORDER - cells["depth"]) << 1

        p1 = cells["ipix"]
        p2 = cells["ipix"] + 1

        intervals = np.vstack((p1 << shift, p2 << shift)).T

        return cls(IntervalSet(intervals))


Instruction:
Here you have a function in Python 3, explain what it does
def from_json(cls, json_moc):
        intervals = np.array([])
        for order, pix_l in json_moc.items():
            if len(pix_l) == 0:
                continue
            pix = np.array(pix_l)
            p1 = pix
            p2 = pix + 1
            shift = 2 * (AbstractMOC.HPY_MAX_NORDER - int(order))

            itv = np.vstack((p1 << shift, p2 << shift)).T
            if intervals.size == 0:
                intervals = itv
            else:
                intervals = np.vstack((intervals, itv))

        return cls(IntervalSet(intervals))

Response: Creates a MOC from a dictionary of HEALPix cell arrays indexed by their depth.


Instruction:
Can you generate the documentation for the following Python 3 function
def _uniq_pixels_iterator(self):
        intervals_uniq_l = IntervalSet.to_nuniq_interval_set(self._interval_set)._intervals
        for uniq_iv in intervals_uniq_l:
            for uniq in range(uniq_iv[0], uniq_iv[1]):
                yield uniq

Response: Generator giving the NUNIQ HEALPix pixels of the MOC.


Instruction:
Can you create a Python 3 function that
loads a MOC from a FITS file.

Response:
def from_fits(cls, filename):
        """
        Loads a MOC from a FITS file.

        The specified FITS file must store the MOC (i.e. the list of HEALPix cells it contains) in a binary HDU table.

        Parameters
        ----------
        filename : str
            The path to the FITS file.

        Returns
        -------
        result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC`
            The resulting MOC.
        """
        table = Table.read(filename)

        intervals = np.vstack((table['UNIQ'], table['UNIQ']+1)).T

        nuniq_interval_set = IntervalSet(intervals)
        interval_set = IntervalSet.from_nuniq_interval_set(nuniq_interval_set)
        return cls(interval_set)


Instruction:
How would you implement a function in Python 3 that
creates a MOC from a string.

Response:
def from_str(cls, value):
        """
        Create a MOC from a str.

        This grammar is expressed is the `MOC IVOA <http://ivoa.net/documents/MOC/20190215/WD-MOC-1.1-20190215.pdf>`__
        specification at section 2.3.2.

        Parameters
        ----------
        value : str
            The MOC as a string following the grammar rules.

        Returns
        -------
        moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC`
            The resulting MOC

        Examples
        --------
        >>> from mocpy import MOC
        >>> moc = MOC.from_str("2/2-25,28,29 4/0 6/")
        """
        # Import lark parser when from_str is called
        # at least one time
        from lark import Lark, Transformer
        class ParsingException(Exception):
            pass

        class TreeToJson(Transformer):
            def value(self, items):
                res = {}
                for item in items:
                    if item is not None: # Do not take into account the "sep" branches
                        res.update(item)
                return res

            def sep(self, items):
                pass

            def depthpix(self, items):
                depth = str(items[0])
                pixs_l = items[1:][0]
                return {depth: pixs_l}

            def uniq_pix(self, pix):
                if pix:
                    return [int(pix[0])]

            def range_pix(self, range_pix):
                lower_bound = int(range_pix[0])
                upper_bound = int(range_pix[1])
                return np.arange(lower_bound, upper_bound + 1, dtype=int)

            def pixs(self, items):
                ipixs = []
                for pix in items:
                    if pix is not None: # Do not take into account the "sep" branches
                        ipixs.extend(pix)
                return ipixs

        # Initialize the parser when from_str is called
        # for the first time
        if AbstractMOC.LARK_PARSER_STR is None:
            AbstractMOC.LARK_PARSER_STR = Lark(r"""
                value: depthpix (sep+ depthpix)*
                depthpix : INT "/" sep* pixs
                pixs : pix (sep+ pix)*
                pix : INT? -> uniq_pix
                    | (INT "-" INT) -> range_pix
                sep : " " | "," | "\n" | "\r"

                %import common.INT
                """, start='value')

        try:
            tree = AbstractMOC.LARK_PARSER_STR.parse(value)
        except Exception as err:
            raise ParsingException("Could not parse {0}. \n Check the grammar section 2.3.2 of http://ivoa.net/documents/MOC/20190215/WD-MOC-1.1-20190215.pdf to see the correct syntax for writing a MOC from a str".format(value))

        moc_json = TreeToJson().transform(tree)

        return cls.from_json(moc_json)


Instruction:
Implement a function in Python 3 to
serialize a MOC to the JSON format.

Response:
def _to_json(uniq):
        """
        Serializes a MOC to the JSON format.

        Parameters
        ----------
        uniq : `~numpy.ndarray`
            The array of HEALPix cells representing the MOC to serialize.

        Returns
        -------
        result_json : {str : [int]}
            A dictionary of HEALPix cell lists indexed by their depth.
        """
        result_json = {}

        depth, ipix = utils.uniq2orderipix(uniq)
        min_depth = np.min(depth[0])
        max_depth = np.max(depth[-1])

        for d in range(min_depth, max_depth+1):
            pix_index = np.where(depth == d)[0]
            if pix_index.size:
                # there are pixels belonging to the current order
                ipix_depth = ipix[pix_index]
                result_json[str(d)] = ipix_depth.tolist()

        return result_json


Instruction:
Create a Python 3 function to
serialize a MOC to the STRING format.

Response:
def _to_str(uniq):
        """
        Serializes a MOC to the STRING format.

        HEALPix cells are separated by a comma. The HEALPix cell at order 0 and number 10 is encoded
        by the string: "0/10", the first digit representing the depth and the second the HEALPix cell number
        for this depth. HEALPix cells next to each other within a specific depth can be expressed as a range and
        therefore written like that: "12/10-150". This encodes the list of HEALPix cells from 10 to 150 at the
        depth 12.

        Parameters
        ----------
        uniq : `~numpy.ndarray`
            The array of HEALPix cells representing the MOC to serialize.

        Returns
        -------
        result : str
            The serialized MOC.
        """
        def write_cells(serial, a, b, sep=''):
            if a == b:
                serial += '{0}{1}'.format(a, sep)
            else:
                serial += '{0}-{1}{2}'.format(a, b, sep)
            return serial

        res = ''

        if uniq.size == 0:
            return res

        depth, ipixels = utils.uniq2orderipix(uniq)
        min_depth = np.min(depth[0])
        max_depth = np.max(depth[-1])

        for d in range(min_depth, max_depth+1):
            pix_index = np.where(depth == d)[0]

            if pix_index.size > 0:
                # Serialize the depth followed by a slash
                res += '{0}/'.format(d)

                # Retrieve the pixel(s) for this depth
                ipix_depth = ipixels[pix_index]
                if ipix_depth.size == 1:
                    # If there is only one pixel we serialize it and
                    # go to the next depth
                    res = write_cells(res, ipix_depth[0], ipix_depth[0])
                else:
                    # Sort them in case there are several
                    ipix_depth = np.sort(ipix_depth)

                    beg_range = ipix_depth[0]
                    last_range = beg_range

                    # Loop over the sorted pixels by tracking the lower bound of
                    # the current range and the last pixel.
                    for ipix in ipix_depth[1:]:
                        # If the current pixel does not follow the previous one
                        # then we can end a range and serializes it
                        if ipix > last_range + 1:
                            res = write_cells(res, beg_range, last_range, sep=',')
                            # The current pixel is the beginning of a new range
                            beg_range = ipix

                        last_range = ipix

                    # Write the last range
                    res = write_cells(res, beg_range, last_range)

                # Add a ' ' separator before writing serializing the pixels of the next depth
                res += ' '

        # Remove the last ' ' character
        res = res[:-1]

        return res


Instruction:
Here you have a function in Python 3, explain what it does
def _to_fits(self, uniq, optional_kw_dict=None):
        depth = self.max_order
        if depth <= 13:
            fits_format = '1J'
        else:
            fits_format = '1K'

        tbhdu = fits.BinTableHDU.from_columns(
            fits.ColDefs([
                fits.Column(name='UNIQ', format=fits_format, array=uniq)
            ]))
        tbhdu.header['PIXTYPE'] = 'HEALPIX'
        tbhdu.header['ORDERING'] = 'NUNIQ'
        tbhdu.header.update(self._fits_header_keywords)
        tbhdu.header['MOCORDER'] = depth
        tbhdu.header['MOCTOOL'] = 'MOCPy'
        if optional_kw_dict:
            for key in optional_kw_dict:
                tbhdu.header[key] = optional_kw_dict[key]

        thdulist = fits.HDUList([fits.PrimaryHDU(), tbhdu])
        return thdulist

Response: Serializes a MOC to the FITS format.


Instruction:
Can you generate the documentation for the following Python 3 function
def serialize(self, format='fits', optional_kw_dict=None):
        formats = ('fits', 'json', 'str')
        if format not in formats:
            raise ValueError('format should be one of %s' % (str(formats)))

        uniq_l = []
        for uniq in self._uniq_pixels_iterator():
            uniq_l.append(uniq)

        uniq = np.array(uniq_l)

        if format == 'fits':
            result = self._to_fits(uniq=uniq,
                                   optional_kw_dict=optional_kw_dict)
        elif format == 'str':
            result = self.__class__._to_str(uniq=uniq)
        else:
            # json format serialization
            result = self.__class__._to_json(uniq=uniq)

        return result

Response: Serializes the MOC into a specific format.


Instruction:
Given the following Python 3 function, write the documentation
def write(self, path, format='fits', overwrite=False, optional_kw_dict=None):
        serialization = self.serialize(format=format, optional_kw_dict=optional_kw_dict)
        if format == 'fits':
            serialization.writeto(path, overwrite=overwrite)
        else:
            import json
            with open(path, 'w') as h:
                h.write(json.dumps(serialization, sort_keys=True, indent=2))

Response: Writes the MOC to a file.


Instruction:
Can you create a Python 3 function that
degrades the MOC instance to a new less precise MOC instance.

Response:
def degrade_to_order(self, new_order):
        """
        Degrades the MOC instance to a new, less precise, MOC.

        The maximum depth (i.e. the depth of the smallest HEALPix cells that can be found in the MOC) of the
        degraded MOC is set to ``new_order``.

        Parameters
        ----------
        new_order : int
            Maximum depth of the output degraded MOC.

        Returns
        -------
        moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC`
            The degraded MOC.
        """
        shift = 2 * (AbstractMOC.HPY_MAX_NORDER - new_order)
        ofs = (int(1) << shift) - 1
        mask = ~ofs
        adda = int(0)
        addb = ofs

        iv_set = []

        for iv in self._interval_set._intervals:
            a = (iv[0] + adda) & mask
            b = (iv[1] + addb) & mask
            if b > a:
                iv_set.append((a, b))

        return self.__class__(IntervalSet(np.asarray(iv_set)))


Instruction:
Can you tell what is the following Python 3 function doing
def set_cursor_x(self, x):

        if x >= 0 and x <= self.server.server_info.get("screen_width"):
            self.cursor_x = x
            self.server.request("screen_set %s cursor_x %i" % (self.ref, self.cursor_x))

Response: Set Screen Cursor X Position


Instruction:
How would you implement a function in Python 3 that
sets Screen Cursor Y Position

Response:
def set_cursor_y(self, y):
        """ Set Screen Cursor Y Position """

        if y >= 0 and y <= self.server.server_info.get("screen_height"):
            self.cursor_y = y
            self.server.request("screen_set %s cursor_y %i" % (self.ref, self.cursor_y))


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

        if duration > 0:
            self.duration = duration
            self.server.request("screen_set %s duration %i" % (self.ref, (self.duration * 8)))

Response: Set Screen Change Interval Duration


Instruction:
Can you tell what is the following Python 3 function doing
def set_timeout(self, timeout):

        if timeout > 0:
            self.timeout = timeout
            self.server.request("screen_set %s timeout %i" % (self.ref, (self.timeout * 8)))

Response: Set Screen Timeout Duration


Instruction:
Create a Python 3 function to
set Screen Priority Class

Response:
def set_priority(self, priority):
        """ Set Screen Priority Class """

        if priority in ["hidden", "background", "info", "foreground", "alert", "input"]:
            self.priority = priority
            self.server.request("screen_set %s priority %s" % (self.ref, self.priority))


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

        if state in ["on", "off", "toggle", "open", "blink", "flash"]:
            self.backlight = state
            self.server.request("screen_set %s backlight %s" % (self.ref, self.backlight))

Response: Set Screen Backlight Mode


Instruction:
Can you write a function in Python 3 where it
sets Screen Heartbeat Display Mode

Response:
def set_heartbeat(self, state):
        """ Set Screen Heartbeat Display Mode """

        if state in ["on", "off", "open"]:
            self.heartbeat = state
            self.server.request("screen_set %s heartbeat %s" % (self.ref, self.heartbeat))


Instruction:
Implement a function in Python 3 to
set Screen Cursor Mode

Response:
def set_cursor(self, cursor):
        """ Set Screen Cursor Mode """

        if cursor in ["on", "off", "under", "block"]:
            self.cursor = cursor
            self.server.request("screen_set %s cursor %s" % (self.ref, self.cursor))


Instruction:
Create a Python 3 function to
clear the current cache entry.

Response:
def clear(self):
        """ Clear Screen """
        widgets.StringWidget(self, ref="_w1_", text=" " * 20, x=1, y=1)
        widgets.StringWidget(self, ref="_w2_", text=" " * 20, x=1, y=2)
        widgets.StringWidget(self, ref="_w3_", text=" " * 20, x=1, y=3)
        widgets.StringWidget(self, ref="_w4_", text=" " * 20, x=1, y=4)


Instruction:
How would you implement a function in Python 3 that
adds a String Widget to the Screen.

Response:
def add_string_widget(self, ref, text="Text", x=1, y=1):
        """ Add String Widget """

        if ref not in self.widgets:
            widget = widgets.StringWidget(screen=self, ref=ref, text=text, x=x, y=y)
            self.widgets[ref] = widget
            return self.widgets[ref]


Instruction:
Implement a Python 3 function for
adding a Title Widget to the screen.

Response:
def add_title_widget(self, ref, text="Title"):
        """ Add Title Widget """

        if ref not in self.widgets:
            widget = widgets.TitleWidget(screen=self, ref=ref, text=text)
            self.widgets[ref] = widget
            return self.widgets[ref]


Instruction:
Can you create a Python 3 function that
adds Horizontal Bar Widget

Response:
def add_hbar_widget(self, ref, x=1, y=1, length=10):
        """ Add Horizontal Bar Widget """

        if ref not in self.widgets:
            widget = widgets.HBarWidget(screen=self, ref=ref, x=x, y=y, length=length)
            self.widgets[ref] = widget
            return self.widgets[ref]


Instruction:
Write a Python 3 script for
adding Vertical Bar Widget

Response:
def add_vbar_widget(self, ref, x=1, y=1, length=10):
        """ Add Vertical Bar Widget """

        if ref not in self.widgets:
            widget = widgets.VBarWidget(screen=self, ref=ref, x=x, y=y, length=length)
            self.widgets[ref] = widget
            return self.widgets[ref]


Instruction:
How would you code a function in Python 3 to
add a Number Widget to the Screen.

Response:
def add_number_widget(self, ref, x=1, value=1):
        """ Add Number Widget """

        if ref not in self.widgets:
            widget = widgets.NumberWidget(screen=self, ref=ref, x=x, value=value)
            self.widgets[ref] = widget
            return self.widgets[ref]


Instruction:
Here you have a function in Python 3, explain what it does
def orbit(self, azim, elev):
        self.azimuth += azim
        self.elevation = np.clip(self.elevation + elev, -90, 90)
        self.view_changed()

Response: Orbits the camera around the center position.


Instruction:
Can you write a function in Python 3 where it
updates rotation parmeters based on mouse movement

Response:
def _update_rotation(self, event):
        """Update rotation parmeters based on mouse movement"""
        p1 = event.mouse_event.press_event.pos
        p2 = event.mouse_event.pos
        if self._event_value is None:
            self._event_value = self.azimuth, self.elevation
        self.azimuth = self._event_value[0] - (p2 - p1)[0] * 0.5
        self.elevation = self._event_value[1] + (p2 - p1)[1] * 0.5


Instruction:
Can you tell what is the following Python 3 function doing
def _rotate_tr(self):
        up, forward, right = self._get_dim_vectors()
        self.transform.rotate(self.elevation, -right)
        self.transform.rotate(self.azimuth, up)

Response: Rotate the transformation matrix based on camera parameters


Instruction:
Given the following Python 3 function, write the documentation
def _dist_to_trans(self, dist):
        rae = np.array([self.roll, self.azimuth, self.elevation]) * np.pi / 180
        sro, saz, sel = np.sin(rae)
        cro, caz, cel = np.cos(rae)
        dx = (+ dist[0] * (cro * caz + sro * sel * saz)
              + dist[1] * (sro * caz - cro * sel * saz))
        dy = (+ dist[0] * (cro * saz - sro * sel * caz)
              + dist[1] * (sro * saz + cro * sel * caz))
        dz = (- dist[0] * sro * cel + dist[1] * cro * cel)
        return dx, dy, dz

Response: Convert mouse x y movement into x y z translations


Instruction:
Write a Python 3 script to
set the configuration for GLFW

Response:
def _set_config(c):
    """Set gl configuration for GLFW """
    glfw.glfwWindowHint(glfw.GLFW_RED_BITS, c['red_size'])
    glfw.glfwWindowHint(glfw.GLFW_GREEN_BITS, c['green_size'])
    glfw.glfwWindowHint(glfw.GLFW_BLUE_BITS, c['blue_size'])
    glfw.glfwWindowHint(glfw.GLFW_ALPHA_BITS, c['alpha_size'])

    glfw.glfwWindowHint(glfw.GLFW_ACCUM_RED_BITS, 0)
    glfw.glfwWindowHint(glfw.GLFW_ACCUM_GREEN_BITS, 0)
    glfw.glfwWindowHint(glfw.GLFW_ACCUM_BLUE_BITS, 0)
    glfw.glfwWindowHint(glfw.GLFW_ACCUM_ALPHA_BITS, 0)

    glfw.glfwWindowHint(glfw.GLFW_DEPTH_BITS, c['depth_size'])
    glfw.glfwWindowHint(glfw.GLFW_STENCIL_BITS, c['stencil_size'])
    # glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, c['major_version'])
    # glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, c['minor_version'])
    # glfw.glfwWindowHint(glfw.GLFW_SRGB_CAPABLE, c['srgb'])
    glfw.glfwWindowHint(glfw.GLFW_SAMPLES, c['samples'])
    glfw.glfwWindowHint(glfw.GLFW_STEREO, c['stereo'])
    if not c['double_buffer']:
        raise RuntimeError('GLFW must double buffer, consider using a '
                           'different backend, or using double buffering')


Instruction:
Can you generate the documentation for the following Python 3 function
def _process_mod(self, key, down):
        if key in MOD_KEYS:
            if down:
                if key not in self._mod:
                    self._mod.append(key)
            elif key in self._mod:
                self._mod.pop(self._mod.index(key))
        return self._mod

Response: Process the mod key.


Instruction:
Make a summary of the following Python 3 code
def _patch():
    import sys
    from OpenGL import GL
    if sys.version_info > (3,):
        buffersubdatafunc = GL.glBufferSubData
        if hasattr(buffersubdatafunc, 'wrapperFunction'):
            buffersubdatafunc = buffersubdatafunc.wrapperFunction
        _m = sys.modules[buffersubdatafunc.__module__]
        _m.long = int

    # Fix missing enum
    try:
        from OpenGL.GL.VERSION import GL_2_0
        GL_2_0.GL_OBJECT_SHADER_SOURCE_LENGTH = GL_2_0.GL_SHADER_SOURCE_LENGTH
    except Exception:
        pass

Response: Monkey - patch pyopengl to fix a bug in glBufferSubData.


Instruction:
Write a Python 3 script to
try getting the given function from PyOpenGL and return it as a dummy function.

Response:
def _get_function_from_pyopengl(funcname):
    """ Try getting the given function from PyOpenGL, return
    a dummy function (that shows a warning when called) if it
    could not be found.
    """
    func = None

    # Get function from GL
    try:
        func = getattr(_GL, funcname)
    except AttributeError:
        # Get function from FBO
        try:
            func = getattr(_FBO, funcname)
        except AttributeError:
            func = None

    # Try using "alias"
    if not bool(func):
        # Some functions are known by a slightly different name
        # e.g. glDepthRangef, glClearDepthf
        if funcname.endswith('f'):
            try:
                func = getattr(_GL, funcname[:-1])
            except AttributeError:
                pass

    # Set dummy function if we could not find it
    if func is None:
        func = _make_unavailable_func(funcname)
        logger.warning('warning: %s not available' % funcname)
    return func


Instruction:
Write a Python 3 script to
inject functions from OpenGL. GL into _pyopengl namespace.

Response:
def _inject():
    """ Copy functions from OpenGL.GL into _pyopengl namespace.
    """
    NS = _pyopengl2.__dict__
    for glname, ourname in _pyopengl2._functions_to_import:
        func = _get_function_from_pyopengl(glname)
        NS[ourname] = func


Instruction:
Given the following Python 3 function, write the documentation
def _get_vispy_font_filename(face, bold, italic):
    name = face + '-'
    name += 'Regular' if not bold and not italic else ''
    name += 'Bold' if bold else ''
    name += 'Italic' if italic else ''
    name += '.ttf'
    return load_data_file('fonts/%s' % name)

Response: Fetch a remote vispy font filename


Instruction:
Given the following Python 3 function, write the documentation
def _check_color_dim(val):
    val = np.atleast_2d(val)
    if val.shape[1] not in (3, 4):
        raise RuntimeError('Value must have second dimension of size 3 or 4')
    return val, val.shape[1]

Response: Ensure val is Nx3 or Nx4.


Instruction:
Explain what the following Python 3 code does
def _hex_to_rgba(hexs):
    hexs = np.atleast_1d(np.array(hexs, '|U9'))
    out = np.ones((len(hexs), 4), np.float32)
    for hi, h in enumerate(hexs):
        assert isinstance(h, string_types)
        off = 1 if h[0] == '#' else 0
        assert len(h) in (6+off, 8+off)
        e = (len(h)-off) // 2
        out[hi, :e] = [int(h[i:i+2], 16) / 255.
                       for i in range(off, len(h), 2)]
    return out

Response: Convert hex to rgba


Instruction:
Make a summary of the following Python 3 code
def _rgb_to_hex(rgbs):
    rgbs, n_dim = _check_color_dim(rgbs)
    return np.array(['#%02x%02x%02x' % tuple((255*rgb[:3]).astype(np.uint8))
                     for rgb in rgbs], '|U7')

Response: Convert rgb to hex triplet


Instruction:
Write a Python 3 script for
converting Nx3 or Nx4 rgb to hsv

Response:
def _rgb_to_hsv(rgbs):
    """Convert Nx3 or Nx4 rgb to hsv"""
    rgbs, n_dim = _check_color_dim(rgbs)
    hsvs = list()
    for rgb in rgbs:
        rgb = rgb[:3]  # don't use alpha here
        idx = np.argmax(rgb)
        val = rgb[idx]
        c = val - np.min(rgb)
        if c == 0:
            hue = 0
            sat = 0
        else:
            if idx == 0:  # R == max
                hue = ((rgb[1] - rgb[2]) / c) % 6
            elif idx == 1:  # G == max
                hue = (rgb[2] - rgb[0]) / c + 2
            else:  # B == max
                hue = (rgb[0] - rgb[1]) / c + 4
            hue *= 60
            sat = c / val
        hsv = [hue, sat, val]
        hsvs.append(hsv)
    hsvs = np.array(hsvs, dtype=np.float32)
    if n_dim == 4:
        hsvs = np.concatenate((hsvs, rgbs[:, 3]), axis=1)
    return hsvs


Instruction:
Write a Python 3 function for
converting Nx3 or Nx4 hsv to rgb

Response:
def _hsv_to_rgb(hsvs):
    """Convert Nx3 or Nx4 hsv to rgb"""
    hsvs, n_dim = _check_color_dim(hsvs)
    # In principle, we *might* be able to vectorize this, but might as well
    # wait until a compelling use case appears
    rgbs = list()
    for hsv in hsvs:
        c = hsv[1] * hsv[2]
        m = hsv[2] - c
        hp = hsv[0] / 60
        x = c * (1 - abs(hp % 2 - 1))
        if 0 <= hp < 1:
            r, g, b = c, x, 0
        elif hp < 2:
            r, g, b = x, c, 0
        elif hp < 3:
            r, g, b = 0, c, x
        elif hp < 4:
            r, g, b = 0, x, c
        elif hp < 5:
            r, g, b = x, 0, c
        else:
            r, g, b = c, 0, x
        rgb = [r + m, g + m, b + m]
        rgbs.append(rgb)
    rgbs = np.array(rgbs, dtype=np.float32)
    if n_dim == 4:
        rgbs = np.concatenate((rgbs, hsvs[:, 3]), axis=1)
    return rgbs


Instruction:
Can you implement a function in Python 3 that
converts Nx3 or Nx4 lab to rgb

Response:
def _lab_to_rgb(labs):
    """Convert Nx3 or Nx4 lab to rgb"""
    # adapted from BSD-licensed work in MATLAB by Mark Ruzon
    # Based on ITU-R Recommendation BT.709 using the D65
    labs, n_dim = _check_color_dim(labs)

    # Convert Lab->XYZ (silly indexing used to preserve dimensionality)
    y = (labs[:, 0] + 16.) / 116.
    x = (labs[:, 1] / 500.) + y
    z = y - (labs[:, 2] / 200.)
    xyz = np.concatenate(([x], [y], [z]))  # 3xN
    over = xyz > 0.2068966
    xyz[over] = xyz[over] ** 3.
    xyz[~over] = (xyz[~over] - 0.13793103448275862) / 7.787

    # Convert XYZ->LAB
    rgbs = np.dot(_xyz2rgb_norm, xyz).T
    over = rgbs > 0.0031308
    rgbs[over] = 1.055 * (rgbs[over] ** (1. / 2.4)) - 0.055
    rgbs[~over] *= 12.92
    if n_dim == 4:
        rgbs = np.concatenate((rgbs, labs[:, 3]), axis=1)
    rgbs = np.clip(rgbs, 0., 1.)
    return rgbs


Instruction:
How would you explain what the following Python 3 function does
def get(self, tags):
        # Try to find our name
        value = tags.get(self.name, '')

        for name in self.alternate_tags:
            # Iterate of alternates until a non-empty value is found
            value = value or tags.get(name, '')

        # If we still have nothing, return our default
        value = value or self.default
        return value

Response: Find an adequate value for this field from a dict of tags.


Instruction:
Write a Python 3 script to
parse the function signature in the code.

Response:
def parse_function_signature(code):
    """
    Return the name, arguments, and return type of the first function
    definition found in *code*. Arguments are returned as [(type, name), ...].
    """
    m = re.search("^\s*" + re_func_decl + "\s*{", code, re.M)
    if m is None:
        print(code)
        raise Exception("Failed to parse function signature. "
                        "Full code is printed above.")
    rtype, name, args = m.groups()[:3]
    if args == 'void' or args.strip() == '':
        args = []
    else:
        args = [tuple(arg.strip().split(' ')) for arg in args.split(',')]
    return name, args, rtype


Instruction:
Here you have a function in Python 3, explain what it does
def find_functions(code):
    regex = "^\s*" + re_func_decl + "\s*{"

    funcs = []
    while True:
        m = re.search(regex, code, re.M)
        if m is None:
            return funcs

        rtype, name, args = m.groups()[:3]
        if args == 'void' or args.strip() == '':
            args = []
        else:
            args = [tuple(arg.strip().split(' ')) for arg in args.split(',')]
        funcs.append((name, args, rtype))

        code = code[m.end():]

Response:
Find all function
    definitions found in code.


Instruction:
Given the following Python 3 function, write the documentation
def find_prototypes(code):

    prots = []
    lines = code.split('\n')
    for line in lines:
        m = re.match("\s*" + re_func_prot, line)
        if m is not None:
            rtype, name, args = m.groups()[:3]
            if args == 'void' or args.strip() == '':
                args = []
            else:
                args = [tuple(arg.strip().split(' '))
                        for arg in args.split(',')]
            prots.append((name, args, rtype))

    return prots

Response: Find all function prototypes in a code.


Instruction:
How would you explain what the following Python 3 function does
def find_program_variables(code):
    vars = {}
    lines = code.split('\n')
    for line in lines:
        m = re.match(r"\s*" + re_prog_var_declaration + r"\s*(=|;)", line)
        if m is not None:
            vtype, dtype, names = m.groups()[:3]
            for name in names.split(','):
                vars[name.strip()] = (vtype, dtype)
    return vars

Response: Find program variables in the sequence of code lines.


Instruction:
Here you have a function in Python 3, explain what it does
def _set_config(c):
    func = sdl2.SDL_GL_SetAttribute
    func(sdl2.SDL_GL_RED_SIZE, c['red_size'])
    func(sdl2.SDL_GL_GREEN_SIZE, c['green_size'])
    func(sdl2.SDL_GL_BLUE_SIZE, c['blue_size'])
    func(sdl2.SDL_GL_ALPHA_SIZE, c['alpha_size'])
    func(sdl2.SDL_GL_DEPTH_SIZE, c['depth_size'])
    func(sdl2.SDL_GL_STENCIL_SIZE, c['stencil_size'])
    func(sdl2.SDL_GL_DOUBLEBUFFER, 1 if c['double_buffer'] else 0)
    samps = c['samples']
    func(sdl2.SDL_GL_MULTISAMPLEBUFFERS, 1 if samps > 0 else 0)
    func(sdl2.SDL_GL_MULTISAMPLESAMPLES, samps if samps > 0 else 0)
    func(sdl2.SDL_GL_STEREO, c['stereo'])

Response: Set the GL configuration for SDL2


Instruction:
Write a Python 3 script for
creating a response object from the raw_response.

Response:
def create_response(self, message=None, end_session=False, card_obj=None,
                        reprompt_message=None, is_ssml=None):
        """
        message - text message to be spoken out by the Echo
        end_session - flag to determine whether this interaction should end the session
        card_obj = JSON card object to substitute the 'card' field in the raw_response
        """
        response = dict(self.base_response)
        if message:
            response['response'] = self.create_speech(message, is_ssml)
        response['response']['shouldEndSession'] = end_session
        if card_obj:
            response['response']['card'] = card_obj
        if reprompt_message:
            response['response']['reprompt'] = self.create_speech(reprompt_message, is_ssml)
        return Response(response)


Instruction:
Implement a Python 3 function for
creating a card object for the raw_response

Response:
def create_card(self, title=None, subtitle=None, content=None, card_type="Simple"):
        """
        card_obj = JSON card object to substitute the 'card' field in the raw_response
        format:
        {
          "type": "Simple", #COMPULSORY
          "title": "string", #OPTIONAL
          "subtitle": "string", #OPTIONAL
          "content": "string" #OPTIONAL
        }
        """
        card = {"type": card_type}
        if title: card["title"] = title
        if subtitle: card["subtitle"] = subtitle
        if content: card["content"] = content
        return card


Instruction:
How would you explain what the following Python 3 function does
def intent(self, intent):
        ''' Decorator to register intent handler'''

        def _handler(func):
            self._handlers['IntentRequest'][intent] = func
            return func

        return _handler

Response: Decorator to register intent handler


Instruction:
Given the following Python 3 function, write the documentation
def request(self, request_type):
        ''' Decorator to register generic request handler '''

        def _handler(func):
            self._handlers[request_type] = func
            return func

        return _handler

Response: Decorator to register generic request handler


Instruction:
Write a Python 3 script for
routing the request to the right handler function

Response:
def route_request(self, request_json, metadata=None):

        ''' Route the request object to the right handler function '''
        request = Request(request_json)
        request.metadata = metadata
        # add reprompt handler or some such for default?
        handler_fn = self._handlers[self._default] # Set default handling for noisy requests

        if not request.is_intent() and (request.request_type() in self._handlers):
            '''  Route request to a non intent handler '''
            handler_fn = self._handlers[request.request_type()]

        elif request.is_intent() and request.intent_name() in self._handlers['IntentRequest']:
            ''' Route to right intent handler '''
            handler_fn = self._handlers['IntentRequest'][request.intent_name()]

        response = handler_fn(request)
        response.set_session(request.session)
        return response.to_json()


Instruction:
Explain what the following Python 3 code does
def _viewbox_unset(self, viewbox):
        self._viewbox = None
        # Disconnect
        viewbox.events.mouse_press.disconnect(self.viewbox_mouse_event)
        viewbox.events.mouse_release.disconnect(self.viewbox_mouse_event)
        viewbox.events.mouse_move.disconnect(self.viewbox_mouse_event)
        viewbox.events.mouse_wheel.disconnect(self.viewbox_mouse_event)
        viewbox.events.resize.disconnect(self.viewbox_resize_event)

Response: Friend method of viewbox to unregister itself.


Instruction:
Write a Python 3 script for
setting the range of the camera for the given camera.

Response:
def set_range(self, x=None, y=None, z=None, margin=0.05):
        """ Set the range of the view region for the camera

        Parameters
        ----------
        x : tuple | None
            X range.
        y : tuple | None
            Y range.
        z : tuple | None
            Z range.
        margin : float
            Margin to use.

        Notes
        -----
        The view is set to the given range or to the scene boundaries
        if ranges are not specified. The ranges should be 2-element
        tuples specifying the min and max for each dimension.

        For the PanZoomCamera the view is fully defined by the range.
        For e.g. the TurntableCamera the elevation and azimuth are not
        set. One should use reset() for that.
        """
        # Flag to indicate that this is an initializing (not user-invoked)
        init = self._xlim is None

        # Collect given bounds
        bounds = [None, None, None]
        if x is not None:
            bounds[0] = float(x[0]), float(x[1])
        if y is not None:
            bounds[1] = float(y[0]), float(y[1])
        if z is not None:
            bounds[2] = float(z[0]), float(z[1])
        # If there is no viewbox, store given bounds in lim variables, and stop
        if self._viewbox is None:
            self._set_range_args = bounds[0], bounds[1], bounds[2], margin
            return

        # There is a viewbox, we're going to set the range for real
        self._resetting = True

        # Get bounds from viewbox if not given
        if all([(b is None) for b in bounds]):
            bounds = self._viewbox.get_scene_bounds()
        else:
            for i in range(3):
                if bounds[i] is None:
                    bounds[i] = self._viewbox.get_scene_bounds(i)

        # Calculate ranges and margins
        ranges = [b[1] - b[0] for b in bounds]
        margins = [(r*margin or 0.1) for r in ranges]
        # Assign limits for this camera
        bounds_margins = [(b[0]-m, b[1]+m) for b, m in zip(bounds, margins)]
        self._xlim, self._ylim, self._zlim = bounds_margins
        # Store center location
        if (not init) or (self._center is None):
            self._center = [(b[0] + r / 2) for b, r in zip(bounds, ranges)]

        # Let specific camera handle it
        self._set_range(init)

        # Finish
        self._resetting = False
        self.view_changed()


Instruction:
Can you implement a function in Python 3 that
gets the current view state of the camera.

Response:
def get_state(self):
        """ Get the current view state of the camera

        Returns a dict of key-value pairs. The exact keys depend on the
        camera. Can be passed to set_state() (of this or another camera
        of the same type) to reproduce the state.
        """
        D = {}
        for key in self._state_props:
            D[key] = getattr(self, key)
        return D


Instruction:
Can you generate the documentation for the following Python 3 function
def set_state(self, state=None, **kwargs):
        D = state or {}
        D.update(kwargs)
        for key, val in D.items():
            if key not in self._state_props:
                raise KeyError('Not a valid camera state property %r' % key)
            setattr(self, key, val)

Response: Set the view state of the camera.


Instruction:
Implement a Python 3 function for
linking this camera with another camera.

Response:
def link(self, camera):
        """ Link this camera with another camera of the same type

        Linked camera's keep each-others' state in sync.

        Parameters
        ----------
        camera : instance of Camera
            The other camera to link.
        """
        cam1, cam2 = self, camera
        # Remove if already linked
        while cam1 in cam2._linked_cameras:
            cam2._linked_cameras.remove(cam1)
        while cam2 in cam1._linked_cameras:
            cam1._linked_cameras.remove(cam2)
        # Link both ways
        cam1._linked_cameras.append(cam2)
        cam2._linked_cameras.append(cam1)


Instruction:
How would you implement a function in Python 3 that
calls when the camera is viewed.

Response:
def view_changed(self):
        """ Called when this camera is changes its view. Also called
        when its associated with a viewbox.
        """
        if self._resetting:
            return  # don't update anything while resetting (are in set_range)
        if self._viewbox:
            # Set range if necessary
            if self._xlim is None:
                args = self._set_range_args or ()
                self.set_range(*args)
            # Store default state if we have not set it yet
            if self._default_state is None:
                self.set_default_state()
            # Do the actual update
            self._update_transform()


Instruction:
Write a Python 3 script for
handling canvas change events.

Response:
def on_canvas_change(self, event):
        """Canvas change event handler

        Parameters
        ----------
        event : instance of Event
            The event.
        """
        # Connect key events from canvas to camera.
        # TODO: canvas should keep track of a single node with keyboard focus.
        if event.old is not None:
            event.old.events.key_press.disconnect(self.viewbox_key_event)
            event.old.events.key_release.disconnect(self.viewbox_key_event)
        if event.new is not None:
            event.new.events.key_press.connect(self.viewbox_key_event)
            event.new.events.key_release.connect(self.viewbox_key_event)


Instruction:
Can you tell what is the following Python 3 function doing
def _set_scene_transform(self, tr):
        # todo: check whether transform has changed, connect to
        # transform.changed event
        pre_tr = self.pre_transform
        if pre_tr is None:
            self._scene_transform = tr
        else:
            self._transform_cache.roll()
            self._scene_transform = self._transform_cache.get([pre_tr, tr])

        # Mark the transform dynamic so that it will not be collapsed with
        # others
        self._scene_transform.dynamic = True

        # Update scene
        self._viewbox.scene.transform = self._scene_transform
        self._viewbox.update()

        # Apply same state to linked cameras, but prevent that camera
        # to return the favor
        for cam in self._linked_cameras:
            if cam is self._linked_cameras_no_update:
                continue
            try:
                cam._linked_cameras_no_update = self
                cam.set_state(self.get_state())
            finally:
                cam._linked_cameras_no_update = None

Response: Sets the viewbox scene transform.


Instruction:
Can you generate the documentation for the following Python 3 function
def _set_config(c):
    glformat = QGLFormat()
    glformat.setRedBufferSize(c['red_size'])
    glformat.setGreenBufferSize(c['green_size'])
    glformat.setBlueBufferSize(c['blue_size'])
    glformat.setAlphaBufferSize(c['alpha_size'])
    if QT5_NEW_API:
        # Qt5 >= 5.4.0 - below options automatically enabled if nonzero.
        glformat.setSwapBehavior(glformat.DoubleBuffer if c['double_buffer']
                                 else glformat.SingleBuffer)
    else:
        # Qt4 and Qt5 < 5.4.0 - buffers must be explicitly requested.
        glformat.setAccum(False)
        glformat.setRgba(True)
        glformat.setDoubleBuffer(True if c['double_buffer'] else False)
        glformat.setDepth(True if c['depth_size'] else False)
        glformat.setStencil(True if c['stencil_size'] else False)
        glformat.setSampleBuffers(True if c['samples'] else False)
    glformat.setDepthBufferSize(c['depth_size'] if c['depth_size'] else 0)
    glformat.setStencilBufferSize(c['stencil_size'] if c['stencil_size']
                                  else 0)
    glformat.setSamples(c['samples'] if c['samples'] else 0)
    glformat.setStereo(c['stereo'])
    return glformat

Response: Set the OpenGL configuration


Instruction:
Can you create a Python 3 function that
gets the window id of a PySide Widget. Might also work for PyQt4.

Response:
def get_window_id(self):
        """ Get the window id of a PySide Widget. Might also work for PyQt4.
        """
        # Get Qt win id
        winid = self.winId()

        # On Linux this is it
        if IS_RPI:
            nw = (ctypes.c_int * 3)(winid, self.width(), self.height())
            return ctypes.pointer(nw)
        elif IS_LINUX:
            return int(winid)  # Is int on PySide, but sip.voidptr on PyQt

        # Get window id from stupid capsule thingy
        # http://translate.google.com/translate?hl=en&sl=zh-CN&u=http://www.cnb
        #logs.com/Shiren-Y/archive/2011/04/06/2007288.html&prev=/search%3Fq%3Dp
        # yside%2Bdirectx%26client%3Dfirefox-a%26hs%3DIsJ%26rls%3Dorg.mozilla:n
        #l:official%26channel%3Dfflb%26biw%3D1366%26bih%3D614
        # Prepare
        ctypes.pythonapi.PyCapsule_GetName.restype = ctypes.c_char_p
        ctypes.pythonapi.PyCapsule_GetName.argtypes = [ctypes.py_object]
        ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
        ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object,
                                                          ctypes.c_char_p]
        # Extract handle from capsule thingy
        name = ctypes.pythonapi.PyCapsule_GetName(winid)
        handle = ctypes.pythonapi.PyCapsule_GetPointer(winid, name)
        return handle


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

    x1 = x[0]
    x2 = x[1]

    f = (4 - 2.1*(x1*x1) + (x1*x1*x1*x1)/3.0)*(x1*x1) + x1*x2 + (-4 + 4*(x2*x2))*(x2*x2)
    return f

Response: A very simple function to make a random number.


Instruction:
How would you explain what the following Python 3 function does
def PathCollection(mode="agg", *args, **kwargs):

    if mode == "raw":
        return RawPathCollection(*args, **kwargs)
    elif mode == "agg+":
        return AggPathCollection(*args, **kwargs)
    return AggFastPathCollection(*args, **kwargs)

Response:
mode: string
      - "raw"   (speed: fastest, size: small, output: ugly, no dash,
                 no thickness)
      - "agg"   (speed: medium, size: medium output: nice, some flaws, no dash)
      - "agg+"  (speed: slow, size: big, output: perfect, no dash)


Instruction:
Can you generate the documentation for the following Python 3 function
def map(self, coords):
        m = np.empty(coords.shape)
        m[:, :3] = (coords[:, :3] * self.scale[np.newaxis, :3] +
                    coords[:, 3:] * self.translate[np.newaxis, :3])
        m[:, 3] = coords[:, 3]
        return m

Response:
Map the coordinates of the
            to the corresponding logarithmic one.


Instruction:
Create a Python 3 function to
change the translation of this transform by the amount given.

Response:
def move(self, move):
        """Change the translation of this transform by the amount given.

        Parameters
        ----------
        move : array-like
            The values to be added to the current translation of the transform.
        """
        move = as_vec4(move, default=(0, 0, 0, 0))
        self.translate = self.translate + move


Instruction:
Write a Python 3 function for
updating the transform such that its scale factor is changed and translate is left unchanged.

Response:
def zoom(self, zoom, center=(0, 0, 0), mapped=True):
        """Update the transform such that its scale factor is changed, but
        the specified center point is left unchanged.

        Parameters
        ----------
        zoom : array-like
            Values to multiply the transform's current scale
            factors.
        center : array-like
            The center point around which the scaling will take place.
        mapped : bool
            Whether *center* is expressed in mapped coordinates (True) or
            unmapped coordinates (False).
        """
        zoom = as_vec4(zoom, default=(1, 1, 1, 1))
        center = as_vec4(center, default=(0, 0, 0, 0))
        scale = self.scale * zoom
        if mapped:
            trans = center - (center - self.translate) * zoom
        else:
            trans = self.scale * (1 - zoom) * center + self.translate
        self._set_st(scale=scale, translate=trans)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def from_mapping(cls, x0, x1):
        t = cls()
        t.set_mapping(x0, x1)
        return t

Response: Create an STTransform from the given mapping.


Instruction:
Here you have a function in Python 3, explain what it does
def set_mapping(self, x0, x1, update=True):
        # if args are Rect, convert to array first
        if isinstance(x0, Rect):
            x0 = x0._transform_in()[:3]
        if isinstance(x1, Rect):
            x1 = x1._transform_in()[:3]

        x0 = np.asarray(x0)
        x1 = np.asarray(x1)
        if (x0.ndim != 2 or x0.shape[0] != 2 or x1.ndim != 2 or
                x1.shape[0] != 2):
            raise TypeError("set_mapping requires array inputs of shape "
                            "(2, N).")
        denom = x0[1] - x0[0]
        mask = denom == 0
        denom[mask] = 1.0
        s = (x1[1] - x1[0]) / denom
        s[mask] = 1.0
        s[x0[1] == x0[0]] = 1.0
        t = x1[0] - s * x0[0]
        s = as_vec4(s, default=(1, 1, 1, 1))
        t = as_vec4(t, default=(0, 0, 0, 0))
        self._set_st(scale=s, translate=t, update=update)

Response: Configure this transform such that it maps points x0 to x1.


Instruction:
How would you code a function in Python 3 to
translate the matrix of the sequence of items in the sequence at the given position.

Response:
def translate(self, pos):
        """
        Translate the matrix

        The translation is applied *after* the transformations already present
        in the matrix.

        Parameters
        ----------
        pos : arrayndarray
            Position to translate by.
        """
        self.matrix = np.dot(self.matrix, transforms.translate(pos[0, :3]))


Instruction:
Given the following Python 3 function, write the documentation
def scale(self, scale, center=None):
        scale = transforms.scale(as_vec4(scale, default=(1, 1, 1, 1))[0, :3])
        if center is not None:
            center = as_vec4(center)[0, :3]
            scale = np.dot(np.dot(transforms.translate(-center), scale),
                           transforms.translate(center))
        self.matrix = np.dot(self.matrix, scale)

Response: Scale the matrix about a given origin.


Instruction:
Can you write a function in Python 3 where it
rotates the matrix by some angle about a given axis.

Response:
def rotate(self, angle, axis):
        """
        Rotate the matrix by some angle about a given axis.

        The rotation is applied *after* the transformations already present
        in the matrix.

        Parameters
        ----------
        angle : float
            The angle of rotation, in degrees.
        axis : array-like
            The x, y and z coordinates of the axis vector to rotate around.
        """
        self.matrix = np.dot(self.matrix, transforms.rotate(angle, axis))


Instruction:
Implement a function in Python 3 to
set the matrix that maps points1 onto points2.

Response:
def set_mapping(self, points1, points2):
        """ Set to a 3D transformation matrix that maps points1 onto points2.

        Parameters
        ----------
        points1 : array-like, shape (4, 3)
            Four starting 3D coordinates.
        points2 : array-like, shape (4, 3)
            Four ending 3D coordinates.
        """
        # note: need to transpose because util.functions uses opposite
        # of standard linear algebra order.
        self.matrix = transforms.affine_map(points1, points2).T


Instruction:
How would you code a function in Python 3 to
set ortho transform for the current locale.

Response:
def set_ortho(self, l, r, b, t, n, f):
        """Set ortho transform

        Parameters
        ----------
        l : float
            Left.
        r : float
            Right.
        b : float
            Bottom.
        t : float
            Top.
        n : float
            Near.
        f : float
            Far.
        """
        self.matrix = transforms.ortho(l, r, b, t, n, f)


Instruction:
How would you explain what the following Python 3 function does
def set_perspective(self, fov, aspect, near, far):
        self.matrix = transforms.perspective(fov, aspect, near, far)

Response: Set the perspective of the object.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_frustum(self, l, r, b, t, n, f):
        self.matrix = transforms.frustum(l, r, b, t, n, f)

Response: Set the frustum of the current object.


Instruction:
Implement a Python 3 function for
computing the log2 of a 32 bit integer using a look up table.

Response:
def log2_lut(v):
    """
    See `this algo <https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup>`__ for
    computing the log2 of a 32 bit integer using a look up table

    Parameters
    ----------
    v : int
        32 bit integer

    Returns
    -------

    """
    res = np.zeros(v.shape, dtype=np.int32)

    tt = v >> 16
    tt_zero = (tt == 0)
    tt_not_zero = ~tt_zero

    t_h = tt >> 8
    t_zero_h = (t_h == 0) & tt_not_zero
    t_not_zero_h = ~t_zero_h & tt_not_zero

    res[t_zero_h] = LogTable256[tt[t_zero_h]] + 16
    res[t_not_zero_h] = LogTable256[t_h[t_not_zero_h]] + 24

    t_l = v >> 8
    t_zero_l = (t_l == 0) & tt_zero
    t_not_zero_l = ~t_zero_l & tt_zero

    res[t_zero_l] = LogTable256[v[t_zero_l]]
    res[t_not_zero_l] = LogTable256[t_l[t_not_zero_l]] + 8

    return res


Instruction:
Can you generate a brief explanation for the following Python 3 code
def uniq2orderipix(uniq):
    order = ((np.log2(uniq//4)) // 2)
    order = order.astype(int)
    ipix = uniq - 4 * (4**order)

    return order, ipix

Response:
convert a HEALPix pixel coded as a NUNIQ number
    to a ( norder ipix ) tuple


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

Response:
def set_data(self, data=None, **kwargs):
        """Set the line data

        Parameters
        ----------
        data : array-like
            The data.
        **kwargs : dict
            Keywoard arguments to pass to MarkerVisual and LineVisal.
        """
        if data is None:
            pos = None
        else:
            if isinstance(data, tuple):
                pos = np.array(data).T.astype(np.float32)
            else:
                pos = np.atleast_1d(data).astype(np.float32)

            if pos.ndim == 1:
                pos = pos[:, np.newaxis]
            elif pos.ndim > 2:
                raise ValueError('data must have at most two dimensions')

            if pos.size == 0:
                pos = self._line.pos

                # if both args and keywords are zero, then there is no
                # point in calling this function.
                if len(kwargs) == 0:
                    raise TypeError("neither line points nor line properties"
                                    "are provided")
            elif pos.shape[1] == 1:
                x = np.arange(pos.shape[0], dtype=np.float32)[:, np.newaxis]
                pos = np.concatenate((x, pos), axis=1)
            # if args are empty, don't modify position
            elif pos.shape[1] > 3:
                raise TypeError("Too many coordinates given (%s; max is 3)."
                                % pos.shape[1])

        # todo: have both sub-visuals share the same buffers.
        line_kwargs = {}
        for k in self._line_kwargs:
            if k in kwargs:
                k_ = self._kw_trans[k] if k in self._kw_trans else k
                line_kwargs[k] = kwargs.pop(k_)
        if pos is not None or len(line_kwargs) > 0:
            self._line.set_data(pos=pos, **line_kwargs)

        marker_kwargs = {}
        for k in self._marker_kwargs:
            if k in kwargs:
                k_ = self._kw_trans[k] if k in self._kw_trans else k
                marker_kwargs[k_] = kwargs.pop(k)
        if pos is not None or len(marker_kwargs) > 0:
            self._markers.set_data(pos=pos, **marker_kwargs)
        if len(kwargs) > 0:
            raise TypeError("Invalid keyword arguments: %s" % kwargs.keys())


Instruction:
Can you implement a function in Python 3 that
sets the data of the current object.

Response:
def set_data(self, pos=None, color=None):
        """Set the data

        Parameters
        ----------
        pos : float
            Position of the line along the axis.
        color : list, tuple, or array
            The color to use when drawing the line. If an array is given, it
            must be of shape (1, 4) and provide one rgba color per vertex.
        """
        if pos is not None:
            pos = float(pos)
            xy = self._pos
            if self._is_vertical:
                xy[0, 0] = pos
                xy[0, 1] = -1
                xy[1, 0] = pos
                xy[1, 1] = 1
            else:
                xy[0, 0] = -1
                xy[0, 1] = pos
                xy[1, 0] = 1
                xy[1, 1] = pos
            self._changed['pos'] = True

        if color is not None:
            color = np.array(color, dtype=np.float32)
            if color.ndim != 1 or color.shape[0] != 4:
                raise ValueError('color must be a 4 element float rgba tuple,'
                                 ' list or array')
            self._color = color
            self._changed['color'] = True


Instruction:
Create a Python 3 function to
compute the bounding values of this visual along the given axis.

Response:
def _compute_bounds(self, axis, view):
        """Return the (min, max) bounding values of this visual along *axis*
        in the local coordinate system.
        """
        is_vertical = self._is_vertical
        pos = self._pos
        if axis == 0 and is_vertical:
            return (pos[0, 0], pos[0, 0])
        elif axis == 1 and not is_vertical:
            return (self._pos[0, 1], self._pos[0, 1])

        return None


Instruction:
Given the following Python 3 function, write the documentation
def curve3_bezier(p1, p2, p3):
    x1, y1 = p1
    x2, y2 = p2
    x3, y3 = p3
    points = []
    _curve3_recursive_bezier(points, x1, y1, x2, y2, x3, y3)

    dx, dy = points[0][0] - x1, points[0][1] - y1
    if (dx * dx + dy * dy) > 1e-10:
        points.insert(0, (x1, y1))

    dx, dy = points[-1][0] - x3, points[-1][1] - y3
    if (dx * dx + dy * dy) > 1e-10:
        points.append((x3, y3))

    return np.array(points).reshape(len(points), 2)

Response: Generate the vertices for a quadratic Bezier curve.


Instruction:
Implement a function in Python 3 to
generate the vertices for a third order Bezier curve.

Response:
def curve4_bezier(p1, p2, p3, p4):
    """
    Generate the vertices for a third order Bezier curve.

    The vertices returned by this function can be passed to a LineVisual or
    ArrowVisual.

    Parameters
    ----------
    p1 : array
        2D coordinates of the start point
    p2 : array
        2D coordinates of the first curve point
    p3 : array
        2D coordinates of the second curve point
    p4 : array
        2D coordinates of the end point

    Returns
    -------
    coords : list
        Vertices for the Bezier curve.

    See Also
    --------
    curve3_bezier

    Notes
    -----
    For more information about Bezier curves please refer to the `Wikipedia`_
    page.

    .. _Wikipedia: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
    """
    x1, y1 = p1
    x2, y2 = p2
    x3, y3 = p3
    x4, y4 = p4
    points = []
    _curve4_recursive_bezier(points, x1, y1, x2, y2, x3, y3, x4, y4)

    dx, dy = points[0][0] - x1, points[0][1] - y1
    if (dx * dx + dy * dy) > 1e-10:
        points.insert(0, (x1, y1))
    dx, dy = points[-1][0] - x4, points[-1][1] - y4
    if (dx * dx + dy * dy) > 1e-10:
        points.append((x4, y4))

    return np.array(points).reshape(len(points), 2)


Instruction:
Here you have a function in Python 3, explain what it does
def render_to_texture(self, data, texture, offset, size):
        assert isinstance(texture, Texture2D)
        set_state(blend=False, depth_test=False)

        # calculate the negative half (within object)
        orig_tex = Texture2D(255 - data, format='luminance',
                             wrapping='clamp_to_edge', interpolation='nearest')
        edf_neg_tex = self._render_edf(orig_tex)

        # calculate positive half (outside object)
        orig_tex[:, :, 0] = data

        edf_pos_tex = self._render_edf(orig_tex)

        # render final product to output texture
        self.program_insert['u_texture'] = orig_tex
        self.program_insert['u_pos_texture'] = edf_pos_tex
        self.program_insert['u_neg_texture'] = edf_neg_tex
        self.fbo_to[-1].color_buffer = texture
        with self.fbo_to[-1]:
            set_viewport(tuple(offset) + tuple(size))
            self.program_insert.draw('triangle_strip')

Response: Render a SDF to a texture at a given offset and size.


Instruction:
Create a Python 3 function for
rendering an EDF to a texture

Response:
def _render_edf(self, orig_tex):
        """Render an EDF to a texture"""
        # Set up the necessary textures
        sdf_size = orig_tex.shape[:2]

        comp_texs = []
        for _ in range(2):
            tex = Texture2D(sdf_size + (4,), format='rgba',
                            interpolation='nearest', wrapping='clamp_to_edge')
            comp_texs.append(tex)
        self.fbo_to[0].color_buffer = comp_texs[0]
        self.fbo_to[1].color_buffer = comp_texs[1]
        for program in self.programs[1:]:  # program_seed does not need this
            program['u_texh'], program['u_texw'] = sdf_size

        # Do the rendering
        last_rend = 0
        with self.fbo_to[last_rend]:
            set_viewport(0, 0, sdf_size[1], sdf_size[0])
            self.program_seed['u_texture'] = orig_tex
            self.program_seed.draw('triangle_strip')
        stepsize = (np.array(sdf_size) // 2).max()
        while stepsize > 0:
            self.program_flood['u_step'] = stepsize
            self.program_flood['u_texture'] = comp_texs[last_rend]
            last_rend = 1 if last_rend == 0 else 0
            with self.fbo_to[last_rend]:
                set_viewport(0, 0, sdf_size[1], sdf_size[0])
                self.program_flood.draw('triangle_strip')
            stepsize //= 2
        return comp_texs[last_rend]


Instruction:
How would you explain what the following Python 3 function does
def _add_intent_interactive(self, intent_num=0):
        '''
        Interactively add a new intent to the intent schema object
        '''
        print ("Name of intent number : ", intent_num)
        slot_type_mappings = load_builtin_slots()
        intent_name = read_from_user(str)
        print ("How many slots?")
        num_slots = read_from_user(int)
        slot_list = []
        for i in range(num_slots):
            print ("Slot name no.", i+1)
            slot_name = read_from_user(str).strip()
            print ("Slot type? Enter a number for AMAZON supported types below,"
                   "else enter a string for a Custom Slot")
            print (json.dumps(slot_type_mappings, indent=True))
            slot_type_str = read_from_user(str)
            try: slot_type = slot_type_mappings[int(slot_type_str)]['name']
            except: slot_type = slot_type_str
            slot_list += [self.build_slot(slot_name, slot_type)]
        self.add_intent(intent_name, slot_list)

Response: Interactively add a new intent to the schema object


Instruction:
Can you generate a brief explanation for the following Python 3 code
def from_filename(self, filename):
        '''
        Build an IntentSchema from a file path
        creates a new intent schema if the file does not exist, throws an error if the file
        exists but cannot be loaded as a JSON
        '''
        if os.path.exists(filename):
            with open(filename) as fp:
                return IntentSchema(json.load(fp, object_pairs_hook=OrderedDict))
        else:
            print ('File does not exist')
            return IntentSchema()

Response:
Build an IntentSchema from a file path
        creates a new IntentSchema if the file does not exist throws an error if the file does not exist returns an IntentSchema


Instruction:
Write a Python 3 function for
annotating functions with VoiceHandler so that they can be automatically mapped to non - intent requests.

Response:
def launch_request_handler(request):
    """ Annotate functions with @VoiceHandler so that they can be automatically mapped
    to request types. Use the 'request_type' field to map them to non-intent requests """

    user_id = request.access_token()
    if user_id in twitter_cache.users():

        user_cache = twitter_cache.get_user_state(user_id)
        user_cache["amzn_id"]= request.user_id()
        base_message = "Welcome to Twitter, {} . How may I help you today ?".format(user_cache["screen_name"])
        print (user_cache)
        if 'pending_action' in user_cache:
            base_message += " You have one pending action . "
            print ("Found pending action")
            if 'description' in user_cache['pending_action']:
                print ("Found description")
                base_message += user_cache['pending_action']['description']
        return r.create_response(base_message)

    card = r.create_card(title="Please log into twitter", card_type="LinkAccount")
    return r.create_response(message="Welcome to twitter, looks like you haven't logged in!"
                             " Log in via the alexa app.", card_obj=card,
                             end_session=True)


Instruction:
Make a summary of the following Python 3 code
def post_tweet_intent_handler(request):
    tweet = request.get_slot_value("Tweet")
    tweet = tweet if tweet else ""
    if tweet:
        user_state = twitter_cache.get_user_state(request.access_token())
        def action():
            return post_tweet(request.access_token(), tweet)

        message = "I am ready to post the tweet, {} ,\n Please say yes to confirm or stop to cancel .".format(tweet)
        user_state['pending_action'] = {"action" : action,
                                        "description" : message}
        return r.create_response(message=message, end_session=False)
    else:
        # No tweet could be disambiguated
        message = " ".join(
            [
                "I'm sorry, I couldn't understand what you wanted to tweet .",
                "Please prepend the message with either post or tweet ."
            ]
        )
        return alexa.create_response(message=message, end_session=False)

Response: Post a tweet to the VoiceHandler.


Instruction:
How would you explain what the following Python 3 function does
def tweet_list_handler(request, tweet_list_builder, msg_prefix=""):

    """ This is a generic function to handle any intent that reads out a list of tweets"""
    # tweet_list_builder is a function that takes a unique identifier and returns a list of things to say
    tweets = tweet_list_builder(request.access_token())
    print (len(tweets), 'tweets found')
    if tweets:
        twitter_cache.initialize_user_queue(user_id=request.access_token(),
                                            queue=tweets)
        text_to_read_out = twitter_cache.user_queue(request.access_token()).read_out_next(MAX_RESPONSE_TWEETS)
        message = msg_prefix + text_to_read_out + ", say 'next' to hear more, or reply to a tweet by number."
        return alexa.create_response(message=message,
                                     end_session=False)
    else:
        return alexa.create_response(message="Sorry, no tweets found, please try something else",
                                 end_session=False)

Response: This function handles the generic intent that reads out a list of tweets and returns a list of tweets.


Instruction:
Explain what the following Python 3 code does
def focused_on_tweet(request):
    slots = request.get_slot_map()
    if "Index" in slots and slots["Index"]:
        index = int(slots['Index'])

    elif "Ordinal" in slots and slots["Index"]:
        parse_ordinal = lambda inp : int("".join([l for l in inp if l in string.digits]))
        index = parse_ordinal(slots['Ordinal'])
    else:
        return False

    index = index - 1 # Going from regular notation to CS notation
    user_state = twitter_cache.get_user_state(request.access_token())
    queue = user_state['user_queue'].queue()
    if index < len(queue):
        # Analyze tweet in queue
        tweet_to_analyze = queue[index]
        user_state['focus_tweet'] = tweet_to_analyze
        return index + 1 # Returning to regular notation
        twitter_cache.serialize()
    return False

Response: Return index if focused on tweet False if couldn t find it


Instruction:
Write a Python 3 script to
handle the next intent

Response:
def next_intent_handler(request):
    """
    Takes care of things whenver the user says 'next'
    """

    message = "Sorry, couldn't find anything in your next queue"
    end_session = True
    if True:
        user_queue = twitter_cache.user_queue(request.access_token())
        if not user_queue.is_finished():
            message = user_queue.read_out_next(MAX_RESPONSE_TWEETS)
            if not user_queue.is_finished():
                end_session = False
                message = message + ". Please, say 'next' if you want me to read out more. "
    return alexa.create_response(message=message,
                                 end_session=end_session)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def use_app(backend_name=None, call_reuse=True):
    global default_app

    # If we already have a default_app, raise error or return
    if default_app is not None:
        names = default_app.backend_name.lower().replace('(', ' ').strip(') ')
        names = [name for name in names.split(' ') if name]
        if backend_name and backend_name.lower() not in names:
            raise RuntimeError('Can only select a backend once, already using '
                               '%s.' % names)
        else:
            if call_reuse:
                default_app.reuse()
            return default_app  # Current backend matches backend_name

    # Create default app
    default_app = Application(backend_name)
    return default_app

Response: Get or create a default application object for the specified backend.


Instruction:
Write a Python 3 function for
writing data to the GL buffer.

Response:
def glBufferData(target, data, usage):
    """ Data can be numpy array or the size of data to allocate.
    """
    if isinstance(data, int):
        size = data
        data = ctypes.c_voidp(0)
    else:
        if not data.flags['C_CONTIGUOUS'] or not data.flags['ALIGNED']:
            data = data.copy('C')
        data_ = data
        size = data_.nbytes
        data = data_.ctypes.data
    res = _lib.glBufferData(target, size, data, usage)


Instruction:
Can you write a function in Python 3 where it
sets the mesh data for the current object.

Response:
def set_data(self, vertices=None, faces=None, vertex_colors=None,
                 face_colors=None, color=None, meshdata=None):
        """Set the mesh data

        Parameters
        ----------
        vertices : array-like | None
            The vertices.
        faces : array-like | None
            The faces.
        vertex_colors : array-like | None
            Colors to use for each vertex.
        face_colors : array-like | None
            Colors to use for each face.
        color : instance of Color
            The color to use.
        meshdata : instance of MeshData | None
            The meshdata.
        """
        if meshdata is not None:
            self._meshdata = meshdata
        else:
            self._meshdata = MeshData(vertices=vertices, faces=faces,
                                      vertex_colors=vertex_colors,
                                      face_colors=face_colors)
        self._bounds = self._meshdata.get_bounds()
        if color is not None:
            self._color = Color(color)
        self.mesh_data_changed()


Instruction:
How would you implement a function in Python 3 that
gets the bounds of the Visual

Response:
def bounds(self, axis, view=None):
        """Get the bounds of the Visual

        Parameters
        ----------
        axis : int
            The axis.
        view : instance of VisualView
            The view to use.
        """
        if view is None:
            view = self
        if axis not in self._vshare.bounds:
            self._vshare.bounds[axis] = self._compute_bounds(axis, view)
        return self._vshare.bounds[axis]


Instruction:
Can you write a function in Python 3 where it
defines the set of GL state parameters to use when drawing .

Response:
def set_gl_state(self, preset=None, **kwargs):
        """Define the set of GL state parameters to use when drawing

        Parameters
        ----------
        preset : str
            Preset to use.
        **kwargs : dict
            Keyword arguments to `gloo.set_state`.
        """
        self._vshare.gl_state = kwargs
        self._vshare.gl_state['preset'] = preset


Instruction:
Can you write a function in Python 3 where it
modifies the set of GL state parameters to use when drawing

Response:
def update_gl_state(self, *args, **kwargs):
        """Modify the set of GL state parameters to use when drawing

        Parameters
        ----------
        *args : tuple
            Arguments.
        **kwargs : dict
            Keyword argments.
        """
        if len(args) == 1:
            self._vshare.gl_state['preset'] = args[0]
        elif len(args) != 0:
            raise TypeError("Only one positional argument allowed.")
        self._vshare.gl_state.update(kwargs)


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_hook(self, shader, name):
        assert name in ('pre', 'post')
        key = (shader, name)
        if key in self._hooks:
            return self._hooks[key]
        hook = StatementList()
        if shader == 'vert':
            self.view_program.vert[name] = hook
        elif shader == 'frag':
            self.view_program.frag[name] = hook
        self._hooks[key] = hook
        return hook

Response: Return a FunctionChain that Filters may use to modify the program.


Instruction:
Can you implement a function in Python 3 that
attaches a Filter to this visual.

Response:
def attach(self, filt, view=None):
        """Attach a Filter to this visual

        Each filter modifies the appearance or behavior of the visual.

        Parameters
        ----------
        filt : object
            The filter to attach.
        view : instance of VisualView | None
            The view to use.
        """
        if view is None:
            self._vshare.filters.append(filt)
            for view in self._vshare.views.keys():
                filt._attach(view)
        else:
            view._filters.append(filt)
            filt._attach(view)