Instruction:
How would you code a function in Python 3 to
add the item to the control associating the given data if not None.

Response:
def append(self, a_string, data=None):
        "Adds the item to the control, associating the given data if not None."
        self.wx_obj.Append(a_string, data)
        # reverse association:
        self._items_dict[data] = a_string


Instruction:
Write a Python 3 function for
deleting the item at the zero - based index n from the control.

Response:
def delete(self, a_position):
        "Deletes the item at the zero-based index 'n' from the control."
        self.wx_obj.Delete(a_position)
        data = self.get_data()
        if data in self._items_dict:
            del self._items_dict[data]


Instruction:
Make a summary of the following Python 3 code
def represent(obj, prefix, parent="", indent=0, context=False, max_cols=80):
    "Construct a string representing the object"
    try:
        name = getattr(obj, "name", "")
        class_name = "%s.%s" % (prefix, obj.__class__.__name__)
        padding = len(class_name) + 1 + indent * 4 + (5 if context else 0)
        params = []
        for (k, spec) in sorted(obj._meta.specs.items(), key=get_sort_key):
            if k == "index":        # index is really defined by creation order
                continue            # also, avoid infinite recursion
            if k == "parent" and parent != "":
                v = parent
            else:
                v = getattr(obj, k, "")
                if (not isinstance(spec, InternalSpec)
                    and v != spec.default
                    and (k != 'id' or v > 0)
                    and isinstance(v,
                         (basestring, int, long, float, bool, dict, list,
                          decimal.Decimal,
                          datetime.datetime, datetime.date, datetime.time,
                          Font, Color))
                    and repr(v) != 'None'
                    ):
                    v = repr(v)
                else:
                    v = None
            if v is not None:
                params.append("%s=%s" % (k, v))
        param_lines = []
        line = ""
        for param in params:
            if len(line + param) + 3 > max_cols - padding:
                param_lines.append(line)
                line = ""
            line += param + ", "
        param_lines.append(line)
        param_str = ("\n%s" % (" " * padding)).join(param_lines)
        return "%s(%s)" % (class_name, param_str)
    except:
        raise
        # uninitialized, use standard representation to not break debuggers
        return object.__repr__(obj)

Response: Construct a string representing the object


Instruction:
Can you create a Python 3 function that
finds an object already created

Response:
def get(obj_name, init=False):
    "Find an object already created"
    wx_parent = None
    # check if new_parent is given as string (useful for designer!)
    if isinstance(obj_name, basestring):
        # find the object reference in the already created gui2py objects
        # TODO: only useful for designer, get a better way
        obj_parent = COMPONENTS.get(obj_name)
        if not obj_parent:
            # try to find window (it can be a plain wx frame/control)
            wx_parent = wx.FindWindowByName(obj_name)
            if wx_parent:
                # store gui object (if any)
                obj_parent = getattr(wx_parent, "obj")
            else:
                # fallback using just object name (backward compatibility)
                for obj in COMPONENTS.values():
                    if obj.name==obj_name:
                        obj_parent = obj
    else:
        obj_parent = obj_name     # use the provided parent (as is)
    return obj_parent or wx_parent


Instruction:
Can you implement a function in Python 3 that
recreates ( if needed ) the wx_obj and apply new properties

Response:
def rebuild(self, recreate=True, force=False, **kwargs):
        "Recreate (if needed) the wx_obj and apply new properties"
        # detect if this involves a spec that needs to recreate the wx_obj:
        needs_rebuild = any([isinstance(spec, (StyleSpec, InitSpec))
                             for spec_name, spec in self._meta.specs.items()
                             if spec_name in kwargs])
        # validate if this gui object needs and support recreation
        if needs_rebuild and recreate or force:
            if DEBUG: print "rebuilding window!"
            # recreate the wx_obj! warning: it will call Destroy()
            self.__init__(**kwargs)
        else:
            if DEBUG: print "just setting attr!"
            for name, value in kwargs.items():
                setattr(self, name, value)


Instruction:
Can you tell what is the following Python 3 function doing
def destroy(self):
        "Remove event references and destroy wx object (and children)"
        # unreference the obj from the components map and parent
        if self._name:
            del COMPONENTS[self._get_fully_qualified_name()]
            if DEBUG: print "deleted from components!"
            if isinstance(self._parent, Component):
                del self._parent[self._name]
                if DEBUG: print "deleted from parent!"
        # destroy the wx_obj (only if sure that reference is not needed!)
        if self.wx_obj:
            self.wx_obj.Destroy()
            for child in self:
                print "destroying child",
                child.destroy()
        # destroy the designer selection marker (if any)
        if hasattr(self, 'sel_marker') and self.sel_marker:
            self.sel_marker.destroy()
        if hasattr(self, 'facade') and self.facade:
            self.facade.destroy()

Response: Remove event references and destroy wx object and children


Instruction:
Can you generate a brief explanation for the following Python 3 code
def duplicate(self, new_parent=None):
        "Create a new object exactly similar to self"
        kwargs = {}
        for spec_name, spec in self._meta.specs.items():
            value = getattr(self, spec_name)
            if isinstance(value, Color):
                print "COLOR", value, value.default
                if value.default:
                    value = None
            if value is not None:
                kwargs[spec_name] = value
        del kwargs['parent']
        new_id = wx.NewId()
        kwargs['id'] = new_id
        kwargs['name'] = "%s_%s" % (kwargs['name'], new_id)
        new_obj = self.__class__(new_parent or self.get_parent(), **kwargs)
        # recursively create a copy of each child (in the new parent!)
        for child in self:
            child.duplicate(new_obj)
        return new_obj

Response: Create a new object exactly similar to self


Instruction:
Can you generate a brief explanation for the following Python 3 code
def reindex(self, z=None):
        "Raises/lower the component in the window hierarchy (Z-order/tab order)"
        # z=0: lowers(first index), z=-1: raises (last)
        # actually, only useful in design mode
        if isinstance(self._parent, Component):
            # get the current index (z-order)
            if not self in self._parent._children_list:
                return len(self._parent._children_list)
            i = self._parent._children_list.index(self)
            if z is None:
                return i
            if not hasattr(self, "designer") and not self.designer:
                raise RuntimeError("reindexing can only be done on design mode")
            # delete the element reference from the list
            del self._parent._children_list[i]
            # insert as last element
            if z < 0:
                self._parent._children_list.append(self)
            else:
                self._parent._children_list.insert(z, self)

Response: Raises / lower the component in the window hierarchy ( Z - order / tab order )


Instruction:
Write a Python 3 function for
storing the gui / wx object parent for this component

Response:
def set_parent(self, new_parent, init=False):
        "Store the gui/wx object parent for this component"
        # set init=True if this is called from the constructor
        self._parent = get(new_parent, init)


Instruction:
Make a summary of the following Python 3 code
def _get_parent_name(self):
        "Return parent window name (used in __repr__ parent spec)"
        parent = self.get_parent()
        parent_names = []
        while parent:
            if isinstance(parent, Component):
                parent_name = parent.name
                # Top Level Windows has no parent!
                if parent_name:
                    parent_names.insert(0, parent_name)
                parent = parent.get_parent()
            else:
                break
        if not parent_names:
            return None
        else:
            return '.'.join(parent_names)

Response: Return parent window name ( used in __repr__ parent spec )


Instruction:
Write a Python 3 script to
return full parents name + self name ( useful as key )

Response:
def _get_fully_qualified_name(self):
        "return full parents name + self name (useful as key)"
        parent_name = self._get_parent_name()
        if not parent_name:
            return self._name
        else:
            return "%s.%s" % (parent_name, self._name)


Instruction:
Here you have a function in Python 3, explain what it does
def snapshot(self):
        "Capture the screen appearance of the control (to be used as facade)"
        width, height = self.wx_obj.GetSize()
        bmp = wx.EmptyBitmap(width, height)
        wdc = wx.ClientDC(self.wx_obj)
        mdc = wx.MemoryDC(bmp)
        mdc.Blit(0, 0, width, height, wdc, 0, 0)
        #bmp.SaveFile("test.bmp", wx.BITMAP_TYPE_BMP)
        wdc.Destroy()
        mdc.Destroy()
        return bmp

Response: Capture the screen appearance of the control ( to be used as facade )


Instruction:
Write a Python 3 script to
call when adding a control to the window

Response:
def _sizer_add(self, child):
        "called when adding a control to the window"
        if self.sizer:
            if DEBUG: print "adding to sizer:", child.name
            border = None
            if not border:
                border = child.sizer_border
            flags = child._sizer_flags
            if child.sizer_align:
                flags |= child._sizer_align
            if child.sizer_expand:
                flags |= wx.EXPAND
            if 'grid' in self.sizer:
                self._sizer.Add(child.wx_obj, flag=flags, border=border,
                                pos=(child.sizer_row, child.sizer_col),
                                span=(child.sizer_rowspan, child.sizer_colspan))
            else:
                self._sizer.Add(child.wx_obj, 0, flags, border)


Instruction:
How would you explain what the following Python 3 function does
def set_parent(self, new_parent, init=False):
        "Re-parent a child control with the new wx_obj parent"
        Component.set_parent(self, new_parent, init)
        # if not called from constructor, we must also reparent in wx:
        if not init:
            if DEBUG: print "reparenting", ctrl.name
            if hasattr(self.wx_obj, "Reparent"):
                self.wx_obj.Reparent(self._parent.wx_obj)

Response: Re - parent a child control with the new wx_obj parent


