Instruction:
How would you explain what the following Python 3 function does
def deinterlace(self, raw):

        # Values per row (of the target image)
        vpr = self.width * self.planes

        # Make a result array, and make it big enough.  Interleaving
        # writes to the output array randomly (well, not quite), so the
        # entire output array must be in memory.
        fmt = 'BH'[self.bitdepth > 8]
        a = array(fmt, [0]*vpr*self.height)
        source_offset = 0

        for xstart, ystart, xstep, ystep in _adam7:
            if xstart >= self.width:
                continue
            # The previous (reconstructed) scanline.  None at the
            # beginning of a pass to indicate that there is no previous
            # line.
            recon = None
            # Pixels per row (reduced pass image)
            ppr = int(math.ceil((self.width-xstart)/float(xstep)))
            # Row size in bytes for this pass.
            row_size = int(math.ceil(self.psize * ppr))
            for y in range(ystart, self.height, ystep):
                filter_type = raw[source_offset]
                source_offset += 1
                scanline = raw[source_offset:source_offset+row_size]
                source_offset += row_size
                recon = self.undo_filter(filter_type, scanline, recon)
                # Convert so that there is one element per pixel value
                flat = self.serialtoflat(recon, ppr)
                if xstep == 1:
                    assert xstart == 0
                    offset = y * vpr
                    a[offset:offset+vpr] = flat
                else:
                    offset = y * vpr + xstart * self.planes
                    end_offset = (y+1) * vpr
                    skip = self.planes * xstep
                    for i in range(self.planes):
                        a[offset+i:end_offset:skip] = \
                            flat[i::self.planes]
        return a

Response: Read raw pixel data undo filters and flatten the image.


Instruction:
Implement a Python 3 function for
iterating over the bytes of the bytes of the next boxed scanline in flat pixel format.

