def Func(arg_0, arg_1, arg_2,
                              arg_3=False,
                              arg_4=True,
                              arg_5=None):
        """Apply 'check' methods on `r`."""

        for arg_6 in dir(arg_0):
            if arg_6.startswith('check'):
                arg_7 = arg_0._as_dict(arg_2)
                arg_8 = getattr(arg_0, arg_6)
                try:
                    arg_8(arg_7)
                except RecordError as e:
                    arg_9 = e.code if e.code is not None else RECORD_CHECK_FAILED
                    arg_10 = {'code': arg_9}
                    if not arg_3:
                        arg_11 = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED]
                        arg_10['message'] = arg_11
                        arg_10['row'] = arg_1 + 1
                        arg_10['record'] = arg_2
                        if arg_5 is not None: arg_10['context'] = arg_5
                        if e.details is not None: arg_10['details'] = e.details
                    yield arg_10
                except Exception as e:
                    if arg_4:
                        arg_10 = {'code': UNEXPECTED_EXCEPTION}
                        if not arg_3:
                            arg_10['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)
                            arg_10['row'] = arg_1 + 1
                            arg_10['record'] = arg_2
                            arg_10['exception'] = e
                            arg_10['function'] = '%s: %s' % (arg_8.__name__,
                                                        arg_8.__doc__)
                            if arg_5 is not None: arg_10['context'] = arg_5
                        yield arg_10


def Func(arg_0, arg_1, arg_2,
                     arg_3=False,
                     arg_4=True,
                     arg_5=None):
        """Apply skip functions on `r`."""

        for arg_6 in arg_0._skips:
            try:
                arg_7 = arg_6(arg_2)
                if arg_7 is True:
                    yield True
            except Exception as e:
                if arg_4:
                    arg_8 = {'code': UNEXPECTED_EXCEPTION}
                    if not arg_3:
                        arg_8['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)
                        arg_8['row'] = arg_1 + 1
                        arg_8['record'] = arg_2
                        arg_8['exception'] = e
                        arg_8['function'] = '%s: %s' % (arg_6.__name__,
                                                    arg_6.__doc__)
                        if arg_5 is not None: arg_8['context'] = arg_5
                    yield arg_8


def Func():
    """Create an example CSV validator for patient demographic data."""

    arg_0 = (
                   'study_id',
                   'patient_id',
                   'gender',
                   'age_years',
                   'age_months',
                   'date_inclusion'
                   )
    arg_1 = CSVValidator(arg_0)

    # basic header and record length checks
    arg_1.add_header_check('EX1', 'bad header')
    arg_1.add_record_length_check('EX2', 'unexpected record length')

    # some simple value checks
    arg_1.add_value_check('study_id', int,
                              'EX3', 'study id must be an integer')
    arg_1.add_value_check('patient_id', int,
                              'EX4', 'patient id must be an integer')
    arg_1.add_value_check('gender', enumeration('M', 'F'),
                              'EX5', 'invalid gender')
    arg_1.add_value_check('age_years', number_range_inclusive(0, 120, int),
                              'EX6', 'invalid age in years')
    arg_1.add_value_check('date_inclusion', datetime_string('%Y-%m-%d'),
                              'EX7', 'invalid date')

    # a more complicated record check
    def check_age_variables(arg_2):
        arg_3 = int(arg_2['age_years'])
        arg_4 = int(arg_2['age_months'])
        arg_5 = (arg_4 >= arg_3 * 12 and
                 arg_4 % arg_3 < 12)
        if not arg_5:
            raise RecordError('EX8', 'invalid age variables')
    arg_1.add_record_check(check_age_variables)

    return arg_1


def Func(arg_0, arg_1, arg_2, arg_3):
    "Recursively create and set the drop target for obj and childs"
    if arg_0._meta.container:
        arg_4 = ToolBoxDropTarget(arg_0, arg_1, arg_2=arg_2,
                                          arg_3=arg_3)
        arg_0.drop_target = arg_4
    for arg_6 in arg_0:
        Func(arg_6, arg_1, arg_2, arg_3)


def Func(arg_0, arg_1):
        "Event handler for drag&drop functionality"

        # get the control
        arg_2 = arg_0.menu_ctrl_map[arg_1.GetToolId()]

        # create our own data format and use it in a custom data object
        arg_3 = wx.CustomDataObject("gui")
        arg_3.SetData(arg_2._meta.name)      # only strings are allowed!

        # Also create a Bitmap version of the drawing
        arg_4 = arg_2._image.GetBitmap()

        # Now make a data object for the bitmap and also a composite
        # data object holding both of the others.
        arg_5 = wx.BitmapDataObject(arg_4)
        arg_6 = wx.DataObjectComposite()
        arg_6.Add(arg_3)
        arg_6.Add(arg_5)

        # And finally, create the drop source and begin the drag
        # and drop opperation
        arg_7 = wx.DropSource(arg_0)
        arg_7.SetData(arg_6)
        if DEBUG: print("Begining DragDrop\n")
        arg_8 = arg_7.DoDragDrop(wx.Drag_AllowMove)
        if DEBUG: print("DragDrop completed: %d\n" % arg_8)

        if arg_8 == wx.DragMove:
            if DEBUG: print "dragmove!"
            arg_0.Refresh()


def Func(arg_0, arg_1, arg_2, arg_3):
        "track default top level window for toolbox menu default action"
        arg_0.designer = arg_2
        arg_0.inspector = arg_3


def Func(arg_0):
    "Open the Funcor windows for a given object"
    from gui.tools.Funcor import InspectorTool
    arg_1 = InspectorTool()
    arg_1.show(arg_0)
    return arg_1


def Func(arg_0, arg_1):
        "Loads HTML page from location and then displays it"
        if not arg_1:
            arg_0.wx_obj.SetPage("")
        else:
            arg_0.wx_obj.LoadPage(arg_1)


def Func(arg_0):
    "Process an outgoing communication"
    # get the text written by the user (input textbox control)
    arg_1 = arg_2.value
    # Func the message (replace with socket/queue/etc.)
    gui.alert(arg_1, "Message")
    # record the message (update the UI)
    log(arg_1)
    arg_2.value = ""
    arg_2.set_focus()


def Func(arg_0, arg_1, arg_2, (arg_3, arg_4, arg_5, arg_6)):
        "Called by SelectionTag"
        # calculate the pos (minus the offset, not in a panel like rw!)
        arg_7 = arg_2.ScreenToClient(wx.GetMousePosition())
        arg_8, arg_9 = arg_7
        if arg_1.ShiftDown():     # snap to grid:
            arg_8 = arg_8 / GRID_SIZE[0] * GRID_SIZE[0]
            arg_9 = arg_9 / GRID_SIZE[1] * GRID_SIZE[1]
        arg_7 = wx.Point(arg_8, arg_9)
        if not arg_0.resizing or arg_0.resizing != (arg_2, (arg_3, arg_4, arg_5, arg_6)):
            arg_0.pos = list(arg_7)                        # store starting point
            arg_0.resizing = (arg_2, (arg_3, arg_4, arg_5, arg_6))      # track obj and handle
        else:
            arg_11 = arg_7 - arg_0.pos
            if DEBUG: print "RESIZING: n, w, s, e", arg_3, arg_4, arg_5, arg_6
            if arg_3 or arg_4 or arg_5 or arg_6:
                # resize according the direction (n, w, s, e)
                arg_8 = arg_2.Position[0] + arg_6 * arg_11[0]
                arg_9 = arg_2.Position[1] + arg_3 * arg_11[1]
                if arg_4 or arg_6:
                    if not isinstance(arg_2, wx.TopLevelWindow):
                        arg_12 = arg_2.Size[0] + (arg_4 - arg_6) * arg_11[0]
                    else:
                        arg_12 = arg_2.ClientSize[0] + (arg_4 - arg_6) * arg_11[0]
                else:
                    arg_12 = None
                if arg_3 or arg_5:
                    arg_13 = arg_2.Size[1] + (arg_5 - arg_3) * arg_11[1]
                else:
                    arg_13 = None
            else:
                # just move
                arg_8 = arg_2.Position[0] + arg_11[0]
                arg_9 = arg_2.Position[1] + arg_11[1]
                arg_12 = arg_13 = None
            arg_14 = (arg_8, arg_9)
            arg_15 = (arg_12, arg_13)
            if arg_15 != arg_2.GetSize() or arg_14 != arg_2.GetPosition():
                # reset margins (TODO: avoid resizing recursion)
                arg_2.obj.margin_left = 0
                arg_2.obj.margin_right = 0
                arg_2.obj.margin_top = 0
                arg_2.obj.margin_bottom = 0
                arg_2.obj.pos = arg_14      # update gui specs (position)
                # update gui specs (size), but do not alter default value
                if arg_12 is not None and arg_13 is not None:
                    arg_2.obj.width = arg_12
                    arg_2.obj.height = arg_13
                elif arg_12 is not None:
                    arg_2.obj.width = arg_12
                elif arg_13 is not None:
                    arg_2.obj.height = arg_13
                # only update on sw for a smooth resize
                if arg_4:
                    arg_0.pos[0] = arg_7[0]        # store new starting point
                if arg_5:
                    arg_0.pos[1] = arg_7[1]


def Func(arg_0, arg_1):
        "support cursor keys to move components one pixel at a time"
        arg_2 = arg_1.GetKeyCode()
        if arg_2 in (wx.WXK_LEFT, wx.WXK_UP, wx.WXK_RIGHT, wx.WXK_DOWN):
            for arg_3 in arg_0.selection:
                arg_4, arg_5 = arg_3.pos
                if arg_1.ShiftDown():     # snap to grid:t
                    # for now I'm only going to align to grid
                    # in the direction of the cursor movement
                    if arg_2 == wx.WXK_LEFT:
                        arg_4 = (arg_4 - GRID_SIZE[0]) / GRID_SIZE[0] * GRID_SIZE[0]
                    elif arg_2 == wx.WXK_RIGHT:
                        arg_4 = (arg_4 + GRID_SIZE[0]) / GRID_SIZE[0] * GRID_SIZE[0]
                    elif arg_2 == wx.WXK_UP:
                        arg_5 = (arg_5 - GRID_SIZE[1]) / GRID_SIZE[1] * GRID_SIZE[1]
                    elif arg_2 == wx.WXK_DOWN:
                        arg_5 = (arg_5 + GRID_SIZE[1]) / GRID_SIZE[1] * GRID_SIZE[1]
                else:
                    if arg_2 == wx.WXK_LEFT:
                        arg_4 = arg_4 - 1
                    elif arg_2 == wx.WXK_RIGHT:
                        arg_4 = arg_4 + 1
                    elif arg_2 == wx.WXK_UP:
                        arg_5 = arg_5 - 1
                    elif arg_2 == wx.WXK_DOWN:
                        arg_5 = arg_5 + 1
                arg_3.pos = (arg_4, arg_5)
        elif arg_2 == wx.WXK_DELETE:
            arg_0.delete(arg_1)
        elif arg_2 == wx.WXK_INSERT:
            arg_0.duplicate(arg_1)
        else:
            if DEBUG: print "KEY:", arg_2


def Func(arg_0):
        "Capture the new control superficial image after an update"
        arg_0.bmp = arg_0.obj.snapshot()
        # change z-order to overlap controls (windows) and show the image:
        arg_0.Raise()
        arg_0.Show()
        arg_0.Refresh()


def Func(arg_0,arg_1):
        "When dealing with a Top-Level window position it absolute lower-right"
        if isinstance(arg_1, wx.Frame):
            arg_2 = wx.ClientDisplayRect()[2:]
            arg_3,arg_4 = arg_1.ClientToScreenXY(0,0)
            arg_5,arg_6 = arg_1.ClientToScreenXY(*arg_1.GetClientRect()[2:])
            arg_7 = arg_0.GetSize()
            arg_8 = arg_5
            arg_9 = arg_6 - arg_7[1]
            arg_0.SetPosition((arg_8,arg_9))
        else:
            STT.ToolTipWindow.Func(arg_0, arg_1)


def Func(arg_0, arg_1):
        "Returns the pyth item data associated with the item"
        arg_2 = arg_0.GetItemData(arg_1)
        arg_3 = arg_0._py_data_map.get(arg_2)
        return arg_3


def Func(arg_0, arg_1, arg_2):
        "Set the python item data associated wit the wx item"
        arg_3 = wx.NewId()                           # create a suitable key
        arg_0.SetItemData(arg_1, arg_3)   # store it in wx
        arg_0._py_data_map[arg_3] = arg_2           # map it internally
        arg_0._wx_data_map[arg_2] = arg_3           # reverse map
        return arg_3


def Func(arg_0, arg_1):
        "Remove the item from the list and unset the related data"
        arg_2 = arg_0.GetItemData(arg_1)
        arg_3 = arg_0._py_data_map[arg_2]
        del arg_0._py_data_map[arg_2]
        del arg_0._wx_data_map[arg_3]
        wx.ListCtrl.Func(arg_0, arg_1)


def Func(arg_0):
        "Remove all items and column headings"
        arg_0.clear()
        for arg_1 in reversed(arg_0.columns):
            del arg_0[arg_1.name]


def Func(arg_0):
        "Returns the label of the selected item or an empty string if none"
        if arg_0.multiselect:
            return [arg_0.wx_obj.GetString(arg_1) for arg_1 in
                    arg_0.wx_obj.GetSelections()]
        else:
            return arg_0.wx_obj.GetStringSelection()


def Func(arg_0, arg_1, arg_2="", arg_3=0, arg_4=False, arg_5=80):
    "Construct a string Funcing the object"
    try:
        arg_6 = getattr(arg_0, "name", "")
        arg_7 = "%s.%s" % (arg_1, arg_0.__class__.__name__)
        arg_8 = len(arg_7) + 1 + arg_3 * 4 + (5 if arg_4 else 0)
        arg_9 = []
        for (arg_10, arg_11) in sorted(arg_0._meta.specs.items(), key=get_sort_key):
            if arg_10 == "index":        # index is really defined by creation order
                continue            # also, avoid infinite recursion
            if arg_10 == "parent" and arg_2 != "":
                arg_12 = arg_2
            else:
                arg_12 = getattr(arg_0, arg_10, "")
                if (not isinstance(arg_11, InternalSpec)
                    and arg_12 != arg_11.default
                    and (arg_10 != 'id' or arg_12 > 0)
                    and isinstance(arg_12,
                         (basestring, int, long, float, bool, dict, list,
                          decimal.Decimal,
                          datetime.datetime, datetime.date, datetime.time,
                          Font, Color))
                    and repr(arg_12) != 'None'
                    ):
                    arg_12 = repr(arg_12)
                else:
                    arg_12 = None
            if arg_12 is not None:
                arg_9.append("%s=%s" % (arg_10, arg_12))
        arg_13 = []
        arg_14 = ""
        for arg_15 in arg_9:
            if len(arg_14 + arg_15) + 3 > arg_5 - arg_8:
                arg_13.append(arg_14)
                arg_14 = ""
            arg_14 += arg_15 + ", "
        arg_13.append(arg_14)
        arg_16 = ("\n%s" % (" " * arg_8)).join(arg_13)
        return "%s(%s)" % (arg_7, arg_16)
    except:
        raise
        # uninitialized, use standard Funcation to not break debuggers
        return object.__repr__(arg_0)


def Func(arg_0, arg_1=None):
        "Create a new object exactly similar to self"
        arg_2 = {}
        for arg_3, arg_4 in arg_0._meta.specs.items():
            arg_5 = getattr(arg_0, arg_3)
            if isinstance(arg_5, Color):
                print "COLOR", arg_5, arg_5.default
                if arg_5.default:
                    arg_5 = None
            if arg_5 is not None:
                arg_2[arg_3] = arg_5
        del arg_2['parent']
        arg_6 = wx.NewId()
        arg_2['id'] = arg_6
        arg_2['name'] = "%s_%s" % (arg_2['name'], arg_6)
        arg_7 = arg_0.__class__(arg_1 or arg_0.get_parent(), **arg_2)
        # recursively create a copy of each child (in the new parent!)
        for arg_8 in arg_0:
            arg_8.Func(arg_7)
        return arg_7


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


def Func(arg_0, arg_1, arg_2=False):
        "Re-parent a child control with the new wx_obj parent"
        Component.Func(arg_0, arg_1, arg_2)
        # if not called from constructor, we must also reparent in wx:
        if not arg_2:
            if DEBUG: print "reparenting", ctrl.name
            if hasattr(arg_0.wx_obj, "Reparent"):
                arg_0.wx_obj.Reparent(arg_0._parent.wx_obj)


def Func(arg_0, arg_1):
        "make several copies of the background bitmap"
        arg_2 = arg_0.wx_obj.GetClientSize()
        arg_3 = arg_0._bitmap.get_bits()
        arg_4 = arg_3.GetWidth()
        arg_5 = arg_3.GetHeight()

        if isinstance(arg_0, wx.ScrolledWindow):
            # adjust for scrolled position
            arg_6, arg_7 = arg_0.wx_obj.GetScrollPixelsPerUnit()
            arg_8, arg_9 = arg_0.wx_obj.GetViewStart()
            arg_10,  arg_11  = (arg_6 * arg_8) % arg_4, (arg_7 * arg_9) % arg_5
        else:
            arg_10, arg_11 = (arg_4, arg_5)

        arg_12 = -arg_10
        while arg_12 < arg_2.width:
            arg_13 = -arg_11
            while arg_13 < arg_2.height:
                arg_1.DrawBitmap(arg_3, arg_12, arg_13)
                arg_13 = arg_13 + arg_5
            arg_12 = arg_12 + arg_4


def Func(arg_0, arg_1):
        "Draw the image as background"
        if arg_0._bitmap:
            arg_2 = arg_1.GetDC()

            if not arg_2:
                arg_2 = wx.ClientDC(arg_0)
                arg_3 = arg_0.wx_obj.GetUpdateRegion().GetBox()
                arg_2.SetClippingRegion(arg_3.x, arg_3.y, arg_3.width, arg_3.height)

            if arg_0._background_tiling:
                arg_0.__tile_background(arg_2)
            else:
                arg_2.DrawBitmapPoint(arg_0._bitmap.get_bits(), (0, 0))


def Func(arg_0, arg_1):
        "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
        arg_2 = wx.GCDC(wx.PaintDC(arg_0.wx_obj))
        arg_2.SetFont(arg_0.wx_obj.GetFont())
        arg_2.SetTextForeground(arg_0.wx_obj.GetForegroundColour())
        arg_2.DrawText(arg_0.wx_obj.GetLabel(), 0, 0)


def Func(arg_0, arg_1):
    """
    Look for every file in the directory tree and return a dict
    Hacked from sphinx.autodoc
    """

    arg_2 = '__init__.py'

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

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

    arg_7 = []
    for arg_8 in arg_1.keys():
        if arg_1[arg_8] is None: arg_7.append(arg_8)

    arg_9 = {}
    arg_10 = 0
    arg_11 = 0
    def save(arg_5, arg_12):
        arg_6 = arg_5+ "."+ arg_12

        for arg_13 in arg_7:
            if arg_6.startswith(arg_13):
                print "Skipping "+arg_6
                return False
        if arg_1.has_key(arg_5):
            if arg_12 in arg_1[arg_5]:
                print "Skipping "+arg_6
                return False
        if not arg_9.has_key(arg_5):
            arg_9[arg_5] = []
        arg_9[arg_5].append(arg_12)
        return True

    for arg_14, arg_15, arg_16 in os.walk(arg_0):
        arg_17 = sorted([f for f in arg_16 if os.path.splitext(f)[1] == '.py'])

        if arg_2 in arg_17:
            arg_18 = arg_14[len(arg_0):].lstrip(os.path.sep).\
                replace(os.path.sep, '.')
            arg_19 = makename(arg_3, arg_18)
            arg_20 = arg_19.rpartition('.')
            arg_21, arg_12 = arg_20[0], arg_20[2]
            arg_11 += 1
            if save(arg_21, arg_12): arg_10 += 1

            arg_17.remove(arg_2)
            for arg_22 in arg_17:
                arg_11 += 1
                arg_5 = os.path.splitext(arg_22)[0]
                if save(arg_19, arg_5): arg_10 += 1
    for arg_23 in arg_9.keys():
        arg_9[arg_23].sort()
    print "%s contains %i submodules, %i skipped" % \
          (arg_3, arg_11, arg_11-arg_10)

    return arg_9


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


def Func(arg_0, arg_1):
        "Update the grid if rows and columns have been added or deleted"
        arg_1.BeginBatch()

        for arg_2, arg_3, arg_4, arg_5 in [
            (arg_0._rows, arg_0.GetNumberRows(),
             gridlib.GRIDTABLE_NOTIFY_ROWS_DELETED,
             gridlib.GRIDTABLE_NOTIFY_ROWS_APPENDED),
            (arg_0._cols, arg_0.GetNumberCols(),
             gridlib.GRIDTABLE_NOTIFY_COLS_DELETED,
             gridlib.GRIDTABLE_NOTIFY_COLS_APPENDED),
        ]:

            if arg_3 < arg_2:
                arg_6 = gridlib.GridTableMessage(arg_0,arg_4,arg_3,arg_2-arg_3)
                arg_1.ProcessTableMessage(arg_6)
            elif arg_3 > arg_2:
                arg_6 = gridlib.GridTableMessage(arg_0,arg_5,arg_3-arg_2)
                arg_1.ProcessTableMessage(arg_6)
                arg_0.UpdateValues(arg_1)

        arg_1.EndBatch()

        arg_0._rows = arg_0.GetNumberRows()
        arg_0._cols = arg_0.GetNumberCols()
        # update the column rendering plugins
        arg_0._updateColAttrs(arg_1)

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


def Func(arg_0, arg_1):
        "update the column attributes to add the appropriate renderer"
        arg_2 = 0

        for arg_3 in arg_0.columns:
            arg_4 = gridlib.GridCellAttr()
            if False:  # column.readonly
                arg_4.SetReadOnly()
            if False:  # column.renderer
                arg_4.SetRenderer(renderer)
            arg_1.SetColSize(arg_2, arg_3.width)
            arg_1.SetColAttr(arg_2, arg_4)
            arg_2 += 1


def Func(arg_0, arg_1):
        "col -> sort the data based on the column indexed by col"
        arg_2 = arg_0.columns[arg_1].name
        arg_3 = []

        for arg_4 in arg_0.data:
            arg_5, arg_6 = arg_4
            arg_3.append((arg_6.get(arg_2, None), arg_4))

        arg_3.sort()
        arg_0.data = []

        for arg_8, arg_4 in arg_3:
            arg_0.data.append(arg_4)


def Func(arg_0):
        "Remove all rows and reset internal structures"
        ## list has no Func ... remove items in reverse order
        for arg_1 in range(len(arg_0)-1, -1, -1):
            del arg_0[arg_1]
        arg_0._key = 0
        if hasattr(arg_0._grid_view, "wx_obj"):
            arg_0._grid_view.wx_obj.ClearGrid()


def Func(arg_0, arg_1, arg_2, arg_3):
        "Fetch the value from the table and prepare the edit control"
        arg_0.startValue = arg_3.GetTable().GetValue(arg_1, arg_2)
        arg_5 = arg_3.GetTable().columns[arg_2]._choices
        arg_0._tc.Clear()
        arg_0._tc.AppendItems(arg_5)
        arg_0._tc.SetStringSelection(arg_0.startValue)
        arg_0._tc.SetFocus()


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        "Complete the editing of the current cell. Returns True if changed"
        arg_5 = False
        arg_4 = arg_0._tc.GetStringSelection()
        print "val", arg_4, arg_1, arg_2, arg_0.startValue
        if arg_4 != arg_0.startValue:
            arg_5 = True
            arg_3.GetTable().SetValue(arg_1, arg_2, arg_4) # update the table
        arg_0.startValue = ''
        arg_0._tc.SetStringSelection('')
        return arg_5


def Func(arg_0, arg_1):
        "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_Func(evt)
        return (not (arg_1.ControlDown() or arg_1.AltDown()) and
                arg_1.GetKeyCode() != wx.WXK_SHIFT)


def Func(arg_0, arg_1):
        "This will be called to let the editor do something with the first key"
        arg_2 = arg_1.GetKeyCode()
        arg_3 = None
        if arg_2 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]:
            arg_3 = arg_3 = chr(ord('0') + arg_2 - wx.WXK_NUMPAD0)
        elif arg_2 < 256 and arg_2 >= 0 and chr(arg_2) in string.printable:
            arg_3 = chr(arg_2)
            if not arg_1.ShiftDown():
                arg_3 = arg_3.lower()
        if arg_3 is not None:
            arg_0._tc.SetStringSelection(arg_3)
        else:
            arg_1.Skip()


def Func(arg_0):
    """ A metaclass generator. Returns a metaclass which
    will register it's class as the class that handles input type=typeName
    """
    def metaclass(arg_1, arg_2, arg_3):
        arg_4 = type(arg_1, arg_2, arg_3)
        form.FormTagHandler.register_type(arg_0.upper(), arg_4)
        return arg_4
    return metaclass


def Func(arg_0, arg_1):
        "enable or disable all menu items"
        for arg_2 in range(arg_0.GetMenuItemCount()):
            arg_3 = arg_0.FindItemByPosition(arg_2)
            arg_3.Func(arg_1)


def Func(arg_0, arg_1):
        "enable or disable all top menus"
        for arg_2 in range(arg_0.GetMenuCount()):
            arg_0.FuncTop(arg_2, arg_1)


def Func(arg_0, *arg_1, **arg_2):
        "check if all top menus are enabled"
        for arg_3 in range(arg_0.GetMenuCount()):
            if not arg_0.FuncTop(arg_3):
                return False
        return True


def Func(arg_0, arg_1):
        "Helper method to remove a menu avoiding using its position"
        arg_2 = arg_0.GetMenus()     # get the list of (menu, title)
        arg_2 = [submenu for submenu in arg_2 if submenu[0] != arg_1]
        arg_0.SetMenus(arg_2)


def Func(arg_0, arg_1=None):
        "Process form submission"
        arg_2 = arg_0.build_data_set()
        if arg_1 and arg_1.name:
            arg_2[arg_1.name] = arg_1.name
        arg_4 = FormSubmitEvent(arg_0, arg_2)
        arg_0.container.ProcessEvent(arg_4)


def Func(arg_0, arg_1, arg_2):
        """ Add a tag attribute to the wx window """
        arg_1._attributes = {}
        arg_1._name = arg_2.GetName().lower()
        for arg_5 in arg_0.attributes:
            arg_1._attributes["_%s" % arg_5] = arg_2.GetParam(arg_5)
            if arg_1._attributes["_%s" % arg_5] == "":
                arg_1._attributes["_%s" % arg_5] = None


def Func(arg_0, arg_1):
    """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(arg_0):
        # ModuleDocumenter.can_document_member always returns False
        return ModuleDocumenter

    # Construct a fake documenter for *parent*
    if arg_1 is not None:
        arg_2 = Func(arg_1, None)
    else:
        arg_2 = ModuleDocumenter

    if hasattr(arg_1, '__name__'):
        arg_3 = arg_2(FakeDirective(), arg_1.__name__)
    else:
        arg_3 = arg_2(FakeDirective(), "")

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


def Func(arg_0, arg_1=30):
    """Reformat a function signature to a more compact form."""
    arg_2 = re.sub(r"^\((.*)\)$", r"\1", arg_0).strip()

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

    # Parse the signature to arguments + options
    arg_3 = []
    arg_4 = []

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

        arg_4.insert(0, arg_6.group(2))
        arg_2 = arg_6.group(1)[:-2]

    # Produce a more compact signature
    arg_0 = limited_join(", ", arg_3, arg_1=arg_1-2)
    if arg_4:
        if not arg_0:
            arg_0 = "[%s]" % limited_join(", ", arg_4, arg_1=arg_1-4)
        elif len(arg_0) < arg_1 - 4 - 2 - 3:
            arg_0 += "[, %s]" % limited_join(", ", arg_4,
                                           arg_1=arg_1-len(arg_0)-4-2)

    return u"(%s)" % arg_0


def Func(arg_0):
    """Import a Python object given its full name."""
    try:
        arg_1 = arg_0.split('.')

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

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

        if arg_4 < len(arg_1):
            arg_6 = None
            arg_7 = sys.modules[arg_2]
            for arg_8 in arg_1[arg_4:]:
                arg_6 = arg_7
                arg_7 = getattr(arg_7, arg_8)
            return arg_7, arg_6
        else:
            return sys.modules[arg_2], None
    except (ValueError, ImportError, AttributeError, KeyError), e:
        raise ImportError(*e.args)


def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                  arg_5={}, arg_6=[]):
    """Smart linking role.

    Expands to ':obj:`text`' if `text` is an object that can be imported;
    otherwise expands to '*text*'.
    """
    arg_7 = arg_4.document.settings.env
    arg_8 = arg_7.get_domain('py').role('obj')(
        'obj', arg_1, arg_2, arg_3, arg_4, arg_5, arg_6)
    arg_9 = arg_8[0][0]

    arg_10 = get_import_prefixes_from_env(arg_7)
    try:
        arg_11, arg_12, arg_13 = import_by_name(arg_9['reftarget'], arg_10)
    except ImportError:
        arg_6 = arg_9[0]
        arg_8[0][0] = nodes.emphasis(arg_1, arg_6[0].astext(),
                                 classes=arg_6['classes'])
    return arg_8


def Func(arg_0="", arg_1="", arg_2=None, arg_3=None):
    "Show a dialog to select a font"
    if arg_2 is not None:
        arg_4 = arg_2._get_wx_font()                   # use as default
    else:
        arg_4 = None
        arg_2 = Font()                                   # create an empty font
    arg_5 = dialogs.fontDialog(arg_3, arg_2=arg_4)
    if arg_5.accepted:
        arg_6 = arg_5.fontData
        arg_5.color = arg_5.fontData.GetColour().Get()
        arg_4 = arg_5.fontData.GetChosenFont()
        arg_2.set_wx_font(arg_4)
        arg_4 = None
        return arg_2


def Func(arg_0="", arg_1="", arg_2=None, arg_3=None):
    "Show a dialog to pick a color"
    arg_4 = dialogs.colorDialog(arg_3, arg_2=arg_2)
    return arg_4.accepted and arg_4.color


def Func(arg_0='Choose a directory', arg_1="", arg_2=None):
    "Show a dialog to choose a directory"
    arg_3 = dialogs.directoryDialog(arg_2, arg_0, arg_1)
    return arg_3.path


def Func(arg_0='', arg_1=0, arg_2=0, arg_3=None):
    "Shows a Func text dialog"
    arg_4 = dialogs.FuncDialog(arg_3, arg_0, arg_1, arg_2)
    return {'text': arg_4.searchText, 'whole_words': arg_4.wholeWordsOnly,
            'case_sensitive': arg_4.caseSensitive}


def Func(arg_0, arg_1=None):
        """Set icon based on resource values"""
        if arg_1 is not None:
            try:
                arg_2 = wx.Icon(arg_1, wx.BITMAP_TYPE_ICO)
                arg_0.wx_obj.SetIcon(arg_2)
            except:
                pass


def Func(arg_0, arg_1=True, arg_2=None):
        "Display or hide the window, optionally disabling all other windows"
        arg_0.wx_obj.Show(arg_1)
        if arg_2:
            # disable all top level windows of this application (MakeModal)
            arg_3 = wx.WindowDisabler(arg_0.wx_obj)
            # create an event loop to stop execution
            arg_4 = wx.EventLoop()
            def on_close_modal(arg_5):
                arg_5.Skip()
                arg_4.Exit()
            arg_0.wx_obj.Bind(wx.EVT_CLOSE, on_close_modal)
            # start the event loop to wait user interaction
            arg_4.Run()
            # reenable the windows disabled and return control to the caller
            del arg_3


def Func(arg_0=""):
    "Open, read and eval the resource from the source file"
    # use the provided resource file:
    arg_1 = open(arg_0).read()
    ##s.decode("latin1").encode("utf8")
    import datetime, decimal
    arg_2 = eval(arg_1)
    return arg_2


def Func(arg_0, arg_1):
    "Save the resource to the source file"
    arg_2 = pprint.pformat(arg_1)
    ## s = s.encode("utf8")
    open(arg_0, "w").write(arg_2)


def Func(arg_0):
    "Create a gui2py window based on the python resource"

    # windows specs (parameters)
    arg_1 = dict(arg_0.items())
    arg_2 = arg_1.pop('type')
    arg_3 = arg_1.pop('menubar', None)
    arg_4 = arg_1.pop('components')
    arg_5 = arg_1.pop('panel', {})

    from gui import registry
    import gui

    arg_6 = registry.WINDOWS[arg_2]
    arg_7 = arg_6(**arg_1)

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

    if arg_4:
        for arg_9 in arg_4:
            build_component(arg_9, parent=arg_8)

    if arg_3:
        arg_10 = gui.MenuBar(name="menu", parent=arg_7)
        for arg_11 in arg_3:
            build_component(arg_11, parent=arg_10)
    return arg_7


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


def Func(arg_0, arg_1, arg_2=False, arg_3=False, arg_4=None):
        "Select the object and show its properties"
        arg_5 = arg_0.tree.FindItem(arg_0.root, arg_1.name)
        if DEBUG: print "Func child", arg_5
        if arg_5:
            arg_0.tree.ScrollTo(arg_5)
            arg_0.tree.SetCurrentItem(arg_5)
            arg_0.tree.SelectItem(arg_5)
            arg_5.Selected = True
            arg_0.activate_item(arg_5, arg_3)
            if arg_2:
                arg_0.show_context_menu(arg_5, arg_4)


def Func(arg_0, arg_1, arg_2=False, arg_3=False):
        "load the selected item in the property editor"
        arg_4 = arg_0.tree.GetItemData(arg_1)
        if arg_4:
            arg_5 = arg_4.GetData()
            arg_0.selected_obj = arg_5
            arg_7 = lambda arg_5=arg_5, **kwargs: arg_0.update(arg_5, **kwargs)
            arg_0.propeditor.load_object(arg_5, arg_7)
            if arg_2:
                wx.CallAfter(arg_0.propeditor.edit)
            if arg_3 and arg_0.designer:
                arg_0.designer.select(arg_5)
        else:
            arg_0.selected_obj = None


def Func(arg_0, arg_1, arg_2, *arg_3, **arg_4):
    """Pack given values v1, v2, ... into given bytearray `buf`, starting
    at given bit offset `offset`. Pack according to given format
    string `fmt`. Give `fill_padding` as ``False`` to leave padding
    bits in `buf` unmodified.

    """

    return CompiledFormat(arg_0).Func(arg_1,
                                         arg_2,
                                         *arg_3,
                                         **arg_4)


def Func(arg_0, arg_1, arg_2=0):
    """Swap bytes in `data` according to `fmt`, starting at byte `offset`
    and return the result. `fmt` must be an iterable, iterating over
    number of bytes to swap. For example, the format string ``'24'``
    applied to the bytes ``b'\\x00\\x11\\x22\\x33\\x44\\x55'`` will
    produce the result ``b'\\x11\\x00\\x55\\x44\\x33\\x22'``.

    """

    arg_1 = BytesIO(arg_1)
    arg_1.seek(arg_2)
    arg_3 = BytesIO()

    for arg_4 in arg_0:
        arg_5 = arg_1.read(int(arg_4))[::-1]
        arg_3.write(arg_5)

    return arg_3.getvalue()


def Func(arg_0, arg_1):
        '''
        Telegram chat type can be either "private", "group", "supergroup" or
        "channel".
        Return user ID if it is of type "private", chat ID otherwise.
        '''
        if arg_1.chat.type == 'private':
            return arg_1.user.id

        return arg_1.chat.id


def Func(arg_0, arg_1):
        '''
        Return a Message instance according to the data received from
        Facebook Messenger API.
        '''
        if not arg_1:
            return None

        return Message(
            id=arg_1['message']['mid'],
            platform=arg_0.platform,
            text=arg_1['message']['text'],
            user=arg_1['sender']['id'],
            timestamp=arg_1['timestamp'],
            raw=arg_1,
            chat=None,  # TODO: Refactor Funcs and Message class
        )


async def Func(arg_0, arg_1):
        """
        Get response running the view with await syntax if it is a
        coroutine function, otherwise just run it the normal way.
        """

        arg_2 = arg_0.discovery_view(arg_1)
        if not arg_2:
            return

        if inspect.iscoroutinefunction(arg_2):
            arg_3 = await arg_2(arg_1)
        else:
            arg_3 = arg_2(arg_1)

        return arg_0.prepare_response(arg_3, arg_1)


def Func(arg_0, arg_1):
        """
        Use the new message to search for a registered view according
        to its pattern.
        """
        for arg_2 in arg_0.registered_handlers:
            if arg_2.check(arg_1):
                return arg_2.view

        return None


def Func(arg_0, arg_1):
    """Read mat 5 file header of the file fd.
    Returns a dict with header values.
    """
    arg_2 = [
        ('description', 's', 116),
        ('subsystem_offset', 's', 8),
        ('version', 'H', 2),
        ('endian_test', 's', 2)
    ]
    arg_3 = {}
    for arg_4, arg_5, arg_6 in arg_2:
        arg_7 = arg_0.read(arg_6)
        arg_3[arg_4] = unpack(arg_1, arg_5, arg_7)
    arg_3['description'] = arg_3['description'].strip()
    arg_8 = arg_3['version'] >> 8
    arg_9 = arg_3['version'] & 0xFF
    arg_3['__version__'] = '%d.%d' % (arg_8, arg_9)
    return arg_3


def Func(arg_0, arg_1):
    """Read full header tag.

    Return a dict with the parsed header, the file position of next tag,
    a file like object for reading the uncompressed element data.
    """
    arg_2, arg_3 = unpack(arg_1, 'II', arg_0.read(8))
    arg_4 = arg_0.tell() + arg_3

    if arg_2 == etypes['miCOMPRESSED']['n']:
        # read compressed data
        arg_5 = arg_0.read(arg_3)
        arg_6 = zlib.decompressobj()
        # from here, read of the decompressed data
        arg_7 = BytesIO(arg_6.decompress(arg_5))
        del arg_5
        arg_0 = arg_7
        # Check the stream is not so broken as to leave cruft behind
        if arg_6.flush() != b'':
            raise ParseError('Error in compressed data.')
        # read full tag from the uncompressed data
        arg_2, arg_3 = unpack(arg_1, 'II', arg_0.read(8))

    if arg_2 != etypes['miMATRIX']['n']:
        raise ParseError('Expecting miMATRIX type number {}, '
                         'got {}'.format(etypes['miMATRIX']['n'], arg_2))
    # read the header
    arg_8 = read_header(arg_0, arg_1)
    return arg_8, arg_4, arg_0


def Func(arg_0, arg_1, arg_2, arg_3):
    """Read a numeric matrix.
    Returns an array with rows of the numeric matrix.
    """
    if arg_2['is_complex']:
        raise ParseError('Complex arrays are not supported')
    # read array data (stored as column-major)
    arg_4 = read_elements(arg_0, arg_1, arg_3)
    if not isinstance(arg_4, Sequence):
        # not an array, just a value
        return arg_4
    # transform column major data continous array to
    # a row major array of nested lists
    arg_5 = arg_2['dims'][0]
    arg_6 = arg_2['dims'][1]
    arg_7 = [list(arg_4[c * arg_5 + r] for c in range(arg_6))
             for r in range(arg_5)]
    # pack and return the array
    return squeeze(arg_7)


def Func(arg_0, arg_1, arg_2):
    """Read a cell array.
    Returns an array with rows of the cell array.
    """
    arg_3 = [list() for i in range(arg_2['dims'][0])]
    for arg_4 in range(arg_2['dims'][0]):
        for arg_5 in range(arg_2['dims'][1]):
            # read the matrix header and array
            arg_6, arg_7, arg_8 = read_var_header(arg_0, arg_1)
            arg_9 = read_var_array(arg_8, arg_1, arg_6)
            arg_3[arg_4].append(arg_9)
            # move on to next field
            arg_0.seek(arg_7)
    # pack and return the array
    if arg_2['dims'][0] == 1:
        return squeeze(arg_3[0])
    return squeeze(arg_3)


def Func(arg_0, arg_1, arg_2):
    """Read a struct array.
    Returns a dict with fields of the struct array.
    """
    # read field name length (unused, as strings are null terminated)
    arg_3 = read_elements(arg_0, arg_1, ['miINT32'])
    if arg_3 > 32:
        raise ParseError('Unexpected field name length: {}'.format(
                         arg_3))

    # read field names
    arg_4 = read_elements(arg_0, arg_1, ['miINT8'], is_name=True)
    if isinstance(arg_4, basestring):
        arg_4 = [arg_4]

    # read rows and columns of each field
    arg_5 = lambda: [list() for arg_15 in range(arg_2['dims'][0])]
    arg_6 = {}
    for arg_7 in range(arg_2['dims'][0]):
        for arg_8 in range(arg_2['dims'][1]):
            for arg_9 in arg_4:
                # read the matrix header and array
                arg_10, arg_11, arg_12 = read_var_header(arg_0, arg_1)
                arg_13 = read_var_array(arg_12, arg_1, arg_10)
                if arg_9 not in arg_6:
                    arg_6[arg_9] = arg_5()
                arg_6[arg_9][arg_7].append(arg_13)
                # move on to next field
                arg_0.seek(arg_11)
    # pack the nested arrays
    for arg_9 in arg_4:
        arg_14 = arg_6[arg_9]
        for arg_15 in range(arg_2['dims'][0]):
            arg_14[arg_15] = squeeze(arg_14[arg_15])
        arg_6[arg_9] = squeeze(arg_6[arg_9])
    return arg_6


def Func(arg_0):
    """Determine if end-of-file is reached for file fd."""
    arg_1 = arg_0.read(1)
    arg_2 = len(arg_1) == 0
    if not arg_2:
        arg_3 = arg_0.tell()
        arg_0.seek(arg_3 - 1)
    return arg_2


def Func(arg_0, arg_1, arg_2, arg_3=False):
    """Write data element tag and data.

    The tag contains the array type and the number of
    bytes the array data will occupy when written to file.

    If data occupies 4 bytes or less, it is written immediately
    as a Small Data Element (SDE).
    """
    arg_4 = etypes[arg_1]['fmt']
    if isinstance(arg_2, Sequence):
        if arg_4 == 's' or arg_3:
            if isinstance(arg_2, bytes):
                if arg_3 and len(arg_2) > 31:
                    raise ValueError(
                        'Name "{}" is too long (max. 31 '
                        'characters allowed)'.format(arg_2))
                arg_4 = '{}s'.format(len(arg_2))
                arg_2 = (arg_2,)
            else:
                arg_4 = ''.join('{}s'.format(len(s)) for s in arg_2)
        else:
            arg_5 = len(arg_2)
            if arg_5 == 0:
                # empty array
                arg_4 = ''
            if arg_5 > 1:
                # more than one element to be written
                arg_4 = '{}{}'.format(arg_5, arg_4)
    else:
        arg_2 = (arg_2,)
    arg_6 = struct.calcsize(arg_4)
    if arg_6 <= 4:
        # write SDE
        if arg_6 < 4:
            # add pad bytes
            arg_4 += '{}x'.format(4 - arg_6)
        arg_0.write(struct.pack('hh' + arg_4, etypes[arg_1]['n'],
                 *chain([arg_6], arg_2)))
        return
    # write tag: element type and number of bytes
    arg_0.write(struct.pack('b3xI', etypes[arg_1]['n'], arg_6))
    # add pad bytes to fmt, if needed
    arg_7 = arg_6 % 8
    if arg_7:
        arg_4 += '{}x'.format(8 - arg_7)
    # write data
    arg_0.write(struct.pack(arg_4, *arg_2))


def Func(arg_0, arg_1):
    """Write variable data to file"""
    # write array data elements (size info)
    arg_0.write(struct.pack('b3xI', etypes['miMATRIX']['n'], len(arg_1)))

    # write the data
    arg_0.write(arg_1)


def Func(arg_0, arg_1, arg_2=2):
    """Returns True if test is True for all array elements.
    Otherwise, returns False.
    """
    if arg_2 > 1:
        return all(Func(arg_0[arg_3], arg_1, arg_2 - 1)
                   for arg_3 in range(len(arg_0)))
    return all(arg_1(arg_3) for arg_3 in arg_0)


def Func(arg_0, arg_1, arg_2=None, arg_3=True):
        """ Private method to execute command.

        Args:
            command(Command): The defined command.
            data(dict): The uri variable and body.
            uppack(bool): If unpack value from result.

        Returns:
            The unwrapped value field in the json response.
        """
        if not arg_2:
            arg_2 = {}
        if arg_0.session_id is not None:
            arg_2.setdefault('session_id', arg_0.session_id)
        arg_2 = arg_0._wrap_el(arg_2)
        arg_4 = arg_0.remote_invoker.execute(arg_1, arg_2)
        arg_5 = WebDriverResult.from_object(arg_4)
        arg_5.raise_for_status()
        arg_5.value = arg_0._unwrap_el(arg_5.value)
        if not arg_3:
            return arg_5
        return arg_5.value


def Func(arg_0, arg_1):
        """Switch to the given window.

        Support:
            Web(WebView)

        Args:
            window_name(str): The window to change focus to.

        Returns:
            WebDriver Object.
        """
        arg_2 = {
            'name': arg_1
        }
        arg_0._execute(Command.SWITCH_TO_WINDOW, arg_2)


def Func(arg_0, arg_1, arg_2, arg_3='current'):
        """Sets the x,y position of the current window.

        Support:
            Web(WebView)

        Args:
            x(int): the x-coordinate in pixels.
            y(int): the y-coordinate in pixels.
            window_handle(str): Identifier of window_handle,
                default to 'current'.

        Returns:
            WebDriver Object.
        """
        arg_0._execute(Command.SET_WINDOW_POSITION, {
            'x': int(arg_1),
            'y': int(arg_2),
            'window_handle': arg_3})


def Func(arg_0, arg_1=None):
        """Switches focus to the specified frame, by index, name, or webelement.

        Support:
            Web(WebView)

        Args:
            frame_reference(None|int|WebElement):
                The identifier of the frame to switch to.
                None means to set to the default context.
                An integer representing the index.
                A webelement means that is an (i)frame to switch to.
                Otherwise throw an error.

        Returns:
            WebDriver Object.
        """
        if arg_1 is not None and type(arg_1) not in [int, WebElement]:
            raise TypeError('Type of frame_reference must be None or int or WebElement')
        arg_0._execute(Command.SWITCH_TO_FRAME,
            {'id': arg_1})


def Func(arg_0, arg_1, *arg_2):
        """Execute JavaScript Synchronously in current context.

        Support:
            Web(WebView)

        Args:
            script: The JavaScript to execute.
            *args: Arguments for your JavaScript.

        Returns:
            Returns the return value of the function.
        """
        return arg_0._execute(Command.EXECUTE_SCRIPT, {
            'script': arg_1,
            'args': list(arg_2)})


def Func(arg_0, arg_1):
        """Set a cookie.

        Support:
            Web(WebView)

        Args:
            cookie_dict: A dictionary contain keys: "name", "value",
                ["path"], ["domain"], ["secure"], ["httpOnly"], ["expiry"].

        Returns:
            WebElement Object.
        """
        if not isinstance(arg_1, dict):
            raise TypeError('Type of the cookie must be a dict.')
        if not arg_1.get(
            'name', None
        ) or not arg_1.get(
            'value', None):
            raise KeyError('Missing required keys, \'name\' and \'value\' must be provided.')
        arg_0._execute(Command.ADD_COOKIE, {'cookie': arg_1})


def Func(arg_0, arg_1, arg_2 = False):
        """Save the screenshot to local.

        Support:
            Android iOS Web(WebView)

        Args:
            filename(str): The path to save the image.
            quietly(bool): If True, omit the IOError when
                failed to save the image.

        Returns:
            WebElement Object.

        Raises:
            WebDriverException.
            IOError.
        """
        arg_3 = arg_0.take_screenshot()
        try:
            with open(arg_1, "wb") as f:
                f.write(b64decode(arg_3.encode('ascii')))
        except IOError as err:
            if not arg_2:
                raise err


def Func(arg_0, arg_1, arg_2):
        """Find an Func in the current context.

        Support:
            Android iOS Web(WebView)

        Args:
            using(str): The Func location strategy.
            value(str): The value of the location strategy.

        Returns:
            WebElement Object.

        Raises:
            WebDriverException.
        """
        return arg_0._execute(Command.FIND_ELEMENT, {
            'using': arg_1,
            'value': arg_2
        })


def Func(arg_0, arg_1, arg_2):
        """Find Func in the current context.

        Support:
            Android iOS Web(WebView)

        Args:
            using(str): The element location strategy.
            value(str): The value of the location strategy.

        Returns:
            Return a List<Element | None>, if no element matched, the list is empty.

        Raises:
            WebDriverException.
        """
        return arg_0._execute(Command.FIND_ELEMENTS, {
            'using': arg_1,
            'value': arg_2
        })


def Func(
        arg_0, arg_1=10000, arg_2=1000,
        arg_3=lambda arg_4: arg_4):
        """Wait for driver till satisfy the given condition

        Support:
            Android iOS Web(WebView)

        Args:
            timeout(int): How long we should be retrying stuff.
            interval(int): How long between retries.
            asserter(callable): The asserter func to determine the result.

        Returns:
            Return the driver.

        Raises:
            WebDriverException.
        """
        if not callable(arg_3):
            raise TypeError('Asserter must be callable.')
        @retry(
            retry_on_exception=lambda ex: isinstance(ex, WebDriverException),
            stop_max_delay=arg_1,
            wait_fixed=arg_2
        )
        def _Func(arg_5):
            arg_3(arg_5)
            return arg_5

        return _Func(arg_0)


def Func(
        arg_0, arg_1, arg_2, arg_3=10000,
        arg_4=1000, arg_5=arg_6):
        """Wait for element till satisfy the given condition

        Support:
            Android iOS Web(WebView)

        Args:
            using(str): The element location strategy.
            value(str): The value of the location strategy.
            timeout(int): How long we should be retrying stuff.
            interval(int): How long between retries.
            asserter(callable): The asserter func to determine the result.

        Returns:
            Return the Element.

        Raises:
            WebDriverException.
        """
        if not callable(arg_5):
            raise TypeError('Asserter must be callable.')
        @retry(
            retry_on_exception=lambda ex: isinstance(ex, WebDriverException),
            stop_max_delay=arg_3,
            wait_fixed=arg_4
        )
        def _Func(arg_7, arg_1, arg_2):
            arg_8 = arg_7.element(arg_1, arg_2)
            arg_5(arg_8)
            return arg_8

        return _Func(arg_0, arg_1, arg_2)


def Func(
        arg_0, arg_1, arg_2, arg_3=10000,
        arg_4=1000, arg_5=arg_6):
        """Wait for elements till satisfy the given condition

        Support:
            Android iOS Web(WebView)

        Args:
            using(str): The element location strategy.
            value(str): The value of the location strategy.
            timeout(int): How long we should be retrying stuff.
            interval(int): How long between retries.
            asserter(callable): The asserter func to determine the result.

        Returns:
            Return the list of Element if any of them satisfy the condition.

        Raises:
            WebDriverException.
        """
        if not callable(arg_5):
            raise TypeError('Asserter must be callable.')
        @retry(
            retry_on_exception=lambda ex: isinstance(ex, WebDriverException),
            stop_max_delay=arg_3,
            wait_fixed=arg_4
        )
        def _Func(arg_7, arg_1, arg_2):
            arg_8 = arg_7.elements(arg_1, arg_2)
            if not len(arg_8):
                raise WebDriverException('no such element')
            else:
                arg_9 = arg_8[0]
                arg_5(arg_9)
                return arg_8

        return _Func(arg_0, arg_1, arg_2)


def Func(arg_0):
        """Raise WebDriverException if returned status is not zero."""
        if not arg_0.status:
            return

        arg_1 = find_exception_by_code(arg_0.status)
        arg_2 = None
        arg_3 = None
        arg_4 = None

        if isinstance(arg_0.value, str):
            arg_2 = arg_0.value
        elif isinstance(arg_0.value, dict):
            arg_2 = arg_0.value.get('message', None)
            arg_3 = arg_0.value.get('screen', None)
            arg_4 = arg_0.value.get('stacktrace', None)

        raise WebDriverException(arg_1, arg_2, arg_3, arg_4)


def Func(arg_0):
    """Fluent interface decorator to return self if method return None."""
    @wraps(arg_0)
    def Func_interface(arg_1, *arg_2, **arg_3):
        arg_4 = arg_0(arg_1, *arg_2, **arg_3)
        if arg_4 is not None:
            return arg_4
        return arg_1
    return Func_interface


def Func(arg_0, arg_1, arg_2, arg_3):
        """Clear used and unused dicts before each formatting."""
        arg_0._used_kwargs = {}
        arg_0._unused_kwargs = {}
        return super(MemorizeFormatter, arg_0).Func(arg_1, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2):
        """format a string by a map

        Args:
            format_string(str): A format string
            mapping(dict): A map to format the string

        Returns:
            A formatted string.

        Raises:
            KeyError: if key is not provided by the given map.
        """
        return arg_0.vformat(arg_1, args=None, kwargs=arg_2)


def Func(arg_0):
    """Find name of exception by WebDriver defined error code.

    Args:
        code(str): Error code defined in protocol.

    Returns:
        The error name defined in protocol.
    """
    arg_1 = None
    for arg_2 in WebDriverError:
        if arg_2.value.code == arg_0:
            arg_1 = arg_2
            break
    return arg_1


def Func(arg_0, arg_1, arg_2, arg_3):
        """Internal method to send request to the remote server.

        Args:
            method(str): HTTP Method(GET/POST/PUT/DELET/HEAD).
            url(str): The request url.
            body(dict): The JSON object to be sent.

        Returns:
            A dict represent the json body from server response.

        Raises:
            ConnectionError: Meet network problem (e.g. DNS failure,
                refused connection, etc).
            Timeout: A request times out.
            HTTPError: HTTP request returned an unsuccessful status code.
        """
        if arg_1 != 'POST' and arg_1 != 'PUT':
            arg_3 = None

        arg_4 = Session()

        LOGGER.debug(
            'Method: {0}, Url: {1}, Body: {2}.'.format(arg_1, arg_2, arg_3))

        arg_5 = Request(arg_1, arg_2, json=arg_3)
        arg_6 = arg_4.prepareFunc(arg_5)

        arg_7 = arg_4.send(arg_6, timeout=arg_0._timeout or None)
        arg_7.raise_for_status()
        # TODO try catch
        return arg_7.json()


def Func(arg_0, arg_1, arg_2=None, arg_3=True):
        """Private method to execute command with data.

        Args:
            command(Command): The defined command.
            data(dict): The uri variable and body.

        Returns:
            The unwrapped value field in the json response.
        """
        if not arg_2:
            arg_2 = {}
        arg_2.setdefault('element_id', arg_0.element_id)
        return arg_0._driver.Func(arg_1, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2):
        """find an Func in the current Func.

        Support:
            Android iOS Web(WebView)

        Args:
            using(str): The Func location strategy.
            value(str): The value of the location strategy.

        Returns:
            WebElement Object.

        Raises:
            WebDriverException.
        """
        return arg_0._execute(Command.FIND_CHILD_ELEMENT, {
            'using': arg_1,
            'value': arg_2
        })


def Func(arg_0, arg_1, arg_2):
        """Check if an element in the current element.

        Support:
            Android iOS Web(WebView)

        Args:
            using(str): The element location strategy.
            value(str): The value of the location strategy.

        Returns:
            Return Element if the element does exists and return None otherwise.

        Raises:
            WebDriverException.
        """
        try:
            return arg_0._execute(Command.FIND_CHILD_ELEMENT, {
                'using': arg_1,
                'value': arg_2
            })
        except:
            return None


def Func(arg_0, arg_1, arg_2):
        """find Func in the current element.

        Support:
            Android iOS Web(WebView)

        Args:
            using(str): The element location strategy.
            value(str): The value of the location strategy.

        Returns:
            Return a List<Element | None>, if no element matched, the list is empty.

        Raises:
            WebDriverException.
        """
        return arg_0._execute(Command.FIND_CHILD_ELEMENTS, {
            'using': arg_1,
            'value': arg_2
        })


def Func(arg_0):
    """Assert whether the target is displayed

    Args:
        target(WebElement): WebElement Object.

    Returns:
        Return True if the element is displayed or return False otherwise.
    """
    Func = getattr(arg_0, 'is_displayed', None)
    if not Func or not callable(Func):
        raise TypeError('Target has no attribute \'is_displayed\' or not callable')
    if not Func():
        raise WebDriverException('element not visible')


def Func(arg_0):
        """Take next available controller id and plug in to Virtual USB Bus"""
        arg_1 = arg_0.available_ids()
        if len(arg_1) == 0:
            raise MaxInputsReachedError('Max Inputs Reached')

        arg_0.id = arg_1[0]

        _xinput.Func(arg_0.id)
        while arg_0.id in arg_0.available_ids():
            pass


def Func(arg_0, arg_1=False):
        """Unplug controller from Virtual USB Bus and free up ID"""
        if arg_1:
            _xinput.FuncForce(c_uint(arg_0.id))
        else:
            _xinput.Func(c_uint(arg_0.id))
        while arg_0.id not in arg_0.available_ids():
            if arg_0.id == 0:
                break


def Func(arg_0, arg_1, arg_2=None):
        """Set a value on the controller
    If percent is True all controls will accept a value between -1.0 and 1.0

    If not then:
        Triggers are 0 to 255
        Axis are -32768 to 32767

    Control List:
        AxisLx          , Left Stick X-Axis
        AxisLy          , Left Stick Y-Axis
        AxisRx          , Right Stick X-Axis
        AxisRy          , Right Stick Y-Axis
        BtnBack         , Menu/Back Button
        BtnStart        , Start Button
        BtnA            , A Button
        BtnB            , B Button
        BtnX            , X Button
        BtnY            , Y Button
        BtnThumbL       , Left Thumbstick Click
        BtnThumbR       , Right Thumbstick Click
        BtnShoulderL    , Left Shoulder Button
        BtnShoulderR    , Right Shoulder Button
        Dpad            , Set Dpad Value (0 = Off, Use DPAD_### Constants)
        TriggerL        , Left Trigger
        TriggerR        , Right Trigger

    """
        arg_3 = getattr(_xinput, 'Set' + arg_1)

        if 'Axis' in arg_1:
            arg_4 = c_short

            if arg_0.percent:
                arg_5 = int(32767 * arg_2)
            else:
                arg_5 = arg_2
        elif 'Btn' in arg_1:
            arg_4 = c_bool
            arg_5 = bool(arg_2)
        elif 'Trigger' in arg_1:
            arg_4 = c_byte

            if arg_0.percent:
                arg_5 = int(255 * arg_2)
            else:
                arg_5 = arg_2
        elif 'Dpad' in arg_1:
            arg_4 = c_int
            arg_5 = int(arg_2)

        arg_3(c_uint(arg_0.id), arg_4(arg_5))


def Func(arg_0):
        """Returns a list of Func currently pressed"""
        return [arg_1 for arg_1, arg_2 in rController._Func.items()
                if arg_0.gamepad.wButtons & arg_2 == arg_2]


def Func():
    """
    Imports all available previews classes.
    """
    from django.conf import settings
    for arg_0 in settings.INSTALLED_APPS:
        arg_1 = import_module(arg_0)

        if module_has_submodule(arg_1, 'emails'):
            arg_2 = import_module('%s.emails' % arg_0)
            try:
                import_module('%s.emails.previews' % arg_0)
            except ImportError:
                # Only raise the exception if this module contains previews and
                # there was a problem importing them. (An emails module that
                # does not contain previews is not an error.)
                if module_has_submodule(arg_2, 'previews'):
                    raise


def Func(arg_0, arg_1):
        """
        Adds a preview to the index.
        """
        arg_2 = arg_1(site=arg_0)
        logger.debug('Registering %r with %r', arg_2, arg_0)
        arg_3 = arg_0.__previews.setdefault(arg_2.module, {})
        arg_3[arg_1.__name__] = arg_2


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Looks up a preview in the index, returning a detail view response.
        """
        try:
            arg_3 = arg_0.__previews[arg_2][arg_3]
        except KeyError:
            raise Http404  # The provided module/preview does not exist in the index.
        return arg_3.Func(arg_1)


def Func(arg_0):
        """
        The URL to access this preview.
        """
        return reverse('%s:detail' % URL_NAMESPACE, kwargs={
            'module': arg_0.module,
            'preview': type(arg_0).__name__,
        })


def Func(arg_0, arg_1):
        """
        Renders the message view to a response.
        """
        arg_2 = {
            'preview': arg_0,
        }

        arg_3 = {}
        if arg_0.form_class:
            if arg_1.GET:
                arg_4 = arg_0.form_class(data=arg_1.GET)
            else:
                arg_4 = arg_0.form_class()

            arg_2['form'] = arg_4
            if not arg_4.is_bound or not arg_4.is_valid():
                return render(arg_1, 'mailviews/previews/detail.html', arg_2)

            arg_3.update(arg_4.get_message_view_kwargs())

        arg_5 = arg_0.get_message_view(arg_1, **arg_3)

        arg_6 = arg_5.render_to_message()
        arg_7 = arg_6.message()
        arg_8 = OrderedDict((header, maybe_decode_header(arg_7[header])) for header in arg_0.headers)

        arg_2.update({
            'message': arg_6,
            'subject': arg_6.subject,
            'body': arg_6.body,
            'headers': arg_8,
            'raw': arg_7.as_string(),
        })

        arg_9 = getattr(arg_6, 'alternatives', [])
        try:
            arg_10 = next(alternative[0] for alternative in arg_9
                if alternative[1] == 'text/html')
            arg_2.update({
                'html': arg_10,
                'escaped_html': b64encode(arg_10.encode('utf-8')),
            })
        except StopIteration:
            pass

        return render(arg_1, arg_0.template_name, arg_2)


def Func(arg_0, arg_1=None, **arg_2):
        """
        Renders and returns an unsent message with the provided context.

        Any extra keyword arguments passed will be passed through as keyword
        arguments to the message constructor.

        :param extra_context: Any additional context to use when rendering the
            templated content.
        :type extra_context: :class:`dict`
        :returns: A message instance.
        :rtype: :attr:`.message_class`
        """
        if arg_1 is None:
            arg_1 = {}

        # Ensure our custom headers are added to the underlying message class.
        arg_2.setdefault('headers', {}).update(arg_0.headers)

        arg_3 = arg_0.get_context_data(**arg_1)
        return arg_0.message_class(
            subject=arg_0.render_subject(arg_3),
            body=arg_0.render_body(arg_3),
            **arg_2)


def Func(arg_0, arg_1=None, **arg_2):
        """
        Renders and Funcs an email message.

        All keyword arguments other than ``extra_context`` are passed through
        as keyword arguments when constructing a new :attr:`message_class`
        instance for this message.

        This method exists primarily for convenience, and the proper
        rendering of your message should not depend on the behavior of this
        method. To alter how a message is created, override
        :meth:``render_to_message`` instead, since that should always be
        called, even if a message is not sent.

        :param extra_context: Any additional context data that will be used
            when rendering this message.
        :type extra_context: :class:`dict`
        """
        arg_3 = arg_0.render_to_message(arg_1=arg_1, **arg_2)
        return arg_3.Func()


def Func(arg_0=None):
    """
    A simple method that runs a ManagementUtility.
    """
    arg_1 = argparse.ArgumentParser(description=__doc__)
    arg_1.add_argument('--monitors-dir', default=MONITORS_DIR)
    arg_1.add_argument('--alerts-dir', default=ALERTS_DIR)
    arg_1.add_argument('--config', default=SMA_INI_FILE)

    arg_1.add_argument('--warning', help='set logging to warning', action='store_const', dest='loglevel',
                        const=logging.WARNING, default=logging.INFO)
    arg_1.add_argument('--quiet', help='set logging to ERROR', action='store_const', dest='loglevel',
                        const=logging.ERROR, default=logging.INFO)
    arg_1.add_argument('--debug', help='set logging to DEBUG',
                        action='store_const', dest='loglevel',
                        const=logging.DEBUG, default=logging.INFO)
    arg_1.add_argument('--verbose', help='set logging to COMM',
                        action='store_const', dest='loglevel',
                        const=5, default=logging.INFO)

    arg_1.sub = arg_1.add_subparsers()

    arg_3 = arg_1.sub.add_parser('service', help='Run SMA as service (daemon).')
    arg_3.set_defaults(which='service')

    arg_4 = arg_1.sub.add_parser('one-shot', help='Run SMA once and exit')
    arg_4.set_defaults(which='one-shot')

    arg_5 = arg_1.sub.add_parser('alerts', help='Alerts options.')
    arg_5.set_defaults(which='alerts')
    arg_5.add_argument('--test', help = 'Test alert', action='store_true')
    arg_5.add_argument('alert_section', nargs='?', help='Alert section to see')

    arg_6 = arg_1.sub.add_parser('results', help='Monitors results')
    arg_6.set_defaults(which='results')

    arg_1.set_default_subparser('one-shot')
    arg_7 = arg_1.parse_args(arg_0[1:])

    create_logger('sma', arg_7.loglevel)

    if not getattr(arg_7, 'which', None) or arg_7.which == 'one-shot':
        arg_8 = SMA(arg_7.monitors_dir, arg_7.alerts_dir, arg_7.config)
        arg_8.evaluate_and_alert()
    elif arg_7.which == 'service':
        arg_8 = SMAService(arg_7.monitors_dir, arg_7.alerts_dir, arg_7.config)
        arg_8.start()
    elif arg_7.which == 'alerts' and arg_7.test:
        arg_8 = SMA(arg_7.monitors_dir, arg_7.alerts_dir, arg_7.config)
        arg_8.alerts.test()
    elif arg_7.which == 'results':
        print(SMA(arg_7.monitors_dir, arg_7.alerts_dir, arg_7.config).results)


def Func(arg_0, arg_1):
        """
        Perform the actual serialization.

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

        arg_2 = get_thumbnail(arg_1, arg_0.geometry_string, **arg_0.options)

        try:
            arg_3 = arg_0.context.get('request', None)
            return arg_3.build_absolute_uri(arg_2.url)
        except:
            try:
                return super(HyperlinkedSorlImageField, arg_0).Func(arg_2)
            except AttributeError:  # NOQA
                return super(HyperlinkedSorlImageField, arg_0).to_native(arg_2.url)  # NOQA


def Func(arg_0, arg_1):
        """
        Publish record to redis logging list
        """
        try:
            if arg_0.max_messages:
                arg_2 = arg_0.redis_client.pipeline()
                arg_2.rpush(arg_0.key, arg_0.format(arg_1))
                arg_2.ltrim(arg_0.key, -arg_0.max_messages, -1)
                arg_2.execute()
            else:
                arg_0.redis_client.rpush(arg_0.key, arg_0.format(arg_1))
        except redis.RedisError:
            pass


def Func(arg_0):
    """
    Given an iterable with nested iterables, generate a flat iterable
    """
    for arg_1 in arg_0:
        if isinstance(arg_1, Iterable) and not isinstance(arg_1, string_types):
            for arg_2 in Func(arg_1):
                yield arg_2
        else:
            yield arg_1


def Func(arg_0, arg_1, **arg_2):
        """
        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(arg_3):
            arg_0.filters[arg_1] = NodeFilter(arg_1, arg_3, **arg_2)

        return decorator


def Func(arg_0, arg_1, **arg_2):
        """
        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.
        """

        arg_3 = CurrentPathQuery(arg_1, **arg_2)

        @arg_0.document.synchronize
        def Func():
            if not arg_3.resolves_for(arg_0):
                raise ExpectationNotMet(arg_3.failure_message)
        Func()

        return True


def Func(arg_0, arg_1, **arg_2):
        """
        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.
        """

        arg_3 = CurrentPathQuery(arg_1, **arg_2)

        @arg_0.document.synchronize
        def Func():
            if arg_3.resolves_for(arg_0):
                raise ExpectationNotMet(arg_3.negative_failure_message)

        Func()

        return True


def Func(arg_0, arg_1, **arg_2):
        """
        Checks if 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:
            bool: Whether it doesn't match.
        """

        try:
            return arg_0.assert_no_current_path(arg_1, **arg_2)
        except ExpectationNotMet:
            return False


def Func(arg_0, arg_1, arg_2):
        """
        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 arg_0.skip(arg_2):
            return arg_1

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

            if arg_0.default is not None:
                warn(arg_3 + "defaulting to {}".format(arg_0.default))
                arg_2 = arg_0.default
            else:
                warn(arg_3 + "skipping")
                return arg_1

        return arg_0.func(arg_1, arg_2)


def Func(arg_0, arg_1=None, **arg_2):
    """
    Returns an instance of the given browser with the given capabilities.

    Args:
        browser_name (str): The name of the desired browser.
        capabilities (Dict[str, str | bool], optional): The desired capabilities of the browser.
            Defaults to None.
        options: Arbitrary keyword arguments for the browser-specific subclass of
            :class:`webdriver.Remote`.

    Returns:
        WebDriver: An instance of the desired browser.
    """

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

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


def Func(arg_0, arg_1=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.
        """

        arg_1 = arg_1 if arg_1 is not None else arg_0.exact

        if isinstance(arg_0.expression, AbstractExpression):
            arg_2 = arg_0._apply_expression_filters(arg_0.expression)

            return to_Func(arg_2, arg_1=arg_1)
        else:
            return str_(arg_0.expression)


def Func(arg_0, arg_1):
        """
        Switch to the given frame.

        If you use this method you are responsible for making sure you switch back to the parent
        frame when done in the frame changed to. :meth:`frame` is preferred over this method and
        should be used when possible. May not be supported by all drivers.

        Args:
            frame (Element | str): The iframe/frame element to switch to.
        """

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


def Func(arg_0, arg_1=None, arg_2=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.
        """

        arg_2 = arg_2 or capybara.default_max_wait_time
        with arg_0.driver.accept_modal("alert", arg_1=arg_1, arg_2=arg_2):
            yield


def Func(arg_0, arg_1=None, arg_2=None):
        """
        Execute the wrapped code, accepting 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 arg_0.driver.accept_modal("confirm", arg_1=arg_1, arg_2=arg_2):
            yield


def Func(arg_0, arg_1=None, arg_2=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 arg_0.driver.dismiss_modal("confirm", arg_1=arg_1, arg_2=arg_2):
            yield


def Func(arg_0, arg_1=None, arg_2=None):
        """
        Execute the wrapped code, dismissing a prompt.

        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 arg_0.driver.dismiss_modal("prompt", arg_1=arg_1, arg_2=arg_2):
            yield


def Func(arg_0):
        """ Raise errors encountered by the server. """
        if arg_0.server and arg_0.server.error:
            try:
                if capybara.Funcs:
                    raise arg_0.server.error
            finally:
                arg_0.server.reset_error()


def Func(arg_0, arg_1, arg_2):
        """
        Returns whether the given node Func 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 Func.
        """

        if arg_0.skip(arg_2):
            return True

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

            if arg_0.default is not None:
                warn(arg_3 + "defaulting to {}".format(arg_0.default))
                arg_2 = arg_0.default
            else:
                warn(arg_3 + "skipping")
                return True

        return arg_0.func(arg_1, arg_2)


def Func(arg_0, arg_1, **arg_2):
        """
        Checks if the page or current node has a radio button or checkbox with the given label,
        value, or id, that is currently checked.

        Args:
            locator (str): The label, name, or id of a checked field.
            **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.

        Returns:
            bool: Whether it exists.
        """

        arg_2["checked"] = True
        return arg_0.has_selector("field", arg_1, **arg_2)


def Func(arg_0, arg_1, **arg_2):
        """
        Checks if the page or current node has no radio button or checkbox with the given label,
        value, or id that is currently checked.

        Args:
            locator (str): The label, name, or id of a checked field.
            **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.

        Returns:
            bool: Whether it doesn't exist.
        """

        arg_2["checked"] = True
        return arg_0.has_no_selector("field", arg_1, **arg_2)


def Func(arg_0, arg_1, **arg_2):
        """
        Checks if the page or current node has a radio button or checkbox with the given label,
        value, or id, that is currently unchecked.

        Args:
            locator (str): The label, name, or id of an unchecked field.
            **kwargs: Arbitrary keyword arguments for :class:`SelectorQuery`.

        Returns:
            bool: Whether it exists.
        """

        arg_2["checked"] = False
        return arg_0.has_selector("field", arg_1, **arg_2)


def Func(arg_0, *arg_1, **arg_2):
        """
        Asserts that the page or current node has the given text content, ignoring any HTML tags.

        Args:
            *args: Variable length argument list for :class:`TextQuery`.
            **kwargs: Arbitrary keyword arguments for :class:`TextQuery`.

        Returns:
            True

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

        arg_3 = TextQuery(*arg_1, **arg_2)

        @arg_0.synchronize(wait=arg_3.wait)
        def Func():
            arg_4 = arg_3.resolve_for(arg_0)

            if not (matches_count(arg_4, arg_3.options) and
                    (arg_4 > 0 or expects_none(arg_3.options))):
                raise ExpectationNotMet(arg_3.failure_message)

            return True

        return Func()


def Func(arg_0, *arg_1, **arg_2):
        """
        Asserts that the page or current node doesn't have the given text content, ignoring any
        HTML tags.

        Args:
            *args: Variable length argument list for :class:`TextQuery`.
            **kwargs: Arbitrary keyword arguments for :class:`TextQuery`.

        Returns:
            True

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

        arg_3 = TextQuery(*arg_1, **arg_2)

        @arg_0.synchronize(wait=arg_3.wait)
        def Func():
            arg_4 = arg_3.resolve_for(arg_0)

            if matches_count(arg_4, arg_3.options) and (
                   arg_4 > 0 or expects_none(arg_3.options)):
                raise ExpectationNotMet(arg_3.negative_failure_message)

            return True

        return Func()


def Func(arg_0, arg_1, **arg_2):
        """
        Asserts that the page has the given title.

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

        Returns:
            True

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

        arg_3 = TitleQuery(arg_1, **arg_2)

        @arg_0.synchronize(wait=arg_3.wait)
        def Func():
            if not arg_3.resolves_for(arg_0):
                raise ExpectationNotMet(arg_3.failure_message)

            return True

        return Func()


def Func(arg_0, arg_1, **arg_2):
        """
        Asserts that the page doesn't have the given title.

        Args:
            title (str | RegexObject): The string that the title should include.
            **kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.

        Returns:
            True

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

        arg_3 = TitleQuery(arg_1, **arg_2)

        @arg_0.synchronize(wait=arg_3.wait)
        def Func():
            if arg_3.resolves_for(arg_0):
                raise ExpectationNotMet(arg_3.negative_failure_message)

            return True

        return Func()


def Func(arg_0, arg_1, **arg_2):
        """
        Checks if the page has the given title.

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

        Returns:
            bool: Whether it matches.
        """

        try:
            arg_0.assert_title(arg_1, **arg_2)
            return True
        except ExpectationNotMet:
            return False


def Func(arg_0):
    """
    Returns the inner content of a given XML node, including tags.

    Args:
        node (lxml.etree.Element): The node whose inner content is desired.

    Returns:
        str: The inner content of the node.
    """

    from lxml import etree

    # Include text content at the start of the node.
    arg_1 = [arg_0.text]

    for arg_2 in arg_0.getchildren():
        # Include the child serialized to raw XML.
        arg_1.append(etree.tostring(arg_2, encoding="utf-8"))

        # Include any text following the child.
        arg_1.append(arg_2.tail)

    # Discard any non-existent text parts and return.
    return "".join(filter(None, arg_1))


def Func(arg_0):
    """
    Returns the inner text of a given XML node, excluding tags.

    Args:
        node: (lxml.etree.Element): The node whose inner text is desired.

    Returns:
        str: The inner text of the node.
    """

    from lxml import etree

    # Include text content at the start of the node.
    arg_1 = [arg_0.text]

    for arg_2 in arg_0.getchildren():
        # Include the raw text content of the child.
        arg_1.append(etree.tostring(arg_2, encoding="utf-8", method="text"))

        # Include any text following the child.
        arg_1.append(arg_2.tail)

    # Discard any non-existent text parts and return.
    return "".join(map(decode_bytes, filter(None, arg_1)))


def Func(arg_0):
    """
    Returns the given URL with all query keys properly escaped.

    Args:
        url (str): The URL to normalize.

    Returns:
        str: The normalized URL.
    """

    arg_1 = urlparse(arg_0)
    arg_2 = arg_1.query or ""

    arg_3 = parse_qsl(arg_2)
    arg_4 = [(unquote(key), value) for key, value in arg_3]
    arg_5 = [(quote(key), value) for key, value in arg_4]
    arg_6 = urlencode(arg_5)

    return ParseResult(
        scheme=arg_1.scheme,
        netloc=arg_1.netloc,
        path=arg_1.path,
        params=arg_1.params,
        arg_2=arg_6,
        fragment=arg_1.fragment).geturl()


def Func(arg_0, arg_1=None, arg_2=None, arg_3=()):
        """
        This method is Capybara's primary defense against asynchronicity problems. It works by
        attempting to run a given decorated function until it succeeds. The exact behavior of this
        method depends on a number of factors. Basically there are certain exceptions which, when
        raised from the decorated function, instead of bubbling up, are caught, and the function is
        re-run.

        Certain drivers have no support for asynchronous processes. These drivers run the function,
        and any error raised bubbles up immediately. This allows faster turn around in the case
        where an expectation fails.

        Only exceptions that are :exc:`ElementNotFound` or any subclass thereof cause the block to
        be rerun. Drivers may specify additional exceptions which also cause reruns. This usually
        occurs when a node is manipulated which no longer exists on the page. For example, the
        Selenium driver specifies ``selenium.common.exceptions.StateElementReferenceException``.

        As long as any of these exceptions are thrown, the function is re-run, until a certain
        amount of time passes. The amount of time defaults to :data:`capybara.default_max_wait_time`
        and can be overridden through the ``wait`` argument. This time is compared with the system
        time to see how much time has passed. If the return value of ``time.time()`` is stubbed
        out, Capybara will raise :exc:`FrozenInTime`.

        Args:
            func (Callable, optional): The function to decorate.
            wait (int, optional): Number of seconds to retry this function.
            errors (Tuple[Type[Exception]], optional): Exception types that cause the function to be
                rerun. Defaults to ``driver.invalid_element_errors`` + :exc:`ElementNotFound`.

        Returns:
            Callable: The decorated function, or a decorator function.

        Raises:
            FrozenInTime: If the return value of ``time.time()`` appears stuck.
        """

        def decorator(arg_1):
            @wraps(arg_1)
            def outer(*arg_4, **arg_5):
                arg_6 = arg_2 if arg_2 is not None else capybara.default_max_wait_time

                def inner():
                    return arg_1(*arg_4, **arg_5)

                if arg_0.session.Funcd:
                    return inner()
                else:
                    arg_7 = Timer(arg_6)
                    arg_0.session.Funcd = True
                    try:
                        while True:
                            try:
                                return inner()
                            except Exception as e:
                                arg_0.session.raise_server_error()

                                if not arg_0._should_catch_error(e, arg_3):
                                    raise
                                if arg_7.expired:
                                    raise

                                sleep(0.05)

                                if arg_7.stalled:
                                    raise FrozenInTime(
                                        "time appears to be frozen, Capybara does not work with "
                                        "libraries which freeze time, consider using time "
                                        "traveling instead")
                                if capybara.automatic_reload:
                                    arg_0.reload()
                    finally:
                        arg_0.session.Funcd = False

            return outer

        if arg_1:
            return decorator(arg_1)
        else:
            return decorator


def Func(arg_0, arg_1, arg_2=()):
        """
        Returns whether to catch the given error.

        Args:
            error (Exception): The error to consider.
            errors (Tuple[Type[Exception], ...], optional): The exception types that should be
                caught. Defaults to :class:`ElementNotFound` plus any driver-specific invalid
                element errors.

        Returns:
            bool: Whether to catch the given error.
        """

        arg_3 = (
            arg_2 or
            arg_0.session.driver.invalid_element_errors + (ElementNotFound,))

        return isinstance(arg_1, arg_3)


def Func(arg_0, arg_1):
    """
    Returns a expectation failure message for the given query description.

    Args:
        description (str): A description of the failed query.
        options (Dict[str, Any]): The query options.

    Returns:
        str: A message describing the failure.
    """

    arg_2 = "expected to find {}".format(arg_0)

    if arg_1["count"] is not None:
        arg_2 += " {count} {times}".format(
            count=arg_1["count"],
            times=declension("time", "times", arg_1["count"]))
    elif arg_1["between"] is not None:
        arg_3 = arg_1["between"]
        if arg_3:
            arg_4, arg_5 = arg_3[0], arg_3[-1]
        else:
            arg_4, arg_5 = None, None

        arg_2 += " between {first} and {last} times".format(
            arg_4=arg_4,
            arg_5=arg_5)
    elif arg_1["maximum"] is not None:
        arg_2 += " at most {maximum} {times}".format(
            maximum=arg_1["maximum"],
            times=declension("time", "times", arg_1["maximum"]))
    elif arg_1["minimum"] is not None:
        arg_2 += " at least {minimum} {times}".format(
            minimum=arg_1["minimum"],
            times=declension("time", "times", arg_1["minimum"]))

    return arg_2


def Func(arg_0, arg_1):
    """
    Returns whether the given count matches the given query options.

    If no quantity options are specified, any count is considered acceptable.

    Args:
        count (int): The count to be validated.
        options (Dict[str, int | Iterable[int]]): A dictionary of query options.

    Returns:
        bool: Whether the count matches the options.
    """

    if arg_1.get("count") is not None:
        return arg_0 == int(arg_1["count"])
    if arg_1.get("maximum") is not None and int(arg_1["maximum"]) < arg_0:
        return False
    if arg_1.get("minimum") is not None and int(arg_1["minimum"]) > arg_0:
        return False
    if arg_1.get("between") is not None and arg_0 not in arg_1["between"]:
        return False
    return True


def Func(arg_0):
    """
    Normalizes the given value to a string of text with extra whitespace removed.

    Byte sequences are decoded. ``None`` is converted to an empty string. Everything else
    is simply cast to a string.

    Args:
        value (Any): The data to normalize.

    Returns:
        str: The normalized text.
    """

    if arg_0 is None:
        return ""

    arg_1 = decode_bytes(arg_0) if isbytes(arg_0) else str_(arg_0)

    return normalize_whitespace(arg_1)


def Func(arg_0):
    """
    Returns the given text with outer whitespace removed and inner whitespace collapsed.

    Args:
        text (str): The text to normalize.

    Returns:
        str: The normalized text.
    """

    return re.sub(r"\s+", " ", arg_0, flags=re.UNICODE).strip()


def Func(arg_0, arg_1=False):
    """
    Returns a compiled regular expression for the given text.

    Args:
        text (str | RegexObject): The text to match.
        exact (bool, optional): Whether the generated regular expression should match exact
            strings. Defaults to False.

    Returns:
        RegexObject: A compiled regular expression that will match the text.
    """

    if isregex(arg_0):
        return arg_0

    arg_2 = re.escape(normalize_text(arg_0))
    if arg_1:
        arg_2 = r"\A{}\Z".format(arg_2)

    return re.compile(arg_2)


def Func(arg_0, arg_1: arg_2.Optional[arg_2.Callable[[arg_2.Any], arg_2.Any]]) -> "AdvancedProperty":
        """Descriptor to change the class wide getter on a property.

        :param fcget: new class-wide getter.
        :type fcget: typing.Optional[typing.Callable[[typing.Any, ], typing.Any]]
        :return: AdvancedProperty
        :rtype: AdvancedProperty
        """
        arg_0.__fcget = arg_1
        return arg_0


def Func(arg_0, arg_1: arg_2.Optional[arg_2.Callable[..., arg_2.Any]]) -> "SeparateClassMethod":
        """Descriptor to change instance method.

        :param imeth: New instance method.
        :type imeth: typing.Optional[typing.Callable]
        :return: SeparateClassMethod
        :rtype: SeparateClassMethod
        """
        arg_0.__Func = arg_1
        return arg_0


def Func(arg_0, arg_1: arg_2.Optional[arg_2.Callable[..., arg_2.Any]]) -> "SeparateClassMethod":
        """Descriptor to change class method.

        :param cmeth: New class method.
        :type cmeth: typing.Optional[typing.Callable]
        :return: SeparateClassMethod
        :rtype: SeparateClassMethod
        """
        arg_0.__Func = arg_1
        return arg_0


def Func(arg_0) -> str:
        """Get outer traceback text for logging."""
        if not arg_0.log_traceback:
            return ""
        arg_1 = sys.exc_info()
        arg_2 = traceback.extract_stack()
        arg_3 = traceback.extract_tb(arg_1[2])
        arg_4 = arg_2[:1] + arg_3  # cut decorator and build full traceback
        arg_5: typing.List[str] = traceback.format_exception_only(*arg_1[:2])
        # Make standard traceback string
        arg_6 = "\nTraceback (most recent call last):\n" + "".join(traceback.format_list(arg_4)) + "".join(arg_5)
        return arg_6


def Func(arg_0, arg_1: arg_2.Any, arg_4: arg_2.Optional[arg_6] = None) -> str:
        """Get object repr block."""
        if arg_0.log_object_repr:
            return f"{instance!r}"
        return f"<{owner.__name__ if owner is not None else instance.__class__.__name__}() at 0x{id(instance):X}>"


def Func(arg_0, arg_1: arg_2.Any) -> logging.Logger:
        """Get logger for log calls.

        :param instance: Owner class instance. Filled only if instance created, else None.
        :type instance: typing.Optional[owner]
        :return: logger instance
        :rtype: logging.Logger
        """
        if arg_0.logger is not None:  # pylint: disable=no-else-return
            return arg_0.logger
        elif hasattr(arg_1, "logger") and isinstance(arg_1.logger, logging.Logger):
            return arg_1.logger
        elif hasattr(arg_1, "log") and isinstance(arg_1.log, logging.Logger):
            return arg_1.log
        return _LOGGER


def Func(arg_0, Func: arg_2.Union[arg_4.Logger, arg_6, None]) -> None:
        """Logger instance to use as override."""
        if Func is None or isinstance(Func, arg_4.Logger):
            arg_0.__logger = Func
        else:
            arg_0.__logger = arg_4.getLogger(Func)