Instruction:
Can you implement a function in Python 3 that
calculates final pos and size ( auto absolute in pixels & relativa

Response:
def _calc_dimension(self, dim_val, dim_max, font_dim):
        "Calculate final pos and size (auto, absolute in pixels & relativa)"
        if dim_val is None:
            return -1   # let wx automatic pos/size
        elif isinstance(dim_val, int):
            return dim_val  # use fixed pixel value (absolute)
        elif isinstance(dim_val, basestring):
            if dim_val.endswith("%"):
                # percentaje, relative to parent max size:
                dim_val = int(dim_val[:-1])
                dim_val = dim_val / 100.0 * dim_max
            elif dim_val.endswith("em"):
                # use current font size (suport fractions):
                dim_val = float(dim_val[:-2])
                dim_val = dim_val * font_dim
            elif dim_val.endswith("px"):
                # fixed pixels
                dim_val = dim_val[:-2]
            elif dim_val == "" or dim_val == "auto":
                dim_val = -1
            return int(dim_val)


Instruction:
Here you have a function in Python 3, explain what it does
def __tile_background(self, dc):
        "make several copies of the background bitmap"
        sz = self.wx_obj.GetClientSize()
        bmp = self._bitmap.get_bits()
        w = bmp.GetWidth()
        h = bmp.GetHeight()

        if isinstance(self, wx.ScrolledWindow):
            # adjust for scrolled position
            spx, spy = self.wx_obj.GetScrollPixelsPerUnit()
            vsx, vsy = self.wx_obj.GetViewStart()
            dx,  dy  = (spx * vsx) % w, (spy * vsy) % h
        else:
            dx, dy = (w, h)

        x = -dx
        while x < sz.width:
            y = -dy
            while y < sz.height:
                dc.DrawBitmap(bmp, x, y)
                y = y + h
            x = x + w

Response: make several copies of the background bitmap


Instruction:
Write a Python 3 function that can
draw the image as background

Response:
def __on_erase_background(self, evt):
        "Draw the image as background"
        if self._bitmap:
            dc = evt.GetDC()

            if not dc:
                dc = wx.ClientDC(self)
                r = self.wx_obj.GetUpdateRegion().GetBox()
                dc.SetClippingRegion(r.x, r.y, r.width, r.height)

            if self._background_tiling:
                self.__tile_background(dc)
            else:
                dc.DrawBitmapPoint(self._bitmap.get_bits(), (0, 0))


Instruction:
Here you have a function in Python 3, explain what it does
def set_parent(self, new_parent, init=False):
        "Associate the component to the control (it could be recreated)"
        # store gui reference inside of wx object (this will enable rebuild...)
        self._parent = get(new_parent, init=False)    # store new parent
        if init:
            self._parent[self._name] = self

Response: Associate the component to the control ( it could be recreated


Instruction:
Can you tell what is the following Python 3 function doing
def rebuild(self, **kwargs):
        "Update a property value with (used by the designer)"
        for name, value in kwargs.items():
            setattr(self, name, value)

Response: Update a property value with ( used by the designer )


Instruction:
How would you explain what the following Python 3 function does
def __on_paint(self, event):
        "Custom draws the label when transparent background is needed"
        # use a Device Context that supports anti-aliased drawing
        # and semi-transparent colours on all platforms
        dc = wx.GCDC(wx.PaintDC(self.wx_obj))
        dc.SetFont(self.wx_obj.GetFont())
        dc.SetTextForeground(self.wx_obj.GetForegroundColour())
        dc.DrawText(self.wx_obj.GetLabel(), 0, 0)

Response: Custom draws the label when transparent background is needed


Instruction:
Can you generate the documentation for the following Python 3 function
def find_modules(rootpath, skip):

    INITPY = '__init__.py'

    rootpath = os.path.normpath(os.path.abspath(rootpath))
    if INITPY in os.listdir(rootpath):
        root_package = rootpath.split(os.path.sep)[-1]
        print "Searching modules in", rootpath
    else:
        print "No modules in", rootpath
        return

    def makename(package, module):
        """Join package and module with a dot."""
        if package:
            name = package
            if module:
                name += '.' + module
        else:
            name = module
        return name

    skipall = []
    for m in skip.keys():
        if skip[m] is None: skipall.append(m)

    tree = {}
    saved = 0
    found = 0
    def save(module, submodule):
        name = module+ "."+ submodule

        for s in skipall:
            if name.startswith(s):
                print "Skipping "+name
                return False
        if skip.has_key(module):
            if submodule in skip[module]:
                print "Skipping "+name
                return False
        if not tree.has_key(module):
            tree[module] = []
        tree[module].append(submodule)
        return True

    for root, subs, files in os.walk(rootpath):
        py_files = sorted([f for f in files if os.path.splitext(f)[1] == '.py'])

        if INITPY in py_files:
            subpackage = root[len(rootpath):].lstrip(os.path.sep).\
                replace(os.path.sep, '.')
            full = makename(root_package, subpackage)
            part = full.rpartition('.')
            base_package, submodule = part[0], part[2]
            found += 1
            if save(base_package, submodule): saved += 1

            py_files.remove(INITPY)
            for py_file in py_files:
                found += 1
                module = os.path.splitext(py_file)[0]
                if save(full, module): saved += 1
    for item in tree.keys():
        tree[item].sort()
    print "%s contains %i submodules, %i skipped" % \
          (root_package, found, found-saved)

    return tree

Response: Find all modules in a directory and return a dict of the names of the modules that are found.


Instruction:
How would you code a function in Python 3 to
return a list of children sub - components that are column headings

Response:
def _get_column_headings(self):
        "Return a list of children sub-components that are column headings"
        # return it in the same order as inserted in the Grid
        headers = [ctrl for ctrl in self if isinstance(ctrl, GridColumn)]
        return sorted(headers, key=lambda ch: ch.index)


Instruction:
How would you explain what the following Python 3 function does
def _set_row_label(self, value):
        "Set the row label format string (empty to hide)"
        if not value:
            self.wx_obj.SetRowLabelSize(0)
        else:
            self.wx_obj._table._row_label = value

Response: Set the row label format string ( empty to hide )


Instruction:
Can you tell what is the following Python 3 function doing
def ResetView(self, grid):
        "Update the grid if rows and columns have been added or deleted"
        grid.BeginBatch()

        for current, new, delmsg, addmsg in [
            (self._rows, self.GetNumberRows(),
             gridlib.GRIDTABLE_NOTIFY_ROWS_DELETED,
             gridlib.GRIDTABLE_NOTIFY_ROWS_APPENDED),
            (self._cols, self.GetNumberCols(),
             gridlib.GRIDTABLE_NOTIFY_COLS_DELETED,
             gridlib.GRIDTABLE_NOTIFY_COLS_APPENDED),
        ]:

            if new < current:
                msg = gridlib.GridTableMessage(self,delmsg,new,current-new)
                grid.ProcessTableMessage(msg)
            elif new > current:
                msg = gridlib.GridTableMessage(self,addmsg,new-current)
                grid.ProcessTableMessage(msg)
                self.UpdateValues(grid)

        grid.EndBatch()

        self._rows = self.GetNumberRows()
        self._cols = self.GetNumberCols()
        # update the column rendering plugins
        self._updateColAttrs(grid)

        # update the scrollbars and the displayed part of the grid
        grid.AdjustScrollbars()
        grid.ForceRefresh()

Response: Update the grid if rows and columns have been added or deleted


Instruction:
Implement a Python 3 function for
updating all displayed values

Response:
def UpdateValues(self, grid):
        "Update all displayed values"
        # This sends an event to the grid table to update all of the values
        msg = gridlib.GridTableMessage(self,
                                    gridlib.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
        grid.ProcessTableMessage(msg)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _updateColAttrs(self, grid):
        "update the column attributes to add the appropriate renderer"
        col = 0

        for column in self.columns:
            attr = gridlib.GridCellAttr()
            if False:  # column.readonly
                attr.SetReadOnly()
            if False:  # column.renderer
                attr.SetRenderer(renderer)
            grid.SetColSize(col, column.width)
            grid.SetColAttr(col, attr)
            col += 1

Response: update the column attributes to add the appropriate renderer


Instruction:
Given the following Python 3 function, write the documentation
def set_parent(self, new_parent, init=False):
        "Associate the header to the control (it could be recreated)"
        self._created = False
        SubComponent.set_parent(self, new_parent, init)
        # if index not given, append the column at the last position:
        if self.index == -1 or self.index >= len(self._parent.columns):
            self.index = len(self._parent.columns) - 1
        # insert the column in the listview:
        self._parent.wx_obj.AppendCols(1)
        #self._parent.wx_obj.SetColLabelValue(self.index, self.text)
        #self.SetColLabel(self.index, self.align)
        #self._parent.wx_obj.SetColSize(self.index, self.width)
        self._created = True

Response: Associate the header to the control ( it could be recreated )


Instruction:
Given the following Python 3 function, write the documentation
def insert(self, pos, values):
        "Insert a number of rows into the grid (and associated table)"
        if isinstance(values, dict):
            row = GridRow(self, **values)
        else:
            row = GridRow(self, *values)
        list.insert(self, pos, row)
        self._grid_view.wx_obj.InsertRows(pos, numRows=1)

Response: Insert a number of rows into the grid ( and associated table )


Instruction:
How would you explain what the following Python 3 function does
def append(self, values):
        "Insert a number of rows into the grid (and associated table)"
        if isinstance(values, dict):
            row = GridRow(self, **values)
        else:
            row = GridRow(self, *values)
        list.append(self, row)
        self._grid_view.wx_obj.AppendRows(numRows=1)

Response: Insert a number of rows into the grid ( and associated table )


Instruction:
Given the following Python 3 function, write the documentation
def clear(self):
        "Remove all rows and reset internal structures"
        ## list has no clear ... remove items in reverse order
        for i in range(len(self)-1, -1, -1):
            del self[i]
        self._key = 0
        if hasattr(self._grid_view, "wx_obj"):
            self._grid_view.wx_obj.ClearGrid()

Response: Remove all rows and reset internal structures


Instruction:
Write a Python 3 function that can
call to create the control which must derive from wxControl. wxComboBox. wxSize

Response:
def Create(self, parent, id, evtHandler):
        "Called to create the control, which must derive from wxControl."
        self._tc = wx.ComboBox(parent, id, "", (100, 50))
        self.SetControl(self._tc)
        # pushing a different event handler instead evtHandler:
        self._tc.PushEventHandler(wx.EvtHandler())
        self._tc.Bind(wx.EVT_COMBOBOX, self.OnChange)


Instruction:
Here you have a function in Python 3, explain what it does
def SetSize(self, rect):
        "Called to position/size the edit control within the cell rectangle."
        self._tc.SetDimensions(rect.x, rect.y, rect.width+2, rect.height+2,
                               wx.SIZE_ALLOW_MINUS_ONE)

Response: Called to position / size the edit control within the cell rectangle.


Instruction:
Can you write a function in Python 3 where it
fetches the value from the table and prepare the edit control

Response:
def BeginEdit(self, row, col, grid):
        "Fetch the value from the table and prepare the edit control"
        self.startValue = grid.GetTable().GetValue(row, col)
        choices = grid.GetTable().columns[col]._choices
        self._tc.Clear()
        self._tc.AppendItems(choices)
        self._tc.SetStringSelection(self.startValue)
        self._tc.SetFocus()


Instruction:
Make a summary of the following Python 3 code
def EndEdit(self, row, col, grid, val=None):
        "Complete the editing of the current cell. Returns True if changed"
        changed = False
        val = self._tc.GetStringSelection()
        print "val", val, row, col, self.startValue
        if val != self.startValue:
            changed = True
            grid.GetTable().SetValue(row, col, val) # update the table
        self.startValue = ''
        self._tc.SetStringSelection('')
        return changed

Response: Complete the editing of the current cell. Returns True if changed


Instruction:
Create a Python 3 function for
returning True to allow the given key to start editing

Response:
def IsAcceptedKey(self, evt):
        "Return True to allow the given key to start editing"
        ## Oops, there's a bug here, we'll have to do it ourself..
        ##return self.base_IsAcceptedKey(evt)
        return (not (evt.ControlDown() or evt.AltDown()) and
                evt.GetKeyCode() != wx.WXK_SHIFT)


Instruction:
How would you explain what the following Python 3 function does
def StartingKey(self, evt):
        "This will be called to let the editor do something with the first key"
        key = evt.GetKeyCode()
        ch = None
        if key in [wx.WXK_NUMPAD0, wx.WXK_NUMPAD1, wx.WXK_NUMPAD2, wx.WXK_NUMPAD3, wx.WXK_NUMPAD4,
                   wx.WXK_NUMPAD5, wx.WXK_NUMPAD6, wx.WXK_NUMPAD7, wx.WXK_NUMPAD8, wx.WXK_NUMPAD9]:
            ch = ch = chr(ord('0') + key - wx.WXK_NUMPAD0)
        elif key < 256 and key >= 0 and chr(key) in string.printable:
            ch = chr(key)
            if not evt.ShiftDown():
                ch = ch.lower()
        if ch is not None:
            self._tc.SetStringSelection(ch)
        else:
            evt.Skip()

Response: This will be called to let the editor do something with the first key


Instruction:
Can you implement a function in Python 3 that
enables or disable all menu items

Response:
def Enable(self, value):
        "enable or disable all menu items"
        for i in range(self.GetMenuItemCount()):
            it = self.FindItemByPosition(i)
            it.Enable(value)


Instruction:
How would you explain what the following Python 3 function does
def IsEnabled(self, *args, **kwargs):
        "check if all menu items are enabled"
        for i in range(self.GetMenuItemCount()):
            it = self.FindItemByPosition(i)
            if not it.IsEnabled():
                return False
        return True

Response: check if all menu items are enabled


Instruction:
Explain what the following Python 3 code does
def find(self, item_id=None):
        "Recursively find a menu item by its id (useful for event handlers)"
        for it in self:
            if it.id == item_id:
                return it
            elif isinstance(it, Menu):
                found = it.find(item_id)
                if found:
                    return found

Response: Recursively find a menu item by its id ( useful for event handlers )


Instruction:
Can you generate the documentation for the following Python 3 function
def Enable(self, value):
        "enable or disable all top menus"
        for i in range(self.GetMenuCount()):
            self.EnableTop(i, value)

Response: enable or disable all top menus


Instruction:
How would you explain what the following Python 3 function does
def IsEnabled(self, *args, **kwargs):
        "check if all top menus are enabled"
        for i in range(self.GetMenuCount()):
            if not self.IsEnabledTop(i):
                return False
        return True

Response: check if all top menus are enabled


Instruction:
Here you have a function in Python 3, explain what it does
def RemoveItem(self, menu):
        "Helper method to remove a menu avoiding using its position"
        menus = self.GetMenus()     # get the list of (menu, title)
        menus = [submenu for submenu in menus if submenu[0] != menu]
        self.SetMenus(menus)

Response: Helper method to remove a menu avoiding using its position


Instruction:
Can you generate a brief explanation for the following Python 3 code
def build_data_set(self):
        "Construct a sequence of name/value pairs from controls"
        data = {}
        for field in self.fields:
            if field.name:# and field.enabled: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                val = field.get_value()
                if val is None:
                    continue
                elif isinstance(val, unicode):
                    # web2py string processing
                    # requires utf-8 encoded text
                    val = val.encode("utf-8")
                data[field.name] = val
        return data

Response: Construct a sequence of name / value pairs from controls


Instruction:
Can you tell what is the following Python 3 function doing
def setObjectTag(self, object, tag):
        object._attributes = {}
        object._name = tag.GetName().lower()
        for name in self.attributes:
            object._attributes["_%s" % name] = tag.GetParam(name)
            if object._attributes["_%s" % name] == "":
                object._attributes["_%s" % name] = None

Response: Add a tag attribute to the wx object


Instruction:
Write a Python 3 function for
inserting items described in autosummary:: to the TOC tree but not generate the TOC tree.

Response:
def process_autosummary_toc(app, doctree):
    """Insert items described in autosummary:: to the TOC tree, but do
    not generate the toctree:: list.
    """
    env = app.builder.env
    crawled = {}
    def crawl_toc(node, depth=1):
        crawled[node] = True
        for j, subnode in enumerate(node):
            try:
                if (isinstance(subnode, autosummary_toc)
                    and isinstance(subnode[0], addnodes.toctree)):
                    env.note_toctree(env.docname, subnode[0])
                    continue
            except IndexError:
                continue
            if not isinstance(subnode, nodes.section):
                continue
            if subnode not in crawled:
                crawl_toc(subnode, depth+1)
    crawl_toc(doctree)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def autosummary_table_visit_html(self, node):
    try:
        tbody = node[0][0][-1]
        for row in tbody:
            col1_entry = row[0]
            par = col1_entry[0]
            for j, subnode in enumerate(list(par)):
                if isinstance(subnode, nodes.Text):
                    new_text = unicode(subnode.astext())
                    new_text = new_text.replace(u" ", u"\u00a0")
                    par[j] = nodes.Text(new_text)
    except IndexError:
        pass

Response: Make the first column of the table non - breakinging.


Instruction:
Write a Python 3 function for
getting an autodoc. Documenter class suitable for documenting the given obj and parent.

Response:
def get_documenter(obj, parent):
    """Get an autodoc.Documenter class suitable for documenting the given
    object.

    *obj* is the Python object to be documented, and *parent* is an
    another Python object (e.g. a module or a class) to which *obj*
    belongs to.
    """
    from sphinx.ext.autodoc import AutoDirective, DataDocumenter, \
         ModuleDocumenter

    if inspect.ismodule(obj):
        # ModuleDocumenter.can_document_member always returns False
        return ModuleDocumenter

    # Construct a fake documenter for *parent*
    if parent is not None:
        parent_doc_cls = get_documenter(parent, None)
    else:
        parent_doc_cls = ModuleDocumenter

    if hasattr(parent, '__name__'):
        parent_doc = parent_doc_cls(FakeDirective(), parent.__name__)
    else:
        parent_doc = parent_doc_cls(FakeDirective(), "")

    # Get the corrent documenter class for *obj*
    classes = [cls for cls in AutoDirective._registry.values()
               if cls.can_document_member(obj, '', False, parent_doc)]
    if classes:
        classes.sort(key=lambda cls: cls.priority)
        return classes[-1]
    else:
        return DataDocumenter


Instruction:
Explain what the following Python 3 code does
def mangle_signature(sig, max_chars=30):
    s = re.sub(r"^\((.*)\)$", r"\1", sig).strip()

    # Strip strings (which can contain things that confuse the code below)
    s = re.sub(r"\\\\", "", s)
    s = re.sub(r"\\'", "", s)
    s = re.sub(r"'[^']*'", "", s)

    # Parse the signature to arguments + options
    args = []
    opts = []

    opt_re = re.compile(r"^(.*, |)([a-zA-Z0-9_*]+)=")
    while s:
        m = opt_re.search(s)
        if not m:
            # The rest are arguments
            args = s.split(', ')
            break

        opts.insert(0, m.group(2))
        s = m.group(1)[:-2]

    # Produce a more compact signature
    sig = limited_join(", ", args, max_chars=max_chars-2)
    if opts:
        if not sig:
            sig = "[%s]" % limited_join(", ", opts, max_chars=max_chars-4)
        elif len(sig) < max_chars - 4 - 2 - 3:
            sig += "[, %s]" % limited_join(", ", opts,
                                           max_chars=max_chars-len(sig)-4-2)

    return u"(%s)" % sig

Response: Reformat a function signature to a more compact form.


Instruction:
Can you tell what is the following Python 3 function doing
def limited_join(sep, items, max_chars=30, overflow_marker="..."):
    full_str = sep.join(items)
    if len(full_str) < max_chars:
        return full_str

    n_chars = 0
    n_items = 0
    for j, item in enumerate(items):
        n_chars += len(item) + len(sep)
        if n_chars < max_chars - len(overflow_marker):
            n_items += 1
        else:
            break

    return sep.join(list(items[:n_items]) + [overflow_marker])

Response: Join a number of strings to one limiting the length to max_chars.


Instruction:
Make a summary of the following Python 3 code
def get_import_prefixes_from_env(env):
    prefixes = [None]

    currmodule = env.temp_data.get('py:module')
    if currmodule:
        prefixes.insert(0, currmodule)

    currclass = env.temp_data.get('py:class')
    if currclass:
        if currmodule:
            prefixes.insert(0, currmodule + "." + currclass)
        else:
            prefixes.insert(0, currclass)

    return prefixes

Response: Obtain current Python import prefixes from env.


Instruction:
How would you explain what the following Python 3 function does
def import_by_name(name, prefixes=[None]):
    tried = []
    for prefix in prefixes:
        try:
            if prefix:
                prefixed_name = '.'.join([prefix, name])
            else:
                prefixed_name = name
            obj, parent = _import_by_name(prefixed_name)
            return prefixed_name, obj, parent
        except ImportError:
            tried.append(prefixed_name)
    raise ImportError('no module named %s' % ' or '.join(tried))

Response: Import a Python object that has the given name under one of the given prefixes.


Instruction:
Explain what the following Python 3 code does
def _import_by_name(name):
    try:
        name_parts = name.split('.')

        # try first interpret `name` as MODNAME.OBJ
        modname = '.'.join(name_parts[:-1])
        if modname:
            try:
                __import__(modname)
                mod = sys.modules[modname]
                return getattr(mod, name_parts[-1]), mod
            except (ImportError, IndexError, AttributeError):
                pass

        # ... then as MODNAME, MODNAME.OBJ1, MODNAME.OBJ1.OBJ2, ...
        last_j = 0
        modname = None
        for j in reversed(range(1, len(name_parts)+1)):
            last_j = j
            modname = '.'.join(name_parts[:j])
            try:
                __import__(modname)
            except:# ImportError:
                continue
            if modname in sys.modules:
                break

        if last_j < len(name_parts):
            parent = None
            obj = sys.modules[modname]
            for obj_name in name_parts[last_j:]:
                parent = obj
                obj = getattr(obj, obj_name)
            return obj, parent
        else:
            return sys.modules[modname], None
    except (ValueError, ImportError, AttributeError, KeyError), e:
        raise ImportError(*e.args)

Response: Import a Python object given its full name.


Instruction:
Create a Python 3 function to
smart linking role. Expands to ':obj:`text`' if `text` is an object that can be imported; otherwise expands to '*text*'.

Response:
def autolink_role(typ, rawtext, etext, lineno, inliner,
                  options={}, content=[]):
    """Smart linking role.

    Expands to ':obj:`text`' if `text` is an object that can be imported;
    otherwise expands to '*text*'.
    """
    env = inliner.document.settings.env
    r = env.get_domain('py').role('obj')(
        'obj', rawtext, etext, lineno, inliner, options, content)
    pnode = r[0][0]

    prefixes = get_import_prefixes_from_env(env)
    try:
        name, obj, parent = import_by_name(pnode['reftarget'], prefixes)
    except ImportError:
        content = pnode[0]
        r[0][0] = nodes.emphasis(rawtext, content[0].astext(),
                                 classes=content['classes'])
    return r


Instruction:
Make a summary of the following Python 3 code
def get_items(self, names):
        env = self.state.document.settings.env

        prefixes = get_import_prefixes_from_env(env)

        items = []

        max_item_chars = 50

        for name in names:
            display_name = name
            if name.startswith('~'):
                name = name[1:]
                display_name = name.split('.')[-1]

            try:
                real_name, obj, parent = import_by_name(name, prefixes=prefixes)
            except ImportError:
                self.warn('failed to import %s' % name)
                items.append((name, '', '', name))
                continue

            # NB. using real_name here is important, since Documenters
            #     handle module prefixes slightly differently
            documenter = get_documenter(obj, parent)(self, real_name)
            if not documenter.parse_name():
                self.warn('failed to parse name %s' % real_name)
                items.append((display_name, '', '', real_name))
                continue
            if not documenter.import_object():
                self.warn('failed to import object %s' % real_name)
                items.append((display_name, '', '', real_name))
                continue

            # -- Grab the signature

            sig = documenter.format_signature()
            if not sig:
                sig = ''
            else:
                max_chars = max(10, max_item_chars - len(display_name))
                sig = mangle_signature(sig, max_chars=max_chars)
                sig = sig.replace('*', r'\*')

            # -- Grab the summary

            doc = list(documenter.process_doc(documenter.get_doc()))

            while doc and not doc[0].strip():
                doc.pop(0)
            m = re.search(r"^([A-Z][^A-Z]*?\.\s)", " ".join(doc).strip())
            if m:
                summary = m.group(1).strip()
            elif doc:
                summary = doc[0].strip()
            else:
                summary = ''

            items.append((display_name, sig, summary, real_name))

        return items

Response: Try to import the given names and return a list of tuples of names signature summary_string real_name.


Instruction:
Can you implement a function in Python 3 that
generates a proper list of table nodes for autosummary:: directive.

Response:
def get_table(self, items):
        """Generate a proper list of table nodes for autosummary:: directive.

        *items* is a list produced by :meth:`get_items`.
        """
        table_spec = addnodes.tabular_col_spec()
        table_spec['spec'] = 'll'

        table = autosummary_table('')
        real_table = nodes.table('', classes=['longtable'])
        table.append(real_table)
        group = nodes.tgroup('', cols=2)
        real_table.append(group)
        group.append(nodes.colspec('', colwidth=10))
        group.append(nodes.colspec('', colwidth=90))
        body = nodes.tbody('')
        group.append(body)

        def append_row(*column_texts):
            row = nodes.row('')
            for text in column_texts:
                node = nodes.paragraph('')
                vl = ViewList()
                vl.append(text, '<autosummary>')
                self.state.nested_parse(vl, 0, node)
                try:
                    if isinstance(node[0], nodes.paragraph):
                        node = node[0]
                except IndexError:
                    pass
                row.append(nodes.entry('', node))
            body.append(row)

        for name, sig, summary, real_name in items:
            qualifier = 'obj'
            if 'nosignatures' not in self.options:
                col1 = ':%s:`%s <%s>`\ %s' % (qualifier, name, real_name, sig)
            else:
                col1 = ':%s:`%s <%s>`' % (qualifier, name, real_name)
            col2 = summary
            append_row(col1, col2)

        return [table_spec, table]


Instruction:
Write a Python 3 script to
show a simple pop - up modal dialog

Response:
def alert(message, title="", parent=None, scrolled=False, icon="exclamation"):
    "Show a simple pop-up modal dialog"
    if not scrolled:
        icons = {'exclamation': wx.ICON_EXCLAMATION, 'error': wx.ICON_ERROR,
             'question': wx.ICON_QUESTION, 'info': wx.ICON_INFORMATION}
        style = wx.OK | icons[icon]
        result = dialogs.messageDialog(parent, message, title, style)
    else:
        result = dialogs.scrolledMessageDialog(parent, message, title)


Instruction:
Here you have a function in Python 3, explain what it does
def confirm(message="", title="", default=False, ok=False, cancel=False,
            parent=None):
    "Ask for confirmation (yes/no or ok and cancel), returns True or False"
    style = wx.CENTRE
    if ok:
        style |= wx.OK
    else:
        style |= wx.YES | wx.NO
        if default:
            style |= wx.YES_DEFAULT
        else:
            style |= wx.NO_DEFAULT
    if cancel:
        style |= wx.CANCEL
    result = dialogs.messageDialog(parent, message, title, style)
    if cancel and result.returned == wx.ID_CANCEL:
        return None
    return result.accepted

Response: Ask for confirmation ( yes / no or ok and cancel returns True or False


Instruction:
Make a summary of the following Python 3 code
def select_font(message="", title="", font=None, parent=None):
    "Show a dialog to select a font"
    if font is not None:
        wx_font = font._get_wx_font()                   # use as default
    else:
        wx_font = None
        font = Font()                                   # create an empty font
    result = dialogs.fontDialog(parent, font=wx_font)
    if result.accepted:
        font_data = result.fontData
        result.color = result.fontData.GetColour().Get()
        wx_font = result.fontData.GetChosenFont()
        font.set_wx_font(wx_font)
        wx_font = None
        return font

Response: Show a dialog to select a font


Instruction:
Can you implement a function in Python 3 that
shows a dialog to pick a color

Response:
def select_color(message="", title="", color=None, parent=None):
    "Show a dialog to pick a color"
    result = dialogs.colorDialog(parent, color=color)
    return result.accepted and result.color


Instruction:
Make a summary of the following Python 3 code
def open_file(title="Open",  directory='', filename='',
              wildcard='All Files (*.*)|*.*', multiple=False, parent=None):
    "Show a dialog to select files to open, return path(s) if accepted"
    style = wx.OPEN
    if multiple:
        style |= wx.MULTIPLE
    result = dialogs.fileDialog(parent, title, directory, filename, wildcard,
                                style)
    if result.paths and not multiple:
        return result.paths[0]
    else:
        return result.paths

Response: Show a dialog to select files to open return path(s ) if accepted


Instruction:
Can you generate a brief explanation for the following Python 3 code
def save_file(title="Save",  directory='', filename='',
              wildcard='All Files (*.*)|*.*', overwrite=False, parent=None):
    "Show a dialog to select file to save, return path(s) if accepted"
    style = wx.SAVE
    if not overwrite:
        style |= wx.OVERWRITE_PROMPT
    result = dialogs.fileDialog(parent, title, directory, filename, wildcard,
                                style)
    return result.paths

Response: Show a dialog to select file to save return path(s ) if accepted


Instruction:
Here you have a function in Python 3, explain what it does
def choose_directory(message='Choose a directory', path="", parent=None):
    "Show a dialog to choose a directory"
    result = dialogs.directoryDialog(parent, message, path)
    return result.path

Response: Show a dialog to choose a directory


Instruction:
Make a summary of the following Python 3 code
def find(default='', whole_words=0, case_sensitive=0, parent=None):
    "Shows a find text dialog"
    result = dialogs.findDialog(parent, default, whole_words, case_sensitive)
    return {'text': result.searchText, 'whole_words': result.wholeWordsOnly,
            'case_sensitive': result.caseSensitive}

Response: Shows a find text dialog


Instruction:
Can you tell what is the following Python 3 function doing
def clear(self):
        "Remove all items and reset internal structures"
        dict.clear(self)
        self._key = 0
        if hasattr(self._tree_view, "wx_obj"):
            self._tree_view.wx_obj.DeleteAllItems()

Response: Remove all items and reset internal structures


Instruction:
Make a summary of the following Python 3 code
def set_has_children(self, has_children=True):
        "Force appearance of the button next to the item"
        # This is useful to allow the user to expand the items which don't have
        # any children now, but instead adding them only when needed, thus
        # minimizing memory usage and loading time.
        self._tree_model._tree_view.wx_obj.SetItemHasChildren(self.wx_item,
                                                              has_children)

Response: Force appearance of the button next to the item


Instruction:
How would you implement a function in Python 3 that
returns the type of an image from the file extension

Response:
def bitmap_type(filename):
    """
    Get the type of an image from the file's extension ( .jpg, etc. )
    """

    if filename == '':
        return None

    name, ext = os.path.splitext(filename)
    ext = ext[1:].upper()
    if ext == 'BMP':
        return wx.BITMAP_TYPE_BMP
    elif ext == 'GIF':
        return wx.BITMAP_TYPE_GIF
    elif ext == 'JPG' or ext == 'JPEG':
        return wx.BITMAP_TYPE_JPEG
    elif ext == 'PCX':
        return wx.BITMAP_TYPE_PCX
    elif ext == 'PICT':
        return wx.BITMAP_TYPE_PICT
    elif ext == 'PNG':
        return wx.BITMAP_TYPE_PNG
    elif ext == 'PNM':
        return wx.BITMAP_TYPE_PNM
    elif ext == 'TIF' or ext == 'TIFF':
        return wx.BITMAP_TYPE_TIF
    elif ext == 'XBM':
        return wx.BITMAP_TYPE_XBM
    elif ext == 'XPM':
        return wx.BITMAP_TYPE_XPM
    else:
        # KEA 2001-10-10
        # rather than throw an exception, we could try and have wxPython figure out the image
        # type by returning wxBITMAP_TYPE_ANY
        raise RuntimeErro('invalid graphics format')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _getbitmap_type( self, filename ) :
        # KEA 2001-07-27
        # was
        #name, ext = filename.split( '.' )
        #ext = ext.upper()
        if filename is None or filename == '':
            return None

        name, ext = os.path.splitext(filename)
        ext = ext[1:].upper()
        if ext == 'BMP':
            return wx.BITMAP_TYPE_BMP
        elif ext == 'GIF':
            return wx.BITMAP_TYPE_GIF
        elif ext == 'JPG' or ext == 'JPEG':
            return wx.BITMAP_TYPE_JPEG
        elif ext == 'PCX':
            return wx.BITMAP_TYPE_PCX
        #elif ext == 'PICT':
        #    return wx.BITMAP_TYPE_PICT
        elif ext == 'PNG':
            return wx.BITMAP_TYPE_PNG
        elif ext == 'PNM':
            return wx.BITMAP_TYPE_PNM
        elif ext == 'TIF' or ext == 'TIFF':
            return wx.BITMAP_TYPE_TIF
        elif ext == 'XBM':
            return wx.BITMAP_TYPE_XBM
        elif ext == 'XPM':
            return wx.BITMAP_TYPE_XPM
        else:
            # KEA 2001-10-10
            # rather than throw an exception, we could try and have wxPython figure out the image
            # type by returning wxBITMAP_TYPE_ANY
            raise RuntimeError('invalid graphics format')

Response: Returns the type of an image from the file extension


Instruction:
Explain what the following Python 3 code does
def _set_icon(self, icon=None):
        if icon is not None:
            try:
                wx_icon = wx.Icon(icon, wx.BITMAP_TYPE_ICO)
                self.wx_obj.SetIcon(wx_icon)
            except:
                pass

Response: Set icon based on resource values


Instruction:
Write a Python 3 script for
displaying or hide the window optionally disabling all other windows

Response:
def show(self, value=True, modal=None):
        "Display or hide the window, optionally disabling all other windows"
        self.wx_obj.Show(value)
        if modal:
            # disable all top level windows of this application (MakeModal)
            disabler = wx.WindowDisabler(self.wx_obj)
            # create an event loop to stop execution
            eventloop = wx.EventLoop()
            def on_close_modal(evt):
                evt.Skip()
                eventloop.Exit()
            self.wx_obj.Bind(wx.EVT_CLOSE, on_close_modal)
            # start the event loop to wait user interaction
            eventloop.Run()
            # reenable the windows disabled and return control to the caller
            del disabler


Instruction:
Can you tell what is the following Python 3 function doing
def draw_arc(self, x1y1, x2y2, xcyc):

        self._buf_image.DrawArcPoint(x1y1, x2y2, xcyc)
        if self.auto_refresh:
            dc = wx.ClientDC(self.wx_obj)
            dc.BlitPointSize((0, 0), (self._size[0], self._size[1]), self._buf_image, (0, 0))

Response: Draws an arc of a circle centered on x1 y1 and x2 y2.


Instruction:
Write a Python 3 script to
open read and eval the resource from the source file

Response:
def parse(filename=""):
    "Open, read and eval the resource from the source file"
    # use the provided resource file:
    s = open(filename).read()
    ##s.decode("latin1").encode("utf8")
    import datetime, decimal
    rsrc = eval(s)
    return rsrc


Instruction:
Write a Python 3 script for
saving the resource to the source file

Response:
def save(filename, rsrc):
    "Save the resource to the source file"
    s = pprint.pformat(rsrc)
    ## s = s.encode("utf8")
    open(filename, "w").write(s)


Instruction:
Write a Python 3 function for
creating the GUI objects defined in the resource ( filename or python struct )

Response:
def load(controller=None, filename="", name=None, rsrc=None):
    "Create the GUI objects defined in the resource (filename or python struct)"
    # if no filename is given, search for the rsrc.py with the same module name:
    if not filename and not rsrc:
        if isinstance(controller, types.ClassType):
            # use the controller class module (to get __file__ for rsrc.py)
            mod_dict = util.get_class_module_dict(controller)
        elif isinstance(controller, types.ModuleType):
            # use the module provided as controller
            mod_dict = controller.__dict__
        elif isinstance(controller, Controller):
            # use the instance provided as controller
            mod_dict = util.get_class_module_dict(controller)
        else:
            # use the caller module (no controller explicitelly provided)
            mod_dict = util.get_caller_module_dict()
            # do not use as controller if it was explicitly False or empty
            if controller is None:
                controller = mod_dict
        if util.main_is_frozen():
            # running standalone
            if '__file__' in mod_dict:
                filename = os.path.split(mod_dict['__file__'])[1]
            else:
                # __main__ has not __file__ under py2exe!
                filename = os.path.split(sys.argv[0])[-1]
            filename = os.path.join(util.get_app_dir(), filename)
        else:
            # figure out the .rsrc.py filename based on the module name
            filename = mod_dict['__file__']
        # chop the .pyc or .pyo from the end
        base, ext = os.path.splitext(filename)
        filename = base + ".rsrc.py"
    # when rsrc is a file name, open, read and eval it:
    if isinstance(filename, basestring):
        rsrc = parse(filename)
    ret = []
    # search over the resource to create the requested object (or all)
    for win in rsrc:
        if not name or win['name'] == name:
            ret.append(build_window(win))
    # associate event handlers
    if ret and controller:
        connect(ret[0], controller)
        # return the first instance created (if any):
        return ret[0]
    else:
        # return all the instances created -for the designer- (if any):
        return ret


Instruction:
Here you have a function in Python 3, explain what it does
def build_window(res):
    "Create a gui2py window based on the python resource"

    # windows specs (parameters)
    kwargs = dict(res.items())
    wintype = kwargs.pop('type')
    menubar = kwargs.pop('menubar', None)
    components = kwargs.pop('components')
    panel = kwargs.pop('panel', {})

    from gui import registry
    import gui

    winclass = registry.WINDOWS[wintype]
    win = winclass(**kwargs)

    # add an implicit panel by default (as pythoncard had)
    if False and panel is not None:
        panel['name'] = 'panel'
        p = gui.Panel(win, **panel)
    else:
        p = win

    if components:
        for comp in components:
            build_component(comp, parent=p)

    if menubar:
        mb = gui.MenuBar(name="menu", parent=win)
        for menu in menubar:
            build_component(menu, parent=mb)
    return win

Response: Create a gui2py window based on the python resource


Instruction:
Can you generate a brief explanation for the following Python 3 code
def build_component(res, parent=None):
    "Create a gui2py control based on the python resource"
    # control specs (parameters)
    kwargs = dict(res.items())
    comtype = kwargs.pop('type')
    if 'components' in res:
        components = kwargs.pop('components')
    elif comtype == 'Menu' and 'items' in res:
        components = kwargs.pop('items')
    else:
        components = []

    from gui import registry

    if comtype in registry.CONTROLS:
        comclass = registry.CONTROLS[comtype]
    elif comtype in registry.MENU:
        comclass = registry.MENU[comtype]
    elif comtype in registry.MISC:
        comclass = registry.MISC[comtype]
    else:
        raise RuntimeError("%s not in registry" % comtype)

    # Instantiate the GUI object
    com = comclass(parent=parent, **kwargs)

    for comp in components:
        build_component(comp, parent=com)

    return com

Response: Create a gui2py control based on the python resource


Instruction:
Can you tell what is the following Python 3 function doing
def dump(obj):
    "Recursive convert a live GUI object to a resource list/dict"

    from .spec import InitSpec, DimensionSpec, StyleSpec, InternalSpec
    import decimal, datetime
    from .font import Font
    from .graphic import Bitmap, Color
    from . import registry

    ret = {'type': obj.__class__.__name__}

    for (k, spec) in obj._meta.specs.items():
        if k == "index":        # index is really defined by creation order
            continue            # also, avoid infinite recursion
        v = getattr(obj, k, "")
        if (not isinstance(spec, InternalSpec)
            and v != spec.default
            and (k != 'id' or v > 0)
            and isinstance(v,
                 (basestring, int, long, float, bool, dict, list,
                  decimal.Decimal,
                  datetime.datetime, datetime.date, datetime.time,
                  Font, Color))
            and repr(v) != 'None'
            and k != 'parent'
            ):
            ret[k] = v

    for ctl in obj:
        if ret['type'] in registry.MENU:
            ret.setdefault('items', []).append(dump(ctl))
        else:
            res = dump(ctl)
            if 'menubar' in res:
                ret.setdefault('menubar', []).append(res.pop('menubar'))
            else:
                ret.setdefault('components', []).append(res)

    return ret

Response: Recursive convert a live GUI object to a resource list / dict


Instruction:
Write a Python 3 script to
translate gui2py attribute name from pythoncard legacy code

Response:
def convert(self, name):
        "translate gui2py attribute name from pythoncard legacy code"
        new_name = PYTHONCARD_PROPERTY_MAP.get(name)
        if new_name:
            print "WARNING: property %s should be %s (%s)" % (name, new_name, self.obj.name)
            return new_name
        else:
            return name


Instruction:
Explain what the following Python 3 code does
def get_data():
    "Read from the clipboard content, return a suitable object (string or bitmap)"
    data = None
    try:
        if wx.TheClipboard.Open():
            if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
                do = wx.TextDataObject()
                wx.TheClipboard.GetData(do)
                data = do.GetText()
            elif wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_BITMAP)):
                do = wx.BitmapDataObject()
                wx.TheClipboard.GetData(do)
                data = do.GetBitmap()
            wx.TheClipboard.Close()
    except:
        data = None
    return data

Response: Read from the clipboard content return a suitable object ( string or bitmap )


Instruction:
Implement a Python 3 function for
writing content to the clipboard data can be either a string or a bitmap

Response:
def set_data(data):
    "Write content to the clipboard, data can be either a string or a bitmap"
    try:
        if wx.TheClipboard.Open():
            if isinstance(data, (str, unicode)):
                do = wx.TextDataObject()
                do.SetText(data)
                wx.TheClipboard.SetData(do)
            elif isinstance(data, wx.Bitmap):
                do = wx.BitmapDataObject()
                do.SetBitmap(data)
                wx.TheClipboard.SetData(do)
            wx.TheClipboard.Close()
    except:
        pass


Instruction:
Implement a function in Python 3 to
find out what items are documented in source. rst. See find_autosummary_in_lines.

Response:
def find_autosummary_in_files(filenames):
    """Find out what items are documented in source/*.rst.

    See `find_autosummary_in_lines`.
    """
    documented = []
    for filename in filenames:
        f = open(filename, 'r')
        lines = f.read().splitlines()
        documented.extend(find_autosummary_in_lines(lines, filename=filename))
        f.close()
    return documented


Instruction:
Can you tell what is the following Python 3 function doing
def find_autosummary_in_docstring(name, module=None, filename=None):
    try:
        real_name, obj, parent = import_by_name(name)
        lines = pydoc.getdoc(obj).splitlines()
        return find_autosummary_in_lines(lines, module=name, filename=filename)
    except AttributeError:
        pass
    except ImportError, e:
        print "Failed to import '%s': %s" % (name, e)
    return []

Response: Find what items are documented in the given object s docstring.


Instruction:
Explain what the following Python 3 code does
def find_autosummary_in_lines(lines, module=None, filename=None):
    autosummary_re = re.compile(r'^(\s*)\.\.\s+autosummary::\s*')
    automodule_re = re.compile(
        r'^\s*\.\.\s+automodule::\s*([A-Za-z0-9_.]+)\s*$')
    module_re = re.compile(
        r'^\s*\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$')
    autosummary_item_re = re.compile(r'^\s+(~?[_a-zA-Z][a-zA-Z0-9_.]*)\s*.*?')
    toctree_arg_re = re.compile(r'^\s+:toctree:\s*(.*?)\s*$')
    template_arg_re = re.compile(r'^\s+:template:\s*(.*?)\s*$')

    documented = []

    toctree = None
    template = None
    current_module = module
    in_autosummary = False
    base_indent = ""

    for line in lines:
        if in_autosummary:
            m = toctree_arg_re.match(line)
            if m:
                toctree = m.group(1)
                if filename:
                    toctree = os.path.join(os.path.dirname(filename),
                                           toctree)
                continue

            m = template_arg_re.match(line)
            if m:
                template = m.group(1).strip()
                continue

            if line.strip().startswith(':'):
                continue # skip options

            m = autosummary_item_re.match(line)
            if m:
                name = m.group(1).strip()
                if name.startswith('~'):
                    name = name[1:]
                if current_module and \
                       not name.startswith(current_module + '.'):
                    name = "%s.%s" % (current_module, name)
                documented.append((name, toctree, template))
                continue

            if not line.strip() or line.startswith(base_indent + " "):
                continue

            in_autosummary = False

        m = autosummary_re.match(line)
        if m:
            in_autosummary = True
            base_indent = m.group(1)
            toctree = None
            template = None
            continue

        m = automodule_re.search(line)
        if m:
            current_module = m.group(1).strip()
            # recurse into the automodule docstring
            documented.extend(find_autosummary_in_docstring(
                current_module, filename=filename))
            continue

        m = module_re.match(line)
        if m:
            current_module = m.group(2)
            continue

    return documented

Response: Find out what items appear in the given lines.


Instruction:
Create a Python 3 function for
adding the object and all their childs

Response:
def load_object(self, obj=None):
        "Add the object and all their childs"
        # if not obj is given, do a full reload using the current root
        if obj:
            self.root_obj = obj
        else:
            obj = self.root_obj
        self.tree.DeleteAllItems()
        self.root = self.tree.AddRoot("application")
        self.tree.SetItemText(self.root, "App", 1)
        self.tree.SetItemText(self.root, "col 2 root", 2)
        #self.tree.SetItemImage(self.root, fldridx, which = wx.TreeItemIcon_Normal)
        #self.tree.SetItemImage(self.root, fldropenidx, which = wx.TreeItemIcon_Expanded)

        self.build_tree(self.root, obj)
        self.tree.Expand(self.root)


Instruction:
Write a Python 3 script for
selecting the object and show its properties

Response:
def inspect(self, obj, context_menu=False, edit_prop=False, mouse_pos=None):
        "Select the object and show its properties"
        child = self.tree.FindItem(self.root, obj.name)
        if DEBUG: print "inspect child", child
        if child:
            self.tree.ScrollTo(child)
            self.tree.SetCurrentItem(child)
            self.tree.SelectItem(child)
            child.Selected = True
            self.activate_item(child, edit_prop)
            if context_menu:
                self.show_context_menu(child, mouse_pos)


Instruction:
Implement a Python 3 function for
loading the selected item in the property editor

Response:
def activate_item(self, child, edit_prop=False, select=False):
        "load the selected item in the property editor"
        d = self.tree.GetItemData(child)
        if d:
            o = d.GetData()
            self.selected_obj = o
            callback = lambda o=o, **kwargs: self.update(o, **kwargs)
            self.propeditor.load_object(o, callback)
            if edit_prop:
                wx.CallAfter(self.propeditor.edit)
            if select and self.designer:
                self.designer.select(o)
        else:
            self.selected_obj = None


Instruction:
How would you code a function in Python 3 to
update the tree item when the object name changes

Response:
def update(self, obj, **kwargs):
        "Update the tree item when the object name changes"
        # search for the old name:
        child = self.tree.FindItem(self.root, kwargs['name'])
        if DEBUG: print "update child", child, kwargs
        if child:
            self.tree.ScrollTo(child)
            self.tree.SetCurrentItem(child)
            self.tree.SelectItem(child)
            child.Selected = True
            # update the new name
            self.tree.SetItemText(child, obj.name, 0)


Instruction:
Here you have a function in Python 3, explain what it does
def show_context_menu(self, item, mouse_pos=None):
        "Open a popup menu with options regarding the selected object"
        if item:
            d = self.tree.GetItemData(item)
            if d:
                obj = d.GetData()
                if obj:
                    # highligh and store the selected object:
                    self.highlight(obj.wx_obj)
                    self.obj = obj

                    # make the context menu
                    menu = wx.Menu()
                    id_del, id_dup, id_raise, id_lower = [wx.NewId() for i
                                                            in range(4)]
                    menu.Append(id_del, "Delete")
                    menu.Append(id_dup, "Duplicate")
                    menu.Append(id_raise, "Bring to Front")
                    menu.Append(id_lower, "Send to Back")

                    # make submenu!
                    sm = wx.Menu()
                    for ctrl in sorted(obj._meta.valid_children,
                                       key=lambda c:
                                            registry.ALL.index(c._meta.name)):
                        new_id = wx.NewId()
                        sm.Append(new_id, ctrl._meta.name)
                        self.Bind(wx.EVT_MENU,
                                  lambda evt, ctrl=ctrl: self.add_child(ctrl, mouse_pos),
                                  id=new_id)

                    menu.AppendMenu(wx.NewId(), "Add child", sm)

                    self.Bind(wx.EVT_MENU, self.delete, id=id_del)
                    self.Bind(wx.EVT_MENU, self.duplicate, id=id_dup)
                    self.Bind(wx.EVT_MENU, self.bring_to_front, id=id_raise)
                    self.Bind(wx.EVT_MENU, self.send_to_back, id=id_lower)

                    self.PopupMenu(menu)
                    menu.Destroy()
                    self.load_object(self.root_obj)

Response: Open a popup menu with options regarding the selected object


Instruction:
Can you generate the documentation for the following Python 3 function
def set_parent(self, new_parent, init=False):
        "Re-parent a child control with the new wx_obj parent (owner)"
        ##SubComponent.set_parent(self, new_parent, init)
        self.wx_obj.SetOwner(new_parent.wx_obj.GetEventHandler())

Response: Re - parent a child control with the new wx_obj parent ( owner


Instruction:
Implement a Python 3 function for
performing the actual serialization.

Response:
def to_representation(self, value):
        """
        Perform the actual serialization.

        Args:
            value: the image to transform
        Returns:
            a url pointing at a scaled and cached image
        """
        if not value:
            return None

        image = get_thumbnail(value, self.geometry_string, **self.options)

        try:
            request = self.context.get('request', None)
            return request.build_absolute_uri(image.url)
        except:
            try:
                return super(HyperlinkedSorlImageField, self).to_representation(image)
            except AttributeError:  # NOQA
                return super(HyperlinkedSorlImageField, self).to_native(image.url)  # NOQA


Instruction:
Write a Python 3 function for
building and registers a :class:`Selector` object with the given name and configuration. Args: name (str): The name of the selector. Yields: SelectorFactory: The factory that will build the :class:`Selector`.

Response:
def add_selector(name):
    """
    Builds and registers a :class:`Selector` object with the given name and configuration.

    Args:
        name (str): The name of the selector.

    Yields:
        SelectorFactory: The factory that will build the :class:`Selector`.
    """

    factory = SelectorFactory(name)
    yield factory
    selectors[name] = factory.build_selector()


Instruction:
How would you implement a function in Python 3 that
returns the expression filters for this selector.

Response:
def expression_filters(self):
        """ Dict[str, ExpressionFilter]: Returns the expression filters for this selector. """

        return {
            name: filter for name, filter in iter(self.filters.items())
            if isinstance(filter, ExpressionFilter)}


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

        return {
            name: filter for name, filter in iter(self.filters.items())
            if isinstance(filter, NodeFilter)}

Response: Returns the node filters for this selector.


Instruction:
Here you have a function in Python 3, explain what it does
def expression_filter(self, name, **kwargs):

        def decorator(func):
            self.filters[name] = ExpressionFilter(name, func, **kwargs)

        return decorator

Response: Returns a decorator function for adding an expression filter.


Instruction:
Can you write a function in Python 3 where it
returns a function that adds a node filter.

Response:
def node_filter(self, name, **kwargs):
        """
        Returns a decorator function for adding a node filter.

        Args:
            name (str): The name of the filter.
            **kwargs: Variable keyword arguments for the filter.

        Returns:
            Callable[[Callable[[Element, Any], bool]]]: A decorator function for adding a node
                filter.
        """

        def decorator(func):
            self.filters[name] = NodeFilter(name, func, **kwargs)

        return decorator


Instruction:
Can you write a function in Python 3 where it
adds filters from a particular global filter set.

Response:
def filter_set(self, name):
        """
        Adds filters from a particular global :class:`FilterSet`.

        Args:
            name (str): The name of the set whose filters should be added.
        """

        filter_set = filter_sets[name]
        for name, filter in iter(filter_set.filters.items()):
            self.filters[name] = filter
        self.descriptions += filter_set.descriptions


Instruction:
Implement a function in Python 3 to
build a new Selector instance with the current configuration.

Response:
def build_selector(self):
        """ Selector: Returns a new :class:`Selector` instance with the current configuration. """

        kwargs = {
            'label': self.label,
            'descriptions': self.descriptions,
            'filters': self.filters}
        if self.format == "xpath":
            kwargs['xpath'] = self.func
        if self.format == "css":
            kwargs['css'] = self.func

        return Selector(self.name, **kwargs)


Instruction:
Can you write a function in Python 3 where it
resolves this query relative to the given node.

Response:
def resolves_for(self, node):
        """
        Resolves this query relative to the given node.

        Args:
            node (node.Base): The node to be evaluated.

        Returns:
            int: The number of matches found.
        """

        self.node = node
        self.actual_styles = node.style(*self.expected_styles.keys())

        return all(
            toregex(value).search(self.actual_styles[style])
            for style, value in iter(self.expected_styles.items()))


Instruction:
How would you implement a function in Python 3 that
asserts that the page has the given path.

Response:
def assert_current_path(self, path, **kwargs):
        """
        Asserts that the page has the given path. By default this will compare against the
        path+query portion of the full URL.

        Args:
            path (str | RegexObject): The string or regex that the current "path" should match.
            **kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`.

        Returns:
            True

        Raises:
            ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
        """

        query = CurrentPathQuery(path, **kwargs)

        @self.document.synchronize
        def assert_current_path():
            if not query.resolves_for(self):
                raise ExpectationNotMet(query.failure_message)
        assert_current_path()

        return True


Instruction:
Write a Python 3 function that can
assert that the page doesn t have the given path.

Response:
def assert_no_current_path(self, path, **kwargs):
        """
        Asserts that the page doesn't have the given path.

        Args:
            path (str | RegexObject): The string or regex that the current "path" should match.
            **kwargs: Arbitrary keyword arguments for :class:`CurrentPathQuery`.

        Returns:
            True

        Raises:
            ExpectationNotMet: If the assertion hasn't succeeded during the wait time.
        """

        query = CurrentPathQuery(path, **kwargs)

        @self.document.synchronize
        def assert_no_current_path():
            if query.resolves_for(self):
                raise ExpectationNotMet(query.negative_failure_message)

        assert_no_current_path()

        return True


Instruction:
Can you generate the documentation for the following Python 3 function
def has_current_path(self, path, **kwargs):

        try:
            return self.assert_current_path(path, **kwargs)
        except ExpectationNotMet:
            return False

Response: Checks if the page has the given path.


Instruction:
Can you tell what is the following Python 3 function doing
def has_no_current_path(self, path, **kwargs):

        try:
            return self.assert_no_current_path(path, **kwargs)
        except ExpectationNotMet:
            return False

Response: Checks if the page doesn t have the given path.


Instruction:
Can you implement a function in Python 3 that
retrieves the text of the element.

Response:
def text(self):
        """
        Retrieve the text of the element. If :data:`capybara.ignore_hidden_elements` is ``True``,
        which it is by default, then this will return only text which is visible. The exact
        semantics of this may differ between drivers, but generally any text within elements with
        ``display: none`` is ignored.

        Returns:
            str: The text of the element.
        """

        if capybara.ignore_hidden_elements or capybara.visible_text_only:
            return self.visible_text
        else:
            return self.all_text


Instruction:
Make a summary of the following Python 3 code
def select_option(self):
        if self.disabled:
            warn("Attempt to select disabled option: {}".format(self.value or self.text))
        self.base.select_option()

Response: Select this node if it is an option element inside a select tag.


Instruction:
Can you create a Python 3 function that
returns the given expression filtered by the given value.

Response:
def apply_filter(self, expr, value):
        """
        Returns the given expression filtered by the given value.

        Args:
            expr (xpath.expression.AbstractExpression): The expression to filter.
            value (object): The desired value with which the expression should be filtered.

        Returns:
            xpath.expression.AbstractExpression: The filtered expression.
        """

        if self.skip(value):
            return expr

        if not self._valid_value(value):
            msg = "Invalid value {value} passed to filter {name} - ".format(
                value=repr(value),
                name=self.name)

            if self.default is not None:
                warn(msg + "defaulting to {}".format(self.default))
                value = self.default
            else:
                warn(msg + "skipping")
                return expr

        return self.func(expr, value)


Instruction:
Can you generate the documentation for the following Python 3 function
def get_browser(browser_name, capabilities=None, **options):

    if browser_name == "chrome":
        return webdriver.Chrome(desired_capabilities=capabilities, **options)
    if browser_name == "edge":
        return webdriver.Edge(capabilities=capabilities, **options)
    if browser_name in ["ff", "firefox"]:
        return webdriver.Firefox(capabilities=capabilities, **options)
    if browser_name in ["ie", "internet_explorer"]:
        return webdriver.Ie(capabilities=capabilities, **options)
    if browser_name == "phantomjs":
        return webdriver.PhantomJS(desired_capabilities=capabilities, **options)
    if browser_name == "remote":
        return webdriver.Remote(desired_capabilities=capabilities, **options)
    if browser_name == "safari":
        return webdriver.Safari(desired_capabilities=capabilities, **options)

    raise ValueError("unsupported browser: {}".format(repr(browser_name)))

Response: Returns an instance of the given browser with the given capabilities.


Instruction:
Write a Python 3 function that can
return the keyword arguments that this query was initialized.

Response:
def kwargs(self):
        """ Dict[str, Any]: The keyword arguments with which this query was initialized. """
        kwargs = {}
        kwargs.update(self.options)
        kwargs.update(self.filter_options)
        return kwargs


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

        description = self.label

        if self.locator:
            description += " {}".format(desc(self.locator))
        if self.options["text"] is not None:
            description += " with text {}".format(desc(self.options["text"]))

        description += self.selector.description(self.filter_options)

        return description

Response: A long description of this query.


Instruction:
Create a Python 3 function for
returning the XPath query for this selector.

Response:
def xpath(self, exact=None):
        """
        Returns the XPath query for this selector.

        Args:
            exact (bool, optional): Whether to exactly match text.

        Returns:
            str: The XPath query for this selector.
        """

        exact = exact if exact is not None else self.exact

        if isinstance(self.expression, AbstractExpression):
            expression = self._apply_expression_filters(self.expression)

            return to_xpath(expression, exact=exact)
        else:
            return str_(self.expression)


Instruction:
Can you create a Python 3 function that
resolves this query relative to the given node.

Response:
def resolve_for(self, node, exact=None):
        """
        Resolves this query relative to the given node.

        Args:
            node (node.Base): The node relative to which this query should be resolved.
            exact (bool, optional): Whether to exactly match text.

        Returns:
            list[Element]: A list of elements matched by this query.
        """

        from capybara.driver.node import Node
        from capybara.node.element import Element
        from capybara.node.simple import Simple

        @node.synchronize
        def resolve():
            if self.selector.format == "css":
                children = node._find_css(self.css())
            else:
                children = node._find_xpath(self.xpath(exact))

            def wrap(child):
                if isinstance(child, Node):
                    return Element(node.session, child, node, self)
                else:
                    return Simple(child)

            children = [wrap(child) for child in children]

            return Result(children, self)

        return resolve()


Instruction:
Can you create a Python 3 function that
returns whether the given node matches all filters.

Response:
def matches_filters(self, node):
        """
        Returns whether the given node matches all filters.

        Args:
            node (Element): The node to evaluate.

        Returns:
            bool: Whether the given node matches.
        """

        visible = self.visible

        if self.options["text"]:
            if isregex(self.options["text"]):
                regex = self.options["text"]
            elif self.exact_text is True:
                regex = re.compile(r"\A{}\Z".format(re.escape(self.options["text"])))
            else:
                regex = toregex(self.options["text"])

            text = normalize_text(
                node.all_text if visible == "all" else node.visible_text)

            if not regex.search(text):
                return False

        if isinstance(self.exact_text, (bytes_, str_)):
            regex = re.compile(r"\A{}\Z".format(re.escape(self.exact_text)))

            text = normalize_text(
                node.all_text if visible == "all" else node.visible_text)

            if not regex.search(text):
                return False

        if visible == "visible":
            if not node.visible:
                return False
        elif visible == "hidden":
            if node.visible:
                return False

        for name, node_filter in iter(self._node_filters.items()):
            if name in self.filter_options:
                if not node_filter.matches(node, self.filter_options[name]):
                    return False
            elif node_filter.has_default:
                if not node_filter.matches(node, node_filter.default):
                    return False

        if self.options["filter"] and not self.options["filter"](node):
            return False

        return True


Instruction:
Given the following Python 3 function, write the documentation
def current_scope(self):
        scope = self._scopes[-1]
        if scope in [None, "frame"]:
            scope = self.document
        return scope

Response: Returns the current scope of the current node.


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

        if not self.current_url:
            return

        result = urlparse(self.current_url)
        scheme, netloc = result.scheme, result.netloc
        host = netloc.split(":")[0] if netloc else None
        return "{0}://{1}".format(scheme, host) if host else None

Response: str - Host of the current page.


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

        self.raise_server_error()

        visit_uri = urlparse(visit_uri)

        if capybara.app_host:
            uri_base = urlparse(capybara.app_host)
        elif self.server:
            uri_base = urlparse("http://{}:{}".format(self.server.host, self.server.port))
        else:
            uri_base = None

        visit_uri = ParseResult(
            scheme=visit_uri.scheme or (uri_base.scheme if uri_base else ""),
            netloc=visit_uri.netloc or (uri_base.netloc if uri_base else ""),
            path=visit_uri.path,
            params=visit_uri.params,
            query=visit_uri.query,
            fragment=visit_uri.fragment)

        self.driver.visit(visit_uri.geturl())

Response: Navigate to the given URL.


Instruction:
How would you explain what the following Python 3 function does
def scope(self, *args, **kwargs):

        new_scope = args[0] if isinstance(args[0], Base) else self.find(*args, **kwargs)
        self._scopes.append(new_scope)
        try:
            yield
        finally:
            self._scopes.pop()

Response: A context manager that finds and returns the elements that are in the given selector.


Instruction:
How would you implement a function in Python 3 that
executes the wrapped code within the given iframe.

Response:
def frame(self, locator=None, *args, **kwargs):
        """
        Execute the wrapped code within the given iframe using the given frame or frame name/id.
        May not be supported by all drivers.

        Args:
            locator (str | Element, optional): The name/id of the frame or the frame's element.
                Defaults to the only frame in the document.
        """

        self.switch_to_frame(self._find_frame(locator, *args, **kwargs))
        try:
            yield
        finally:
            self.switch_to_frame("parent")


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

        if isinstance(frame, Element):
            self.driver.switch_to_frame(frame)
            self._scopes.append("frame")
        elif frame == "parent":
            if self._scopes[-1] != "frame":
                raise ScopeError("`switch_to_frame(\"parent\")` cannot be called "
                                 "from inside a descendant frame's `scope` context.")
            self._scopes.pop()
            self.driver.switch_to_frame("parent")
        elif frame == "top":
            if "frame" in self._scopes:
                idx = self._scopes.index("frame")
                if any([scope not in ["frame", None] for scope in self._scopes[idx:]]):
                    raise ScopeError("`switch_to_frame(\"top\")` cannot be called "
                                     "from inside a descendant frame's `scope` context.")
                self._scopes = self._scopes[:idx]
                self.driver.switch_to_frame("top")
        else:
            raise ValueError(
                "You must provide a frame element, \"parent\", or \"top\" "
                "when calling switch_to_frame")

Response: Switches the current locale to the given frame.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def switch_to_window(self, window, wait=None):

        if len(self._scopes) > 1:
            raise ScopeError(
                "`switch_to_window` is not supposed to be invoked from "
                "within `scope`s, `frame`s, or other `window`s.")

        if isinstance(window, Window):
            self.driver.switch_to_window(window.handle)
            return window
        else:
            @self.document.synchronize(errors=(WindowError,), wait=wait)
            def switch_and_get_matching_window():
                original_window_handle = self.driver.current_window_handle
                try:
                    for handle in self.driver.window_handles:
                        self.driver.switch_to_window(handle)
                        result = window()
                        if result:
                            return Window(self, handle)
                except Exception:
                    self.driver.switch_to_window(original_window_handle)
                    raise

                self.driver.switch_to_window(original_window_handle)
                raise WindowError("Could not find a window matching lambda")

            return switch_and_get_matching_window()

Response: Switches to a window.


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

        original = self.current_window
        if window != original:
            self.switch_to_window(window)
        self._scopes.append(None)
        try:
            yield
        finally:
            self._scopes.pop()
            if original != window:
                self.switch_to_window(original)

Response: Context manager for the given window.


Instruction:
Given the following Python 3 function, write the documentation
def window_opened_by(self, trigger_func, wait=None):

        old_handles = set(self.driver.window_handles)
        trigger_func()

        @self.document.synchronize(wait=wait, errors=(WindowError,))
        def get_new_window():
            opened_handles = set(self.driver.window_handles) - old_handles
            if len(opened_handles) != 1:
                raise WindowError("lambda passed to `window_opened_by` "
                                  "opened {0} windows instead of 1".format(len(opened_handles)))
            return Window(self, list(opened_handles)[0])

        return get_new_window()

Response: Get the window that has been opened by the passed lambda.


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

        args = [arg.base if isinstance(arg, Base) else arg for arg in args]
        self.driver.execute_script(script, *args)

Response: Execute a JavaScript script and return a result.


Instruction:
Create a Python 3 function for
evaluating the given JavaScript and returns the result.

Response:
def evaluate_script(self, script, *args):
        """
        Evaluate the given JavaScript and return the result. Be careful when using this with
        scripts that return complex objects, such as jQuery statements. :meth:`execute_script`
        might be a better alternative.

        Args:
            script (str): A string of JavaScript to evaluate.
            *args: Variable length argument list to pass to the executed JavaScript string.

        Returns:
            object: The result of the evaluated JavaScript (may be driver specific).
        """

        args = [arg.base if isinstance(arg, Base) else arg for arg in args]
        result = self.driver.evaluate_script(script, *args)
        return self._wrap_element_script_result(result)


Instruction:
Can you create a Python 3 function that
executes the wrapped code accepting an alert.

Response:
def accept_alert(self, text=None, wait=None):
        """
        Execute the wrapped code, accepting an alert.

        Args:
            text (str | RegexObject, optional): Text to match against the text in the modal.
            wait (int | float, optional): Maximum time to wait for the modal to appear after
                executing the wrapped code.

        Raises:
            ModalNotFound: If a modal dialog hasn't been found.
        """

        wait = wait or capybara.default_max_wait_time
        with self.driver.accept_modal("alert", text=text, wait=wait):
            yield


Instruction:
Given the following Python 3 function, write the documentation
def accept_confirm(self, text=None, wait=None):

        with self.driver.accept_modal("confirm", text=text, wait=wait):
            yield

Response: Execute the wrapped code accepting a confirm.


Instruction:
Can you write a function in Python 3 where it
executes the wrapped code dismissing a modal.

Response:
def dismiss_confirm(self, text=None, wait=None):
        """
        Execute the wrapped code, dismissing a confirm.

        Args:
            text (str | RegexObject, optional): Text to match against the text in the modal.
            wait (int | float, optional): Maximum time to wait for the modal to appear after
                executing the wrapped code.

        Raises:
            ModalNotFound: If a modal dialog hasn't been found.
        """

        with self.driver.dismiss_modal("confirm", text=text, wait=wait):
            yield


Instruction:
Can you implement a function in Python 3 that
executes the wrapped code accepting a prompt optionally responding to the prompt.

Response:
def accept_prompt(self, text=None, response=None, wait=None):
        """
        Execute the wrapped code, accepting a prompt, optionally responding to the prompt.

        Args:
            text (str | RegexObject, optional): Text to match against the text in the modal.
            response (str, optional): Response to provide to the prompt.
            wait (int | float, optional): Maximum time to wait for the modal to appear after
                executing the wrapped code.

        Raises:
            ModalNotFound: If a modal dialog hasn't been found.
        """

        with self.driver.accept_modal("prompt", text=text, response=response, wait=wait):
            yield


Instruction:
Make a summary of the following Python 3 code
def dismiss_prompt(self, text=None, wait=None):

        with self.driver.dismiss_modal("prompt", text=text, wait=wait):
            yield

Response: Execute the wrapped code dismissing a prompt.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def save_page(self, path=None):

        path = _prepare_path(path, "html")

        with open(path, "wb") as f:
            f.write(encode_string(self.body))

        return path

Response: Save a snapshot of the page.


Instruction:
Implement a function in Python 3 to
save a screenshot of the page.

Response:
def save_screenshot(self, path=None, **kwargs):
        """
        Save a screenshot of the page.

        If invoked without arguments, it will save a file to :data:`capybara.save_path` and the
        file will be given a randomly generated filename. If invoked with a relative path, the path
        will be relative to :data:`capybara.save_path`.

        Args:
            path (str, optional): The path to where it should be saved.
            **kwargs: Arbitrary keywords arguments for the driver.

        Returns:
            str: The path to which the file was saved.
        """

        path = _prepare_path(path, "png")
        self.driver.save_screenshot(path, **kwargs)
        return path


Instruction:
Implement a Python 3 function for
resetting the session and return the current session s cookie.

Response:
def reset(self):
        """
        Reset the session (i.e., remove cookies and navigate to a blank page).

        This method does not:
        * accept modal dialogs if they are present (the Selenium driver does, but others may not),
        * clear the browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc., or
        * modify the state of the driver/underlying browser in any other way

        as doing so would result in performance downsides and it's not needed to do everything
        from the list above for most apps.

        If you want to do anything from the list above on a general basis you can write a test
        teardown method.
        """

        self.driver.reset()
        if self.server:
            self.server.wait_for_pending_requests()
        self.raise_server_error()


Instruction:
Can you tell what is the following Python 3 function doing
def raise_server_error(self):
        if self.server and self.server.error:
            try:
                if capybara.raise_server_errors:
                    raise self.server.error
            finally:
                self.server.reset_error()

Response: Raise errors encountered by the server.


Instruction:
Write a Python 3 function that can
return whether the given node matches the filter rule with the given value.

Response:
def matches(self, node, value):
        """
        Returns whether the given node matches the filter rule with the given value.

        Args:
            node (Element): The node to filter.
            value (object): The desired value with which the node should be evaluated.

        Returns:
            bool: Whether the given node matches.
        """

        if self.skip(value):
            return True

        if not self._valid_value(value):
            msg = "Invalid value {value} passed to filter {name} - ".format(
                value=repr(value),
                name=self.name)

            if self.default is not None:
                warn(msg + "defaulting to {}".format(self.default))
                value = self.default
            else:
                warn(msg + "skipping")
                return True

        return self.func(node, value)


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

    global_vars = {}

    # Compile and execute the individual file to prevent
    # the package from being automatically loaded.
    source = read(os.path.join("capybara", "version.py"))
    code = compile(source, "version.py", "exec")
    exec(code, global_vars)

    return global_vars['__version__']

Response: Returns the package version.


Instruction:
How would you implement a function in Python 3 that
resolves this query relative to the given node.

Response:
def resolves_for(self, node):
        """
        Resolves this query relative to the given node.

        Args:
            node (node.Document): The node to be evaluated.

        Returns:
            bool: Whether the given node matches this query.
        """

        self.actual_title = normalize_text(node.title)
        return bool(self.search_regexp.search(self.actual_title))


Instruction:
Can you tell what is the following Python 3 function doing
def frame_title(self):
        elements = self._find_xpath("/html/head/title")
        titles = [element.all_text for element in elements]
        return titles[0] if len(titles) else ""

Response: str - The title for the current frame.


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

        if self.tag_name == "textarea":
            return inner_content(self.native)
        elif self.tag_name == "select":
            if self["multiple"] == "multiple":
                selected_options = self._find_xpath(".//option[@selected='selected']")
                return [_get_option_value(option) for option in selected_options]
            else:
                options = (
                    self._find_xpath(".//option[@selected='selected']") +
                    self._find_xpath(".//option"))
                return _get_option_value(options[0]) if options else None
        elif self.tag_name == "input" and self["type"] in ["checkbox", "radio"]:
            return self["value"] or "on"
        else:
            return self["value"]

Response: str - The value of the form element.


Instruction:
Can you generate the documentation for the following Python 3 function
def add_filter_set(name):

    factory = FilterSetFactory(name)
    yield factory
    filter_sets[name] = factory.build_filter_set()

Response: A context manager that builds and registers a global filter set.