Instruction:
Implement a Python 3 function for
detaching a filter from the hierarchy.

Response:
def detach(self, filt, view=None):
        """Detach a filter.

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


Instruction:
How would you implement a function in Python 3 that
adds a subvisual to the set of subvisuals.

Response:
def add_subvisual(self, visual):
        """Add a subvisual

        Parameters
        ----------
        visual : instance of Visual
            The visual to add.
        """
        visual.transforms = self.transforms
        visual._prepare_transforms(visual)
        self._subvisuals.append(visual)
        visual.events.update.connect(self._subv_update)
        self.update()


Instruction:
Can you implement a function in Python 3 that
removes a subvisual from the set of subvisuals.

Response:
def remove_subvisual(self, visual):
        """Remove a subvisual

        Parameters
        ----------
        visual : instance of Visual
            The visual to remove.
        """
        visual.events.update.disconnect(self._subv_update)
        self._subvisuals.remove(visual)
        self.update()


Instruction:
Implement a Python 3 function for
defining 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`.
        """
        for v in self._subvisuals:
            v.set_gl_state(preset=preset, **kwargs)


Instruction:
Make a summary of the following Python 3 code
def update_gl_state(self, *args, **kwargs):
        for v in self._subvisuals:
            v.update_gl_state(*args, **kwargs)

Response:
Modify the set of GL state parameters to use when drawing
            is called