Response:
def iterboxed(self, rows):
        """Iterator that yields each scanline in boxed row flat pixel
        format.  `rows` should be an iterator that yields the bytes of
        each row in turn.
        """

        def asvalues(raw):
            """Convert a row of raw bytes into a flat row.  Result will
            be a freshly allocated object, not shared with
            argument.
            """

            if self.bitdepth == 8:
                return array('B', raw)
            if self.bitdepth == 16:
                raw = tostring(raw)
                return array('H', struct.unpack('!%dH' % (len(raw)//2), raw))
            assert self.bitdepth < 8
            width = self.width
            # Samples per byte
            spb = 8//self.bitdepth
            out = array('B')
            mask = 2**self.bitdepth - 1
            shifts = map(self.bitdepth.__mul__, reversed(range(spb)))
            for o in raw:
                out.extend(map(lambda i: mask&(o>>i), shifts))
            return out[:width]

        return imap(asvalues, rows)


Instruction:
How would you code a function in Python 3 to
convert serial format ( byte stream ) pixel data to flat row.

Response:
def serialtoflat(self, bytes, width=None):
        """Convert serial format (byte stream) pixel data to flat row
        flat pixel.
        """

        if self.bitdepth == 8:
            return bytes
        if self.bitdepth == 16:
            bytes = tostring(bytes)
            return array('H',
              struct.unpack('!%dH' % (len(bytes)//2), bytes))
        assert self.bitdepth < 8
        if width is None:
            width = self.width
        # Samples per byte
        spb = 8//self.bitdepth
        out = array('B')
        mask = 2**self.bitdepth - 1
        shifts = map(self.bitdepth.__mul__, reversed(range(spb)))
        l = width
        for o in bytes:
            out.extend([(mask&(o>>s)) for s in shifts][:l])
            l -= spb
            if l <= 0:
                l = width
        return out


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

        # length of row, in bytes
        rb = self.row_bytes
        a = array('B')
        # The previous (reconstructed) scanline.  None indicates first
        # line of image.
        recon = None
        for some in raw:
            a.extend(some)
            while len(a) >= rb + 1:
                filter_type = a[0]
                scanline = a[1:rb+1]
                del a[:rb+1]
                recon = self.undo_filter(filter_type, scanline, recon)
                yield recon
        if len(a) != 0:
            # :file:format We get here with a file format error:
            # when the available bytes (after decompressing) do not
            # pack into exact rows.
            raise FormatError(
              'Wrong size for decompressed IDAT chunk.')
        assert len(a) == 0

Response:
Iterator that undoes the effect of filtering and yields
        each row in serialised format.


Instruction:
Write a Python 3 function that can
read just enough of the input to determine the next available pair length and type. Returns None if there are no more chunks.

Response:
def chunklentype(self):
        """Reads just enough of the input to determine the next
        chunk's length and type, returned as a (*length*, *type*) pair
        where *type* is a string.  If there are no more chunks, ``None``
        is returned.
        """

        x = self.file.read(8)
        if not x:
            return None
        if len(x) != 8:
            raise FormatError(
              'End of file whilst reading chunk length and type.')
        length,type = struct.unpack('!I4s', x)
        type = bytestostr(type)
        if length > 2**31-1:
            raise FormatError('Chunk %s is too large: %d.' % (type,length))
        return length,type


Instruction:
Here you have a function in Python 3, explain what it does
def read(self, lenient=False):

        def iteridat():
            """Iterator that yields all the ``IDAT`` chunks as strings."""
            while True:
                try:
                    type, data = self.chunk(lenient=lenient)
                except ValueError as e:
                    raise ChunkError(e.args[0])
                if type == 'IEND':
                    # http://www.w3.org/TR/PNG/#11IEND
                    break
                if type != 'IDAT':
                    continue
                # type == 'IDAT'
                # http://www.w3.org/TR/PNG/#11IDAT
                if self.colormap and not self.plte:
                    warnings.warn("PLTE chunk is required before IDAT chunk")
                yield data

        def iterdecomp(idat):
            """Iterator that yields decompressed strings.  `idat` should
            be an iterator that yields the ``IDAT`` chunk data.
            """

            # Currently, with no max_length parameter to decompress,
            # this routine will do one yield per IDAT chunk: Not very
            # incremental.
            d = zlib.decompressobj()
            # Each IDAT chunk is passed to the decompressor, then any
            # remaining state is decompressed out.
            for data in idat:
                # :todo: add a max_length argument here to limit output
                # size.
                yield array('B', d.decompress(data))
            yield array('B', d.flush())

        self.preamble(lenient=lenient)
        raw = iterdecomp(iteridat())

        if self.interlace:
            raw = array('B', itertools.chain(*raw))
            arraycode = 'BH'[self.bitdepth>8]
            # Like :meth:`group` but producing an array.array object for
            # each row.
            pixels = imap(lambda *row: array(arraycode, row),
                       *[iter(self.deinterlace(raw))]*self.width*self.planes)
        else:
            pixels = self.iterboxed(self.iterstraight(raw))
        meta = dict()
        for attr in 'greyscale alpha planes bitdepth interlace'.split():
            meta[attr] = getattr(self, attr)
        meta['size'] = (self.width, self.height)
        for attr in 'gamma transparent background'.split():
            a = getattr(self, attr, None)
            if a is not None:
                meta[attr] = a
        if self.plte:
            meta['palette'] = self.palette()
        return self.width, self.height, pixels, meta

Response: Read the PNG file and decode it.


Instruction:
How would you explain what the following Python 3 function does
def palette(self, alpha='natural'):

        if not self.plte:
            raise FormatError(
                "Required PLTE chunk is missing in colour type 3 image.")
        plte = group(array('B', self.plte), 3)
        if self.trns or alpha == 'force':
            trns = array('B', self.trns or '')
            trns.extend([255]*(len(plte)-len(trns)))
            plte = map(operator.add, plte, group(trns, 1))
        return plte

Response: Returns a sequence of 3 - tuples or 4 - tuples for the given image.


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

        self.preamble()

        # Simple case, no conversion necessary.
        if not self.colormap and not self.trns and not self.sbit:
            return self.read()

        x,y,pixels,meta = self.read()

        if self.colormap:
            meta['colormap'] = False
            meta['alpha'] = bool(self.trns)
            meta['bitdepth'] = 8
            meta['planes'] = 3 + bool(self.trns)
            plte = self.palette()
            def iterpal(pixels):
                for row in pixels:
                    row = map(plte.__getitem__, row)
                    yield array('B', itertools.chain(*row))
            pixels = iterpal(pixels)
        elif self.trns:
            # It would be nice if there was some reasonable way
            # of doing this without generating a whole load of
            # intermediate tuples.  But tuples does seem like the
            # easiest way, with no other way clearly much simpler or
            # much faster.  (Actually, the L to LA conversion could
            # perhaps go faster (all those 1-tuples!), but I still
            # wonder whether the code proliferation is worth it)
            it = self.transparent
            maxval = 2**meta['bitdepth']-1
            planes = meta['planes']
            meta['alpha'] = True
            meta['planes'] += 1
            typecode = 'BH'[meta['bitdepth']>8]
            def itertrns(pixels):
                for row in pixels:
                    # For each row we group it into pixels, then form a
                    # characterisation vector that says whether each
                    # pixel is opaque or not.  Then we convert
                    # True/False to 0/maxval (by multiplication),
                    # and add it as the extra channel.
                    row = group(row, planes)
                    opa = map(it.__ne__, row)
                    opa = map(maxval.__mul__, opa)
                    opa = zip(opa) # convert to 1-tuples
                    yield array(typecode,
                      itertools.chain(*map(operator.add, row, opa)))
            pixels = itertrns(pixels)
        targetbitdepth = None
        if self.sbit:
            sbit = struct.unpack('%dB' % len(self.sbit), self.sbit)
            targetbitdepth = max(sbit)
            if targetbitdepth > meta['bitdepth']:
                raise Error('sBIT chunk %r exceeds bitdepth %d' %
                    (sbit,self.bitdepth))
            if min(sbit) <= 0:
                raise Error('sBIT chunk %r has a 0-entry' % sbit)
            if targetbitdepth == meta['bitdepth']:
                targetbitdepth = None
        if targetbitdepth:
            shift = meta['bitdepth'] - targetbitdepth
            meta['bitdepth'] = targetbitdepth
            def itershift(pixels):
                for row in pixels:
                    yield map(shift.__rrshift__, row)
            pixels = itershift(pixels)
        return x,y,pixels,meta

Response: Returns the image data as a direct representation of an anonymization of an anonymization of an image.


Instruction:
Create a Python 3 function to
return image pixels as per : meth : asDirect method but scale all pixel values to be floating point values between 0. 0 and maxval*.

Response:
def asFloat(self, maxval=1.0):
        """Return image pixels as per :meth:`asDirect` method, but scale
        all pixel values to be floating point values between 0.0 and
        *maxval*.
        """

        x,y,pixels,info = self.asDirect()
        sourcemaxval = 2**info['bitdepth']-1
        del info['bitdepth']
        info['maxval'] = float(maxval)
        factor = float(maxval)/float(sourcemaxval)
        def iterfloat():
            for row in pixels:
                yield map(factor.__mul__, row)
        return x,y,iterfloat(),info


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

        width,height,pixels,meta = self.asDirect()
        if meta['alpha']:
            raise Error("will not convert image with alpha channel to RGB")
        if not meta['greyscale']:
            return width,height,pixels,meta
        meta['greyscale'] = False
        typecode = 'BH'[meta['bitdepth'] > 8]
        def iterrgb():
            for row in pixels:
                a = array(typecode, [0]) * 3 * width
                for i in range(3):
                    a[i::3] = row
                yield a
        return width,height,iterrgb(),meta

Response: Return image as RGB pixels.


Instruction:
Create a Python 3 function to
return image as RGBA pixels.

Response:
def asRGBA(self):
        """Return image as RGBA pixels.  Greyscales are expanded into
        RGB triplets; an alpha channel is synthesized if necessary.
        The return values are as for the :meth:`read` method
        except that the *metadata* reflect the returned pixels, not the
        source image.  In particular, for this method
        ``metadata['greyscale']`` will be ``False``, and
        ``metadata['alpha']`` will be ``True``.
        """

        width,height,pixels,meta = self.asDirect()
        if meta['alpha'] and not meta['greyscale']:
            return width,height,pixels,meta
        typecode = 'BH'[meta['bitdepth'] > 8]
        maxval = 2**meta['bitdepth'] - 1
        maxbuffer = struct.pack('=' + typecode, maxval) * 4 * width
        def newarray():
            return array(typecode, maxbuffer)

        if meta['alpha'] and meta['greyscale']:
            # LA to RGBA
            def convert():
                for row in pixels:
                    # Create a fresh target row, then copy L channel
                    # into first three target channels, and A channel
                    # into fourth channel.
                    a = newarray()
                    pngfilters.convert_la_to_rgba(row, a)
                    yield a
        elif meta['greyscale']:
            # L to RGBA
            def convert():
                for row in pixels:
                    a = newarray()
                    pngfilters.convert_l_to_rgba(row, a)
                    yield a
        else:
            assert not meta['alpha'] and not meta['greyscale']
            # RGB to RGBA
            def convert():
                for row in pixels:
                    a = newarray()
                    pngfilters.convert_rgb_to_rgba(row, a)
                    yield a
        meta['alpha'] = True
        meta['greyscale'] = False
        return width,height,convert(),meta


Instruction:
How would you implement a function in Python 3 that
loads a file from the remote demo - data repository.

Response:
def load_data_file(fname, directory=None, force_download=False):
    """Get a standard vispy demo data file

    Parameters
    ----------
    fname : str
        The filename on the remote ``demo-data`` repository to download,
        e.g. ``'molecular_viewer/micelle.npy'``. These correspond to paths
        on ``https://github.com/vispy/demo-data/``.
    directory : str | None
        Directory to use to save the file. By default, the vispy
        configuration directory is used.
    force_download : bool | str
        If True, the file will be downloaded even if a local copy exists
        (and this copy will be overwritten). Can also be a YYYY-MM-DD date
        to ensure a file is up-to-date (modified date of a file on disk,
        if present, is checked).

    Returns
    -------
    fname : str
        The path to the file on the local system.
    """
    _url_root = 'http://github.com/vispy/demo-data/raw/master/'
    url = _url_root + fname
    if directory is None:
        directory = config['data_path']
        if directory is None:
            raise ValueError('config["data_path"] is not defined, '
                             'so directory must be supplied')

    fname = op.join(directory, op.normcase(fname))  # convert to native
    if op.isfile(fname):
        if not force_download:  # we're done
            return fname
        if isinstance(force_download, string_types):
            ntime = time.strptime(force_download, '%Y-%m-%d')
            ftime = time.gmtime(op.getctime(fname))
            if ftime >= ntime:
                return fname
            else:
                print('File older than %s, updating...' % force_download)
    if not op.isdir(op.dirname(fname)):
        os.makedirs(op.abspath(op.dirname(fname)))
    # let's go get the file
    _fetch_file(url, fname)
    return fname


Instruction:
How would you implement a function in Python 3 that
downloads a file chunk by chunk and show advancement

Response:
def _chunk_read(response, local_file, chunk_size=65536, initial_size=0):
    """Download a file chunk by chunk and show advancement

    Can also be used when resuming downloads over http.

    Parameters
    ----------
    response: urllib.response.addinfourl
        Response to the download request in order to get file size.
    local_file: file
        Hard disk file where data should be written.
    chunk_size: integer, optional
        Size of downloaded chunks. Default: 8192
    initial_size: int, optional
        If resuming, indicate the initial size of the file.
    """
    # Adapted from NISL:
    # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py

    bytes_so_far = initial_size
    # Returns only amount left to download when resuming, not the size of the
    # entire file
    total_size = int(response.headers['Content-Length'].strip())
    total_size += initial_size

    progress = ProgressBar(total_size, initial_value=bytes_so_far,
                           max_chars=40, spinner=True, mesg='downloading')
    while True:
        chunk = response.read(chunk_size)
        bytes_so_far += len(chunk)
        if not chunk:
            sys.stderr.write('\n')
            break
        _chunk_write(chunk, local_file, progress)


Instruction:
Write a Python 3 script to
write a chunk to file and update the progress bar

Response:
def _chunk_write(chunk, local_file, progress):
    """Write a chunk to file and update the progress bar"""
    local_file.write(chunk)
    progress.update_with_increment_value(len(chunk))


Instruction:
Create a Python 3 function to
download requested file from url and save it to file_name.

Response:
def _fetch_file(url, file_name, print_destination=True):
    """Load requested file, downloading it if needed or requested

    Parameters
    ----------
    url: string
        The url of file to be downloaded.
    file_name: string
        Name, along with the path, of where downloaded file will be saved.
    print_destination: bool, optional
        If true, destination of where file was saved will be printed after
        download finishes.
    """
    # Adapted from NISL:
    # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py

    temp_file_name = file_name + ".part"
    local_file = None
    initial_size = 0
    # Checking file size and displaying it alongside the download url
    n_try = 3
    for ii in range(n_try):
        try:
            data = urllib.request.urlopen(url, timeout=15.)
        except Exception as e:
            if ii == n_try - 1:
                raise RuntimeError('Error while fetching file %s.\n'
                                   'Dataset fetching aborted (%s)' % (url, e))
    try:
        file_size = int(data.headers['Content-Length'].strip())
        print('Downloading data from %s (%s)' % (url, sizeof_fmt(file_size)))
        local_file = open(temp_file_name, "wb")
        _chunk_read(data, local_file, initial_size=initial_size)
        # temp file must be closed prior to the move
        if not local_file.closed:
            local_file.close()
        shutil.move(temp_file_name, file_name)
        if print_destination is True:
            sys.stdout.write('File saved as %s.\n' % file_name)
    except Exception as e:
        raise RuntimeError('Error while fetching file %s.\n'
                           'Dataset fetching aborted (%s)' % (url, e))
    finally:
        if local_file is not None:
            if not local_file.closed:
                local_file.close()


Instruction:
Given the following Python 3 function, write the documentation
def update(self, cur_value, mesg=None):
        # Ensure floating-point division so we can get fractions of a percent
        # for the progressbar.
        self.cur_value = cur_value
        progress = float(self.cur_value) / self.max_value
        num_chars = int(progress * self.max_chars)
        num_left = self.max_chars - num_chars

        # Update the message
        if mesg is not None:
            self.mesg = mesg

        # The \r tells the cursor to return to the beginning of the line rather
        # than starting a new line.  This allows us to have a progressbar-style
        # display in the console window.
        bar = self.template.format(self.progress_character * num_chars,
                                   ' ' * num_left,
                                   progress * 100,
                                   self.spinner_symbols[self.spinner_index],
                                   self.mesg)
        sys.stdout.write(bar)
        # Increament the spinner
        if self.spinner:
            self.spinner_index = (self.spinner_index + 1) % self.n_spinner

        # Force a flush because sometimes when using bash scripts and pipes,
        # the output is not printed until after the program exits.
        sys.stdout.flush()

Response: Update the progressbar with current value of process and message.


Instruction:
Write a Python 3 function for
updating the progressbar with the value of the increment instead of the current value of process as in update

Response:
def update_with_increment_value(self, increment_value, mesg=None):
        """Update progressbar with the value of the increment instead of the
        current value of process as in update()

        Parameters
        ----------
        increment_value : int
            Value of the increment of process.  The percent of the progressbar
            will be computed as
            (self.cur_value + increment_value / max_value) * 100
        mesg : str
            Message to display to the right of the progressbar.  If None, the
            last message provided will be used.  To clear the current message,
            pass a null string, ''.
        """
        self.cur_value += increment_value
        self.update(self.cur_value, mesg)


Instruction:
Implement a function in Python 3 to
return the default widget that occupies the entire area of the canvas.

Response:
def central_widget(self):
        """ Returns the default widget that occupies the entire area of the
        canvas.
        """
        if self._central_widget is None:
            self._central_widget = Widget(size=self.size, parent=self.scene)
        return self._central_widget


Instruction:
Can you generate the documentation for the following Python 3 function
def render(self, region=None, size=None, bgcolor=None):
        self.set_current()
        # Set up a framebuffer to render to
        offset = (0, 0) if region is None else region[:2]
        csize = self.size if region is None else region[2:]
        s = self.pixel_scale
        size = tuple([x * s for x in csize]) if size is None else size
        fbo = gloo.FrameBuffer(color=gloo.RenderBuffer(size[::-1]),
                               depth=gloo.RenderBuffer(size[::-1]))

        self.push_fbo(fbo, offset, csize)
        try:
            self._draw_scene(bgcolor=bgcolor)
            return fbo.read()
        finally:
            self.pop_fbo()

Response: Render the scene to an offscreen buffer and return the image array.


Instruction:
Write a Python 3 function for
drawing a visual and its children to the canvas or currently active one.

Response:
def draw_visual(self, visual, event=None):
        """ Draw a visual and its children to the canvas or currently active
        framebuffer.

        Parameters
        ----------
        visual : Visual
            The visual to draw
        event : None or DrawEvent
            Optionally specifies the original canvas draw event that initiated
            this draw.
        """
        prof = Profiler()

        # make sure this canvas's context is active
        self.set_current()

        try:
            self._drawing = True
            # get order to draw visuals
            if visual not in self._draw_order:
                self._draw_order[visual] = self._generate_draw_order()
            order = self._draw_order[visual]

            # draw (while avoiding branches with visible=False)
            stack = []
            invisible_node = None
            for node, start in order:
                if start:
                    stack.append(node)
                    if invisible_node is None:
                        if not node.visible:
                            # disable drawing until we exit this node's subtree
                            invisible_node = node
                        else:
                            if hasattr(node, 'draw'):
                                node.draw()
                                prof.mark(str(node))
                else:
                    if node is invisible_node:
                        invisible_node = None
                    stack.pop()
        finally:
            self._drawing = False


Instruction:
Implement a Python 3 function for
generating the order to draw visuals.

Response:
def _generate_draw_order(self, node=None):
        """Return a list giving the order to draw visuals.

        Each node appears twice in the list--(node, True) appears before the
        node's children are drawn, and (node, False) appears after.
        """
        if node is None:
            node = self._scene
        order = [(node, True)]
        children = node.children
        children.sort(key=lambda ch: ch.order)
        for ch in children:
            order.extend(self._generate_draw_order(ch))
        order.append((node, False))
        return order


Instruction:
Given the following Python 3 function, write the documentation
def visual_at(self, pos):
        tr = self.transforms.get_transform('canvas', 'framebuffer')
        fbpos = tr.map(pos)[:2]

        try:
            id_ = self._render_picking(region=(fbpos[0], fbpos[1],
                                               1, 1))
            vis = VisualNode._visual_ids.get(id_[0, 0], None)
        except RuntimeError:
            # Don't have read_pixels() support for IPython. Fall back to
            # bounds checking.
            return self._visual_bounds_at(pos)
        return vis

Response: Return the visual at a given position.


Instruction:
Make a summary of the following Python 3 code
def _visual_bounds_at(self, pos, node=None):
        if node is None:
            node = self.scene

        for ch in node.children:
            hit = self._visual_bounds_at(pos, ch)
            if hit is not None:
                return hit

        if (not isinstance(node, VisualNode) or not node.visible or
                not node.interactive):
            return None

        bounds = [node.bounds(axis=i) for i in range(2)]

        if None in bounds:
            return None

        tr = self.scene.node_transform(node).inverse
        corners = np.array([
            [bounds[0][0], bounds[1][0]],
            [bounds[0][0], bounds[1][1]],
            [bounds[0][1], bounds[1][0]],
            [bounds[0][1], bounds[1][1]]])
        bounds = tr.map(corners)
        xhit = bounds[:, 0].min() < pos[0] < bounds[:, 0].max()
        yhit = bounds[:, 1].min() < pos[1] < bounds[:, 1].max()
        if xhit and yhit:
            return node

Response: Find a visual whose bounding rect encompasses pos.


Instruction:
Create a Python 3 function to
return a list of visuals within radius pixels of pos.

Response:
def visuals_at(self, pos, radius=10):
        """Return a list of visuals within *radius* pixels of *pos*.

        Visuals are sorted by their proximity to *pos*.

        Parameters
        ----------
        pos : tuple
            (x, y) position at which to find visuals.
        radius : int
            Distance away from *pos* to search for visuals.
        """
        tr = self.transforms.get_transform('canvas', 'framebuffer')
        pos = tr.map(pos)[:2]

        id = self._render_picking(region=(pos[0]-radius, pos[1]-radius,
                                          radius * 2 + 1, radius * 2 + 1))
        ids = []
        seen = set()
        for i in range(radius):
            subr = id[radius-i:radius+i+1, radius-i:radius+i+1]
            subr_ids = set(list(np.unique(subr)))
            ids.extend(list(subr_ids - seen))
            seen |= subr_ids
        visuals = [VisualNode._visual_ids.get(x, None) for x in ids]
        return [v for v in visuals if v is not None]


Instruction:
How would you explain what the following Python 3 function does
def _render_picking(self, **kwargs):
        try:
            self._scene.picking = True
            img = self.render(bgcolor=(0, 0, 0, 0), **kwargs)
        finally:
            self._scene.picking = False
        img = img.astype('int32') * [2**0, 2**8, 2**16, 2**24]
        id_ = img.sum(axis=2).astype('int32')
        return id_

Response:
Render the scene in picking mode returning a 2D array of visual
        IDs.


Instruction:
Write a Python 3 function that can
disconnect from the mouse events and notifies the related events that the user has closed the resource.

Response:
def on_close(self, event):
        """Close event handler

        Parameters
        ----------
        event : instance of Event
            The event.
        """
        self.events.mouse_press.disconnect(self._process_mouse_event)
        self.events.mouse_move.disconnect(self._process_mouse_event)
        self.events.mouse_release.disconnect(self._process_mouse_event)
        self.events.mouse_wheel.disconnect(self._process_mouse_event)


Instruction:
Can you generate the documentation for the following Python 3 function
def push_viewport(self, viewport):
        vp = list(viewport)
        # Normalize viewport before setting;
        if vp[2] < 0:
            vp[0] += vp[2]
            vp[2] *= -1
        if vp[3] < 0:
            vp[1] += vp[3]
            vp[3] *= -1

        self._vp_stack.append(vp)
        try:
            self.context.set_viewport(*vp)
        except:
            self._vp_stack.pop()
            raise

        self._update_transforms()

Response: Pushes a viewport on the stack.


Instruction:
Write a Python 3 function that can
pop a viewport from the stack.

Response:
def pop_viewport(self):
        """ Pop a viewport from the stack.
        """
        vp = self._vp_stack.pop()
        # Activate latest
        if len(self._vp_stack) > 0:
            self.context.set_viewport(*self._vp_stack[-1])
        else:
            self.context.set_viewport(0, 0, *self.physical_size)

        self._update_transforms()
        return vp


Instruction:
Can you generate a brief explanation for the following Python 3 code
def push_fbo(self, fbo, offset, csize):
        self._fb_stack.append((fbo, offset, csize))
        try:
            fbo.activate()
            h, w = fbo.color_buffer.shape[:2]
            self.push_viewport((0, 0, w, h))
        except Exception:
            self._fb_stack.pop()
            raise

        self._update_transforms()

Response: Push a new FBO onto the stack.


Instruction:
Can you generate the documentation for the following Python 3 function
def pop_fbo(self):
        fbo = self._fb_stack.pop()
        fbo[0].deactivate()
        self.pop_viewport()
        if len(self._fb_stack) > 0:
            old_fbo = self._fb_stack[-1]
            old_fbo[0].activate()

        self._update_transforms()
        return fbo

Response: Pop an FBO from the stack.


Instruction:
Can you implement a function in Python 3 that
updates the canvas s TransformSystem to correct for the current .

Response:
def _update_transforms(self):
        """Update the canvas's TransformSystem to correct for the current
        canvas size, framebuffer, and viewport.
        """
        if len(self._fb_stack) == 0:
            fb_size = fb_rect = None
        else:
            fb, origin, fb_size = self._fb_stack[-1]
            fb_rect = origin + fb_size

        if len(self._vp_stack) == 0:
            viewport = None
        else:
            viewport = self._vp_stack[-1]

        self.transforms.configure(viewport=viewport, fbo_size=fb_size,
                                  fbo_rect=fb_rect)


Instruction:
Can you generate the documentation for the following Python 3 function
def resize(self, shape, format=None, internalformat=None):
        return self._resize(shape, format, internalformat)

Response:
Set the texture size and format of the a
           .


Instruction:
Implement a Python 3 function for
setting the data for the current node in the texture.

Response:
def set_data(self, data, offset=None, copy=False):
        """Set texture data

        Parameters
        ----------
        data : ndarray
            Data to be uploaded
        offset: int | tuple of ints
            Offset in texture where to start copying data
        copy: bool
            Since the operation is deferred, data may change before
            data is actually uploaded to GPU memory. Asking explicitly
            for a copy will prevent this behavior.

        Notes
        -----
        This operation implicitely resizes the texture to the shape of
        the data if given offset is None.
        """
        return self._set_data(data, offset, copy)


Instruction:
How would you code a function in Python 3 to
set the data of the current object to be uploaded to GPU memory.

Response:
def set_data(self, data, offset=None, copy=False):
        """Set texture data

        Parameters
        ----------
        data : ndarray
            Data to be uploaded
        offset: int | tuple of ints
            Offset in texture where to start copying data
        copy: bool
            Since the operation is deferred, data may change before
            data is actually uploaded to GPU memory. Asking explicitly
            for a copy will prevent this behavior.

        Notes
        -----
        This operation implicitely resizes the texture to the shape of
        the data if given offset is None.
        """
        self._set_emulated_shape(data)
        Texture2D.set_data(self, self._normalize_emulated_shape(data),
                           offset, copy)
        self._update_variables()


Instruction:
Can you generate the documentation for the following Python 3 function
def resize(self, shape, format=None, internalformat=None):
        self._set_emulated_shape(shape)
        Texture2D.resize(self, self._normalize_emulated_shape(shape),
                         format, internalformat)
        self._update_variables()

Response: Set the size and format of the texture.


Instruction:
Implement a function in Python 3 to
get a free region of given size and allocate it.

Response:
def get_free_region(self, width, height):
        """Get a free region of given size and allocate it

        Parameters
        ----------
        width : int
            Width of region to allocate
        height : int
            Height of region to allocate

        Returns
        -------
        bounds : tuple | None
            A newly allocated region as (x, y, w, h) or None
            (if failed).
        """
        best_height = best_width = np.inf
        best_index = -1
        for i in range(len(self._atlas_nodes)):
            y = self._fit(i, width, height)
            if y >= 0:
                node = self._atlas_nodes[i]
                if (y+height < best_height or
                        (y+height == best_height and node[2] < best_width)):
                    best_height = y+height
                    best_index = i
                    best_width = node[2]
                    region = node[0], y, width, height
        if best_index == -1:
            return None

        node = region[0], region[1] + height, width
        self._atlas_nodes.insert(best_index, node)
        i = best_index+1
        while i < len(self._atlas_nodes):
            node = self._atlas_nodes[i]
            prev_node = self._atlas_nodes[i-1]
            if node[0] < prev_node[0]+prev_node[2]:
                shrink = prev_node[0]+prev_node[2] - node[0]
                x, y, w = self._atlas_nodes[i]
                self._atlas_nodes[i] = x+shrink, y, w-shrink
                if self._atlas_nodes[i][2] <= 0:
                    del self._atlas_nodes[i]
                    i -= 1
                else:
                    break
            else:
                break
            i += 1

        # Merge nodes
        i = 0
        while i < len(self._atlas_nodes)-1:
            node = self._atlas_nodes[i]
            next_node = self._atlas_nodes[i+1]
            if node[1] == next_node[1]:
                self._atlas_nodes[i] = node[0], node[1], node[2]+next_node[2]
                del self._atlas_nodes[i+1]
            else:
                i += 1

        return region


Instruction:
How would you explain what the following Python 3 function does
def _fit(self, index, width, height):
        node = self._atlas_nodes[index]
        x, y = node[0], node[1]
        width_left = width
        if x+width > self._shape[1]:
            return -1
        i = index
        while width_left > 0:
            node = self._atlas_nodes[i]
            y = max(y, node[1])
            if y+height > self._shape[0]:
                return -1
            width_left -= node[2]
            i += 1
        return y

Response: Test if region ( width height fit into self. _atlas_nodes [ index ]


Instruction:
Here you have a function in Python 3, explain what it does
def _vector_or_scalar(x, type='row'):
    if isinstance(x, (list, tuple)):
        x = np.array(x)
    if isinstance(x, np.ndarray):
        assert x.ndim == 1
        if type == 'column':
            x = x[:, None]
    return x

Response: Convert an object to either a scalar or a row or column vector.


Instruction:
Make a summary of the following Python 3 code
def _vector(x, type='row'):
    if isinstance(x, (list, tuple)):
        x = np.array(x, dtype=np.float32)
    elif not isinstance(x, np.ndarray):
        x = np.array([x], dtype=np.float32)
    assert x.ndim == 1
    if type == 'column':
        x = x[:, None]
    return x

Response: Convert an object to a row or column vector.


Instruction:
Here you have a function in Python 3, explain what it does
def _normalize(x, cmin=None, cmax=None, clip=True):
    if not isinstance(x, np.ndarray):
        x = np.array(x)
    if cmin is None:
        cmin = x.min()
    if cmax is None:
        cmax = x.max()
    if cmin == cmax:
        return .5 * np.ones(x.shape)
    else:
        cmin, cmax = float(cmin), float(cmax)
        y = (x - cmin) * 1. / (cmax - cmin)
        if clip:
            y = np.clip(y, 0., 1.)
        return y

Response: Normalize an array from the range cmin cmax to [ 0 1 ) with optional clipping.


Instruction:
Explain what the following Python 3 code does
def _mix_simple(a, b, x):
    x = np.clip(x, 0.0, 1.0)
    return (1.0 - x)*a + x*b

Response: Mix b with a with proportion x.


Instruction:
Write a Python 3 function for
performing smooth Hermite interpolation between 0 and 1 when edge0 < x < edge1.

Response:
def smoothstep(edge0, edge1, x):
    """ performs smooth Hermite interpolation
        between 0 and 1 when edge0 < x < edge1.  """
    # Scale, bias and saturate x to 0..1 range
    x = np.clip((x - edge0)/(edge1 - edge0), 0.0, 1.0)
    # Evaluate polynomial
    return x*x*(3 - 2*x)


Instruction:
Implement a function in Python 3 to
step interpolation from a set of colors. x belongs in [ 0 1 ).

Response:
def step(colors, x, controls=None):
    x = x.ravel()
    """Step interpolation from a set of colors. x belongs in [0, 1]."""
    assert (controls[0], controls[-1]) == (0., 1.)
    ncolors = len(colors)
    assert ncolors == len(controls) - 1
    assert ncolors >= 2
    x_step = _find_controls(x, controls, ncolors-1)
    return colors[x_step, ...]


Instruction:
How would you explain what the following Python 3 function does
def _glsl_mix(controls=None):
    assert (controls[0], controls[-1]) == (0., 1.)
    ncolors = len(controls)
    assert ncolors >= 2
    if ncolors == 2:
        s = "    return mix($color_0, $color_1, t);\n"
    else:
        s = ""
        for i in range(ncolors-1):
            if i == 0:
                ifs = 'if (t < %.6f)' % (controls[i+1])
            elif i == (ncolors-2):
                ifs = 'else'
            else:
                ifs = 'else if (t < %.6f)' % (controls[i+1])
            adj_t = '(t - %s) / %s' % (controls[i],
                                       controls[i+1] - controls[i])
            s += ("%s {\n    return mix($color_%d, $color_%d, %s);\n} " %
                  (ifs, i, i+1, adj_t))
    return "vec4 colormap(float t) {\n%s\n}" % s

Response:
Generate a GLSL template function from a given interpolation patterns
    and control points.


Instruction:
Can you generate the documentation for the following Python 3 function
def _process_glsl_template(template, colors):
    for i in range(len(colors) - 1, -1, -1):
        color = colors[i]
        assert len(color) == 4
        vec4_color = 'vec4(%.3f, %.3f, %.3f, %.3f)' % tuple(color)
        template = template.replace('$color_%d' % i, vec4_color)
    return template

Response: Replace color_i by color i in the GLSL template.


Instruction:
Write a Python 3 script to
obtain a colormap from the _colormaps dictionary.

Response:
def get_colormap(name, *args, **kwargs):
    """Obtain a colormap

    Some colormaps can have additional configuration parameters. Refer to
    their corresponding documentation for more information.

    Parameters
    ----------
    name : str | Colormap
        Colormap name. Can also be a Colormap for pass-through.

    Examples
    --------

        >>> get_colormap('autumn')
        >>> get_colormap('single_hue', hue=10)
    """
    if isinstance(name, BaseColormap):
        cmap = name
    else:
        if not isinstance(name, string_types):
            raise TypeError('colormap must be a Colormap or string name')
        if name not in _colormaps:
            raise KeyError('colormap name %s not found' % name)
        cmap = _colormaps[name]

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

    return cmap


Instruction:
Can you implement a function in Python 3 that
returns the Python mapping function from the 0 1 interval to a list of rgba colors.

Response:
def map(self, x):
        """The Python mapping function from the [0,1] interval to a
        list of rgba colors

        Parameters
        ----------
        x : array-like
            The values to map.

        Returns
        -------
        colors : list
            List of rgba colors.
        """
        return self._map_function(self.colors.rgba, x, self._controls)


Instruction:
How would you explain what the following Python 3 function does
def visual_border_width(self):
        render_to_doc =  \
            self.transforms.get_transform('document', 'visual')

        vec = render_to_doc.map([self.border_width, self.border_width, 0])
        origin = render_to_doc.map([0, 0, 0])

        visual_border_width = [vec[0] - origin[0], vec[1] - origin[1]]

        # we need to flip the y axis because coordinate systems are inverted
        visual_border_width[1] *= -1

        return visual_border_width

Response: The border width in visual coordinates


Instruction:
Explain what the following Python 3 code does
def run(self, fig):
        # Calling savefig executes the draw() command, putting elements
        # in the correct place.
        fig.savefig(io.BytesIO(), format='png', dpi=fig.dpi)
        if self.close_mpl:
            import matplotlib.pyplot as plt
            plt.close(fig)
        self.crawl_fig(fig)

Response: Run the exporter on the given figure


Instruction:
Write a Python 3 function that can
process the transform and convert data to figure or data coordinates.

Response:
def process_transform(transform, ax=None, data=None, return_trans=False,
                          force_trans=None):
        """Process the transform and convert data to figure or data coordinates

        Parameters
        ----------
        transform : matplotlib Transform object
            The transform applied to the data
        ax : matplotlib Axes object (optional)
            The axes the data is associated with
        data : ndarray (optional)
            The array of data to be transformed.
        return_trans : bool (optional)
            If true, return the final transform of the data
        force_trans : matplotlib.transform instance (optional)
            If supplied, first force the data to this transform

        Returns
        -------
        code : string
            Code is either "data", "axes", "figure", or "display", indicating
            the type of coordinates output.
        transform : matplotlib transform
            the transform used to map input data to output data.
            Returned only if return_trans is True
        new_data : ndarray
            Data transformed to match the given coordinate code.
            Returned only if data is specified
        """
        if isinstance(transform, transforms.BlendedGenericTransform):
            warnings.warn("Blended transforms not yet supported. "
                          "Zoom behavior may not work as expected.")

        if force_trans is not None:
            if data is not None:
                data = (transform - force_trans).transform(data)
            transform = force_trans

        code = "display"
        if ax is not None:
            for (c, trans) in [("data", ax.transData),
                               ("axes", ax.transAxes),
                               ("figure", ax.figure.transFigure),
                               ("display", transforms.IdentityTransform())]:
                if transform.contains_branch(trans):
                    code, transform = (c, transform - trans)
                    break

        if data is not None:
            if return_trans:
                return code, transform.transform(data), transform
            else:
                return code, transform.transform(data)
        else:
            if return_trans:
                return code, transform
            else:
                return code


Instruction:
Implement a function in Python 3 to
crawl the figure and process all axes

Response:
def crawl_fig(self, fig):
        """Crawl the figure and process all axes"""
        with self.renderer.draw_figure(fig=fig,
                                       props=utils.get_figure_properties(fig)):
            for ax in fig.axes:
                self.crawl_ax(ax)


Instruction:
How would you code a function in Python 3 to
crawl the axes and process all elements within the axes.

Response:
def crawl_ax(self, ax):
        """Crawl the axes and process all elements within"""
        with self.renderer.draw_axes(ax=ax,
                                     props=utils.get_axes_properties(ax)):
            for line in ax.lines:
                self.draw_line(ax, line)
            for text in ax.texts:
                self.draw_text(ax, text)
            for (text, ttp) in zip([ax.xaxis.label, ax.yaxis.label, ax.title],
                                   ["xlabel", "ylabel", "title"]):
                if(hasattr(text, 'get_text') and text.get_text()):
                    self.draw_text(ax, text, force_trans=ax.transAxes,
                                   text_type=ttp)
            for artist in ax.artists:
                # TODO: process other artists
                if isinstance(artist, matplotlib.text.Text):
                    self.draw_text(ax, artist)
            for patch in ax.patches:
                self.draw_patch(ax, patch)
            for collection in ax.collections:
                self.draw_collection(ax, collection)
            for image in ax.images:
                self.draw_image(ax, image)

            legend = ax.get_legend()
            if legend is not None:
                props = utils.get_legend_properties(ax, legend)
                with self.renderer.draw_legend(legend=legend, props=props):
                    if props['visible']:
                        self.crawl_legend(ax, legend)


Instruction:
How would you explain what the following Python 3 function does
def crawl_legend(self, ax, legend):
        legendElements = list(utils.iter_all_children(legend._legend_box,
                                                      skipContainers=True))
        legendElements.append(legend.legendPatch)
        for child in legendElements:
            # force a large zorder so it appears on top
            child.set_zorder(1E6 + child.get_zorder())

            try:
                # What kind of object...
                if isinstance(child, matplotlib.patches.Patch):
                    self.draw_patch(ax, child, force_trans=ax.transAxes)
                elif isinstance(child, matplotlib.text.Text):
                    if not (child is legend.get_children()[-1]
                            and child.get_text() == 'None'):
                        self.draw_text(ax, child, force_trans=ax.transAxes)
                elif isinstance(child, matplotlib.lines.Line2D):
                    self.draw_line(ax, child, force_trans=ax.transAxes)
                elif isinstance(child, matplotlib.collections.Collection):
                    self.draw_collection(ax, child,
                                         force_pathtrans=ax.transAxes)
                else:
                    warnings.warn("Legend element %s not impemented" % child)
            except NotImplementedError:
                warnings.warn("Legend element %s not impemented" % child)

Response: Recursively look through objects in legend and draw them.


Instruction:
Make a summary of the following Python 3 code
def draw_line(self, ax, line, force_trans=None):
        coordinates, data = self.process_transform(line.get_transform(),
                                                   ax, line.get_xydata(),
                                                   force_trans=force_trans)
        linestyle = utils.get_line_style(line)
        if linestyle['dasharray'] is None:
            linestyle = None
        markerstyle = utils.get_marker_style(line)
        if (markerstyle['marker'] in ['None', 'none', None]
                or markerstyle['markerpath'][0].size == 0):
            markerstyle = None
        label = line.get_label()
        if markerstyle or linestyle:
            self.renderer.draw_marked_line(data=data, coordinates=coordinates,
                                           linestyle=linestyle,
                                           markerstyle=markerstyle,
                                           label=label,
                                           mplobj=line)

Response: Process a matplotlib line and call renderer. draw_line


Instruction:
Here you have a function in Python 3, explain what it does
def draw_text(self, ax, text, force_trans=None, text_type=None):
        content = text.get_text()
        if content:
            transform = text.get_transform()
            position = text.get_position()
            coords, position = self.process_transform(transform, ax,
                                                      position,
                                                      force_trans=force_trans)
            style = utils.get_text_style(text)
            self.renderer.draw_text(text=content, position=position,
                                    coordinates=coords,
                                    text_type=text_type,
                                    style=style, mplobj=text)

Response: Process a matplotlib text object and call renderer. draw_text


Instruction:
Can you create a Python 3 function that
processes a matplotlib patch object and call renderer. draw_path

Response:
def draw_patch(self, ax, patch, force_trans=None):
        """Process a matplotlib patch object and call renderer.draw_path"""
        vertices, pathcodes = utils.SVG_path(patch.get_path())
        transform = patch.get_transform()
        coordinates, vertices = self.process_transform(transform,
                                                       ax, vertices,
                                                       force_trans=force_trans)
        linestyle = utils.get_path_style(patch, fill=patch.get_fill())
        self.renderer.draw_path(data=vertices,
                                coordinates=coordinates,
                                pathcodes=pathcodes,
                                style=linestyle,
                                mplobj=patch)


Instruction:
Here you have a function in Python 3, explain what it does
def draw_collection(self, ax, collection,
                        force_pathtrans=None,
                        force_offsettrans=None):
        """Process a matplotlib collection and call renderer.draw_collection"""
        (transform, transOffset,
         offsets, paths) = collection._prepare_points()

        offset_coords, offsets = self.process_transform(
            transOffset, ax, offsets, force_trans=force_offsettrans)
        path_coords = self.process_transform(
            transform, ax, force_trans=force_pathtrans)

        processed_paths = [utils.SVG_path(path) for path in paths]
        processed_paths = [(self.process_transform(
            transform, ax, path[0], force_trans=force_pathtrans)[1], path[1])
            for path in processed_paths]

        path_transforms = collection.get_transforms()
        try:
            # matplotlib 1.3: path_transforms are transform objects.
            # Convert them to numpy arrays.
            path_transforms = [t.get_matrix() for t in path_transforms]
        except AttributeError:
            # matplotlib 1.4: path transforms are already numpy arrays.
            pass

        styles = {'linewidth': collection.get_linewidths(),
                  'facecolor': collection.get_facecolors(),
                  'edgecolor': collection.get_edgecolors(),
                  'alpha': collection._alpha,
                  'zorder': collection.get_zorder()}

        offset_dict = {"data": "before",
                       "screen": "after"}
        offset_order = offset_dict[collection.get_offset_position()]

        self.renderer.draw_path_collection(paths=processed_paths,
                                           path_coordinates=path_coords,
                                           path_transforms=path_transforms,
                                           offsets=offsets,
                                           offset_coordinates=offset_coords,
                                           offset_order=offset_order,
                                           styles=styles,
                                           mplobj=collection)

Response: Process a matplotlib collection and call renderer. draw_path_collection


Instruction:
Can you generate a brief explanation for the following Python 3 code
def draw_image(self, ax, image):
        self.renderer.draw_image(imdata=utils.image_to_base64(image),
                                 extent=image.get_extent(),
                                 coordinates="data",
                                 style={"alpha": image.get_alpha(),
                                        "zorder": image.get_zorder()},
                                 mplobj=image)

Response: Process a matplotlib image object and call renderer. draw_image


Instruction:
How would you explain what the following Python 3 function does
def draw_marked_line(self, data, coordinates, linestyle, markerstyle,
                         label, mplobj=None):
        """Draw a line that also has markers.

        If this isn't reimplemented by a renderer object, by default, it will
        make a call to BOTH draw_line and draw_markers when both markerstyle
        and linestyle are not None in the same Line2D object.

        """
        if linestyle is not None:
            self.draw_line(data, coordinates, linestyle, label, mplobj)
        if markerstyle is not None:
            self.draw_markers(data, coordinates, markerstyle, label, mplobj)

Response: Draw a line that also has markers.


Instruction:
How would you code a function in Python 3 to
draw a line from the data coordinates and style.

Response:
def draw_line(self, data, coordinates, style, label, mplobj=None):
        """
        Draw a line. By default, draw the line via the draw_path() command.
        Some renderers might wish to override this and provide more
        fine-grained behavior.

        In matplotlib, lines are generally created via the plt.plot() command,
        though this command also can create marker collections.

        Parameters
        ----------
        data : array_like
            A shape (N, 2) array of datapoints.
        coordinates : string
            A string code, which should be either 'data' for data coordinates,
            or 'figure' for figure (pixel) coordinates.
        style : dictionary
            a dictionary specifying the appearance of the line.
        mplobj : matplotlib object
            the matplotlib plot element which generated this line
        """
        pathcodes = ['M'] + (data.shape[0] - 1) * ['L']
        pathstyle = dict(facecolor='none', **style)
        pathstyle['edgecolor'] = pathstyle.pop('color')
        pathstyle['edgewidth'] = pathstyle.pop('linewidth')
        self.draw_path(data=data, coordinates=coordinates,
                       pathcodes=pathcodes, style=pathstyle, mplobj=mplobj)


Instruction:
How would you code a function in Python 3 to
build an iterator over the elements of the path collection

Response:
def _iter_path_collection(paths, path_transforms, offsets, styles):
        """Build an iterator over the elements of the path collection"""
        N = max(len(paths), len(offsets))

        if not path_transforms:
            path_transforms = [np.eye(3)]

        edgecolor = styles['edgecolor']
        if np.size(edgecolor) == 0:
            edgecolor = ['none']
        facecolor = styles['facecolor']
        if np.size(facecolor) == 0:
            facecolor = ['none']

        elements = [paths, path_transforms, offsets,
                    edgecolor, styles['linewidth'], facecolor]

        it = itertools
        return it.islice(py3k.zip(*py3k.map(it.cycle, elements)), N)


Instruction:
Can you implement a function in Python 3 that
draws a collection of paths.

Response:
def draw_path_collection(self, paths, path_coordinates, path_transforms,
                             offsets, offset_coordinates, offset_order,
                             styles, mplobj=None):
        """
        Draw a collection of paths. The paths, offsets, and styles are all
        iterables, and the number of paths is max(len(paths), len(offsets)).

        By default, this is implemented via multiple calls to the draw_path()
        function. For efficiency, Renderers may choose to customize this
        implementation.

        Examples of path collections created by matplotlib are scatter plots,
        histograms, contour plots, and many others.

        Parameters
        ----------
        paths : list
            list of tuples, where each tuple has two elements:
            (data, pathcodes).  See draw_path() for a description of these.
        path_coordinates: string
            the coordinates code for the paths, which should be either
            'data' for data coordinates, or 'figure' for figure (pixel)
            coordinates.
        path_transforms: array_like
            an array of shape (*, 3, 3), giving a series of 2D Affine
            transforms for the paths. These encode translations, rotations,
            and scalings in the standard way.
        offsets: array_like
            An array of offsets of shape (N, 2)
        offset_coordinates : string
            the coordinates code for the offsets, which should be either
            'data' for data coordinates, or 'figure' for figure (pixel)
            coordinates.
        offset_order : string
            either "before" or "after". This specifies whether the offset
            is applied before the path transform, or after.  The matplotlib
            backend equivalent is "before"->"data", "after"->"screen".
        styles: dictionary
            A dictionary in which each value is a list of length N, containing
            the style(s) for the paths.
        mplobj : matplotlib object
            the matplotlib plot element which generated this collection
        """
        if offset_order == "before":
            raise NotImplementedError("offset before transform")

        for tup in self._iter_path_collection(paths, path_transforms,
                                              offsets, styles):
            (path, path_transform, offset, ec, lw, fc) = tup
            vertices, pathcodes = path
            path_transform = transforms.Affine2D(path_transform)
            vertices = path_transform.transform(vertices)
            # This is a hack:
            if path_coordinates == "figure":
                path_coordinates = "points"
            style = {"edgecolor": utils.color_to_hex(ec),
                     "facecolor": utils.color_to_hex(fc),
                     "edgewidth": lw,
                     "dasharray": "10,0",
                     "alpha": styles['alpha'],
                     "zorder": styles['zorder']}
            self.draw_path(data=vertices, coordinates=path_coordinates,
                           pathcodes=pathcodes, style=style, offset=offset,
                           offset_coordinates=offset_coordinates,
                           mplobj=mplobj)


Instruction:
Create a Python 3 function to
draw a set of markers for the current object.

Response:
def draw_markers(self, data, coordinates, style, label, mplobj=None):
        """
        Draw a set of markers. By default, this is done by repeatedly
        calling draw_path(), but renderers should generally overload
        this method to provide a more efficient implementation.

        In matplotlib, markers are created using the plt.plot() command.

        Parameters
        ----------
        data : array_like
            A shape (N, 2) array of datapoints.
        coordinates : string
            A string code, which should be either 'data' for data coordinates,
            or 'figure' for figure (pixel) coordinates.
        style : dictionary
            a dictionary specifying the appearance of the markers.
        mplobj : matplotlib object
            the matplotlib plot element which generated this marker collection
        """
        vertices, pathcodes = style['markerpath']
        pathstyle = dict((key, style[key]) for key in ['alpha', 'edgecolor',
                                                       'facecolor', 'zorder',
                                                       'edgewidth'])
        pathstyle['dasharray'] = "10,0"
        for vertex in data:
            self.draw_path(data=vertices, coordinates="points",
                           pathcodes=pathcodes, style=pathstyle,
                           offset=vertex, offset_coordinates=coordinates,
                           mplobj=mplobj)


Instruction:
Write a Python 3 script to
draw a path from the data coordinates and pathcodes associated with the data.

Response:
def draw_path(self, data, coordinates, pathcodes, style,
                  offset=None, offset_coordinates="data", mplobj=None):
        """
        Draw a path.

        In matplotlib, paths are created by filled regions, histograms,
        contour plots, patches, etc.

        Parameters
        ----------
        data : array_like
            A shape (N, 2) array of datapoints.
        coordinates : string
            A string code, which should be either 'data' for data coordinates,
            'figure' for figure (pixel) coordinates, or "points" for raw
            point coordinates (useful in conjunction with offsets, below).
        pathcodes : list
            A list of single-character SVG pathcodes associated with the data.
            Path codes are one of ['M', 'm', 'L', 'l', 'Q', 'q', 'T', 't',
                                   'S', 's', 'C', 'c', 'Z', 'z']
            See the SVG specification for details.  Note that some path codes
            consume more than one datapoint (while 'Z' consumes none), so
            in general, the length of the pathcodes list will not be the same
            as that of the data array.
        style : dictionary
            a dictionary specifying the appearance of the line.
        offset : list (optional)
            the (x, y) offset of the path. If not given, no offset will
            be used.
        offset_coordinates : string (optional)
            A string code, which should be either 'data' for data coordinates,
            or 'figure' for figure (pixel) coordinates.
        mplobj : matplotlib object
            the matplotlib plot element which generated this path
        """
        raise NotImplementedError()


Instruction:
Implement a function in Python 3 to
create a TimeMOC from an astropy. time. Time object.

Response:
def from_times(cls, times, delta_t=DEFAULT_OBSERVATION_TIME):
        """
        Create a TimeMOC from a `astropy.time.Time`

        Parameters
        ----------
        times : `astropy.time.Time`
            astropy observation times
        delta_t : `astropy.time.TimeDelta`, optional
            the duration of one observation. It is set to 30 min by default. This data is used to compute the
            more efficient TimeMOC order to represent the observations (Best order = the less precise order which
            is able to discriminate two observations separated by ``delta_t``).

        Returns
        -------
        time_moc : `~mocpy.tmoc.TimeMOC`
        """
        times_arr = np.asarray(times.jd * TimeMOC.DAY_MICRO_SEC, dtype=int)
        intervals_arr = np.vstack((times_arr, times_arr + 1)).T

        # degrade the TimeMoc to the order computer from ``delta_t``
        order = TimeMOC.time_resolution_to_order(delta_t)
        return TimeMOC(IntervalSet(intervals_arr)).degrade_to_order(order)


Instruction:
Create a Python 3 function for
creating a TimeMOC from a range defined by two astropy. time. Time objects.

Response:
def from_time_ranges(cls, min_times, max_times, delta_t=DEFAULT_OBSERVATION_TIME):
        """
        Create a TimeMOC from a range defined by two `astropy.time.Time`

        Parameters
        ----------
        min_times : `astropy.time.Time`
            astropy times defining the left part of the intervals
        max_times : `astropy.time.Time`
            astropy times defining the right part of the intervals
        delta_t : `astropy.time.TimeDelta`, optional
            the duration of one observation. It is set to 30 min by default. This data is used to compute the
            more efficient TimeMOC order to represent the observations (Best order = the less precise order which
            is able to discriminate two observations separated by ``delta_t``).

        Returns
        -------
        time_moc : `~mocpy.tmoc.TimeMOC`
        """
        min_times_arr = np.asarray(min_times.jd * TimeMOC.DAY_MICRO_SEC, dtype=int)
        max_times_arr = np.asarray(max_times.jd * TimeMOC.DAY_MICRO_SEC, dtype=int)

        intervals_arr = np.vstack((min_times_arr, max_times_arr + 1)).T

        # degrade the TimeMoc to the order computer from ``delta_t``
        order = TimeMOC.time_resolution_to_order(delta_t)
        return TimeMOC(IntervalSet(intervals_arr)).degrade_to_order(order)


Instruction:
Can you write a function in Python 3 where it
adds all the pixels at max order in the neighbourhood of the moc

Response:
def add_neighbours(self):
        """
        Add all the pixels at max order in the neighbourhood of the moc

        """
        time_delta = 1 << (2*(IntervalSet.HPY_MAX_ORDER - self.max_order))

        intervals_arr = self._interval_set._intervals
        intervals_arr[:, 0] = np.maximum(intervals_arr[:, 0] - time_delta, 0)
        intervals_arr[:, 1] = np.minimum(intervals_arr[:, 1] + time_delta, (1 << 58) - 1)

        self._interval_set = IntervalSet(intervals_arr)


Instruction:
Write a Python 3 script to
remove all the pixels at max order located at the bound of the moc

Response:
def remove_neighbours(self):
        """
        Remove all the pixels at max order located at the bound of the moc

        """
        time_delta = 1 << (2*(IntervalSet.HPY_MAX_ORDER - self.max_order))

        intervals_arr = self._interval_set._intervals
        intervals_arr[:, 0] = np.minimum(intervals_arr[:, 0] + time_delta, (1 << 58) - 1)
        intervals_arr[:, 1] = np.maximum(intervals_arr[:, 1] - time_delta, 0)

        good_intervals = intervals_arr[:, 1] > intervals_arr[:, 0]

        self._interval_set = IntervalSet(intervals_arr[good_intervals])


Instruction:
Write a Python 3 script to
process the degradation of self and another_moc.

Response:
def _process_degradation(self, another_moc, order_op):
        """
        Degrade (down-sampling) self and ``another_moc`` to ``order_op`` order

        Parameters
        ----------
        another_moc : `~mocpy.tmoc.TimeMoc`
        order_op : int
            the order in which self and ``another_moc`` will be down-sampled to.

        Returns
        -------
        result : (`~mocpy.tmoc.TimeMoc`, `~mocpy.tmoc.TimeMoc`)
            self and ``another_moc`` degraded TimeMocs

        """
        max_order = max(self.max_order, another_moc.max_order)
        if order_op > max_order:
            message = 'Requested time resolution for the operation cannot be applied.\n' \
                      'The TimeMoc object resulting from the operation is of time resolution {0} sec.'.format(
                TimeMOC.order_to_time_resolution(max_order).sec)
            warnings.warn(message, UserWarning)

        self_degradation = self.degrade_to_order(order_op)
        another_moc_degradation = another_moc.degrade_to_order(order_op)

        result = self_degradation, another_moc_degradation
        return result


Instruction:
How would you explain what the following Python 3 function does
def intersection(self, another_moc, delta_t=DEFAULT_OBSERVATION_TIME):

        order_op = TimeMOC.time_resolution_to_order(delta_t)

        self_degraded, moc_degraded = self._process_degradation(another_moc, order_op)
        return super(TimeMOC, self_degraded).intersection(moc_degraded)

Response: Intersection between self and another_moc.


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

        if self._interval_set.empty():
            return 0

        total_time_us = 0
        # The interval set is checked for consistency before looping over all the intervals
        for (start_time, stop_time) in self._interval_set._intervals:
            total_time_us = total_time_us + (stop_time - start_time)

        duration = TimeDelta(total_time_us / 1e6, format='sec', scale='tdb')
        return duration

Response: Get the total duration covered by the temporal moc


Instruction:
Here you have a function in Python 3, explain what it does
def consistency(self):

        result = self.total_duration.jd / (self.max_time - self.min_time).jd
        return result

Response: Get the percentage of fill between the min and max time of the moc.


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

        min_time = Time(self._interval_set.min / TimeMOC.DAY_MICRO_SEC, format='jd', scale='tdb')
        return min_time

Response: Returns the minimum time of the tmoc first observation


Instruction:
Implement a Python 3 function for
getting the max time of the tmoc last observation

Response:
def max_time(self):
        """
        Get the `~astropy.time.Time` time of the tmoc last observation

        Returns
        -------
        max_time : `~astropy.time.Time`
            time of the last observation

        """

        max_time = Time(self._interval_set.max / TimeMOC.DAY_MICRO_SEC, format='jd', scale='tdb')
        return max_time


Instruction:
Implement a function in Python 3 to
return a mask array that contains the values of the given times in the object.

Response:
def contains(self, times, keep_inside=True, delta_t=DEFAULT_OBSERVATION_TIME):
        """
        Get a mask array (e.g. a numpy boolean array) of times being inside (or outside) the
        TMOC instance.

        Parameters
        ----------
        times : `astropy.time.Time`
            astropy times to check whether they are contained in the TMOC or not.
        keep_inside : bool, optional
            True by default. If so the filtered table contains only observations that are located the MOC.
            If ``keep_inside`` is False, the filtered table contains all observations lying outside the MOC.
        delta_t : `astropy.time.TimeDelta`, optional
            the duration of one observation. It is set to 30 min by default. This data is used to compute the
            more efficient TimeMOC order to represent the observations (Best order = the less precise order which
            is able to discriminate two observations separated by ``delta_t``).

        Returns
        -------
        array : `~numpy.darray`
            A mask boolean array
        """
        # the requested order for filtering the astropy observations table is more precise than the order
        # of the TimeMoc object
        current_max_order = self.max_order
        new_max_order = TimeMOC.time_resolution_to_order(delta_t)
        if new_max_order > current_max_order:
            message = 'Requested time resolution filtering cannot be applied.\n' \
                      'Filtering is applied with a time resolution of {0} sec.'.format(
                TimeMOC.order_to_time_resolution(current_max_order).sec)
            warnings.warn(message, UserWarning)

        rough_tmoc = self.degrade_to_order(new_max_order)

        pix_arr = (times.jd * TimeMOC.DAY_MICRO_SEC)
        pix_arr = pix_arr.astype(int)

        intervals_arr = rough_tmoc._interval_set._intervals
        inf_arr = np.vstack([pix_arr[i] >= intervals_arr[:, 0] for i in range(pix_arr.shape[0])])
        sup_arr = np.vstack([pix_arr[i] <= intervals_arr[:, 1] for i in range(pix_arr.shape[0])])

        if keep_inside:
            res = inf_arr & sup_arr
            filtered_rows = np.any(res, axis=1)
        else:
            res = ~inf_arr | ~sup_arr
            filtered_rows = np.all(res, axis=1)

        return filtered_rows


Instruction:
Create a Python 3 function to
plot the time of the object in a time window.

Response:
def plot(self, title='TimeMoc', view=(None, None)):
        """
        Plot the TimeMoc in a time window.

        This method uses interactive matplotlib. The user can move its mouse through the plot to see the
        time (at the mouse position).

        Parameters
        ----------
        title : str, optional
            The title of the plot. Set to 'TimeMoc' by default.
        view : (`~astropy.time.Time`, `~astropy.time.Time`), optional
            Define the view window in which the observations are plotted. Set to (None, None) by default (i.e.
            all the observation time window is rendered).

        """
        from matplotlib.colors import LinearSegmentedColormap
        import matplotlib.pyplot as plt

        if self._interval_set.empty():
            print('Nothing to print. This TimeMoc object is empty.')
            return

        plot_order = 15
        if self.max_order > plot_order:
            plotted_moc = self.degrade_to_order(plot_order)
        else:
            plotted_moc = self

        min_jd = plotted_moc.min_time.jd if not view[0] else view[0].jd
        max_jd = plotted_moc.max_time.jd if not view[1] else view[1].jd

        if max_jd < min_jd:
            raise ValueError("Invalid selection: max_jd = {0} must be > to min_jd = {1}".format(max_jd, min_jd))

        fig1 = plt.figure(figsize=(9.5, 5))
        ax = fig1.add_subplot(111)

        ax.set_xlabel('iso')
        ax.get_yaxis().set_visible(False)

        size = 2000
        delta = (max_jd - min_jd) / size
        min_jd_time = min_jd

        ax.set_xticks([0, size])
        ax.set_xticklabels(Time([min_jd_time, max_jd], format='jd', scale='tdb').iso, rotation=70)

        y = np.zeros(size)
        for (s_time_us, e_time_us) in plotted_moc._interval_set._intervals:
            s_index = int((s_time_us / TimeMOC.DAY_MICRO_SEC - min_jd_time) / delta)
            e_index = int((e_time_us / TimeMOC.DAY_MICRO_SEC - min_jd_time) / delta)
            y[s_index:(e_index+1)] = 1.0

        # hack in case of full time mocs.
        if np.all(y):
            y[0] = 0

        z = np.tile(y, (int(size//10), 1))

        plt.title(title)

        color_map = LinearSegmentedColormap.from_list('w2r', ['#fffff0', '#aa0000'])
        color_map.set_under('w')
        color_map.set_bad('gray')

        plt.imshow(z, interpolation='bilinear', cmap=color_map)

        def on_mouse_motion(event):
            for txt in ax.texts:
                txt.set_visible(False)

            text = ax.text(0, 0, "", va="bottom", ha="left")

            time = Time(event.xdata * delta + min_jd_time, format='jd', scale='tdb')

            tx = '{0}'.format(time.iso)
            text.set_position((event.xdata - 50, 700))
            text.set_rotation(70)
            text.set_text(tx)

        cid = fig1.canvas.mpl_connect('motion_notify_event', on_mouse_motion)

        plt.show()


Instruction:
Write a Python 3 function for
handling a new update.

Response:
def handle(self, client, subhooks=()):
        """Handle a new update.

        Fetches new data from the client, then compares it to the previous
        lookup.

        Returns:
            (bool, new_data): whether changes occurred, and the new value.
        """
        new_data = self.fetch(client)

        # Holds the list of updated fields.
        updated = {}

        if not subhooks:
            # We always want to compare to previous values.
            subhooks = [self.name]

        for subhook in subhooks:
            new_key = self.extract_key(new_data, subhook)
            if new_key != self.previous_keys.get(subhook):
                updated[subhook] = new_key

        if updated:
            logger.debug("Hook %s: data changed from %r to %r", self.name, self.previous_keys, updated)
            self.previous_keys.update(updated)
            return (True, new_data)

        return (False, None)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _text_to_vbo(text, font, anchor_x, anchor_y, lowres_size):
    # Necessary to flush commands before requesting current viewport because
    # There may be a set_viewport command waiting in the queue.
    # TODO: would be nicer if each canvas just remembers and manages its own
    # viewport, rather than relying on the context for this.
    canvas = context.get_current_canvas()
    canvas.context.flush_commands()

    text_vtype = np.dtype([('a_position', np.float32, 2),
                           ('a_texcoord', np.float32, 2)])
    vertices = np.zeros(len(text) * 4, dtype=text_vtype)
    prev = None
    width = height = ascender = descender = 0
    ratio, slop = 1. / font.ratio, font.slop
    x_off = -slop
    # Need to make sure we have a unicode string here (Py2.7 mis-interprets
    # characters like "•" otherwise)
    if sys.version[0] == '2' and isinstance(text, str):
        text = text.decode('utf-8')
    # Need to store the original viewport, because the font[char] will
    # trigger SDF rendering, which changes our viewport
    # todo: get rid of call to glGetParameter!
    orig_viewport = canvas.context.get_viewport()
    for ii, char in enumerate(text):
        glyph = font[char]
        kerning = glyph['kerning'].get(prev, 0.) * ratio
        x0 = x_off + glyph['offset'][0] * ratio + kerning
        y0 = glyph['offset'][1] * ratio + slop
        x1 = x0 + glyph['size'][0]
        y1 = y0 - glyph['size'][1]
        u0, v0, u1, v1 = glyph['texcoords']
        position = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]]
        texcoords = [[u0, v0], [u0, v1], [u1, v1], [u1, v0]]
        vi = ii * 4
        vertices['a_position'][vi:vi+4] = position
        vertices['a_texcoord'][vi:vi+4] = texcoords
        x_move = glyph['advance'] * ratio + kerning
        x_off += x_move
        ascender = max(ascender, y0 - slop)
        descender = min(descender, y1 + slop)
        width += x_move
        height = max(height, glyph['size'][1] - 2*slop)
        prev = char
    # Also analyse chars with large ascender and descender, otherwise the
    # vertical alignment can be very inconsistent
    for char in 'hy':
        glyph = font[char]
        y0 = glyph['offset'][1] * ratio + slop
        y1 = y0 - glyph['size'][1]
        ascender = max(ascender, y0 - slop)
        descender = min(descender, y1 + slop)
        height = max(height, glyph['size'][1] - 2*slop)

    if orig_viewport is not None:
        canvas.context.set_viewport(*orig_viewport)

    # Tight bounding box (loose would be width, font.height /.asc / .desc)
    width -= glyph['advance'] * ratio - (glyph['size'][0] - 2*slop)
    dx = dy = 0
    if anchor_y == 'top':
        dy = -ascender
    elif anchor_y in ('center', 'middle'):
        dy = -(height / 2 + descender)
    elif anchor_y == 'bottom':
        dy = -descender
    # Already referenced to baseline
    # elif anchor_y == 'baseline':
    #     dy = -descender
    if anchor_x == 'right':
        dx = -width
    elif anchor_x == 'center':
        dx = -width / 2.
    vertices['a_position'] += (dx, dy)
    vertices['a_position'] /= lowres_size
    return vertices

Response: Convert text to VBO.


Instruction:
Write a Python 3 function for
building and store a glyph corresponding to a single character.

Response:
def _load_char(self, char):
        """Build and store a glyph corresponding to an individual character

        Parameters
        ----------
        char : str
            A single character to be represented.
        """
        assert isinstance(char, string_types) and len(char) == 1
        assert char not in self._glyphs
        # load new glyph data from font
        _load_glyph(self._font, char, self._glyphs)
        # put new glyph into the texture
        glyph = self._glyphs[char]
        bitmap = glyph['bitmap']

        # convert to padded array
        data = np.zeros((bitmap.shape[0] + 2*self._spread,
                         bitmap.shape[1] + 2*self._spread), np.uint8)
        data[self._spread:-self._spread, self._spread:-self._spread] = bitmap

        # Store, while scaling down to proper size
        height = data.shape[0] // self.ratio
        width = data.shape[1] // self.ratio
        region = self._atlas.get_free_region(width + 2, height + 2)
        if region is None:
            raise RuntimeError('Cannot store glyph')
        x, y, w, h = region
        x, y, w, h = x + 1, y + 1, w - 2, h - 2

        self._renderer.render_to_texture(data, self._atlas, (x, y), (w, h))
        u0 = x / float(self._atlas.shape[1])
        v0 = y / float(self._atlas.shape[0])
        u1 = (x+w) / float(self._atlas.shape[1])
        v1 = (y+h) / float(self._atlas.shape[0])
        texcoords = (u0, v0, u1, v1)
        glyph.update(dict(size=(w, h), texcoords=texcoords))


Instruction:
Make a summary of the following Python 3 code
def get_font(self, face, bold=False, italic=False):
        key = '%s-%s-%s' % (face, bold, italic)
        if key not in self._fonts:
            font = dict(face=face, bold=bold, italic=italic)
            self._fonts[key] = TextureFont(font, self._renderer)
        return self._fonts[key]

Response: Get a font described by face and size


Instruction:
Given the following Python 3 function, write the documentation
def stft(x, n_fft=1024, step=512, fs=2*np.pi, window='hann'):
    x = np.asarray(x, float)
    if x.ndim != 1:
        raise ValueError('x must be 1D')
    if window is not None:
        if window not in ('hann',):
            raise ValueError('window must be "hann" or None')
        w = np.hanning(n_fft)
    else:
        w = np.ones(n_fft)
    n_fft = int(n_fft)
    step = max(n_fft // 2, 1) if step is None else int(step)
    fs = float(fs)
    zero_pad = n_fft - len(x)
    if zero_pad > 0:
        x = np.concatenate((x, np.zeros(zero_pad, float)))
    n_freqs = n_fft // 2 + 1
    n_estimates = (len(x) - n_fft) // step + 1
    result = np.empty((n_freqs, n_estimates), np.complex128)
    for ii in range(n_estimates):
        result[:, ii] = np.fft.rfft(w * x[ii * step:ii * step + n_fft]) / n_fft
    return result

Response: Compute the STFT of the data.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def fft_freqs(n_fft, fs):
    return np.arange(0, (n_fft // 2 + 1)) / float(n_fft) * float(fs)

Response: Return the frequency of the DFT in the specified FFT.


Instruction:
How would you implement a function in Python 3 that
sets the data used for this visual.

Response:
def set_data(self, pos=None, color=None, width=None, connect=None,
                 arrows=None):
        """Set the data used for this visual

        Parameters
        ----------
        pos : array
            Array of shape (..., 2) or (..., 3) specifying vertex coordinates.
        color : Color, tuple, or array
            The color to use when drawing the line. If an array is given, it
            must be of shape (..., 4) and provide one rgba color per vertex.
            Can also be a colormap name, or appropriate `Function`.
        width:
            The width of the line in px. Line widths > 1px are only
            guaranteed to work when using 'agg' method.
        connect : str or array
            Determines which vertices are connected by lines.

                * "strip" causes the line to be drawn with each vertex
                  connected to the next.
                * "segments" causes each pair of vertices to draw an
                  independent line segment
                * numpy arrays specify the exact set of segment pairs to
                  connect.
        arrows : array
            A Nx4 matrix where each row contains the x and y coordinate of the
            first and second vertex of the arrow body. Remember that the second
            vertex is used as center point for the arrow head, and the first
            vertex is only used for determining the arrow head orientation.

        """

        if arrows is not None:
            self._arrows = arrows
            self._arrows_changed = True

        LineVisual.set_data(self, pos, color, width, connect)


Instruction:
Can you generate the documentation for the following Python 3 function
def strip_html(text):
    def reply_to(text):
        replying_to = []
        split_text = text.split()
        for index, token in enumerate(split_text):
            if token.startswith('@'): replying_to.append(token[1:])
            else:
                message = split_text[index:]
                break
        rply_msg = ""
        if len(replying_to) > 0:
            rply_msg = "Replying to "
            for token in replying_to[:-1]: rply_msg += token+","
            if len(replying_to)>1: rply_msg += 'and '
            rply_msg += replying_to[-1]+". "
        return rply_msg + " ".join(message)

    text = reply_to(text)
    text = text.replace('@', ' ')
    return " ".join([token for token in text.split()
                     if  ('http:' not in token) and ('https:' not in token)])

Response: Remove ugly twitter html


Instruction:
Can you tell what is the following Python 3 function doing
def make_twitter_request(url, user_id, params={}, request_type='GET'):
    if request_type == "GET":
        return requests.get(url, auth=get_twitter_auth(user_id), params=params)
    elif request_type == "POST":
        return requests.post(url, auth=get_twitter_auth(user_id), params=params)

Response: Generates a request to twitter API using a particular user s authorization


Instruction:
Make a summary of the following Python 3 code
def geo_search(user_id, search_location):
    url = "https://api.twitter.com/1.1/geo/search.json"
    params =  {"query" : search_location }
    response = make_twitter_request(url, user_id, params).json()
    return response

Response: Search for a location - free form


Instruction:
Create a Python 3 function to
read out the tweets from the processed Tweets list.

Response:
def read_out_tweets(processed_tweets, speech_convertor=None):
    """
    Input - list of processed 'Tweets'
    output - list of spoken responses
    """
    return ["tweet number {num} by {user}. {text}.".format(num=index+1, user=user, text=text)
               for index, (user, text) in enumerate(processed_tweets)]


Instruction:
Can you create a Python 3 function that
searches twitter API for tweets about a user.

Response:
def search_for_tweets_about(user_id, params):
    """ Search twitter API """
    url = "https://api.twitter.com/1.1/search/tweets.json"
    response = make_twitter_request(url, user_id, params)
    return process_tweets(response.json()["statuses"])


Instruction:
Implement a Python 3 function for
adding value in form of dict

Response:
def add_val(self, val):
        """add value in form of dict"""
        if not isinstance(val, type({})):
            raise ValueError(type({}))
        self.read()
        self.config.update(val)
        self.save()


Instruction:
How would you code a function in Python 3 to
read a single segment of a mesh from a file.

Response:
def read_mesh(fname):
    """Read mesh data from file.

    Parameters
    ----------
    fname : str
        File name to read. Format will be inferred from the filename.
        Currently only '.obj' and '.obj.gz' are supported.

    Returns
    -------
    vertices : array
        Vertices.
    faces : array | None
        Triangle face definitions.
    normals : array
        Normals for the mesh.
    texcoords : array | None
        Texture coordinates.
    """
    # Check format
    fmt = op.splitext(fname)[1].lower()
    if fmt == '.gz':
        fmt = op.splitext(op.splitext(fname)[0])[1].lower()

    if fmt in ('.obj'):
        return WavefrontReader.read(fname)
    elif not format:
        raise ValueError('read_mesh needs could not determine format.')
    else:
        raise ValueError('read_mesh does not understand format %s.' % fmt)


Instruction:
Create a Python 3 function to
write a mesh to a file.

Response:
def write_mesh(fname, vertices, faces, normals, texcoords, name='',
               format='obj', overwrite=False, reshape_faces=True):
    """ Write mesh data to file.

    Parameters
    ----------
    fname : str
        Filename to write. Must end with ".obj" or ".gz".
    vertices : array
        Vertices.
    faces : array | None
        Triangle face definitions.
    normals : array
        Normals for the mesh.
    texcoords : array | None
        Texture coordinates.
    name : str
        Name of the object.
    format : str
        Currently only "obj" is supported.
    overwrite : bool
        If the file exists, overwrite it.
    reshape_faces : bool
        Reshape the `faces` array to (Nf, 3). Set to `False`
        if you need to write a mesh with non triangular faces.
    """
    # Check file
    if op.isfile(fname) and not overwrite:
        raise IOError('file "%s" exists, use overwrite=True' % fname)

    # Check format
    if format not in ('obj'):
        raise ValueError('Only "obj" format writing currently supported')
    WavefrontWriter.write(fname, vertices, faces,
                          normals, texcoords, name, reshape_faces)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_shaders(self, vert, frag):
        if not vert or not frag:
            raise ValueError('Vertex and fragment code must both be non-empty')

        # pre-process shader code for #include directives
        vert, frag = preprocess(vert), preprocess(frag)

        # Store source code, send it to glir, parse the code for variables
        self._shaders = vert, frag

        self._glir.command('SHADERS', self._id, vert, frag)
        # All current variables become pending variables again
        for key, val in self._user_variables.items():
            self._pending_variables[key] = val
        self._user_variables = {}
        # Parse code (and process pending variables)
        self._parse_variables_from_code()

Response: Set the vertex and fragment shaders.


Instruction:
Can you create a Python 3 function that
parses variables from the source code.

Response:
def _parse_variables_from_code(self):
        """ Parse uniforms, attributes and varyings from the source code.
        """

        # Get one string of code with comments removed
        code = '\n\n'.join(self._shaders)
        code = re.sub(r'(.*)(//.*)', r'\1', code, re.M)

        # Regexp to look for variable names
        var_regexp = ("\s*VARIABLE\s+"  # kind of variable
                      "((highp|mediump|lowp)\s+)?"  # Precision (optional)
                      "(?P<type>\w+)\s+"  # type
                      "(?P<name>\w+)\s*"  # name
                      "(\[(?P<size>\d+)\])?"  # size (optional)
                      "(\s*\=\s*[0-9.]+)?"  # default value (optional)
                      "\s*;"  # end
                      )

        # Parse uniforms, attributes and varyings
        self._code_variables = {}
        for kind in ('uniform', 'attribute', 'varying', 'const'):
            regex = re.compile(var_regexp.replace('VARIABLE', kind),
                               flags=re.MULTILINE)
            for m in re.finditer(regex, code):
                gtype = m.group('type')
                size = int(m.group('size')) if m.group('size') else -1
                this_kind = kind
                if size >= 1:
                    # uniform arrays get added both as individuals and full
                    for i in range(size):
                        name = '%s[%d]' % (m.group('name'), i)
                        self._code_variables[name] = kind, gtype, name, -1
                    this_kind = 'uniform_array'
                name = m.group('name')
                self._code_variables[name] = this_kind, gtype, name, size

        # Now that our code variables are up-to date, we can process
        # the variables that were set but yet unknown.
        self._process_pending_variables()


Instruction:
Can you tell what is the following Python 3 function doing
def bind(self, data):
        # Check
        if not isinstance(data, VertexBuffer):
            raise ValueError('Program.bind() requires a VertexBuffer.')
        # Apply
        for name in data.dtype.names:
            self[name] = data[name]

Response:
Binds a vertex buffer that has structured data

            to the program.


Instruction:
How would you implement a function in Python 3 that
tries to apply the pending variables that were not set but not known yet.

Response:
def _process_pending_variables(self):
        """ Try to apply the variables that were set but not known yet.
        """
        # Clear our list of pending variables
        self._pending_variables, pending = {}, self._pending_variables
        # Try to apply it. On failure, it will be added again
        for name, data in pending.items():
            self[name] = data