Instruction:
How would you code a function in Python 3 to
attach 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.
        """
        for v in self._subvisuals:
            v.attach(filt, v)


Instruction:
How would you explain what the following Python 3 function does
def detach(self, filt, view=None):
        for v in self._subvisuals:
            v.detach(filt, v)

Response: Detach a filter from all the subvisuals.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def addMov(self, product, quantity=None, mode="buy", stop_limit=None,
               auto_margin=None, name_counter=None):
        """main function for placing movements
        stop_limit = {'gain': [mode, value], 'loss': [mode, value]}"""
        # ~ ARGS ~
        if (not isinstance(product, type('')) or
                (not isinstance(name_counter, type('')) and
                 name_counter is not None)):
            raise ValueError('product and name_counter have to be a string')
        if not isinstance(stop_limit, type({})) and stop_limit is not None:
            raise ValueError('it has to be a dictionary')
        # exclusive args
        if quantity is not None and auto_margin is not None:
            raise ValueError("quantity and auto_margin are exclusive")
        elif quantity is None and auto_margin is None:
            raise ValueError("need at least one quantity")
        # ~ MAIN ~
        # open new window
        mov = self.new_mov(product)
        mov.open()
        mov.set_mode(mode)
        # set quantity
        if quantity is not None:
            mov.set_quantity(quantity)
            # for best performance in long times
            try:
                margin = mov.get_unit_value() * quantity
            except TimeoutError:
                mov.close()
                logger.warning("market closed for %s" % mov.product)
                return False
        # auto_margin calculate quantity (how simple!)
        elif auto_margin is not None:
            unit_value = mov.get_unit_value()
            mov.set_quantity(auto_margin * unit_value)
            margin = auto_margin
        # stop limit (how can be so simple!)
        if stop_limit is not None:
            mov.set_limit('gain', stop_limit['gain'][0], stop_limit['gain'][1])
            mov.set_limit('loss', stop_limit['loss'][0], stop_limit['loss'][1])
        # confirm
        try:
            mov.confirm()
        except (exceptions.MaxQuantLimit, exceptions.MinQuantLimit) as e:
            logger.warning(e.err)
            # resolve immediately
            mov.set_quantity(e.quant)
            mov.confirm()
        except Exception:
            logger.exception('undefined error in movement confirmation')
        mov_logger.info(f"added {mov.product} movement of {mov.quantity} " +
                        f"with margin of {margin}")
        mov_logger.debug(f"stop_limit: {stop_limit}")

Response: add a new Movements to the current window


Instruction:
Write a Python 3 script for
checking stocks in preference

Response:
def checkStock(self):
        """check stocks in preference"""
        if not self.preferences:
            logger.debug("no preferences")
            return None
        soup = BeautifulSoup(
            self.xpath(path['stock-table'])[0].html, "html.parser")
        count = 0
        # iterate through product in left panel
        for product in soup.select("div.tradebox"):
            prod_name = product.select("span.instrument-name")[0].text
            stk_name = [x for x in self.preferences
                        if x.lower() in prod_name.lower()]
            if not stk_name:
                continue
            name = prod_name
            if not [x for x in self.stocks if x.product == name]:
                self.stocks.append(Stock(name))
            stock = [x for x in self.stocks if x.product == name][0]
            if 'tradebox-market-closed' in product['class']:
                stock.market = False
            if not stock.market:
                logger.debug("market closed for %s" % stock.product)
                continue
            sell_price = product.select("div.tradebox-price-sell")[0].text
            buy_price = product.select("div.tradebox-price-buy")[0].text
            sent = int(product.select(path['sent'])[0].text.strip('%')) / 100
            stock.new_rec([sell_price, buy_price, sent])
            count += 1
        logger.debug(f"added %d stocks" % count)
        return self.stocks


Instruction:
Write a Python 3 function that can
clear the left panel and preferences

Response:
def clearPrefs(self):
        """clear the left panel and preferences"""
        self.preferences.clear()
        tradebox_num = len(self.css('div.tradebox'))
        for i in range(tradebox_num):
            self.xpath(path['trade-box'])[0].right_click()
            self.css1('div.item-trade-contextmenu-list-remove').click()
        logger.info("cleared preferences")


Instruction:
Can you implement a function in Python 3 that
adds preference in self. preferences

Response:
def addPrefs(self, prefs=[]):
        """add preference in self.preferences"""
        if len(prefs) == len(self.preferences) == 0:
            logger.debug("no preferences")
            return None
        self.preferences.extend(prefs)
        self.css1(path['search-btn']).click()
        count = 0
        for pref in self.preferences:
            self.css1(path['search-pref']).fill(pref)
            self.css1(path['pref-icon']).click()
            btn = self.css1('div.add-to-watchlist-popup-item .icon-wrapper')
            if not self.css1('svg', btn)['class'] is None:
                btn.click()
                count += 1
            # remove window
            self.css1(path['pref-icon']).click()
        # close finally
        self.css1(path['back-btn']).click()
        self.css1(path['back-btn']).click()
        logger.debug("updated %d preferences" % count)
        return self.preferences


Instruction:
Create a Python 3 function for
loading glyph from font into dict

Response:
def _load_glyph(f, char, glyphs_dict):
    """Load glyph from font into dict"""
    from ...ext.freetype import (FT_LOAD_RENDER, FT_LOAD_NO_HINTING,
                                 FT_LOAD_NO_AUTOHINT)
    flags = FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT
    face = _load_font(f['face'], f['bold'], f['italic'])
    face.set_char_size(f['size'] * 64)
    # get the character of interest
    face.load_char(char, flags)
    bitmap = face.glyph.bitmap
    width = face.glyph.bitmap.width
    height = face.glyph.bitmap.rows
    bitmap = np.array(bitmap.buffer)
    w0 = bitmap.size // height if bitmap.size > 0 else 0
    bitmap.shape = (height, w0)
    bitmap = bitmap[:, :width].astype(np.ubyte)

    left = face.glyph.bitmap_left
    top = face.glyph.bitmap_top
    advance = face.glyph.advance.x / 64.
    glyph = dict(char=char, offset=(left, top), bitmap=bitmap,
                 advance=advance, kerning={})
    glyphs_dict[char] = glyph
    # Generate kerning
    for other_char, other_glyph in glyphs_dict.items():
        kerning = face.get_kerning(other_char, char)
        glyph['kerning'][other_char] = kerning.x / 64.
        kerning = face.get_kerning(char, other_char)
        other_glyph['kerning'][char] = kerning.x / 64.


Instruction:
Can you generate the documentation for the following Python 3 function
def _set_clipper(self, node, clipper):
        if node in self._clippers:
            self.detach(self._clippers.pop(node))
        if clipper is not None:
            self.attach(clipper)
            self._clippers[node] = clipper

Response: Assign a clipper that is inherited from a parent node.


Instruction:
Here you have a function in Python 3, explain what it does
def _update_trsys(self, event):
        doc = self.document_node
        scene = self.scene_node
        root = self.root_node
        self.transforms.visual_transform = self.node_transform(scene)
        self.transforms.scene_transform = scene.node_transform(doc)
        self.transforms.document_transform = doc.node_transform(root)

        Node._update_trsys(self, event)

Response: Update the transforms object for this Node ; assign these to the visual s TransformSystem.


Instruction:
Explain what the following Python 3 code does
def cfnumber_to_number(cfnumber):
    numeric_type = cf.CFNumberGetType(cfnumber)
    cfnum_to_ctype = {kCFNumberSInt8Type: c_int8, kCFNumberSInt16Type: c_int16,
                      kCFNumberSInt32Type: c_int32,
                      kCFNumberSInt64Type: c_int64,
                      kCFNumberFloat32Type: c_float,
                      kCFNumberFloat64Type: c_double,
                      kCFNumberCharType: c_byte, kCFNumberShortType: c_short,
                      kCFNumberIntType: c_int, kCFNumberLongType: c_long,
                      kCFNumberLongLongType: c_longlong,
                      kCFNumberFloatType: c_float,
                      kCFNumberDoubleType: c_double,
                      kCFNumberCFIndexType: CFIndex,
                      kCFNumberCGFloatType: CGFloat}

    if numeric_type in cfnum_to_ctype:
        t = cfnum_to_ctype[numeric_type]
        result = t()
        if cf.CFNumberGetValue(cfnumber, numeric_type, byref(result)):
            return result.value
    else:
        raise Exception(
            'cfnumber_to_number: unhandled CFNumber type %d' % numeric_type)

Response: Convert CFNumber to python int or float.


Instruction:
Can you tell what is the following Python 3 function doing
def cftype_to_value(cftype):
    if not cftype:
        return None
    typeID = cf.CFGetTypeID(cftype)
    if typeID in known_cftypes:
        convert_function = known_cftypes[typeID]
        return convert_function(cftype)
    else:
        return cftype

Response: Convert a CFType into an equivalent python type.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def cfset_to_set(cfset):
    count = cf.CFSetGetCount(cfset)
    buffer = (c_void_p * count)()
    cf.CFSetGetValues(cfset, byref(buffer))
    return set([cftype_to_value(c_void_p(buffer[i])) for i in range(count)])

Response: Convert CFSet to python set.


Instruction:
Can you create a Python 3 function that
converts CFArray to python list.

Response:
def cfarray_to_list(cfarray):
    """Convert CFArray to python list."""
    count = cf.CFArrayGetCount(cfarray)
    return [cftype_to_value(c_void_p(cf.CFArrayGetValueAtIndex(cfarray, i)))
            for i in range(count)]


Instruction:
Here you have a function in Python 3, explain what it does
def ctype_for_encoding(self, encoding):
        if encoding in self.typecodes:
            return self.typecodes[encoding]
        elif encoding[0:1] == b'^' and encoding[1:] in self.typecodes:
            return POINTER(self.typecodes[encoding[1:]])
        elif encoding[0:1] == b'^' and encoding[1:] in [CGImageEncoding,
                                                        NSZoneEncoding]:
            return c_void_p
        elif encoding[0:1] == b'r' and encoding[1:] in self.typecodes:
            return self.typecodes[encoding[1:]]
        elif encoding[0:2] == b'r^' and encoding[2:] in self.typecodes:
            return POINTER(self.typecodes[encoding[2:]])
        else:
            raise Exception('unknown encoding for %s: %s'
                            % (self.name, encoding))

Response: Return ctypes type for an encoded Objective - C type.


Instruction:
Here you have a function in Python 3, explain what it does
def classmethod(self, encoding):
        # Add encodings for hidden self and cmd arguments.
        encoding = ensure_bytes(encoding)
        typecodes = parse_type_encoding(encoding)
        typecodes.insert(1, b'@:')
        encoding = b''.join(typecodes)

        def decorator(f):
            def objc_class_method(objc_cls, objc_cmd, *args):
                py_cls = ObjCClass(objc_cls)
                py_cls.objc_cmd = objc_cmd
                args = convert_method_arguments(encoding, args)
                result = f(py_cls, *args)
                if isinstance(result, ObjCClass):
                    result = result.ptr.value
                elif isinstance(result, ObjCInstance):
                    result = result.ptr.value
                return result
            name = f.__name__.replace('_', ':')
            self.add_class_method(objc_class_method, name, encoding)
            return objc_class_method
        return decorator

Response: Function decorator for class methods.


Instruction:
Make a summary of the following Python 3 code
def append(self, P0, P1, itemsize=None, **kwargs):

        itemsize = itemsize or 1
        itemcount = len(P0) // itemsize

        V = np.empty(itemcount, dtype=self.vtype)

        # Apply default values on vertices
        for name in self.vtype.names:
            if name not in ['collection_index', 'P0', 'P1', 'index']:
                V[name] = kwargs.get(name, self._defaults[name])

        V['P0'] = P0
        V['P1'] = P1
        V = V.repeat(4, axis=0)
        V['index'] = np.resize([0, 1, 2, 3], 4 * itemcount * itemsize)

        I = np.ones((itemcount, 6), dtype=int)
        I[:] = 0, 1, 2, 0, 2, 3
        I[:] += 4 * np.arange(itemcount)[:, np.newaxis]
        I = I.ravel()

        # Uniforms
        if self.utype:
            U = np.zeros(itemcount, dtype=self.utype)
            for name in self.utype.names:
                if name not in ["__unused__"]:
                    U[name] = kwargs.get(name, self._defaults[name])
        else:
            U = None

        Collection.append(
            self, vertices=V, uniforms=U, indices=I, itemsize=4 * itemcount)

Response: Append a new set of segments to the collection.


Instruction:
Here you have a function in Python 3, explain what it does
def get_frag_shader(volumes, clipped=False, n_volume_max=5):

    declarations = ""
    before_loop = ""
    in_loop = ""
    after_loop = ""

    for index in range(n_volume_max):
        declarations += "uniform $sampler_type u_volumetex_{0:d};\n".format(index)
        before_loop += "dummy = $sample(u_volumetex_{0:d}, loc).g;\n".format(index)

    declarations += "uniform $sampler_type dummy1;\n"
    declarations += "float dummy;\n"

    for label in sorted(volumes):

        index = volumes[label]['index']

        # Global declarations
        declarations += "uniform float u_weight_{0:d};\n".format(index)
        declarations += "uniform int u_enabled_{0:d};\n".format(index)

        # Declarations before the raytracing loop
        before_loop += "float max_val_{0:d} = 0;\n".format(index)

        # Calculation inside the main raytracing loop

        in_loop += "if(u_enabled_{0:d} == 1) {{\n\n".format(index)

        if clipped:
            in_loop += ("if(loc.r > u_clip_min.r && loc.r < u_clip_max.r &&\n"
                        "   loc.g > u_clip_min.g && loc.g < u_clip_max.g &&\n"
                        "   loc.b > u_clip_min.b && loc.b < u_clip_max.b) {\n\n")

        in_loop += "// Sample texture for layer {0}\n".format(label)
        in_loop += "val = $sample(u_volumetex_{0:d}, loc).g;\n".format(index)

        if volumes[label].get('multiply') is not None:
            index_other = volumes[volumes[label]['multiply']]['index']
            in_loop += ("if (val != 0) {{ val *= $sample(u_volumetex_{0:d}, loc).g; }}\n"
                        .format(index_other))

        in_loop += "max_val_{0:d} = max(val, max_val_{0:d});\n\n".format(index)

        if clipped:
            in_loop += "}\n\n"

        in_loop += "}\n\n"

        # Calculation after the main loop

        after_loop += "// Compute final color for layer {0}\n".format(label)
        after_loop += ("color = $cmap{0:d}(max_val_{0:d});\n"
                       "color.a *= u_weight_{0:d};\n"
                       "total_color += color.a * color;\n"
                       "max_alpha = max(color.a, max_alpha);\n"
                       "count += color.a;\n\n").format(index)

    if not clipped:
        before_loop += "\nfloat val3 = u_clip_min.g + u_clip_max.g;\n\n"

    # Code esthetics
    before_loop = indent(before_loop, " " * 4).strip()
    in_loop = indent(in_loop, " " * 16).strip()
    after_loop = indent(after_loop, " " * 4).strip()

    return FRAG_SHADER.format(declarations=declarations,
                              before_loop=before_loop,
                              in_loop=in_loop,
                              after_loop=after_loop)

Response: Get the fragment shader code for the given volumes.


Instruction:
How would you code a function in Python 3 to
connect to the EGL display server.

Response:
def eglGetDisplay(display=EGL_DEFAULT_DISPLAY):
    """ Connect to the EGL display server.
    """
    res = _lib.eglGetDisplay(display)
    if not res or res == EGL_NO_DISPLAY:
        raise RuntimeError('Could not create display')
    return res


Instruction:
Given the following Python 3 function, write the documentation
def eglInitialize(display):
    majorVersion = (_c_int*1)()
    minorVersion = (_c_int*1)()
    res = _lib.eglInitialize(display, majorVersion, minorVersion)
    if res == EGL_FALSE:
        raise RuntimeError('Could not initialize')
    return majorVersion[0], minorVersion[0]

Response: Initialize EGL and return EGL version tuple.


Instruction:
Create a Python 3 function to
query string from display

Response:
def eglQueryString(display, name):
    """ Query string from display
    """
    out = _lib.eglQueryString(display, name)
    if not out:
        raise RuntimeError('Could not query %s' % name)
    return out


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

        if indexed is None:
            if self._edges is None:
                self._compute_edges(indexed=None)
            return self._edges
        elif indexed == 'faces':
            if self._edges_indexed_by_faces is None:
                self._compute_edges(indexed='faces')
            return self._edges_indexed_by_faces
        else:
            raise Exception("Invalid indexing mode. Accepts: None, 'faces'")

Response: Returns the edges of the current node in the current mesh.


Instruction:
Create a Python 3 function to
set the faces of the current skeleton.

Response:
def set_faces(self, faces):
        """Set the faces

        Parameters
        ----------
        faces : ndarray
            (Nf, 3) array of faces. Each row in the array contains
            three indices into the vertex array, specifying the three corners
            of a triangular face.
        """
        self._faces = faces
        self._edges = None
        self._edges_indexed_by_faces = None
        self._vertex_faces = None
        self._vertices_indexed_by_faces = None
        self.reset_normals()
        self._vertex_colors_indexed_by_faces = None
        self._face_colors_indexed_by_faces = None


Instruction:
How would you code a function in Python 3 to
get the vertices in the unique key store.

Response:
def get_vertices(self, indexed=None):
        """Get the vertices

        Parameters
        ----------
        indexed : str | None
            If Note, return an array (N,3) of the positions of vertices in
            the mesh. By default, each unique vertex appears only once.
            If indexed is 'faces', then the array will instead contain three
            vertices per face in the mesh (and a single vertex may appear more
            than once in the array).

        Returns
        -------
        vertices : ndarray
            The vertices.
        """
        if indexed is None:
            if (self._vertices is None and
                    self._vertices_indexed_by_faces is not None):
                self._compute_unindexed_vertices()
            return self._vertices
        elif indexed == 'faces':
            if (self._vertices_indexed_by_faces is None and
                    self._vertices is not None):
                self._vertices_indexed_by_faces = \
                    self._vertices[self.get_faces()]
            return self._vertices_indexed_by_faces
        else:
            raise Exception("Invalid indexing mode. Accepts: None, 'faces'")


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_bounds(self):
        if self._vertices_indexed_by_faces is not None:
            v = self._vertices_indexed_by_faces
        elif self._vertices is not None:
            v = self._vertices
        else:
            return None
        bounds = [(v[:, ax].min(), v[:, ax].max()) for ax in range(v.shape[1])]
        return bounds

Response:
Get the mesh bounds Returns -------
        bounds = list of tuples of mesh bounds.


Instruction:
Create a Python 3 function for
setting the vertices of the current object.

Response:
def set_vertices(self, verts=None, indexed=None, reset_normals=True):
        """Set the mesh vertices

        Parameters
        ----------
        verts : ndarray | None
            The array (Nv, 3) of vertex coordinates.
        indexed : str | None
            If indexed=='faces', then the data must have shape (Nf, 3, 3) and
            is assumed to be already indexed as a list of faces. This will
            cause any pre-existing normal vectors to be cleared unless
            reset_normals=False.
        reset_normals : bool
            If True, reset the normals.
        """
        if indexed is None:
            if verts is not None:
                self._vertices = verts
            self._vertices_indexed_by_faces = None
        elif indexed == 'faces':
            self._vertices = None
            if verts is not None:
                self._vertices_indexed_by_faces = verts
        else:
            raise Exception("Invalid indexing mode. Accepts: None, 'faces'")

        if reset_normals:
            self.reset_normals()


Instruction:
Write a Python 3 script to
return True if this data set has vertex color information.

Response:
def has_vertex_color(self):
        """Return True if this data set has vertex color information"""
        for v in (self._vertex_colors, self._vertex_colors_indexed_by_faces,
                  self._vertex_colors_indexed_by_edges):
            if v is not None:
                return True
        return False


Instruction:
Can you create a Python 3 function that
returns True if this data set has face color information.

Response:
def has_face_color(self):
        """Return True if this data set has face color information"""
        for v in (self._face_colors, self._face_colors_indexed_by_faces,
                  self._face_colors_indexed_by_edges):
            if v is not None:
                return True
        return False


Instruction:
Implement a function in Python 3 to
get face normals of the current object.

Response:
def get_face_normals(self, indexed=None):
        """Get face normals

        Parameters
        ----------
        indexed : str | None
            If None, return an array (Nf, 3) of normal vectors for each face.
            If 'faces', then instead return an indexed array (Nf, 3, 3)
            (this is just the same array with each vector copied three times).

        Returns
        -------
        normals : ndarray
            The normals.
        """
        if self._face_normals is None:
            v = self.get_vertices(indexed='faces')
            self._face_normals = np.cross(v[:, 1] - v[:, 0],
                                          v[:, 2] - v[:, 0])

        if indexed is None:
            return self._face_normals
        elif indexed == 'faces':
            if self._face_normals_indexed_by_faces is None:
                norms = np.empty((self._face_normals.shape[0], 3, 3),
                                 dtype=np.float32)
                norms[:] = self._face_normals[:, np.newaxis, :]
                self._face_normals_indexed_by_faces = norms
            return self._face_normals_indexed_by_faces
        else:
            raise Exception("Invalid indexing mode. Accepts: None, 'faces'")


Instruction:
How would you code a function in Python 3 to
get vertex normals for the unique entry in the mesh.

Response:
def get_vertex_normals(self, indexed=None):
        """Get vertex normals

        Parameters
        ----------
        indexed : str | None
            If None, return an (N, 3) array of normal vectors with one entry
            per unique vertex in the mesh. If indexed is 'faces', then the
            array will contain three normal vectors per face (and some
            vertices may be repeated).

        Returns
        -------
        normals : ndarray
            The normals.
        """
        if self._vertex_normals is None:
            faceNorms = self.get_face_normals()
            vertFaces = self.get_vertex_faces()
            self._vertex_normals = np.empty(self._vertices.shape,
                                            dtype=np.float32)
            for vindex in xrange(self._vertices.shape[0]):
                faces = vertFaces[vindex]
                if len(faces) == 0:
                    self._vertex_normals[vindex] = (0, 0, 0)
                    continue
                norms = faceNorms[faces]  # get all face normals
                norm = norms.sum(axis=0)  # sum normals
                renorm = (norm**2).sum()**0.5
                if renorm > 0:
                    norm /= renorm
                self._vertex_normals[vindex] = norm

        if indexed is None:
            return self._vertex_normals
        elif indexed == 'faces':
            return self._vertex_normals[self.get_faces()]
        else:
            raise Exception("Invalid indexing mode. Accepts: None, 'faces'")


Instruction:
Make a summary of the following Python 3 code
def get_vertex_colors(self, indexed=None):
        if indexed is None:
            return self._vertex_colors
        elif indexed == 'faces':
            if self._vertex_colors_indexed_by_faces is None:
                self._vertex_colors_indexed_by_faces = \
                    self._vertex_colors[self.get_faces()]
            return self._vertex_colors_indexed_by_faces
        else:
            raise Exception("Invalid indexing mode. Accepts: None, 'faces'")

Response: Get vertex colors for a specific locale.


Instruction:
Can you write a function in Python 3 where it
sets the vertex color array for the current object.

Response:
def set_vertex_colors(self, colors, indexed=None):
        """Set the vertex color array

        Parameters
        ----------
        colors : array
            Array of colors. Must have shape (Nv, 4) (indexing by vertex)
            or shape (Nf, 3, 4) (vertices indexed by face).
        indexed : str | None
            Should be 'faces' if colors are indexed by faces.
        """
        colors = _fix_colors(np.asarray(colors))
        if indexed is None:
            if colors.ndim != 2:
                raise ValueError('colors must be 2D if indexed is None')
            if colors.shape[0] != self.n_vertices:
                raise ValueError('incorrect number of colors %s, expected %s'
                                 % (colors.shape[0], self.n_vertices))
            self._vertex_colors = colors
            self._vertex_colors_indexed_by_faces = None
        elif indexed == 'faces':
            if colors.ndim != 3:
                raise ValueError('colors must be 3D if indexed is "faces"')
            if colors.shape[0] != self.n_faces:
                raise ValueError('incorrect number of faces')
            self._vertex_colors = None
            self._vertex_colors_indexed_by_faces = colors
        else:
            raise ValueError('indexed must be None or "faces"')


Instruction:
Can you write a function in Python 3 where it
gets the face colors of the current node.

Response:
def get_face_colors(self, indexed=None):
        """Get the face colors

        Parameters
        ----------
        indexed : str | None
            If indexed is None, return (Nf, 4) array of face colors.
            If indexed=='faces', then instead return an indexed array
            (Nf, 3, 4)  (note this is just the same array with each color
            repeated three times).

        Returns
        -------
        colors : ndarray
            The colors.
        """
        if indexed is None:
            return self._face_colors
        elif indexed == 'faces':
            if (self._face_colors_indexed_by_faces is None and
                    self._face_colors is not None):
                Nf = self._face_colors.shape[0]
                self._face_colors_indexed_by_faces = \
                    np.empty((Nf, 3, 4), dtype=self._face_colors.dtype)
                self._face_colors_indexed_by_faces[:] = \
                    self._face_colors.reshape(Nf, 1, 4)
            return self._face_colors_indexed_by_faces
        else:
            raise Exception("Invalid indexing mode. Accepts: None, 'faces'")


Instruction:
How would you explain what the following Python 3 function does
def set_face_colors(self, colors, indexed=None):
        colors = _fix_colors(colors)
        if colors.shape[0] != self.n_faces:
            raise ValueError('incorrect number of colors %s, expected %s'
                             % (colors.shape[0], self.n_faces))
        if indexed is None:
            if colors.ndim != 2:
                raise ValueError('colors must be 2D if indexed is None')
            self._face_colors = colors
            self._face_colors_indexed_by_faces = None
        elif indexed == 'faces':
            if colors.ndim != 3:
                raise ValueError('colors must be 3D if indexed is "faces"')
            self._face_colors = None
            self._face_colors_indexed_by_faces = colors
        else:
            raise ValueError('indexed must be None or "faces"')

Response: Set the face color array.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def n_faces(self):
        if self._faces is not None:
            return self._faces.shape[0]
        elif self._vertices_indexed_by_faces is not None:
            return self._vertices_indexed_by_faces.shape[0]

Response: The number of faces in the mesh.


Instruction:
How would you code a function in Python 3 to
return a list of vertex indices that use it.

Response:
def get_vertex_faces(self):
        """
        List mapping each vertex index to a list of face indices that use it.
        """
        if self._vertex_faces is None:
            self._vertex_faces = [[] for i in xrange(len(self.get_vertices()))]
            for i in xrange(self._faces.shape[0]):
                face = self._faces[i]
                for ind in face:
                    self._vertex_faces[ind].append(i)
        return self._vertex_faces


Instruction:
Explain what the following Python 3 code does
def save(self):
        import pickle
        if self._faces is not None:
            names = ['_vertices', '_faces']
        else:
            names = ['_vertices_indexed_by_faces']

        if self._vertex_colors is not None:
            names.append('_vertex_colors')
        elif self._vertex_colors_indexed_by_faces is not None:
            names.append('_vertex_colors_indexed_by_faces')

        if self._face_colors is not None:
            names.append('_face_colors')
        elif self._face_colors_indexed_by_faces is not None:
            names.append('_face_colors_indexed_by_faces')

        state = dict([(n, getattr(self, n)) for n in names])
        return pickle.dumps(state)

Response: Serialize this mesh to a string appropriate for disk storage


Instruction:
Explain what the following Python 3 code does
def restore(self, state):
        import pickle
        state = pickle.loads(state)
        for k in state:
            if isinstance(state[k], list):
                state[k] = np.array(state[k])
            setattr(self, k, state[k])

Response: Restore the state of a previously saved object.


Instruction:
Write a Python 3 script for
returning a base color map for a given set of color maps.

Response:
def cubehelix(start=0.5, rot=1, gamma=1.0, reverse=True, nlev=256.,
         minSat=1.2, maxSat=1.2, minLight=0., maxLight=1.,
         **kwargs):
    """
    A full implementation of Dave Green's "cubehelix" for Matplotlib.
    Based on the FORTRAN 77 code provided in
    D.A. Green, 2011, BASI, 39, 289.

    http://adsabs.harvard.edu/abs/2011arXiv1108.5083G

    User can adjust all parameters of the cubehelix algorithm.
    This enables much greater flexibility in choosing color maps, while
    always ensuring the color map scales in intensity from black
    to white. A few simple examples:

    Default color map settings produce the standard "cubehelix".

    Create color map in only blues by setting rot=0 and start=0.

    Create reverse (white to black) backwards through the rainbow once
    by setting rot=1 and reverse=True.

    Parameters
    ----------
    start : scalar, optional
        Sets the starting position in the color space. 0=blue, 1=red,
        2=green. Defaults to 0.5.
    rot : scalar, optional
        The number of rotations through the rainbow. Can be positive
        or negative, indicating direction of rainbow. Negative values
        correspond to Blue->Red direction. Defaults to -1.5
    gamma : scalar, optional
        The gamma correction for intensity. Defaults to 1.0
    reverse : boolean, optional
        Set to True to reverse the color map. Will go from black to
        white. Good for density plots where shade~density. Defaults to False
    nlev : scalar, optional
        Defines the number of discrete levels to render colors at.
        Defaults to 256.
    sat : scalar, optional
        The saturation intensity factor. Defaults to 1.2
        NOTE: this was formerly known as "hue" parameter
    minSat : scalar, optional
        Sets the minimum-level saturation. Defaults to 1.2
    maxSat : scalar, optional
        Sets the maximum-level saturation. Defaults to 1.2
    startHue : scalar, optional
        Sets the starting color, ranging from [0, 360], as in
        D3 version by @mbostock
        NOTE: overrides values in start parameter
    endHue : scalar, optional
        Sets the ending color, ranging from [0, 360], as in
        D3 version by @mbostock
        NOTE: overrides values in rot parameter
    minLight : scalar, optional
        Sets the minimum lightness value. Defaults to 0.
    maxLight : scalar, optional
        Sets the maximum lightness value. Defaults to 1.

    Returns
    -------
    data : ndarray, shape (N, 3)
        Control points.
    """

# override start and rot if startHue and endHue are set
    if kwargs is not None:
        if 'startHue' in kwargs:
            start = (kwargs.get('startHue') / 360. - 1.) * 3.
        if 'endHue' in kwargs:
            rot = kwargs.get('endHue') / 360. - start / 3. - 1.
        if 'sat' in kwargs:
            minSat = kwargs.get('sat')
            maxSat = kwargs.get('sat')

# set up the parameters
    fract = np.linspace(minLight, maxLight, nlev)
    angle = 2.0 * pi * (start / 3.0 + rot * fract + 1.)
    fract = fract**gamma

    satar = np.linspace(minSat, maxSat, nlev)
    amp = satar * fract * (1. - fract) / 2.

# compute the RGB vectors according to main equations
    red = fract + amp * (-0.14861 * np.cos(angle) + 1.78277 * np.sin(angle))
    grn = fract + amp * (-0.29227 * np.cos(angle) - 0.90649 * np.sin(angle))
    blu = fract + amp * (1.97294 * np.cos(angle))

# find where RBB are outside the range [0,1], clip
    red[np.where((red > 1.))] = 1.
    grn[np.where((grn > 1.))] = 1.
    blu[np.where((blu > 1.))] = 1.

    red[np.where((red < 0.))] = 0.
    grn[np.where((grn < 0.))] = 0.
    blu[np.where((blu < 0.))] = 0.

# optional color reverse
    if reverse is True:
        red = red[::-1]
        blu = blu[::-1]
        grn = grn[::-1]

    return np.array((red, grn, blu)).T


Instruction:
How would you code a function in Python 3 to
convert matplotlib color code to hex color code

Response:
def color_to_hex(color):
    """Convert matplotlib color code to hex color code"""
    if color is None or colorConverter.to_rgba(color)[3] == 0:
        return 'none'
    else:
        rgb = colorConverter.to_rgb(color)
        return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))


Instruction:
Implement a function in Python 3 to
convert a many - to - one mapping to a one - to - one mapping

Response:
def _many_to_one(input_dict):
    """Convert a many-to-one mapping to a one-to-one mapping"""
    return dict((key, val)
                for keys, val in input_dict.items()
                for key in keys)


Instruction:
Here you have a function in Python 3, explain what it does
def get_dasharray(obj):
    if obj.__dict__.get('_dashSeq', None) is not None:
        return ','.join(map(str, obj._dashSeq))
    else:
        ls = obj.get_linestyle()
        dasharray = LINESTYLES.get(ls, 'not found')
        if dasharray == 'not found':
            warnings.warn("line style '{0}' not understood: "
                          "defaulting to solid line.".format(ls))
            dasharray = LINESTYLES['solid']
        return dasharray

Response: Get an SVG dash array for the given matplotlib line or path object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def SVG_path(path, transform=None, simplify=False):
    if transform is not None:
        path = path.transformed(transform)

    vc_tuples = [(vertices if path_code != Path.CLOSEPOLY else [],
                  PATH_DICT[path_code])
                 for (vertices, path_code)
                 in path.iter_segments(simplify=simplify)]

    if not vc_tuples:
        # empty path is a special case
        return np.zeros((0, 2)), []
    else:
        vertices, codes = zip(*vc_tuples)
        vertices = np.array(list(itertools.chain(*vertices))).reshape(-1, 2)
        return vertices, list(codes)

Response: Construct the vertices and SVG codes for the path.


Instruction:
Can you tell what is the following Python 3 function doing
def get_path_style(path, fill=True):
    style = {}
    style['alpha'] = path.get_alpha()
    if style['alpha'] is None:
        style['alpha'] = 1
    style['edgecolor'] = color_to_hex(path.get_edgecolor())
    if fill:
        style['facecolor'] = color_to_hex(path.get_facecolor())
    else:
        style['facecolor'] = 'none'
    style['edgewidth'] = path.get_linewidth()
    style['dasharray'] = get_dasharray(path)
    style['zorder'] = path.get_zorder()
    return style

Response: Get the style dictionary for matplotlib path objects


Instruction:
How would you explain what the following Python 3 function does
def get_line_style(line):
    style = {}
    style['alpha'] = line.get_alpha()
    if style['alpha'] is None:
        style['alpha'] = 1
    style['color'] = color_to_hex(line.get_color())
    style['linewidth'] = line.get_linewidth()
    style['dasharray'] = get_dasharray(line)
    style['zorder'] = line.get_zorder()
    return style

Response: Get the style dictionary for matplotlib line objects


Instruction:
Create a Python 3 function for
getting the style dictionary for matplotlib marker objects

Response:
def get_marker_style(line):
    """Get the style dictionary for matplotlib marker objects"""
    style = {}
    style['alpha'] = line.get_alpha()
    if style['alpha'] is None:
        style['alpha'] = 1

    style['facecolor'] = color_to_hex(line.get_markerfacecolor())
    style['edgecolor'] = color_to_hex(line.get_markeredgecolor())
    style['edgewidth'] = line.get_markeredgewidth()

    style['marker'] = line.get_marker()
    markerstyle = MarkerStyle(line.get_marker())
    markersize = line.get_markersize()
    markertransform = (markerstyle.get_transform() +
                       Affine2D().scale(markersize, -markersize))
    style['markerpath'] = SVG_path(markerstyle.get_path(),
                                   markertransform)
    style['markersize'] = markersize
    style['zorder'] = line.get_zorder()
    return style


Instruction:
Implement a function in Python 3 to
return the text style dict for a text instance

Response:
def get_text_style(text):
    """Return the text style dict for a text instance"""
    style = {}
    style['alpha'] = text.get_alpha()
    if style['alpha'] is None:
        style['alpha'] = 1
    style['fontsize'] = text.get_size()
    style['color'] = color_to_hex(text.get_color())
    style['halign'] = text.get_horizontalalignment()  # left, center, right
    style['valign'] = text.get_verticalalignment()  # baseline, center, top
    style['malign'] = text._multialignment  # text alignment when '\n' in text
    style['rotation'] = text.get_rotation()
    style['zorder'] = text.get_zorder()
    return style


Instruction:
Implement a function in Python 3 to
return the property dictionary for a matplotlib. Axis instance

Response:
def get_axis_properties(axis):
    """Return the property dictionary for a matplotlib.Axis instance"""
    props = {}
    label1On = axis._major_tick_kw.get('label1On', True)

    if isinstance(axis, matplotlib.axis.XAxis):
        if label1On:
            props['position'] = "bottom"
        else:
            props['position'] = "top"
    elif isinstance(axis, matplotlib.axis.YAxis):
        if label1On:
            props['position'] = "left"
        else:
            props['position'] = "right"
    else:
        raise ValueError("{0} should be an Axis instance".format(axis))

    # Use tick values if appropriate
    locator = axis.get_major_locator()
    props['nticks'] = len(locator())
    if isinstance(locator, ticker.FixedLocator):
        props['tickvalues'] = list(locator())
    else:
        props['tickvalues'] = None

    # Find tick formats
    formatter = axis.get_major_formatter()
    if isinstance(formatter, ticker.NullFormatter):
        props['tickformat'] = ""
    elif isinstance(formatter, ticker.FixedFormatter):
        props['tickformat'] = list(formatter.seq)
    elif not any(label.get_visible() for label in axis.get_ticklabels()):
        props['tickformat'] = ""
    else:
        props['tickformat'] = None

    # Get axis scale
    props['scale'] = axis.get_scale()

    # Get major tick label size (assumes that's all we really care about!)
    labels = axis.get_ticklabels()
    if labels:
        props['fontsize'] = labels[0].get_fontsize()
    else:
        props['fontsize'] = None

    # Get associated grid
    props['grid'] = get_grid_style(axis)

    return props


Instruction:
Write a Python 3 script for
returning an iterator over all childen and nested children using obj s get_children method.

Response:
def iter_all_children(obj, skipContainers=False):
    """
    Returns an iterator over all childen and nested children using
    obj's get_children() method

    if skipContainers is true, only childless objects are returned.
    """
    if hasattr(obj, 'get_children') and len(obj.get_children()) > 0:
        for child in obj.get_children():
            if not skipContainers:
                yield child
            # could use `yield from` in python 3...
            for grandchild in iter_all_children(child, skipContainers):
                yield grandchild
    else:
        yield obj


Instruction:
Can you generate the documentation for the following Python 3 function
def image_to_base64(image):
    ax = image.axes
    binary_buffer = io.BytesIO()

    # image is saved in axes coordinates: we need to temporarily
    # set the correct limits to get the correct image
    lim = ax.axis()
    ax.axis(image.get_extent())
    image.write_png(binary_buffer)
    ax.axis(lim)

    binary_buffer.seek(0)
    return base64.b64encode(binary_buffer.read()).decode('utf-8')

Response: Convert a matplotlib image to a base64 png representation.


Instruction:
Given the following Python 3 function, write the documentation
def set_interactive(enabled=True, app=None):
    if enabled:
        inputhook_manager.enable_gui('vispy', app)
    else:
        inputhook_manager.disable_gui()

Response: Activate the IPython hook for VisPy.


Instruction:
Write a Python 3 script to
write text and scroll the log.

Response:
def write(self, text='', wrap=True):
        """Write text and scroll

        Parameters
        ----------
        text : str
            Text to write. ``''`` can be used for a blank line, as a newline
            is automatically added to the end of each line.
        wrap : str
            If True, long messages will be wrapped to span multiple lines.
        """
        # Clear line
        if not isinstance(text, string_types):
            raise TypeError('text must be a string')
        # ensure we only have ASCII chars
        text = text.encode('utf-8').decode('ascii', errors='replace')
        self._pending_writes.append((text, wrap))
        self.update()


Instruction:
Given the following Python 3 function, write the documentation
def _do_pending_writes(self):
        for text, wrap in self._pending_writes:
            # truncate in case of *really* long messages
            text = text[-self._n_cols*self._n_rows:]
            text = text.split('\n')
            text = [t if len(t) > 0 else '' for t in text]
            nr, nc = self._n_rows, self._n_cols
            for para in text:
                para = para[:nc] if not wrap else para
                lines = [para[ii:(ii+nc)] for ii in range(0, len(para), nc)]
                lines = [''] if len(lines) == 0 else lines
                for line in lines:
                    # Update row and scroll if necessary
                    self._text_lines.insert(0, line)
                    self._text_lines = self._text_lines[:nr]
                    self._bytes_012[1:] = self._bytes_012[:-1]
                    self._bytes_345[1:] = self._bytes_345[:-1]
                    self._insert_text_buf(line, 0)
        self._pending_writes = []

Response: Do any pending text writes


Instruction:
Write a Python 3 function that can
insert text into bytes buffers

Response:
def _insert_text_buf(self, line, idx):
        """Insert text into bytes buffers"""
        self._bytes_012[idx] = 0
        self._bytes_345[idx] = 0
        # Crop text if necessary
        I = np.array([ord(c) - 32 for c in line[:self._n_cols]])
        I = np.clip(I, 0, len(__font_6x8__)-1)
        if len(I) > 0:
            b = __font_6x8__[I]
            self._bytes_012[idx, :len(I)] = b[:, :3]
            self._bytes_345[idx, :len(I)] = b[:, 3:]


Instruction:
Write a Python 3 function that can
set verbatim code replacement AttributeNames AttributeNames

Response:
def replace(self, str1, str2):
        """ Set verbatim code replacement

        It is strongly recommended to use function['$foo'] = 'bar' where
        possible because template variables are less likely to changed
        than the code itself in future versions of vispy.

        Parameters
        ----------
        str1 : str
            String to replace
        str2 : str
            String to replace str1 with
        """
        if str2 != self._replacements.get(str1, None):
            self._replacements[str1] = str2
            self.changed(code_changed=True)


Instruction:
Can you tell what is the following Python 3 function doing
def _parse_template_vars(self):
        template_vars = set()
        for var in parsing.find_template_variables(self._code):
            var = var.lstrip('$')
            if var == self.name:
                continue
            if var in ('pre', 'post'):
                raise ValueError('GLSL uses reserved template variable $%s' %
                                 var)
            template_vars.add(var)
        return template_vars

Response:
find all template variables in self. _code excluding the
        function name.


Instruction:
How would you implement a function in Python 3 that
returns code with new name expressions and replacements applied.

Response:
def _get_replaced_code(self, names):
        """ Return code, with new name, expressions, and replacements applied.
        """
        code = self._code

        # Modify name
        fname = names[self]
        code = code.replace(" " + self.name + "(", " " + fname + "(")

        # Apply string replacements first -- these may contain $placeholders
        for key, val in self._replacements.items():
            code = code.replace(key, val)

        # Apply assignments to the end of the function

        # Collect post lines
        post_lines = []
        for key, val in self._assignments.items():
            if isinstance(key, Variable):
                key = names[key]
            if isinstance(val, ShaderObject):
                val = val.expression(names)
            line = '    %s = %s;' % (key, val)
            post_lines.append(line)

        # Add a default $post placeholder if needed
        if 'post' in self._expressions:
            post_lines.append('    $post')

        # Apply placeholders for hooks
        post_text = '\n'.join(post_lines)
        if post_text:
            post_text = '\n' + post_text + '\n'
        code = code.rpartition('}')
        code = code[0] + post_text + code[1] + code[2]

        # Add a default $pre placeholder if needed
        if 'pre' in self._expressions:
            m = re.search(fname + r'\s*\([^{]*\)\s*{', code)
            if m is None:
                raise RuntimeError("Cound not find beginning of function '%s'"
                                   % fname)
            ind = m.span()[1]
            code = code[:ind] + "\n    $pre\n" + code[ind:]

        # Apply template variables
        for key, val in self._expressions.items():
            val = val.expression(names)
            search = r'\$' + key + r'($|[^a-zA-Z0-9_])'
            code = re.sub(search, val+r'\1', code)

        # Done
        if '$' in code:
            v = parsing.find_template_variables(code)
            logger.warning('Unsubstituted placeholders in code: %s\n'
                           '  replacements made: %s',
                           v, list(self._expressions.keys()))

        return code + '\n'


Instruction:
Write a Python 3 script for
returning * code * with indentation and leading / trailing blank lines removed.

Response:
def _clean_code(self, code):
        """ Return *code* with indentation and leading/trailing blank lines
        removed.
        """
        lines = code.split("\n")
        min_indent = 100
        for line in lines:
            if line.strip() != "":
                indent = len(line) - len(line.lstrip())
                min_indent = min(indent, min_indent)
        if min_indent > 0:
            lines = [line[min_indent:] for line in lines]
        code = "\n".join(lines)
        return code


Instruction:
Create a Python 3 function for
creating a new ChainFunction and attach it to the current object

Response:
def add_chain(self, var):
        """
        Create a new ChainFunction and attach to $var.
        """
        chain = FunctionChain(var, [])
        self._chains[var] = chain
        self[var] = chain


Instruction:
Can you create a Python 3 function that
appends a new function to the end of the chain.

Response:
def append(self, function, update=True):
        """ Append a new function to the end of this chain.
        """
        self._funcs.append(function)
        self._add_dep(function)
        if update:
            self._update()


Instruction:
Can you tell what is the following Python 3 function doing
def insert(self, index, function, update=True):
        self._funcs.insert(index, function)
        self._add_dep(function)
        if update:
            self._update()

Response: Insert a new function into the chain at the specified index.


Instruction:
Can you create a Python 3 function that
removes a function from the chain.

Response:
def remove(self, function, update=True):
        """ Remove a function from the chain.
        """
        self._funcs.remove(function)
        self._remove_dep(function)
        if update:
            self._update()


Instruction:
How would you code a function in Python 3 to
add an item to the list unless it is already present.

Response:
def add(self, item, position=5):
        """Add an item to the list unless it is already present.

        If the item is an expression, then a semicolon will be appended to it
        in the final compiled code.
        """
        if item in self.items:
            return
        self.items[item] = position
        self._add_dep(item)
        self.order = None
        self.changed(code_changed=True)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def remove(self, item):
        self.items.pop(item)
        self._remove_dep(item)
        self.order = None
        self.changed(code_changed=True)

Response: Remove an item from the list.


Instruction:
Implement a Python 3 function for
returning an array of vertex indexes three per triangular face in the mesh.

Response:
def faces(self):
        """Return an array (Nf, 3) of vertex indexes, three per triangular
        face in the mesh.

        If faces have not been computed for this mesh, the function
        computes them.
        If no vertices or faces are specified, the function returns None.
        """

        if self._faces is None:
            if self._vertices is None:
                return None
            self.triangulate()
        return self._faces


Instruction:
Create a Python 3 function to
return an array of vertices.

Response:
def vertices(self):
        """Return an array (Nf, 3) of vertices.

        If only faces exist, the function computes the vertices and
        returns them.
        If no vertices or faces are specified, the function returns None.
        """

        if self._faces is None:
            if self._vertices is None:
                return None
            self.triangulate()
        return self._vertices


Instruction:
Create a Python 3 function for
returning an array of vertex indexes representing the convex hull of this mesh.

Response:
def convex_hull(self):
        """Return an array of vertex indexes representing the convex hull.

        If faces have not been computed for this mesh, the function
        computes them.
        If no vertices or faces are specified, the function returns None.
        """
        if self._faces is None:
            if self._vertices is None:
                return None
            self.triangulate()
        return self._convex_hull


Instruction:
Here you have a function in Python 3, explain what it does
def triangulate(self):
        npts = self._vertices.shape[0]
        if np.any(self._vertices[0] != self._vertices[1]):
            # start != end, so edges must wrap around to beginning.
            edges = np.empty((npts, 2), dtype=np.uint32)
            edges[:, 0] = np.arange(npts)
            edges[:, 1] = edges[:, 0] + 1
            edges[-1, 1] = 0
        else:
            # start == end; no wrapping required.
            edges = np.empty((npts-1, 2), dtype=np.uint32)
            edges[:, 0] = np.arange(npts)
            edges[:, 1] = edges[:, 0] + 1

        tri = Triangulation(self._vertices, edges)
        tri.triangulate()
        return tri.pts, tri.tris

Response: Triangulates the set of vertices and stores the triangles in faces and the convex hull.


Instruction:
Write a Python 3 function that can
locate a filename into the shader library.

Response:
def find(name):
    """Locate a filename into the shader library."""

    if op.exists(name):
        return name

    path = op.dirname(__file__) or '.'

    paths = [path] + config['include_path']

    for path in paths:
        filename = op.abspath(op.join(path, name))
        if op.exists(filename):
            return filename

        for d in os.listdir(path):
            fullpath = op.abspath(op.join(path, d))
            if op.isdir(fullpath):
                filename = op.abspath(op.join(fullpath, name))
                if op.exists(filename):
                    return filename

    return None


Instruction:
Explain what the following Python 3 code does
def get(name):

    filename = find(name)
    if filename is None:
        raise RuntimeError('Could not find %s' % name)
    with open(filename) as fid:
        return fid.read()

Response: Retrieve code from the given filename.


Instruction:
Implement a Python 3 function for
expecting - try many times with sleep time

Response:
def expect(func, args, times=7, sleep_t=0.5):
    """try many times as in times with sleep time"""
    while times > 0:
        try:
            return func(*args)
        except Exception as e:
            times -= 1
            logger.debug("expect failed - attempts left: %d" % times)
            time.sleep(sleep_t)
            if times == 0:
                raise exceptions.BaseExc(e)


Instruction:
Make a summary of the following Python 3 code
def num(string):
    if not isinstance(string, type('')):
        raise ValueError(type(''))
    try:
        string = re.sub('[^a-zA-Z0-9\.\-]', '', string)
        number = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", string)
        return float(number[0])
    except Exception as e:
        logger = logging.getLogger('tradingAPI.utils.num')
        logger.debug("number not found in %s" % string)
        logger.debug(e)
        return None

Response: convert a string to float


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_number_unit(number):
    n = str(float(number))
    mult, submult = n.split('.')
    if float(submult) != 0:
        unit = '0.' + (len(submult)-1)*'0' + '1'
        return float(unit)
    else:
        return float(1)

Response: get the unit of number


Instruction:
Given the following Python 3 function, write the documentation
def get_pip(mov=None, api=None, name=None):
    # ~ check args
    if mov is None and api is None:
        logger.error("need at least one of those")
        raise ValueError()
    elif mov is not None and api is not None:
        logger.error("mov and api are exclusive")
        raise ValueError()
    if api is not None:
        if name is None:
            logger.error("need a name")
            raise ValueError()
        mov = api.new_mov(name)
        mov.open()
    if mov is not None:
        mov._check_open()
    # find in the collection
    try:
        logger.debug(len(Glob().theCollector.collection))
        pip = Glob().theCollector.collection['pip']
        if name is not None:
            pip_res = pip[name]
        elif mov is not None:
            pip_res = pip[mov.product]
        logger.debug("pip found in the collection")
        return pip_res
    except KeyError:
        logger.debug("pip not found in the collection")
    # ~ vars
    records = []
    intervals = [10, 20, 30]

    def _check_price(interval=10):
        timeout = time.time() + interval
        while time.time() < timeout:
            records.append(mov.get_price())
            time.sleep(0.5)

    # find variation
    for interval in intervals:
        _check_price(interval)
        if min(records) == max(records):
            logger.debug("no variation in %d seconds" % interval)
            if interval == intervals[-1]:
                raise TimeoutError("no variation")
        else:
            break
    # find longer price
    for price in records:
        if 'best_price' not in locals():
            best_price = price
        if len(str(price)) > len(str(best_price)):
            logger.debug("found new best_price %f" % price)
            best_price = price
    # get pip
    pip = get_number_unit(best_price)
    Glob().pipHandler.add_val({mov.product: pip})
    return pip

Response: get value of pip


Instruction:
Implement a function in Python 3 to
return the total amount of items in the cache.

Response:
def itemsize(self):
        """ Individual item sizes """
        return self._items[:self._count, 1] - self._items[:self._count, 0]


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

        if capacity >= self._data.size:
            capacity = int(2 ** np.ceil(np.log2(capacity)))
            self._data = np.resize(self._data, capacity)

Response: Reserves the underlying array to the given capacity.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def insert(self, index, data, itemsize=None):

        if not self._sizeable:
            raise AttributeError("List is not sizeable")

        if isinstance(data, (list, tuple)) and isinstance(data[0], (list, tuple)):  # noqa
            itemsize = [len(l) for l in data]
            data = [item for sublist in data for item in sublist]

        data = np.array(data, copy=False).ravel()
        size = data.size

        # Check item size and get item number
        if itemsize is not None:
            if isinstance(itemsize, int):
                if (size % itemsize) != 0:
                    raise ValueError("Cannot partition data as requested")
                _count = size // itemsize
                _itemsize = np.ones(_count, dtype=int) * (size // _count)
            else:
                _itemsize = np.array(itemsize, copy=False)
                _count = len(itemsize)
                if _itemsize.sum() != size:
                    raise ValueError("Cannot partition data as requested")
        else:
            _count = 1

        # Check if data array is big enough and resize it if necessary
        if self._size + size >= self._data.size:
            capacity = int(2 ** np.ceil(np.log2(self._size + size)))
            self._data = np.resize(self._data, capacity)

        # Check if item array is big enough and resize it if necessary
        if self._count + _count >= len(self._items):
            capacity = int(2 ** np.ceil(np.log2(self._count + _count)))
            self._items = np.resize(self._items, (capacity, 2))

        # Check index
        if index < 0:
            index += len(self)
        if index < 0 or index > len(self):
            raise IndexError("List insertion index out of range")

        # Inserting
        if index < self._count:
            istart = index
            dstart = self._items[istart][0]
            dstop = self._items[istart][1]
            # Move data
            Z = self._data[dstart:self._size]
            self._data[dstart + size:self._size + size] = Z
            # Update moved items
            I = self._items[istart:self._count] + size
            self._items[istart + _count:self._count + _count] = I

        # Appending
        else:
            dstart = self._size
            istart = self._count

        # Only one item (faster)
        if _count == 1:
            # Store data
            self._data[dstart:dstart + size] = data
            self._size += size
            # Store data location (= item)
            self._items[istart][0] = dstart
            self._items[istart][1] = dstart + size
            self._count += 1

        # Several items
        else:
            # Store data
            dstop = dstart + size
            self._data[dstart:dstop] = data
            self._size += size

            # Store items
            items = np.ones((_count, 2), int) * dstart
            C = _itemsize.cumsum()
            items[1:, 0] += C[:-1]
            items[0:, 1] += C
            istop = istart + _count
            self._items[istart:istop] = items
            self._count += _count

Response: Insert data before index.


Instruction:
Write a Python 3 script for
appending data to the end of the array.

Response:
def append(self, data, itemsize=None):
        """
        Append data to the end.

        Parameters
        ----------

        data : array_like
            An array, any object exposing the array interface, an object
            whose __array__ method returns an array, or any (nested) sequence.

        itemsize:  int or 1-D array
            If `itemsize is an integer, N, the array will be divided
            into elements of size N. If such partition is not possible,
            an error is raised.

            If `itemsize` is 1-D array, the array will be divided into
            elements whose succesive sizes will be picked from itemsize.
            If the sum of itemsize values is different from array size,
            an error is raised.
        """

        self.insert(len(self), data, itemsize)


Instruction:
Given the following Python 3 function, write the documentation
def minimize(func, bounds=None, nvar=None, args=(), disp=False,
             eps=1e-4,
             maxf=20000,
             maxT=6000,
             algmethod=0,
             fglobal=-1e100,
             fglper=0.01,
             volper=-1.0,
             sigmaper=-1.0,
             **kwargs
             ):
    """
    Solve an optimization problem using the DIRECT (Dividing Rectangles) algorithm.
    It can be used to solve general nonlinear programming problems of the form:

    .. math::

           \min_ {x \in R^n} f(x)

    subject to

    .. math::

           x_L \leq  x  \leq x_U

    Where :math:`x` are the optimization variables (with upper and lower
    bounds), :math:`f(x)` is the objective function.

    Parameters
    ----------
    func : objective function
        called as `func(x, *args)`; does not need to be defined everywhere,
        raise an Exception where function is not defined

    bounds : array-like
            ``(min, max)`` pairs for each element in ``x``, defining
            the bounds on that parameter.

    nvar: integer
        Dimensionality of x (only needed if `bounds` is not defined)

    eps : float
        Ensures sufficient decrease in function value when a new potentially
        optimal interval is chosen.

    maxf : integer
        Approximate upper bound on objective function evaluations.

        .. note::

            Maximal allowed value is 90000 see documentation of Fortran library.

    maxT : integer
        Maximum number of iterations.

        .. note::

            Maximal allowed value is 6000 see documentation of Fortran library.

    algmethod : integer
        Whether to use the original or modified DIRECT algorithm. Possible values:

        * ``algmethod=0`` - use the original DIRECT algorithm
        * ``algmethod=1`` - use the modified DIRECT-l algorithm

    fglobal : float
        Function value of the global optimum. If this value is not known set this
        to a very large negative value.

    fglper : float
        Terminate the optimization when the percent error satisfies:

        .. math::

            100*(f_{min} - f_{global})/\max(1, |f_{global}|) \leq f_{glper}

    volper : float
        Terminate the optimization once the volume of a hyperrectangle is less
        than volper percent of the original hyperrectangel.

    sigmaper : float
        Terminate the optimization once the measure of the hyperrectangle is less
        than sigmaper.

    Returns
    -------
    res : OptimizeResult
        The optimization result represented as a ``OptimizeResult`` object.
        Important attributes are: ``x`` the solution array, ``success`` a
        Boolean flag indicating if the optimizer exited successfully and
        ``message`` which describes the cause of the termination. See
        `OptimizeResult` for a description of other attributes.

    """

    if bounds is None:
        l = np.zeros(nvar, dtype=np.float64)
        u = np.ones(nvar, dtype=np.float64)
    else:
        bounds = np.asarray(bounds)
        l = bounds[:, 0]
        u = bounds[:, 1]

    def _objective_wrap(x, iidata, ddata, cdata, n, iisize, idsize, icsize):
        """
        Wrap the python objective to comply with the signature required by the
        Fortran library.

        Returns the function value and a flag indicating whether function is defined.
        If function is not defined return np.nan
        """
        try:
            return func(x, *args), 0
        except:
            return np.nan, 1

    #
    # Dummy values so that the python wrapper will comply with the required
    # signature of the fortran library.
    #
    iidata = np.ones(0, dtype=np.int32)
    ddata = np.ones(0, dtype=np.float64)
    cdata = np.ones([0, 40], dtype=np.uint8)

    #
    # Call the DIRECT algorithm
    #
    x, fun, ierror = direct(
                        _objective_wrap,
                        eps,
                        maxf,
                        maxT,
                        l,
                        u,
                        algmethod,
                        'dummylogfile',
                        fglobal,
                        fglper,
                        volper,
                        sigmaper,
                        iidata,
                        ddata,
                        cdata,
                        disp
                        )

    return OptimizeResult(x=x,fun=fun, status=ierror, success=ierror>0,
                          message=SUCCESS_MESSAGES[ierror-1] if ierror>0 else ERROR_MESSAGES[abs(ierror)-1])

Response: Returns a new object that minimizes the given function.


Instruction:
How would you explain what the following Python 3 function does
def get_dpi(raise_error=True):
    try:
        user32.SetProcessDPIAware()
    except AttributeError:
        pass  # not present on XP
    dc = user32.GetDC(0)
    h_size = gdi32.GetDeviceCaps(dc, HORZSIZE)
    v_size = gdi32.GetDeviceCaps(dc, VERTSIZE)
    h_res = gdi32.GetDeviceCaps(dc, HORZRES)
    v_res = gdi32.GetDeviceCaps(dc, VERTRES)
    user32.ReleaseDC(None, dc)
    return (h_res/float(h_size) + v_res/float(v_size)) * 0.5 * 25.4

Response: Get the DPI from the OS and return it.


Instruction:
Explain what the following Python 3 code does
def build_if_needed(self):
        if self._need_build:
            self._build()
            self._need_build = False
        self.update_variables()

Response: Build the shader source if necessary.


Instruction:
Write a Python 3 script to
return a function that maps a number n from range a b c d to a range a . Optionally a curvefn can be provided to transform output. Optionally a normfn can be provided to transform output.

Response:
def nmap(a, b, c, d, curvefn=None, normfn=None):
    """
    Returns a function that maps a number n from range (a, b) onto a range
    (c, d). If no curvefn is given, linear mapping will be used. Optionally a
    normalisation function normfn can be provided to transform output.
    """
    if not curvefn:
        curvefn = lambda x: x

    def map(n):
        r = 1.0 * (n - a) / (b - a)
        out = curvefn(r) * (d - c) + c
        if not normfn:
            return out
        return normfn(out)
    return map


Instruction:
Can you create a Python 3 function that
links this axis to a ViewBox This makes it so that the axis s domain always matches the visible range in the ViewBox.

Response:
def link_view(self, view):
        """Link this axis to a ViewBox

        This makes it so that the axis's domain always matches the
        visible range in the ViewBox.

        Parameters
        ----------
        view : instance of ViewBox
            The ViewBox to link.
        """
        if view is self._linked_view:
            return
        if self._linked_view is not None:
            self._linked_view.scene.transform.changed.disconnect(
                self._view_changed)
        self._linked_view = view
        view.scene.transform.changed.connect(self._view_changed)
        self._view_changed()


Instruction:
Can you implement a function in Python 3 that
updates the axis domain based on the current transform.

Response:
def _view_changed(self, event=None):
        """Linked view transform has changed; update ticks.
        """
        tr = self.node_transform(self._linked_view.scene)
        p1, p2 = tr.map(self._axis_ends())
        if self.orientation in ('left', 'right'):
            self.axis.domain = (p1[1], p2[1])
        else:
            self.axis.domain = (p1[0], p2[0])


Instruction:
Can you generate the documentation for the following Python 3 function
def viewbox_mouse_event(self, event):
        # When the attached ViewBox reseives a mouse event, it is sent to the
        # camera here.

        self.mouse_pos = event.pos[:2]
        if event.type == 'mouse_wheel':
            # wheel rolled; adjust the magnification factor and hide the
            # event from the superclass
            m = self.mag_target
            m *= 1.2 ** event.delta[1]
            m = m if m > 1 else 1
            self.mag_target = m
        else:
            # send everything _except_ wheel events to the superclass
            super(MagnifyCamera, self).viewbox_mouse_event(event)

        # start the timer to smoothly modify the transform properties.
        if not self.timer.running:
            self.timer.start()

        self._update_transform()

Response: This method is called by the mouse event handler to send the viewbox events to the camera.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def glBufferData(target, data, usage):
    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
    try:
        nativefunc = glBufferData._native
    except AttributeError:
        nativefunc = glBufferData._native = _get_gl_func("glBufferData", None, (ctypes.c_uint, ctypes.c_int, ctypes.c_void_p, ctypes.c_uint,))
    res = nativefunc(target, size, data, usage)

Response: This function is used to allocate memory for a buffer.


Instruction:
Here you have a function in Python 3, explain what it does
def next_power_of_2(n):
    n -= 1  # greater than OR EQUAL TO n
    shift = 1
    while (n + 1) & n:  # n+1 is not a power of 2 yet
        n |= n >> shift
        shift *= 2
    return max(4, n + 1)

Response: Return next power of 2 greater than or equal to n


Instruction:
Here you have a function in Python 3, explain what it does
def append(self, vertices, uniforms=None, indices=None, itemsize=None):

        # Vertices
        # -----------------------------
        vertices = np.array(vertices).astype(self.vtype).ravel()
        vsize = self._vertices_list.size

        # No itemsize given
        # -----------------
        if itemsize is None:
            index = 0
            count = 1

        # Uniform itemsize (int)
        # ----------------------
        elif isinstance(itemsize, int):
            count = len(vertices) / itemsize
            index = np.repeat(np.arange(count), itemsize)

        # Individual itemsize (array)
        # ---------------------------
        elif isinstance(itemsize, (np.ndarray, list)):
            count = len(itemsize)
            index = np.repeat(np.arange(count), itemsize)
        else:
            raise ValueError("Itemsize not understood")

        if self.utype:
            vertices["collection_index"] = index + len(self)
        self._vertices_list.append(vertices, itemsize)

        # Indices
        # -----------------------------
        if self.itype is not None:
            # No indices given (-> automatic generation)
            if indices is None:
                indices = vsize + np.arange(len(vertices))
                self._indices_list.append(indices, itemsize)

            # Indices given
            # FIXME: variables indices (list of list or ArrayList)
            else:
                if itemsize is None:
                    I = np.array(indices) + vsize
                elif isinstance(itemsize, int):
                    I = vsize + (np.tile(indices, count) +
                                 itemsize * np.repeat(np.arange(count), len(indices)))  # noqa
                else:
                    raise ValueError("Indices not compatible with items")
                self._indices_list.append(I, len(indices))

        # Uniforms
        # -----------------------------
        if self.utype:
            if uniforms is None:
                uniforms = np.zeros(count, dtype=self.utype)
            else:
                uniforms = np.array(uniforms).astype(self.utype).ravel()
            self._uniforms_list.append(uniforms, itemsize=1)

        self._need_update = True

Response: Append a new entry to the internal list.


Instruction:
How would you explain what the following Python 3 function does
def _compute_texture_shape(self, size=1):

        # We should use this line but we may not have a GL context yet
        # linesize = gl.glGetInteger(gl.GL_MAX_TEXTURE_SIZE)
        linesize = 1024
        count = self._uniforms_float_count
        cols = 4 * linesize // int(count)
        rows = max(1, int(math.ceil(size / float(cols))))
        shape = rows, cols * (count // 4), count
        self._ushape = shape
        return shape

Response: Compute uniform texture shape


Instruction:
How would you explain what the following Python 3 function does
def get_layout(name, *args, **kwargs):
    if name not in _layout_map:
        raise KeyError("Graph layout '%s' not found. Should be one of %s"
                       % (name, AVAILABLE_LAYOUTS))

    layout = _layout_map[name]

    if inspect.isclass(layout):
        layout = layout(*args, **kwargs)

    return layout

Response: Returns a graph layout with the given name.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update_viewer_state(rec, context):

    if '_protocol' not in rec:

        rec.pop('properties')

        rec['state'] = {}
        rec['state']['values'] = rec.pop('options')

        layer_states = []

        for layer in rec['layers']:
            state_id = str(uuid.uuid4())
            state_cls = STATE_CLASS[layer['_type'].split('.')[-1]]
            state = state_cls(layer=context.object(layer.pop('layer')))
            properties = set(layer.keys()) - set(['_type'])
            for prop in sorted(properties, key=state.update_priority, reverse=True):
                value = layer.pop(prop)
                value = context.object(value)
                if isinstance(value, six.string_types) and value == 'fixed':
                    value = 'Fixed'
                if isinstance(value, six.string_types) and value == 'linear':
                    value = 'Linear'
                setattr(state, prop, value)
            context.register_object(state_id, state)
            layer['state'] = state_id
            layer_states.append(state)

        list_id = str(uuid.uuid4())
        context.register_object(list_id, layer_states)
        rec['state']['values']['layers'] = list_id

        rec['state']['values']['visible_axes'] = rec['state']['values'].pop('visible_box')

Response: Update the state of the viewer in - place.


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

    pattern = r"(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*\n)"
    # first group captures quoted strings (double or single)
    # second group captures comments (//single-line or /* multi-line */)
    regex = re.compile(pattern, re.MULTILINE | re.DOTALL)

    def do_replace(match):
        # if the 2nd group (capturing comments) is not None,
        # it means we have captured a non-quoted (real) comment string.
        if match.group(2) is not None:
            return ""  # so we will return empty to remove the comment
        else:  # otherwise, we will return the 1st group
            return match.group(1)  # captured quoted-string

    return regex.sub(do_replace, code)

Response: Remove C - style comment from GLSL code string.


Instruction:
Implement a function in Python 3 to
merge all includes recursively.

Response:
def merge_includes(code):
    """Merge all includes recursively."""

    pattern = '\#\s*include\s*"(?P<filename>[a-zA-Z0-9\_\-\.\/]+)"'
    regex = re.compile(pattern)
    includes = []

    def replace(match):
        filename = match.group("filename")

        if filename not in includes:
            includes.append(filename)
            path = glsl.find(filename)
            if not path:
                logger.critical('"%s" not found' % filename)
                raise RuntimeError("File not found", filename)
            text = '\n// --- start of "%s" ---\n' % filename
            with open(path) as fh:
                text += fh.read()
            text += '// --- end of "%s" ---\n' % filename
            return text
        return ''

    # Limit recursion to depth 10
    for i in range(10):
        if re.search(regex, code):
            code = re.sub(regex, replace, code)
        else:
            break

    return code


Instruction:
Implement a function in Python 3 to
add a new widget to the grid.

Response:
def add_widget(self, widget=None, row=None, col=None, row_span=1,
                   col_span=1, **kwargs):
        """
        Add a new widget to this grid. This will cause other widgets in the
        grid to be resized to make room for the new widget. Can be used
        to replace a widget as well

        Parameters
        ----------
        widget : Widget | None
            The Widget to add. New widget is constructed if widget is None.
        row : int
            The row in which to add the widget (0 is the topmost row)
        col : int
            The column in which to add the widget (0 is the leftmost column)
        row_span : int
            The number of rows to be occupied by this widget. Default is 1.
        col_span : int
            The number of columns to be occupied by this widget. Default is 1.
        **kwargs : dict
            parameters sent to the new Widget that is constructed if
            widget is None

        Notes
        -----
        The widget's parent is automatically set to this grid, and all other
        parent(s) are removed.
        """
        if row is None:
            row = self._next_cell[0]
        if col is None:
            col = self._next_cell[1]

        if widget is None:
            widget = Widget(**kwargs)
        else:
            if kwargs:
                raise ValueError("cannot send kwargs if widget is given")

        _row = self._cells.setdefault(row, {})
        _row[col] = widget
        self._grid_widgets[self._n_added] = (row, col, row_span, col_span,
                                             widget)
        self._n_added += 1
        widget.parent = self

        self._next_cell = [row, col+col_span]

        widget._var_w = Variable("w-(row: %s | col: %s)" % (row, col))
        widget._var_h = Variable("h-(row: %s | col: %s)" % (row, col))

        # update stretch based on colspan/rowspan
        # usually, if you make something consume more grids or columns,
        # you also want it to actually *take it up*, ratio wise.
        # otherwise, it will never *use* the extra rows and columns,
        # thereby collapsing the extras to 0.
        stretch = list(widget.stretch)
        stretch[0] = col_span if stretch[0] is None else stretch[0]
        stretch[1] = row_span if stretch[1] is None else stretch[1]
        widget.stretch = stretch

        self._need_solver_recreate = True

        return widget


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

        self._grid_widgets = dict((key, val)
                                  for (key, val) in self._grid_widgets.items()
                                  if val[-1] != widget)

        self._need_solver_recreate = True

Response: Removes a widget from this grid


Instruction:
Can you tell what is the following Python 3 function doing
def resize_widget(self, widget, row_span, col_span):

        row = None
        col = None

        for (r, c, rspan, cspan, w) in self._grid_widgets.values():
            if w == widget:
                row = r
                col = c

                break

        if row is None or col is None:
            raise ValueError("%s not found in grid" % widget)

        self.remove_widget(widget)
        self.add_widget(widget, row, col, row_span, col_span)
        self._need_solver_recreate = True

Response: Resize a widget in the grid to new dimensions.


Instruction:
How would you code a function in Python 3 to
create a new Grid and add it as a child widget.

Response:
def add_grid(self, row=None, col=None, row_span=1, col_span=1,
                 **kwargs):
        """
        Create a new Grid and add it as a child widget.

        Parameters
        ----------
        row : int
            The row in which to add the widget (0 is the topmost row)
        col : int
            The column in which to add the widget (0 is the leftmost column)
        row_span : int
            The number of rows to be occupied by this widget. Default is 1.
        col_span : int
            The number of columns to be occupied by this widget. Default is 1.
        **kwargs : dict
            Keyword arguments to pass to the new `Grid`.
        """
        from .grid import Grid
        grid = Grid(**kwargs)
        return self.add_widget(grid, row, col, row_span, col_span)


Instruction:
Can you implement a function in Python 3 that
creates a new ViewBox and add it as a child widget.

Response:
def add_view(self, row=None, col=None, row_span=1, col_span=1,
                 **kwargs):
        """
        Create a new ViewBox and add it as a child widget.

        Parameters
        ----------
        row : int
            The row in which to add the widget (0 is the topmost row)
        col : int
            The column in which to add the widget (0 is the leftmost column)
        row_span : int
            The number of rows to be occupied by this widget. Default is 1.
        col_span : int
            The number of columns to be occupied by this widget. Default is 1.
        **kwargs : dict
            Keyword arguments to pass to `ViewBox`.
        """
        from .viewbox import ViewBox
        view = ViewBox(**kwargs)
        return self.add_widget(view, row, col, row_span, col_span)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def find_font(face, bold, italic):
    bold = FC_WEIGHT_BOLD if bold else FC_WEIGHT_REGULAR
    italic = FC_SLANT_ITALIC if italic else FC_SLANT_ROMAN
    face = face.encode('utf8')
    fontconfig.FcInit()
    pattern = fontconfig.FcPatternCreate()
    fontconfig.FcPatternAddInteger(pattern, FC_WEIGHT, bold)
    fontconfig.FcPatternAddInteger(pattern, FC_SLANT, italic)
    fontconfig.FcPatternAddString(pattern, FC_FAMILY, face)
    fontconfig.FcConfigSubstitute(0, pattern, FcMatchPattern)
    fontconfig.FcDefaultSubstitute(pattern)
    result = FcType()
    match = fontconfig.FcFontMatch(0, pattern, byref(result))
    fontconfig.FcPatternDestroy(pattern)
    if not match:
        raise RuntimeError('Could not match font "%s"' % face)
    value = FcValue()
    fontconfig.FcPatternGet(match, FC_FAMILY, 0, byref(value))
    if(value.u.s != face):
        warnings.warn('Could not find face match "%s", falling back to "%s"'
                      % (face, value.u.s))
    result = fontconfig.FcPatternGet(match, FC_FILE, 0, byref(value))
    if result != 0:
        raise RuntimeError('No filename or FT face for "%s"' % face)
    fname = value.u.s
    return fname.decode('utf-8')

Response: Find font in the current language


Instruction:
Can you generate the documentation for the following Python 3 function
def set_log_level(verbose, match=None, return_old=False):
    # This method is responsible for setting properties of the handler and
    # formatter such that proper messages (possibly with the vispy caller
    # prepended) are displayed. Storing log messages is only available
    # via the context handler (use_log_level), so that configuration is
    # done by the context handler itself.
    if isinstance(verbose, bool):
        verbose = 'info' if verbose else 'warning'
    if isinstance(verbose, string_types):
        verbose = verbose.lower()
        if verbose not in logging_types:
            raise ValueError('Invalid argument "%s"' % verbose)
        verbose = logging_types[verbose]
    else:
        raise TypeError('verbose must be a bool or string')
    logger = logging.getLogger('vispy')
    old_verbose = logger.level
    old_match = _lh._vispy_set_match(match)
    logger.setLevel(verbose)
    if verbose <= logging.DEBUG:
        _lf._vispy_set_prepend(True)
    else:
        _lf._vispy_set_prepend(False)
    out = None
    if return_old:
        out = (old_verbose, old_match)
    return out

Response: Convenience function for setting the logging level of the given log objects.


Instruction:
How would you implement a function in Python 3 that
sends an exception and traceback to the logger. This function is used in cases where an exception is handled safely but nevertheless should generate a descriptive error message. An extra line is inserted into the stack trace indicating where the exception was caught. Parameters ---------- level : str See ``set_log_level`` for options. tb_skip : int The number of traceback entries to ignore, prior to the point where the exception was caught. The default is 2.

Response:
def log_exception(level='warning', tb_skip=2):
    """
    Send an exception and traceback to the logger.

    This function is used in cases where an exception is handled safely but
    nevertheless should generate a descriptive error message. An extra line
    is inserted into the stack trace indicating where the exception was caught.

    Parameters
    ----------
    level : str
        See ``set_log_level`` for options.
    tb_skip : int
        The number of traceback entries to ignore, prior to the point where
        the exception was caught. The default is 2.
    """
    stack = "".join(traceback.format_stack()[:-tb_skip])
    tb = traceback.format_exception(*sys.exc_info())
    msg = tb[0]  # "Traceback (most recent call last):"
    msg += stack
    msg += "  << caught exception here: >>\n"
    msg += "".join(tb[1:]).rstrip()
    logger.log(logging_types[level], msg)


Instruction:
Can you implement a function in Python 3 that
handles exceptions in the exception namespace.

Response:
def _handle_exception(ignore_callback_errors, print_callback_errors, obj,
                      cb_event=None, node=None):
    """Helper for prining errors in callbacks

    See EventEmitter._invoke_callback for a use example.
    """
    if not hasattr(obj, '_vispy_err_registry'):
        obj._vispy_err_registry = {}
    registry = obj._vispy_err_registry

    if cb_event is not None:
        cb, event = cb_event
        exp_type = 'callback'
    else:
        exp_type = 'node'
    type_, value, tb = sys.exc_info()
    tb = tb.tb_next  # Skip *this* frame
    sys.last_type = type_
    sys.last_value = value
    sys.last_traceback = tb
    del tb  # Get rid of it in this namespace
    # Handle
    if not ignore_callback_errors:
        raise
    if print_callback_errors != "never":
        this_print = 'full'
        if print_callback_errors in ('first', 'reminders'):
            # need to check to see if we've hit this yet
            if exp_type == 'callback':
                key = repr(cb) + repr(event)
            else:
                key = repr(node)
            if key in registry:
                registry[key] += 1
                if print_callback_errors == 'first':
                    this_print = None
                else:  # reminders
                    ii = registry[key]
                    # Use logarithmic selection
                    # (1, 2, ..., 10, 20, ..., 100, 200, ...)
                    if ii == (2 ** int(np.log2(ii))):
                        this_print = ii
                    else:
                        this_print = None
            else:
                registry[key] = 1
        if this_print == 'full':
            logger.log_exception()
            if exp_type == 'callback':
                logger.error("Invoking %s for %s" % (cb, event))
            else:  # == 'node':
                logger.error("Drawing node %s" % node)
        elif this_print is not None:
            if exp_type == 'callback':
                logger.error("Invoking %s repeat %s"
                             % (cb, this_print))
            else:  # == 'node':
                logger.error("Drawing node %s repeat %s"
                             % (node, this_print))


Instruction:
Can you write a function in Python 3 where it
serializes a NumPy array.

Response:
def _serialize_buffer(buffer, array_serialization=None):
    """Serialize a NumPy array."""
    if array_serialization == 'binary':
        # WARNING: in NumPy 1.9, tostring() has been renamed to tobytes()
        # but tostring() is still here for now for backward compatibility.
        return buffer.ravel().tostring()
    elif array_serialization == 'base64':
        return {'storage_type': 'base64',
                'buffer': base64.b64encode(buffer).decode('ascii')
                }
    raise ValueError("The array serialization method should be 'binary' or "
                     "'base64'.")


Instruction:
Implement a function in Python 3 to
log message emitter that optionally matches and or records

Response:
def _vispy_emit_match_andor_record(self, record):
        """Log message emitter that optionally matches and/or records"""
        test = record.getMessage()
        match = self._vispy_match
        if (match is None or re.search(match, test) or
                re.search(match, _get_vispy_caller())):
            if self._vispy_emit_record:
                fmt_rec = self._vispy_formatter.format(record)
                self._vispy_emit_list.append(fmt_rec)
            if self._vispy_print_msg:
                return logging.StreamHandler.emit(self, record)
            else:
                return


Instruction:
Here you have a function in Python 3, explain what it does
def create(self, obj, ref=None):
        if isinstance(ref, Variable):
            ref = ref.name
        elif isinstance(ref, string_types) and ref.startswith('gl_'):
            # gl_ names not allowed for variables
            ref = ref[3:].lower()

        # Allow any type of object to be converted to ShaderObject if it
        # provides a magic method:
        if hasattr(obj, '_shader_object'):
            obj = obj._shader_object()

        if isinstance(obj, ShaderObject):
            if isinstance(obj, Variable) and obj.name is None:
                obj.name = ref
        elif isinstance(obj, string_types):
            obj = TextExpression(obj)
        else:
            obj = Variable(ref, obj)
            # Try prepending the name to indicate attribute, uniform, varying
            if obj.vtype and obj.vtype[0] in 'auv':
                obj.name = obj.vtype[0] + '_' + obj.name

        return obj

Response: Convert obj to a new ShaderObject.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def dependencies(self, sort=False):
        alldeps = []
        if sort:
            def key(obj):
                # sort deps such that we get functions, variables, self.
                if not isinstance(obj, Variable):
                    return (0, 0)
                else:
                    return (1, obj.vtype)

            deps = sorted(self._deps, key=key)
        else:
            deps = self._deps

        for dep in deps:
            alldeps.extend(dep.dependencies(sort=sort))
        alldeps.append(self)
        return alldeps

Response: Return all dependencies required to use this object.


Instruction:
How would you explain what the following Python 3 function does
def _add_dep(self, dep):
        if dep in self._deps:
            self._deps[dep] += 1
        else:
            self._deps[dep] = 1
            dep._dependents[self] = None

Response: Add a dependency to this object.


Instruction:
Explain what the following Python 3 code does
def _remove_dep(self, dep):
        refcount = self._deps[dep]
        if refcount == 1:
            self._deps.pop(dep)
            dep._dependents.pop(self)
        else:
            self._deps[dep] -= 1

Response: Decrement the reference count for the dependency and remove it from the list of dependents.


Instruction:
How would you explain what the following Python 3 function does
def _dep_changed(self, dep, code_changed=False, value_changed=False):
        self.changed(code_changed, value_changed)

Response: Called when a dependency s expression has changed.


Instruction:
Write a Python 3 function that can
inform dependents that this shaderobject has changed.

Response:
def changed(self, code_changed=False, value_changed=False):
        """Inform dependents that this shaderobject has changed.
        """
        for d in self._dependents:
            d._dep_changed(self, code_changed=code_changed,
                           value_changed=value_changed)