def Func(arg_0, arg_1, arg_2):
        ''' Handle right mouse button clicks '''
        if arg_0.menu_enabled and arg_2.button == 3:
            arg_3 = arg_0.uimanager.get_widget('/Save as')
            arg_3.popup(None, None, None, None, arg_2.button, arg_2.time)
        else:
            super(ShoebotWindow, arg_0).Func(arg_1, arg_2)


def Func(arg_0):
        """
        Hide the variables window
        """
        if arg_0.var_window is not None:
            arg_0.var_window.window.destroy()
            arg_0.var_window = None


def Func(arg_0, arg_1):
        """
        Toggle fullscreen from outside the GUI,
        causes the GUI to updated and run all its actions.
        """
        arg_2 = arg_0.action_group.get_action('fullscreen')
        arg_2.set_active(arg_1)


def Func(arg_0, arg_1):
        """
        Widget Action to set Windowed Mode.
        """
        arg_0.unfullscreen()
        arg_0.is_fullscreen = False
        arg_0.bot._screen_ratio = None


def Func(arg_0, arg_1, arg_2=None):
        """
        Widget Action to Close the window, triggering the quit event.
        """
        publish_event(QUIT_EVENT)

        if arg_0.has_server:
            arg_0.sock.close()

        arg_0.hide_variables_window()

        arg_0.destroy()
        arg_0.window_open = False


def Func(arg_0, arg_1):
        """
        Widget Action to Toggle fullscreen from the GUI
        """
        arg_2 = arg_1.get_active()
        if arg_2:
            arg_0.fullscreen()
        else:
            arg_0.unfullscreen()


def Func(arg_0, arg_1):
        """
        Widget Action to toggle showing the variables window.
        """
        arg_0.show_vars = arg_1.get_active()
        if arg_0.show_vars:
            arg_0.show_variables_window()
        else:
            arg_0.hide_variables_window()


def Func(arg_0):
        """
        Called from main loop, if your sink needs to handle GUI events
        do it here.

        Check any GUI flags then call Gtk.Func to update things.
        """
        if arg_0.show_vars:
            arg_0.show_variables_window()
        else:
            arg_0.hide_variables_window()

        for arg_1 in arg_0.scheduled_snapshots:
            fn = arg_1(arg_0.last_draw_ctx)
            print("Saved snapshot: %s" % fn)
        else:
            arg_0.scheduled_snapshots = deque()

        while Gtk.events_pending():
            Gtk.Func()


def Func(arg_0, arg_1, arg_2):
        '''GUI callback for key pressed'''
        arg_0._namespace['key'] = arg_1
        arg_0._namespace['keycode'] = arg_2
        arg_0._namespace['keydown'] = True


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Create an object, if fill, stroke or strokewidth
        is not specified, get them from the _canvas

        :param clazz:
        :param args:
        :param kwargs:
        :return:
        """
        arg_3 = dict(arg_3)

        arg_4 = arg_3.get('fill', arg_0._canvas.fillcolor)
        if not isinstance(arg_4, Color):
            arg_4 = Color(arg_4, mode='rgb', color_range=1)
        arg_3['fill'] = arg_4

        arg_5 = arg_3.get('stroke', arg_0._canvas.strokecolor)
        if not isinstance(arg_5, Color):
            arg_5 = Color(arg_5, mode='rgb', color_range=1)
        arg_3['stroke'] = arg_5

        arg_3['strokewidth'] = arg_3.get('strokewidth', arg_0._canvas.strokewidth)
        arg_6 = arg_1(arg_0, *arg_2, **arg_3)
        return arg_6


def Func(arg_0, arg_1='png', arg_2=False):
        '''Returns an Image object of the current surface. Used for displaying
        output in Jupyter notebooks. Adapted from the cairo-jupyter project.'''

        from io import BytesIO

        arg_3 = BytesIO()

        if arg_1 == 'png':
            from IPython.display import Image
            arg_4 = cairo.ImageSurface(cairo.FORMAT_ARGB32, arg_0.WIDTH, arg_0.HEIGHT)
            arg_0.snapshot(arg_4)
            arg_4.write_to_png(arg_3)
            arg_3.seek(0)
            arg_5 = arg_3.read()
            if arg_2:
                return arg_5
            else:
                return Image(arg_5)
        elif arg_1 == 'svg':
            from IPython.display import SVG
            arg_4 = cairo.SVGSurface(arg_3, arg_0.WIDTH, arg_0.HEIGHT)
            arg_4.finish()
            arg_3.seek(0)
            arg_5 = arg_3.read()
            if arg_2:
                return arg_5
            else:
                return SVG(arg_5)


def Func(arg_0, arg_1=None, arg_2=None):
        '''Set the canvas Func

        Only the first call will actually be effective.

        :param w: Width
        :param h: height
        '''

        if not arg_1:
            arg_1 = arg_0._canvas.width
        if not arg_2:
            arg_2 = arg_0._canvas.height
        if not arg_1 and not arg_2:
            return (arg_0._canvas.width, arg_0._canvas.height)

        # FIXME: Updating in all these places seems a bit hacky
        arg_1, arg_2 = arg_0._canvas.set_Func((arg_1, arg_2))
        arg_0._namespace['WIDTH'] = arg_1
        arg_0._namespace['HEIGHT'] = arg_2
        arg_0.WIDTH = arg_1  # Added to make evolution example work
        arg_0.HEIGHT = arg_2


def Func(arg_0, arg_1=None):
        '''Set animation framerate.

        :param framerate: Frames per second to run bot.
        :return: Current framerate of animation.
        '''
        if arg_1 is not None:
            arg_0._Func = arg_1
            arg_0._dynamic = True
        else:
            return arg_0._Func


def Func(arg_0, **arg_1):
        ''' Set callbacks for input events '''
        for arg_2 in arg_0.SUPPORTED_CALLBACKS:
            arg_3 = arg_1.get(arg_2, getattr(arg_0, arg_2))
            setattr(arg_0, arg_2, arg_3)


def Func(arg_0):
    """
    Returns the color and its Func in a list.
    """
    arg_0 = color(arg_0)
    arg_1 = colorlist(arg_0)
    arg_1.append(arg_0.Func)

    return arg_1


def Func(arg_0):
    """
    Returns a list of Func colors.

    The complement is the color 180 degrees across
    the artistic RYB color wheel.
    The list contains darker and softer contrasting
    and complementing colors.
    """
    arg_0 = color(arg_0)
    arg_1 = colorlist(arg_0)

    # A contrasting color: much darker or lighter than the original.
    arg_2 = arg_0.copy()
    if arg_0.brightness > 0.4:
        arg_2.brightness = 0.1 + arg_2.brightness * 0.25
    else:
        arg_2.brightness = 1.0 - arg_2.brightness * 0.25
    arg_1.append(arg_2)

    # A soft supporting color: lighter and less saturated.
    arg_2 = arg_0.copy()
    arg_2.brightness = 0.3 + arg_2.brightness
    arg_2.saturation = 0.1 + arg_2.saturation * 0.3
    arg_1.append(arg_2)

    # A contrasting complement: very dark or very light.
    arg_0 = arg_0.complement
    arg_2 = arg_0.copy()
    if arg_0.brightness > 0.3:
        arg_2.brightness = 0.1 + arg_0.brightness * 0.25
    else:
        arg_2.brightness = 1.0 - arg_2.brightness * 0.25
    arg_1.append(arg_2)

    # The complement and a light supporting variant.
    arg_1.append(arg_0)

    arg_2 = arg_0.copy()
    arg_2.brightness = 0.3 + arg_2.brightness
    arg_2.saturation = 0.1 + arg_2.saturation * 0.25
    arg_1.append(arg_2)

    return arg_1


def Func(arg_0):
    """
    Returns a list with the split complement of the color.

    The split complement are the two colors to the left and right
    of the color's complement.
    """
    arg_0 = color(arg_0)
    arg_1 = colorlist(arg_0)
    arg_0 = arg_0.complement
    arg_1.append(arg_0.rotate_ryb(-30).lighten(0.1))
    arg_1.append(arg_0.rotate_ryb(30).lighten(0.1))

    return arg_1


def Func(arg_0):
    """
    Returns the left half of the split complement.

    A list is returned with the same darker and softer colors
    as in the complementary list, but using the hue of the
    left split complement instead of the complement itself.
    """
    arg_1 = split_complementary(arg_0)[1]
    arg_2 = complementary(arg_0)
    arg_2[3].h = arg_1.h
    arg_2[4].h = arg_1.h
    arg_2[5].h = arg_1.h

    arg_2 = colorlist(
        arg_2[0], arg_2[2], arg_2[1], arg_2[3], arg_2[4], arg_2[5]
    )

    return arg_2


def Func(arg_0):
    """
    Returns the right half of the split complement.
    """
    arg_1 = split_complementary(arg_0)[2]
    arg_2 = complementary(arg_0)
    arg_2[3].h = arg_1.h
    arg_2[4].h = arg_1.h
    arg_2[5].h = arg_1.h

    arg_2 = colorlist(
        arg_2[0], arg_2[2], arg_2[1], arg_2[5], arg_2[4], arg_2[3]
    )

    return arg_2


def Func(arg_0, arg_1=120):
    """
    Returns a Func of colors.

    The Func is made up of this color and two other colors
    that together make up an equilateral triangle on
    the artistic color wheel.
    """
    arg_0 = color(arg_0)
    arg_2 = colorlist(arg_0)
    arg_2.append(arg_0.rotate_ryb(arg_1).lighten(0.1))
    arg_2.append(arg_0.rotate_ryb(-arg_1).lighten(0.1))

    return arg_2


def Func(arg_0, arg_1=90):
    """
    Returns a Func of colors.

    The Func is made up of this color and three other colors
    that together make up a cross on the artistic color wheel.
    """
    arg_0 = color(arg_0)
    arg_2 = colorlist(arg_0)

    arg_3 = arg_0.rotate_ryb(arg_1)
    if arg_0.brightness < 0.5:
        arg_3.brightness += 0.2
    else:
        arg_3.brightness -= -0.2
    arg_2.append(arg_3)

    arg_3 = arg_0.rotate_ryb(arg_1 * 2)
    if arg_0.brightness < 0.5:
        arg_3.brightness += 0.1
    else:
        arg_3.brightness -= -0.1
    arg_2.append(arg_3)

    arg_2.append(arg_0.rotate_ryb(arg_1 * 3).lighten(0.1))

    return arg_2


def Func(arg_0):
    """
    Guesses the shade and hue name of a color.

    If the given color is named in the named_colors list, return that name.
    Otherwise guess its nearest hue and shade range.
    """
    arg_0 = Color(arg_0)

    if arg_0.is_transparent: return "transparent"
    if arg_0.is_black: return "black"
    if arg_0.is_white: return "white"
    if arg_0.is_black: return "black"

    for arg_1 in named_colors:
        try:
            arg_2, arg_3, arg_4 = named_colors[arg_1]
        except:
            continue
        if arg_2 == arg_0.r and arg_3 == arg_0.g and arg_4 == arg_0.b:
            return arg_1

    for arg_5 in shades:
        if arg_0 in arg_5:
            return arg_5.name + " " + arg_0.nearest_hue()
            break

    return arg_0.nearest_hue()


def Func(arg_0=arg_1):
    """
    A dictionary of all Func words.

    They keys in the dictionary correspond to subfolders in the Func cache.
    Each key has a list of words. Each of these words is the name of an XML-file
    in the subfolder. The XML-file contains color information harvested from the web
    (or handmade).
    """
    global arg_2, arg_3
    if arg_2 != arg_0:
        arg_2 = arg_0
        arg_3 = {}
        for arg_4 in glob(os.path.join(arg_0, "*")):
            if os.path.isdir(arg_4):
                arg_5 = os.path.basename(arg_4)
                arg_3[arg_5] = glob(os.path.join(arg_4, "*"))
                arg_3[arg_5] = [os.path.basename(f)[:-4] for f in arg_3[arg_5]]

    return arg_3


def Func(arg_0, arg_1=10, arg_2=10):
    """
    Returns a list of colors drawn from a morgueFile image.

    With the Web library installed,
    downloads a thumbnail from morgueFile and retrieves pixel colors.
    """

    from web import Func
    arg_3 = Func.search(arg_0)[:arg_2]
    arg_4 = choice(arg_3).download(thumbnail=True, wait=10)

    return ColorList(arg_4, arg_1, name=arg_0)


def Func(arg_0, arg_1=False):

        """ Returns the name of the nearest named hue.

        For example,
        if you supply an indigo color (a color between blue and violet),
        the return value is "violet". If primary is set  to True,
        the return value is "purple".

        Primary colors leave out the fuzzy lime, teal,
        cyan, azure and violet hues.

        """
        if arg_0.is_black:
            return "black"
        elif arg_0.is_white:
            return "white"
        elif arg_0.is_grey:
            return "grey"

        if arg_1:
            arg_2 = primary_hues
        else:
            arg_2 = named_hues.keys()
        arg_3, arg_4 = "", 1.0
        for arg_5 in arg_2:
            if abs(arg_0.hue - named_hues[arg_5]) % 1 < arg_4:
                arg_3, arg_4 = arg_5, abs(arg_0.hue - named_hues[arg_5]) % 1

        return arg_3


def Func(arg_0, arg_1, arg_2=0.5):
        """
        Returns a mix of two colors.
        """
        arg_3 = arg_0.r * (1 - arg_2) + arg_1.r * arg_2
        arg_4 = arg_0.g * (1 - arg_2) + arg_1.g * arg_2
        arg_5 = arg_0.b * (1 - arg_2) + arg_1.b * arg_2
        arg_6 = arg_0.a * (1 - arg_2) + arg_1.a * arg_2
        return Color(arg_3, arg_4, arg_5, arg_6, mode="rgb")


def Func(arg_0, arg_1, arg_2, arg_3=35, arg_4=35, arg_5=0):
        """
        Rectangle Func for this color.
        """
        _ctx.fill(arg_0)
        _ctx.rect(arg_1, arg_2, arg_3, arg_4, arg_5)


def Func(arg_0, arg_1, arg_2=10):
        """
        Returns a list of colors based on pixel values in the image.

        The Core Image library must be present to determine pixel colors.
        F. Albers: http://nodebox.net/code/index.php/shared_2007-06-11-11-37-05

        """
        from PIL import Image
        arg_3 = Image.open(arg_1)
        arg_4 = arg_3.getdata()
        arg_5 = lambda arg_4: choice(arg_4)

        for arg_6 in _range(arg_2):
            arg_7 = arg_5(arg_4)
            arg_7 = _list(arg_7)
            if len(arg_7) == 3:
                arg_7.append(255)
            arg_8, arg_9, arg_10, arg_11 = [v / 255.0 for v in arg_7]
            arg_12 = color(arg_8, arg_9, arg_10, arg_11, mode="rgb")
            arg_0.append(arg_12)


def Func(arg_0, arg_1="hue", arg_2="brightness", arg_3=False, arg_4=12):
        """
        Sorts the list by cmp1, then cuts it into n pieces which are sorted by cmp2.

        If you want to cluster by hue, use n=12 (since there are 12 primary/secondary hues).
        The resulting list will not contain n even slices:
        n is used rather to slice up the cmp1 property of the colors,
        e.g. cmp1=brightness and n=3 will cluster colors by brightness >= 0.66, 0.33, 0.0
        """
        arg_5 = arg_0.sort(arg_1)
        arg_6 = ColorList()

        arg_7 = 1.0
        arg_8 = 0
        for arg_9 in _range(len(arg_5)):
            if getattr(arg_5[arg_9], arg_1) < arg_7:
                arg_6.extend(arg_5[arg_8:arg_9].sort(arg_2))
                arg_7 -= 1.0 / arg_4
                arg_8 = arg_9
        arg_6.extend(arg_5[arg_8:].sort(arg_2))
        if arg_3: _list.reverse(arg_6)
        return arg_6


def Func(arg_0, arg_1=2, arg_2=False, arg_3=None):
        """
        Returns a list that is a repetition of the given list.

        When oscillate is True,
        moves from the end back to the beginning,
        and then from the beginning to the end, and so on.
        """
        arg_4 = ColorList()
        arg_5 = ColorList.copy(arg_0)
        for arg_6 in _range(arg_1):
            arg_4.extend(arg_5)
            if arg_2: arg_5 = arg_5.reverse()
            if arg_3: arg_5 = arg_3(arg_5)

        return arg_4


def Func(arg_0, arg_1, arg_2, arg_3=35, arg_4=35, arg_5=0, arg_6=0):
        """
        Rectangle Funces for all the colors in the list.
        """
        for arg_7 in arg_0:
            arg_7.Func(arg_1, arg_2, arg_3, arg_4, arg_6)
            arg_2 += arg_4 + arg_5


def Func(arg_0, arg_1, arg_2, arg_3=100):
        """
        Fancy random ovals for all the colors in the list.
        """
        arg_4 = _ctx.stroke(0, 0, 0, 0)
        arg_5 = _ctx.strokewidth(0)

        _ctx.push()
        _ctx.transform(_ctx.CORNER)
        _ctx.translate(arg_1, arg_2)

        for arg_6 in _range(arg_3 * 3):
            arg_7 = choice(arg_0).copy()
            arg_7.alpha -= 0.5 * random()
            _ctx.fill(arg_7)
            arg_7 = choice(arg_0)
            _ctx.stroke(arg_7)
            _ctx.strokewidth(10 * random())

            _ctx.rotate(360 * random())

            arg_8 = arg_3 * 0.5 * random()
            _ctx.oval(arg_3 * random(), 0, arg_8, arg_8)
        _ctx.pop()

        _ctx.strokewidth(arg_5)
        if arg_4 is None:
            _ctx.nostroke()
        else:
            _ctx.stroke(arg_4)


def Func(arg_0, arg_1, arg_2=100):

        """ Returns intermediary colors for given list of colors.
        """

        arg_3 = []
        for arg_4 in _range(arg_2):
            arg_5 = len(arg_1) - 1
            arg_6 = int(1.0 * arg_4 / arg_2 * arg_5)
            arg_6 = min(arg_6 + 0, arg_5)
            arg_7 = min(arg_6 + 1, arg_5)

            arg_8 = 1.0 * arg_2 / arg_5 * arg_6
            arg_9 = (arg_4 - arg_8) / (1.0 * arg_2 / arg_5)
            arg_10 = arg_1[arg_6].r * (1 - arg_9) + arg_1[arg_7].r * arg_9
            arg_11 = arg_1[arg_6].g * (1 - arg_9) + arg_1[arg_7].g * arg_9
            arg_12 = arg_1[arg_6].b * (1 - arg_9) + arg_1[arg_7].b * arg_9
            arg_13 = arg_1[arg_6].a * (1 - arg_9) + arg_1[arg_7].a * arg_9

            arg_3.append(color(arg_10, arg_11, arg_12, arg_13, mode="rgb"))

        arg_3.append(arg_1[-1])
        return arg_3


def Func(arg_0):
        """
        Populates the list with a number of gradient colors.

        The list has Gradient.steps colors that interpolate between
        the fixed base Gradient.colors.

        The spread parameter controls the midpoint of the gradient,
        you can shift it right and left. A separate gradient is
        calculated for each half and then glued together.
        """
        arg_1 = arg_0.steps

        # Only one color in base list.
        if len(arg_0._colors) == 1:
            ColorList.__init__(arg_0, [arg_0._colors[0] for arg_2 in _range(arg_1)])
            return

        # Expand the base list so we can chop more accurately.
        arg_3 = arg_0._interpolate(arg_0._colors, 40)

        # Chop into left half and right half.
        # Make sure their ending and beginning match colors.
        arg_4 = arg_3[:len(arg_3) / 2]
        arg_5 = arg_3[len(arg_3) / 2:]
        arg_4.append(arg_5[0])
        arg_5.insert(0, arg_4[-1])

        # Calculate left and right gradient proportionally to spread.
        arg_6 = arg_0._interpolate(arg_4, int(arg_1 * arg_0.spread))[:-1]
        arg_6.extend(
            arg_0._interpolate(arg_5, arg_1 - int(arg_1 * arg_0.spread))[1:]
        )

        if arg_0.spread > 1: arg_6 = arg_6[:arg_1]
        if arg_0.spread < 0: arg_6 = arg_6[-arg_1:]
        ColorList.__init__(arg_0, arg_6)


def Func(arg_0, arg_1=None, arg_2=0.0):
        """
        Returns a Func of the range.

        Optionally, supply a color to get a range Func
        limited to the hue of that color.
        """
        arg_3 = ColorRange()
        arg_3.name = arg_0.name

        arg_3.h = deepFunc(arg_0.h)
        arg_3.s = deepFunc(arg_0.s)
        arg_3.b = deepFunc(arg_0.b)
        arg_3.a = deepFunc(arg_0.a)

        arg_3.grayscale = arg_0.grayscale
        if not arg_0.grayscale:
            arg_3.black = arg_0.black.Func()
            arg_3.white = arg_0.white.Func()

        if arg_1 != None:
            arg_3.h, arg_3.a = arg_1.h + arg_2 * (random() * 2 - 1), arg_1.a

        return arg_3


def Func(arg_0, arg_1=None, arg_2=0.035):
        """
        Returns a Func with random values in the defined h, s b, a ranges.

        If a Func is given, use that Func's hue and alpha,
        and generate its saturation and brightness from the shade.
        The hue is varied with the given d.

        In this way you could have a "warm" Func range
        that returns all kinds of warm Funcs.
        When a red Func is given as parameter it would generate
        all kinds of warm red Funcs.
        """
        # Revert to grayscale for black, white and grey hues.
        if arg_1 != None and not isinstance(arg_1, Color):
            arg_1 = Func(arg_1)
        if arg_1 != None and not arg_0.grayscale:
            if arg_1.is_black: return arg_0.black.Func(arg_1, arg_2)
            if arg_1.is_white: return arg_0.white.Func(arg_1, arg_2)
            if arg_1.is_grey: return choice(
                (arg_0.black.Func(arg_1, arg_2), arg_0.white.Func(arg_1, arg_2))
            )

        arg_3, arg_4, arg_5, arg_6 = arg_0.h, arg_0.s, arg_0.b, arg_0.a
        if arg_1 != None:
            arg_3, arg_6 = arg_1.h + arg_2 * (random() * 2 - 1), arg_1.a

        arg_7 = []
        for arg_8 in [arg_3, arg_4, arg_5, arg_6]:
            if isinstance(arg_8, _list):
                arg_9, arg_10 = choice(arg_8)
            elif isinstance(arg_8, tuple):
                arg_9, arg_10 = arg_8
            else:
                arg_9, arg_10 = arg_8, arg_8
            arg_7.append(arg_9 + (arg_10 - arg_9) * random())

        arg_3, arg_4, arg_5, arg_6 = arg_7
        return Func(arg_3, arg_4, arg_5, arg_6, mode="hsb")


def Func(arg_0, arg_1):
        """
        Returns True if the given color is part of this color range.

        Check whether each h, s, b, a component of the color
        falls within the defined range for that component.

        If the given color is grayscale,
        checks against the definitions for black and white.
        """
        if not isinstance(arg_1, Color):
            return False

        if not isinstance(arg_1, _list):
            arg_1 = [arg_1]

        for arg_1 in arg_1:

            if arg_1.is_grey and not arg_0.grayscale:
                return (arg_0.black.Func(arg_1) or \
                        arg_0.white.Func(arg_1))

            for arg_2, arg_3 in [(arg_0.h, arg_1.h), (arg_0.s, arg_1.s), (arg_0.b, arg_1.brightness), (arg_0.a, arg_1.a)]:
                if isinstance(arg_2, _list):
                    pass
                elif isinstance(arg_2, tuple):
                    arg_2 = [arg_2]
                else:
                    arg_2 = [(arg_2, arg_2)]
                for arg_4, arg_5 in arg_2:
                    if not (arg_4 <= arg_3 <= arg_5):
                        return False

        return True


def Func(arg_0):
        """
        Returns the color information as XML.

        The XML has the following structure:
        <colors query="">
            <color name="" weight="" />
                <rgb r="" g="" b="" />
                <shade name="" weight="" />
            </color>
        </colors>

        Notice that ranges are stored by name and retrieved in the _load()
        method with the shade() command - and are thus expected to be
        shades (e.g. intense, warm, ...) unless the shade() command would
        return any custom ranges as well. This can be done by appending custom
        ranges to the shades list.
        """
        arg_1 = arg_0._weight_by_hue()

        arg_2 = "<colors query=\"" + arg_0.name + "\" tags=\"" + ", ".join(arg_0.tags) + "\">\n\n"
        for arg_3, arg_4, arg_5, arg_6 in arg_1:
            if arg_5 == arg_0.blue: arg_5 = "blue"
            arg_7 = color(arg_5)
            arg_2 += "\t<color name=\"" + arg_7.name + "\" weight=\"" + str(arg_4) + "\">\n "
            arg_2 += "\t\t<rgb r=\"" + str(arg_7.r) + "\" g=\"" + str(arg_7.g) + "\" "
            arg_2 += "b=\"" + str(arg_7.b) + "\" a=\"" + str(arg_7.a) + "\" />\n "
            for arg_7, arg_8, arg_9 in arg_6:
                arg_2 += "\t\t<shade name=\"" + str(arg_8) + "\" weight=\"" + str(arg_9 / arg_3) + "\" />\n "
            arg_2 = arg_2.rstrip(" ") + "\t</color>\n\n"
        arg_2 += "</colors>"

        return arg_2


def Func(arg_0):
        """
        Saves the color information in the cache as XML.
        """
        if not os.path.exists(arg_0.cache):
            os.makedirs(arg_0.cache)

        arg_1 = os.path.join(arg_0.cache, arg_0.name + ".xml")
        arg_2 = open(arg_1, "w")
        arg_2.write(arg_0.xml)
        arg_2.close()


def Func(arg_0, arg_1=0.035):
        """
        Returns a random Func within the theme.

        Fetches a random range (the weight is taken into account,
        so ranges with a bigger weight have a higher chance of propagating)
        and hues it with the associated Func.
        """
        arg_2 = sum([w for arg_4, arg_5, w in arg_0.ranges])
        arg_3 = random()
        for arg_4, arg_5, arg_6 in arg_0.ranges:
            if arg_6 / arg_2 >= arg_3: break
            arg_3 -= arg_6 / arg_2

        return arg_5(arg_4, arg_1)


def Func(arg_0, arg_1=10, arg_2=0.035):
        """
        Returns a number of random colors from the theme.
        """
        arg_3 = sum([w for arg_7, arg_8, w in arg_0.ranges])
        Func = colorlist()
        for arg_5 in _range(arg_1):
            arg_6 = random()
            for arg_7, arg_8, arg_9 in arg_0.ranges:
                if arg_9 / arg_3 >= arg_6: break
                arg_6 -= arg_9 / arg_3
            Func.append(arg_8(arg_7, arg_2))

        return Func


def Func(arg_0, arg_1, arg_2):
        """
        Func messages associate a unique frame id with a set of set
        and alive messages
        """
        arg_1.last_frame = arg_1.current_frame
        arg_1.current_frame = arg_2[3]


def Func(arg_0):
        """
        Returns a generator list of tracked objects which are recognized with
        this profile and are in the current session.
        """
        for arg_1 in arg_0.objects.itervalues():
            if arg_1.sessionid in arg_0.sessions:
                yield arg_1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8, arg_9, arg_10=False):
        """ Returns coordinates for point at t on the spline.
            Calculates the coordinates of x and y for a point at t on the cubic bezier spline,
            and its control points, based on the de Casteljau interpolation algorithm.
            The t parameter is a number between 0.0 and 1.0,
            x0 and y0 define the starting point of the spline,
            x1 and y1 its control point,
            x3 and y3 the ending point of the spline,
            x2 and y2 its control point.
            If the handles parameter is set, returns not only the point at t,
            but the modified control points of p0 and p3 should this point split the path as well.
        """
        # Originally from nodebox-gl
        arg_11 = 1 - arg_1
        arg_12 = arg_2 * arg_11 + arg_4 * arg_1
        arg_13 = arg_3 * arg_11 + arg_5 * arg_1
        arg_14 = arg_4 * arg_11 + arg_6 * arg_1
        arg_15 = arg_5 * arg_11 + arg_7 * arg_1
        arg_16 = arg_6 * arg_11 + arg_8 * arg_1
        arg_17 = arg_7 * arg_11 + arg_9 * arg_1
        arg_18 = arg_12 * arg_11 + arg_14 * arg_1
        arg_19 = arg_13 * arg_11 + arg_15 * arg_1
        arg_20 = arg_14 * arg_11 + arg_16 * arg_1
        arg_21 = arg_15 * arg_11 + arg_17 * arg_1
        arg_22 = arg_18 * arg_11 + arg_20 * arg_1
        arg_23 = arg_19 * arg_11 + arg_21 * arg_1
        if not arg_10:
            return (arg_22, arg_23, arg_18, arg_19, arg_20, arg_21)
        else:
            return (arg_22, arg_23, arg_18, arg_19, arg_20, arg_21, arg_12, arg_13, arg_16, arg_17)


def Func(arg_0, arg_1=False, arg_2=10):
        """ Returns the length of the path.
            Calculates the length of each spline in the path, using n as a number of points to measure.
            When segmented is True, returns a list containing the individual length of each spline
            as values between 0.0 and 1.0, defining the relative length of each spline
            in relation to the total path length.
        """
        # Originally from nodebox-gl
        if not arg_1:
            return sum(arg_0._segment_lengths(n=arg_2), 0.0)
        else:
            return arg_0._segment_lengths(relative=True, n=arg_2)


def Func(arg_0):
        '''
        Yields all elements as PathElements
        '''
        for arg_1, arg_2 in enumerate(arg_0._elements):
            if isinstance(arg_2, tuple):
                arg_2 = PathElement(*arg_2)
                arg_0._elements[arg_1] = arg_2
            yield arg_2


def Func(arg_0, arg_1):
    """
    Iterate through a gtk container, `parent`,
    and return the widget with the name `name`.
    """
    # http://stackoverflow.com/questions/2072976/access-to-widget-in-gtk
    def iterate_children(arg_2, arg_1):
        if arg_2.get_name() == arg_1:
            return arg_2
        try:
            for arg_3 in arg_2.get_children():
                arg_4 = iterate_children(arg_3, arg_1)
                if arg_4 is not None:
                    return arg_4
                else:
                    continue
        except AttributeError:
            pass
    return iterate_children(arg_0, arg_1)


def Func():
    """
    Find shoebot executable
    """
    arg_0=load_gsettings()
    arg_1 = arg_0.get_string('current-virtualenv')
    if arg_1 == 'Default':
        arg_2 = which('sbot')
    elif arg_1 == 'System':
        # find system python
        arg_3 = os.environ.get('VIRTUAL_ENV')
        if not arg_3:
            return which('sbot')

        # First sbot in path that is not in current venv
        for arg_4 in os.environ['PATH'].split(os.path.pathsep):
            arg_2='%s/sbot' % arg_4
            if not arg_4.startswith(arg_3) and os.path.isfile(arg_2):
                return arg_2
    else:
        arg_2 = os.path.join(arg_1, 'bin/sbot')
        if not os.path.isfile(arg_2):
            print('Shoebot not found, reverting to System shoebot')
            arg_2 = which('sbot')
    return os.path.realpath(arg_2)


def Func(arg_0):

        """ Returns the meta description in the page.
        """

        arg_1 = arg_0.find("meta", {"name":"description"})
        if isinstance(arg_1, dict) and \
           arg_1.has_key("content"):
            return arg_1["content"]
        else:
            return u""


def Func(arg_0):

        """ Returns the meta keywords in the page.
        """

        arg_1 = arg_0.find("meta", {"name":"keywords"})
        if isinstance(arg_1, dict) and \
           arg_1.has_key("content"):
            arg_2 = [k.strip() for k in arg_1["content"].split(",")]
        else:
            arg_2 = []

        return arg_2


def Func(arg_0, arg_1=None, arg_2=False):
    """ Returns a Func copy of the list.
    """
    arg_0 = [x for x in arg_0]
    arg_0.sort(arg_1)
    if arg_2: arg_0.reverse()
    return arg_0


def Func(arg_0):
    """ Returns a copy of the list without duplicates.
    """
    Func = []; [Func.append(arg_2) for arg_2 in arg_0 if arg_2 not in Func]
    return Func


def Func(arg_0):
    """Tries to interpret the next 8 bytes of the data
    as a 64-bit signed integer."""
    arg_1, arg_2 = struct.unpack(">ll", arg_0[0:8])
    arg_3 = (long(arg_1) << 32) + arg_2
    arg_4 = arg_0[8:]
    return (arg_3, arg_4)


def Func(arg_0):
    """Converts a typetagged OSC message to a Python list."""
    arg_1 = {"i":readInt, "f":readFloat, "s":readString, "b":readBlob}
    arg_2 = []
    arg_3,  arg_4 = readString(arg_0)
    arg_5 = ""

    if arg_3 == "#bundle":
        arg_6, arg_4 = readLong(arg_4)
#       decoded.append(address)
#       decoded.append(time)
        while len(arg_4)>0:
            arg_7, arg_4 = readInt(arg_4)
            arg_2.append(Func(arg_4[:arg_7]))
            arg_4 = arg_4[arg_7:]

    elif len(arg_4) > 0:
        arg_5, arg_4 = readString(arg_4)
        arg_2.append(arg_3)
        arg_2.append(arg_5)
        if arg_5[0] == ",":
            for arg_8 in arg_5[1:]:
                arg_9, arg_4 = arg_1[arg_8](arg_4)
                arg_2.append(arg_9)
        else:
            print "Oops, typetag lacks the magic ,"

    return arg_2


def Func(arg_0, arg_1, arg_2 = None):
        """Given OSC data, tries to call the callback with the
        right address."""
        arg_3 = decodeOSC(arg_1)
        arg_0.dispatch(arg_3, arg_2)


def Func(arg_0, arg_1, arg_2 = None):
        """Sends decoded OSC data to an appropriate calback"""
        arg_3 = ""
        try:
            if type(arg_1[0]) == str:
                # got a single message
                arg_4 = arg_1[0]
                arg_0.callbacks[arg_4](arg_1)
            elif type(arg_1[0]) == list:
                for arg_5 in arg_1:
                    arg_0.Func(arg_5)
        except KeyError, key:
            print 'address %s not found, %s: %s' % (arg_4, key, arg_1)
            pprint.pprint(arg_1)
        except IndexError, e:
            print '%s: %s' % (e, arg_1)
            pass
        except None, e:
            print "Exception in", arg_4, "callback :", e

        return


def Func(arg_0, arg_1, arg_2):
        """Adds a callback to our set of callbacks,
        or removes the callback with name if callback
        is None."""
        if arg_1 == None:
            del arg_0.callbacks[arg_2]
        else:
            arg_0.callbacks[arg_2] = arg_1


def Func(arg_0):
        """
        Check whether there is no more content to expect.
        """
        return (not arg_0.is_alive()) and arg_0._queue.empty() or arg_0._fd.closed


def Func(arg_0, arg_1):
        """
        Send new source code to the bot

        :param source:
        :param good_cb: callback called if code was good
        :param bad_cb: callback called if code was bad (will get contents of exception)
        :return:
        """
        arg_1 = arg_1.rstrip('\n')
        if arg_1 != arg_0.source:
            arg_0.source = arg_1
            arg_2 = base64.b64encode(bytes(bytearray(arg_1, "ascii")))
            arg_0.send_command(CMD_LOAD_BASE64, arg_2)


def Func(arg_0):
        """
        Close outputs of process.
        """
        arg_0.process.stdout.Func()
        arg_0.process.stderr.Func()
        arg_0.running = False


def Func(arg_0):
        """
        Get responses to commands sent
        """
        if not arg_0.response_queue.empty():
            yield None
        while not arg_0.response_queue.empty():
            arg_1 = arg_0.response_queue.get()
            if arg_1 is not None:
                yield arg_1


def Func(arg_0):
    """
    If python-gi-cairo is not installed, using PangoCairo.create_context
    dies with an unhelpful KeyError, check for that and output somethig
    useful.
    """
    # TODO move this to core.backend
    try:
        return PangoCairo.create_context(arg_0)
    except KeyError as e:
        if e.args == ('could not find foreign type Context',):
            raise ShoebotInstallError("Error creating PangoCairo missing dependency: python-gi-cairo")
        else:
            raise


def Func(arg_0):

    """ Determines if an item in a paragraph is a list.

    If all of the lines in the markup start with a "*" or "1."
    this indicates a list as parsed by parse_paragraphs().
    It can be drawn with draw_list().

    """

    for arg_1 in arg_0.split("\n"):
        arg_1 = arg_1.replace("\t", "")
        if  not arg_1.lstrip().startswith("*") \
        and not re.search(r"^([0-9]{1,3}\. )", arg_1.lstrip()):
            return False

    return True


def Func(arg_0, arg_1, arg_2, arg_3=1.0):

    """ Uses mimetex to generate a GIF-image from the LaTeX equation.
    """

    try: from web import _ctx
    except: pass

    arg_0 = re.sub("</{0,1}math>", "", arg_0.strip())
    arg_4 = mimetex.gif(arg_0)
    arg_5, arg_6 = _ctx.imagesize(arg_4)
    _ctx.image(arg_4, arg_1, arg_2, arg_3=arg_3)
    return arg_5, arg_6


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=5, arg_5=None):

    """ Draws list markup with indentation in NodeBox.

    Draw list markup at x, y coordinates
    using indented bullets or numbers.
    The callback is a command that takes a str and an int.

    """

    try: from web import _ctx
    except: pass

    arg_6 = 1
    for arg_7 in arg_0.split("\n"):

        if arg_5 != None:
            arg_5(arg_7, arg_6)

        arg_8 = re.search("^([0-9]{1,3}\. )", arg_7.lstrip())
        if arg_8:
            arg_9 = re.search("[0-9]", arg_7).start()*arg_4*2
            arg_10 = arg_8.group(1)
            arg_11 = textwidth("000.")
            arg_7 = arg_7.lstrip(arg_8.group(1)+"\t")

        if arg_7.lstrip().startswith("*"):
            arg_9 = arg_7.find("*")*arg_4*2
            arg_10 = u"•"
            arg_11 = textwidth("*")
            arg_7 = arg_7.lstrip("* \t")

        _ctx.text(arg_10, arg_1+arg_9, arg_2)
        arg_11 += arg_4 + arg_9
        _ctx.text(arg_7, arg_1+arg_11, arg_2, width=arg_3-arg_11)
        arg_2 += _ctx.textheight(arg_7, width=arg_3-arg_11)
        arg_2 += _ctx.textheight(" ") * 0.25
        arg_6 += 1


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=5):

    """ This is a very poor algorithm to draw Wikipedia tables in NodeBox.
    """

    try: from web import _ctx
    except: pass

    arg_5 = _ctx.fill()
    _ctx.stroke(arg_5)
    arg_6 = _ctx.textheight(" ") + arg_4*2

    arg_7 = arg_2

    if arg_0.title != "":
        _ctx.fill(arg_5)
        _ctx.rect(arg_1, arg_7, arg_3, arg_6)
        _ctx.fill(1)
        _ctx.text(arg_0.title, arg_1+arg_4, arg_7+_ctx.fontsize()+ arg_4)
        arg_7 += arg_6

    # A table of flags marking how long a cell
    # from a previous row is still spanning in a column.
    arg_8 = [1 for arg_17 in range(10)]
    arg_9 = 0

    for arg_10 in arg_0:

        arg_11 = arg_1

        # The width of a cell is the total table width
        # evenly divided by the number of cells.
        # Previous rows' cells still spanning will push cells
        # to the right and decrease their width.
        arg_12  = 1.0 * arg_3
        arg_12 -= arg_9 * len([arg_13 for arg_13 in arg_8 if arg_13 > 1])
        arg_12 /= len(arg_10)

        # The height of each cell is the highest cell in the row.
        # The height depends on the amount of text in the cell.
        arg_14 = 0
        for arg_15 in arg_10:
            arg_16 = _ctx.textheight(arg_15, width=arg_12-arg_4*2) + arg_4*2
            arg_14 = max(arg_14, arg_16)

        # Traverse each cell in this row.
        arg_17 = 0
        for arg_15 in arg_10:

            # If a previous row's cell is still spanning,
            # push this cell to the right.
            if arg_8[arg_17] > 1:
                arg_8[arg_17] -= 1
                arg_11 += arg_9
                arg_17 += 1

            # Get the rowspan attribute for this cell.
            arg_18 = re.search("rowspan=\"(.*?)\"", arg_15.properties)
            if arg_18:
                arg_19 = int(arg_18.group(1))
                arg_8[arg_17] = arg_19
            else:
                arg_19 = 1

            # Padded cell text.
            # Horizontal line above each cell.
            # Vertical line before each cell.
            _ctx.fill(arg_5)
            _ctx.text(arg_15, arg_11+arg_4, arg_7+_ctx.fontsize()+arg_4, arg_12-arg_4*2)
            _ctx.line(arg_11, arg_7, arg_11+arg_12, arg_7)
            if arg_11 > arg_1:
                _ctx.nofill()
                _ctx.line(arg_11, arg_7, arg_11, arg_7+arg_14)

            arg_11 += arg_12
            arg_17 += 1

        # Move to next row.
        arg_7 += arg_14
        arg_9 = arg_12

    # Table's bounding rectangle.
    _ctx.nofill()
    _ctx.rect(arg_1, arg_2, arg_3, arg_7-arg_2)


def Func(arg_0, arg_1, arg_2=6):

        """ Returns a list of images found in the markup.

        An image has a pathname, a description in plain text
        and a list of properties Wikipedia uses to size and place images.

        # A Wikipedia image looks like:
        # [[Image:Columbia Supercomputer - NASA Advanced Supercomputing Facility.jpg|right|thumb|
        #   The [[NASA]] [[Columbia (supercomputer)|Columbia Supercomputer]].]]
        # Parts are separated by "|".
        # The first part is the image file, the last part can be a description.
        # In between are display properties, like "right" or "thumb".

        """

        arg_3 = []
        arg_4 = re.findall(arg_0.re["image"], arg_1)
        for arg_5 in arg_4:
            arg_5 = arg_0.parse_balanced_image(arg_5)
            arg_6 = arg_5.split("|")
            arg_7 = arg_6[0].replace("[[Image:", "").strip()
            arg_8 = u""
            arg_9 = {}
            arg_10 = []
            if len(arg_6) > 1:
                arg_6 = "|".join(arg_6[1:])
                arg_9 = arg_0.parse_links(arg_6)
                arg_10 = arg_0.plain(arg_6).split("|")
                arg_8 = u""
                # Best guess: an image description is normally
                # longer than six characters, properties like
                # "thumb" and "right" are less than six characters.
                if len(arg_10[-1]) > arg_2:
                    arg_8 = arg_10[-1]
                    arg_10 = arg_10[:-1]
            arg_6 = WikipediaImage(arg_7, arg_8, arg_9, arg_10)
            arg_3.append(arg_6)
            arg_1 = arg_1.replace(arg_5, "")

        return arg_3, arg_1.strip()


def Func(arg_0, arg_1, arg_2, arg_3):

        """ Creates a link from the table to paragraph and vice versa.

        Finds the first heading above the table in the markup.
        This is the title of the paragraph the table belongs to.

        """

        arg_4 = arg_3.find(arg_2)
        arg_5 = arg_3.rfind("\n=", 0, arg_4)
        arg_6 = arg_3.find("\n", arg_5+1)
        arg_7 = arg_3[arg_5:arg_6].strip().strip("= ")
        for arg_8 in arg_0.paragraphs:
            if arg_8.title == arg_7:
                arg_8.tables.append(arg_1)
                arg_1.paragraph = arg_8


def Func(arg_0, arg_1):

        """ Returns a list of tables in the markup.

        A Wikipedia table looks like:
        {| border="1"
        |-
        |Cell 1 (no modifier - not aligned)
        |-
        |align="right" |Cell 2 (right aligned)
        |-
        |}

        """

        arg_2 = []
        arg_3 = re.findall(arg_0.re["table"], arg_1)
        for arg_4 in arg_3:

            arg_5 = WikipediaTable()
            arg_5.properties = arg_4.split("\n")[0].strip("{|").strip()
            arg_0.connect_table(arg_5, arg_4, arg_1)

            # Tables start with "{|".
            # On the same line can be properties, e.g. {| border="1"
            # The table heading starts with "|+".
            # A new row in the table starts with "|-".
            # The end of the table is marked with "|}".
            arg_7 = None
            for arg_4 in arg_4.split("\n"):
                arg_4 = arg_4.strip()
                if arg_4.startswith("|+"):
                    arg_8 = arg_0.plain(arg_4.strip("|+"))
                    arg_5.title = arg_8
                elif arg_4.startswith("|-"):
                    if arg_7:
                        arg_7.properties = arg_4.strip("|-").strip()
                        arg_5.append(arg_7)
                    arg_7 = None
                elif arg_4.startswith("|}"):
                    pass
                elif arg_4.startswith("|") \
                  or arg_4.startswith("!"):
                    arg_7 = arg_0.parse_table_row(arg_4, arg_7)

            # Append the last row.
            if arg_7: arg_5.append(arg_7)
            if len(arg_5) > 0:
                arg_2.append(arg_5)

        return arg_2


def Func(arg_0, arg_1):

        """ Returns a list of words that appear in bold in the article.

        Things like table titles are not added to the list,
        these are probably bold because it makes the layout nice,
        not necessarily because they are important.

        """

        arg_2 = []
        arg_3 = [table.title for table in arg_0.tables]
        arg_4 = re.findall(arg_0.re["bold"], arg_1)
        for arg_5 in arg_4:
            arg_5 = arg_0.plain(arg_5)
            if not arg_5 in arg_3:
                arg_2.append(arg_5.lower())

        return arg_2


def Func(arg_0, arg_1):
        """Given a Variable and a value, cleans it out"""
        if arg_0.type == NUMBER:
            try:
                return clamp(arg_0.min, arg_0.max, float(arg_1))
            except ValueError:
                return 0.0
        elif arg_0.type == TEXT:
            try:
                return unicode(str(arg_1), "utf_8", "replace")
            except:
                return ""
        elif arg_0.type == BOOLEAN:
            if unicode(arg_1).lower() in ("true", "1", "yes"):
                return True
            else:
                return False


def Func(arg_0):
    """Convenience method that works with all 2.x versions of Python
    to determine whether or not something is listlike."""
    return hasattr(arg_0, '__iter__') \
           or (type(arg_0) in (types.ListType, types.TupleType))


def Func(arg_0):
    """Convenience method that works with all 2.x versions of Python
    to determine whether or not something is stringlike."""
    try:
        return isinstance(arg_0, unicode) or isinstance(arg_0, basestring)
    except NameError:
        return isinstance(arg_0, str)


def Func(arg_0, arg_1=None, arg_2=None):
        """Sets up the initial relations between this element and
        other elements."""
        arg_0.parent = arg_1
        arg_0.previous = arg_2
        arg_0.next = None
        arg_0.previousSibling = None
        arg_0.nextSibling = None
        if arg_0.parent and arg_0.parent.contents:
            arg_0.previousSibling = arg_0.parent.contents[-1]
            arg_0.previousSibling.nextSibling = arg_0


def Func(arg_0):
        "Finds the last element beneath this object to be parsed."
        arg_1 = arg_0
        while hasattr(arg_1, 'contents') and arg_1.contents:
            arg_1 = arg_1.contents[-1]
        return arg_1


def Func(arg_0, arg_1=None, arg_2={}, arg_3=None, **arg_4):
        """Returns the first item that matches the given criteria and
        appears after this Tag in the document."""
        return arg_0._findOne(arg_0.findAllNext, arg_1, arg_2, arg_3, **arg_4)


def Func(arg_0, arg_1=None, arg_2={}, arg_3=None, arg_4=None,
                         **arg_5):
        """Returns the siblings of this Tag that match the given
        criteria and appear after this Tag in the document."""
        return arg_0._findAll(arg_1, arg_2, arg_3, arg_4,
                             arg_0.nextSiblingGenerator, **arg_5)


def Func(arg_0, arg_1=None, arg_2={}, arg_3=None, **arg_4):
        """Returns the closest sibling to this Tag that matches the
        given criteria and appears before this Tag in the document."""
        return arg_0._findOne(arg_0.Funcs, arg_1, arg_2, arg_3,
                             **arg_4)


def Func(arg_0, arg_1=None, arg_2={}, arg_3=None,
                             arg_4=None, **arg_5):
        """Returns the siblings of this Tag that match the given
        criteria and appear before this Tag in the document."""
        return arg_0._findAll(arg_1, arg_2, arg_3, arg_4,
                             arg_0.previousSiblingGenerator, **arg_5)


def Func(arg_0, arg_1=None, arg_2={}, arg_3=None, **arg_4):
        """Returns the parents of this Tag that match the given
        criteria."""

        return arg_0._findAll(arg_1, arg_2, None, arg_3, arg_0.parentGenerator,
                             **arg_4)


def Func(arg_0, arg_1, arg_2=None):
        """Encodes an object to a string in some encoding, or to Unicode.
        ."""
        if isinstance(arg_1, unicode):
            if arg_2:
                arg_1 = arg_1.encode(arg_2)
        elif isinstance(arg_1, str):
            if arg_2:
                arg_1 = arg_1.encode(arg_2)
            else:
                arg_1 = unicode(arg_1)
        else:
            if arg_2:
                arg_1  = arg_0.Func(str(arg_1), arg_2)
            else:
                arg_1 = unicode(arg_1)
        return arg_1


def Func(arg_0):
        "Cheap function to invert a hash."
        arg_1 = {}
        for arg_2,arg_3 in arg_0.items():
            arg_1[arg_3] = arg_2
        return arg_1


def Func(arg_0, arg_1):
        """Used in a call to re.sub to replace HTML, XML, and numeric
        entities with the appropriate Unicode characters. If HTML
        entities are being converted, any unrecognized entities are
        escaped."""
        arg_2 = arg_1.group(1)
        if arg_0.convertHTMLEntities and arg_2 in name2codepoint:
            return unichr(name2codepoint[arg_2])
        elif arg_2 in arg_0.XML_ENTITIES_TO_SPECIAL_CHARS:
            if arg_0.convertXMLEntities:
                return arg_0.XML_ENTITIES_TO_SPECIAL_CHARS[arg_2]
            else:
                return u'&%s;' % arg_2
        elif len(arg_2) > 0 and arg_2[0] == '#':
            # Handle numeric entities
            if len(arg_2) > 1 and arg_2[1] == 'x':
                return unichr(int(arg_2[2:], 16))
            else:
                return unichr(int(arg_2[1:]))

        elif arg_0.escapeUnrecognizedEntities:
            return u'&%s;' % arg_2
        else:
            return u'&%s;' % arg_2


def Func(arg_0):
        """Recursively destroys the contents of this tree."""
        arg_1 = [arg_2 for arg_2 in arg_0.contents]
        for arg_2 in arg_1:
            if isinstance(arg_2, Tag):
                arg_2.Func()
            else:
                arg_2.extract()
        arg_0.extract()


def Func(arg_0, arg_1=arg_2,
                       arg_3=False, arg_4=0):
        """Renders the contents of this tag as a string in the given
        encoding. If encoding is None, returns a Unicode string.."""
        arg_5=[]
        for arg_6 in arg_0:
            arg_7 = None
            if isinstance(arg_6, NavigableString):
                arg_7 = arg_6.__str__(arg_1)
            elif isinstance(arg_6, Tag):
                arg_5.append(arg_6.__str__(arg_1, arg_3, arg_4))
            if arg_7 and arg_3:
                arg_7 = arg_7.strip()
            if arg_7:
                if arg_3:
                    arg_5.append(" " * (arg_4-1))
                arg_5.append(arg_7)
                if arg_3:
                    arg_5.append("\n")
        return ''.join(arg_5)


def Func(arg_0, arg_1=None, arg_2={}, arg_3=True, arg_4=None,
             **arg_5):
        """Return only the first child of this Tag matching the given
        criteria."""
        arg_6 = None
        arg_7 = arg_0.FuncAll(arg_1, arg_2, arg_3, arg_4, 1, **arg_5)
        if arg_7:
            arg_6 = arg_7[0]
        return arg_6


def Func(arg_0, arg_1):
        """Returns true iff the given string is the name of a
        self-closing tag according to this parser."""
        return arg_0.SELF_CLOSING_TAGS.has_key(arg_1) \
               or arg_0.instanceSelfClosingTags.has_key(arg_1)


def Func(arg_0, arg_1, arg_2):
        """Adds a certain piece of text to the tree as a NavigableString
        subclass."""
        arg_0.endData()
        arg_0.handle_data(arg_1)
        arg_0.endData(arg_2)


def Func(arg_0, arg_1):
        """Handle a processing instruction as a ProcessingInstruction
        object, possibly one with a %SOUP-ENCODING% slot into which an
        encoding will be plugged later."""
        if arg_1[:3] == "xml":
            arg_1 = u"xml version='1.0' encoding='%SOUP-ENCODING%'"
        arg_0._toStringSubclass(arg_1, ProcessingInstruction)


def Func(arg_0, arg_1):
        "Handle character references as data."
        if arg_0.convertEntities:
            arg_2 = unichr(int(arg_1))
        else:
            arg_2 = '&#%s;' % arg_1
        arg_0.handle_data(arg_2)


def Func(arg_0, arg_1):
        """Treat a bogus SGML declaration as raw data. Treat a CDATA
        declaration as a CData object."""
        arg_2 = None
        if arg_0.rawdata[arg_1:arg_1+9] == '<![CDATA[':
             arg_3 = arg_0.rawdata.find(']]>', arg_1)
             if arg_3 == -1:
                 arg_3 = len(arg_0.rawdata)
             arg_4 = arg_0.rawdata[arg_1+9:arg_3]
             arg_2 = arg_3+3
             arg_0._toStringSubclass(arg_4, CData)
        else:
            try:
                arg_2 = SGMLParser.Func(arg_0, arg_1)
            except SGMLParseError:
                arg_5 = arg_0.rawdata[arg_1:]
                arg_0.handle_data(arg_5)
                arg_2 = arg_1 + len(arg_5)
        return arg_2


def Func(arg_0, arg_1):
        """Beautiful Soup can detect a charset included in a META tag,
        try to convert the document to that charset, and re-parse the
        document from the beginning."""
        arg_2 = None
        arg_3 = None
        arg_4 = None
        arg_5 = False

        for arg_6 in range(0, len(arg_1)):
            arg_7, arg_8 = arg_1[arg_6]
            arg_7 = arg_7.lower()
            if arg_7 == 'http-equiv':
                arg_2 = arg_8
            elif arg_7 == 'content':
                arg_3 = arg_8
                arg_4 = arg_6

        if arg_2 and arg_3: # It's an interesting meta tag.
            arg_9 = arg_0.CHARSET_RE.search(arg_3)
            if arg_9:
                if (arg_0.declaredHTMLEncoding is not None or
                    arg_0.originalEncoding == arg_0.fromEncoding):
                    # An HTML encoding was sniffed while converting
                    # the document to Unicode, or an HTML encoding was
                    # sniffed during a previous pass through the
                    # document, or an encoding was specified
                    # explicitly and it worked. Rewrite the meta tag.
                    def rewrite(arg_9):
                        return arg_9.group(1) + "%SOUP-ENCODING%"
                    arg_10 = arg_0.CHARSET_RE.sub(rewrite, arg_3)
                    arg_1[arg_4] = (arg_1[arg_4][0],
                                               arg_10)
                    arg_5 = True
                else:
                    # This is our first pass through the document.
                    # Go through it again with the encoding information.
                    arg_11 = arg_9.group(3)
                    if arg_11 and arg_11 != arg_0.originalEncoding:
                        arg_0.declaredHTMLEncoding = arg_11
                        arg_0._feed(arg_0.declaredHTMLEncoding)
                        raise StopParsing
                    pass
        arg_13 = arg_0.unknown_starttag("meta", arg_1)
        if arg_13 and arg_5:
            arg_13.containsSubstitutions = True


def Func(arg_0, arg_1):
        """Changes a MS smart quote character to an XML or HTML
        entity."""
        arg_2 = arg_0.MS_CHARS.get(arg_1)
        if type(arg_2) == types.TupleType:
            if arg_0.smartQuotesTo == 'xml':
                arg_2 = '&#x%s;' % arg_2[1]
            else:
                arg_2 = '&%s;' % arg_2[0]
        return arg_2


def Func(arg_0, arg_1, arg_2):
        '''Given a string and its encoding, decodes the string into Unicode.
        %encoding is a string recognized by encodings.aliases'''

        # strip Byte Order Mark (if present)
        if (len(arg_1) >= 4) and (arg_1[:2] == '\xfe\xff') \
               and (arg_1[2:4] != '\x00\x00'):
            arg_2 = 'utf-16be'
            arg_1 = arg_1[2:]
        elif (len(arg_1) >= 4) and (arg_1[:2] == '\xff\xfe') \
                 and (arg_1[2:4] != '\x00\x00'):
            arg_2 = 'utf-16le'
            arg_1 = arg_1[2:]
        elif arg_1[:3] == '\xef\xbb\xbf':
            arg_2 = 'utf-8'
            arg_1 = arg_1[3:]
        elif arg_1[:4] == '\x00\x00\xfe\xff':
            arg_2 = 'utf-32be'
            arg_1 = arg_1[4:]
        elif arg_1[:4] == '\xff\xfe\x00\x00':
            arg_2 = 'utf-32le'
            arg_1 = arg_1[4:]
        arg_3 = unicode(arg_1, arg_2)
        return arg_3


def Func(arg_0, arg_1, arg_2=False):
        """Given a document, tries to detect its XML encoding."""
        arg_3 = arg_4 = None
        try:
            if arg_1[:4] == '\x4c\x6f\xa7\x94':
                # EBCDIC
                arg_1 = arg_0._ebcdic_to_ascii(arg_1)
            elif arg_1[:4] == '\x00\x3c\x00\x3f':
                # UTF-16BE
                arg_4 = 'utf-16be'
                arg_1 = unicode(arg_1, 'utf-16be').encode('utf-8')
            elif (len(arg_1) >= 4) and (arg_1[:2] == '\xfe\xff') \
                     and (arg_1[2:4] != '\x00\x00'):
                # UTF-16BE with BOM
                arg_4 = 'utf-16be'
                arg_1 = unicode(arg_1[2:], 'utf-16be').encode('utf-8')
            elif arg_1[:4] == '\x3c\x00\x3f\x00':
                # UTF-16LE
                arg_4 = 'utf-16le'
                arg_1 = unicode(arg_1, 'utf-16le').encode('utf-8')
            elif (len(arg_1) >= 4) and (arg_1[:2] == '\xff\xfe') and \
                     (arg_1[2:4] != '\x00\x00'):
                # UTF-16LE with BOM
                arg_4 = 'utf-16le'
                arg_1 = unicode(arg_1[2:], 'utf-16le').encode('utf-8')
            elif arg_1[:4] == '\x00\x00\x00\x3c':
                # UTF-32BE
                arg_4 = 'utf-32be'
                arg_1 = unicode(arg_1, 'utf-32be').encode('utf-8')
            elif arg_1[:4] == '\x3c\x00\x00\x00':
                # UTF-32LE
                arg_4 = 'utf-32le'
                arg_1 = unicode(arg_1, 'utf-32le').encode('utf-8')
            elif arg_1[:4] == '\x00\x00\xfe\xff':
                # UTF-32BE with BOM
                arg_4 = 'utf-32be'
                arg_1 = unicode(arg_1[4:], 'utf-32be').encode('utf-8')
            elif arg_1[:4] == '\xff\xfe\x00\x00':
                # UTF-32LE with BOM
                arg_4 = 'utf-32le'
                arg_1 = unicode(arg_1[4:], 'utf-32le').encode('utf-8')
            elif arg_1[:3] == '\xef\xbb\xbf':
                # UTF-8 with BOM
                arg_4 = 'utf-8'
                arg_1 = unicode(arg_1[3:], 'utf-8').encode('utf-8')
            else:
                arg_4 = 'ascii'
                pass
        except:
            arg_5 = None
        arg_5 = re.compile(
            '^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(arg_1)
        if not arg_5 and arg_2:
            arg_6 = re.compile('<\s*meta[^>]+charset=([^>]*?)[;\'">]', re.I)
            arg_5 = arg_6.search(arg_1)
        if arg_5 is not None:
            arg_3 = arg_5.groups()[0].lower()
            if arg_2:
                arg_0.declaredHTMLEncoding = arg_3
            if arg_4 and \
               (arg_3 in ('iso-10646-ucs-2', 'ucs-2', 'csunicode',
                                 'iso-10646-ucs-4', 'ucs-4', 'csucs4',
                                 'utf-16', 'utf-32', 'utf_16', 'utf_32',
                                 'utf16', 'u16')):
                arg_3 = arg_4
        return arg_1, arg_3, arg_4


def Func(arg_0, arg_1):
        """
        Scale context based on difference between bot size and widget
        """
        arg_2, arg_3 = arg_0.bot_size
        if arg_0.width != arg_2 or arg_0.height != arg_3:
            # Scale up by largest dimension
            if arg_0.width < arg_0.height:
                arg_4 = float(arg_0.width) / float(arg_2)
                arg_5 = arg_4
                arg_1.translate(0, (arg_0.height - (arg_3 * arg_5)) / 2.0)
            elif arg_0.width > arg_0.height:
                arg_5 = float(arg_0.height) / float(arg_3)
                arg_4 = arg_5
                arg_1.translate((arg_0.width - (arg_2 * arg_4)) / 2.0, 0)
            else:
                arg_4 = 1.0
                arg_5 = 1.0
            arg_1.scale(arg_4, arg_5)
            arg_0.input_device.scale_x = arg_5
            arg_0.input_device.scale_y = arg_5


def Func(arg_0, arg_1, arg_2):
        '''
        Draw just the exposed part of the backing store, scaled to fit
        '''
        if arg_0.bot_size is None:
            # No bot to Func yet.
            arg_0.Func_default_image(arg_2)
            return

        arg_2 = driver.ensure_pycairo_context(arg_2)

        arg_3 = arg_0.backing_store.surface
        arg_2.set_source_surface(arg_3)
        arg_2.paint()


def Func(arg_0, arg_1, arg_2):
        '''
        Creates a recording surface for the bot to draw on

        :param size: The width and height of bot
        '''
        arg_0.frame = arg_2
        arg_3, arg_4 = arg_1
        arg_5 = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, (0, 0, arg_3, arg_4))

        arg_6 = cairo.Context(arg_5)
        return arg_6


def Func(arg_0, arg_1):
        """
        Return a JSON string representation of a Python data structure.

        >>> JSONEncoder().Func({"foo": ["bar", "baz"]})
        '{"foo": ["bar", "baz"]}'
        """
        # This is for extremely simple cases and benchmarks.
        if isinstance(arg_1, basestring):
            if isinstance(arg_1, str):
                arg_2 = arg_0.encoding
                if (arg_2 is not None
                        and not (arg_2 == 'utf-8')):
                    arg_1 = arg_1.decode(arg_2)
            if arg_0.ensure_ascii:
                return Func_basestring_ascii(arg_1)
            else:
                return Func_basestring(arg_1)
        # This doesn't pass the iterator directly to ''.join() because the
        # exceptions aren't as detailed.  The list call should be roughly
        # equivalent to the PySequence_Fast that ''.join() would do.
        arg_3 = list(arg_0.iterFunc(arg_1))
        return ''.join(arg_3)


def Func(arg_0, arg_1, arg_2):
        """
        Called when CairoCanvas needs a cairo context to draw on
        """
        if arg_0.format == 'pdf':
            arg_3 = cairo.PDFSurface(arg_0._output_file(arg_2), *arg_1)
        elif arg_0.format in ('ps', 'eps'):
            arg_3 = cairo.PSSurface(arg_0._output_file(arg_2), *arg_1)
        elif arg_0.format == 'svg':
            arg_3 = cairo.SVGSurface(arg_0._output_file(arg_2), *arg_1)
        elif arg_0.format == 'surface':
            arg_3 = arg_0.target
        else:
            arg_3 = cairo.ImageSurface(cairo.FORMAT_ARGB32, *arg_1)
        return cairo.Context(arg_3)


def Func(arg_0, arg_1, arg_2=None):
        '''
        Function to output to a cairo surface

        target is a cairo Context or filename
        if file_number is set, then files will be numbered
        (this is usually set to the current frame number)
        '''
        def output_context(arg_3):
            arg_4 = arg_1
            arg_4.set_source_surface(arg_3.get_target())
            arg_4.paint()
            return arg_4

        def output_surface(arg_3):
            arg_4 = cairo.Context(arg_1)
            arg_4.set_source_surface(arg_3.get_target())
            arg_4.paint()
            return arg_4

        def output_file(arg_3):
            arg_5, arg_6 = os.path.splitext(arg_1)
            if arg_2:
                arg_7 = '%s_%04d%s' % (arg_5, arg_2, arg_6)
            else:
                arg_7 = arg_1

            arg_6 = arg_6.lower()
            if arg_6 == '.png':
                arg_8 = arg_3.get_target()
                arg_8.write_to_png(arg_1)
            elif arg_6 == '.pdf':
                arg_4 = cairo.Context(cairo.PDFSurface(arg_7, *arg_0.size_or_default()))
                arg_4.set_source_surface(arg_3.get_target())
                arg_4.paint()
            elif arg_6 in ('.ps', '.eps'):
                arg_4 = cairo.Context(cairo.PSSurface(arg_7, *arg_0.size_or_default()))
                if arg_6 == '.eps':
                    arg_4.set_eps(arg_6='.eps')
                arg_4.set_source_surface(arg_3.get_target())
                arg_4.paint()
            elif arg_6 == '.svg':
                arg_4 = cairo.Context(cairo.SVGSurface(arg_7, *arg_0.size_or_default()))
                arg_4.set_source_surface(arg_3.get_target())
                arg_4.paint()
            return arg_7

        if isinstance(arg_1, cairo.Context):
            return output_context
        elif isinstance(arg_1, cairo.Surface):
            return output_surface
        else:
            return output_file


def Func(arg_0, arg_1=None, arg_2=None, arg_3=False, arg_4=None, arg_5=False, arg_6=None,
                  arg_7=None, arg_8=False):
    """
    Create canvas and sink for attachment to a bot

    canvas is what draws images, 'sink' is the final consumer of the images

    :param src: Defaults for title or outputfile if not specified.

    :param format: CairoImageSink image format, if using buff instead of outputfile
    :param buff: CairoImageSink buffer object to send output to

    :param outputfile: CairoImageSink output filename e.g. "hello.svg"
    :param multifile: CairoImageSink if True,

    :param title: ShoebotWindow - set window title
    :param fullscreen: ShoebotWindow - set window title
    :param show_vars: ShoebotWindow - display variable window

    Two kinds of sink are provided: CairoImageSink and ShoebotWindow

    ShoebotWindow

    Displays a window to draw shoebot inside.

    CairoImageSink

    Output to a filename (or files if multifile is set), or a buffer object.
    """
    from core import CairoCanvas, CairoImageSink # https://github.com/shoebot/shoebot/issues/206

    if arg_2:
        arg_9 = CairoImageSink(arg_2, arg_1, arg_3, arg_4)
    elif arg_5 or arg_8:
        from gui import ShoebotWindow
        if not arg_6:
            if arg_0 and os.path.isfile(arg_0):
                arg_6 = os.path.splitext(os.path.basename(arg_0))[0] + ' - Shoebot'
            else:
                arg_6 = 'Untitled - Shoebot'
        arg_9 = ShoebotWindow(arg_6, arg_8, arg_7=arg_7)
    else:
        if arg_0 and isinstance(arg_0, cairo.Surface):
            arg_2 = arg_0
            arg_1 = 'surface'
        elif arg_0 and os.path.isfile(arg_0):
            arg_2 = os.path.splitext(os.path.basename(arg_0))[0] + '.' + (arg_1 or 'svg')
        else:
            arg_2 = 'output.svg'
        arg_9 = CairoImageSink(arg_2, arg_1, arg_3, arg_4)
    arg_10 = CairoCanvas(arg_9)

    return arg_10


def Func(arg_0):
        """
        Return True if the buffer was saved
        """
        arg_1 = ShoebotFileChooserDialog(_('Save File'), None, Gtk.FileChooserAction.SAVE,
                                           (Gtk.STOCK_SAVE, Gtk.ResponseType.ACCEPT,
                                            Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL))
        arg_1.set_do_overwrite_confirmation(True)
        arg_1.set_transient_for(arg_0)
        arg_2 = arg_1.run() == Gtk.ResponseType.ACCEPT
        if arg_2:
            arg_3 = arg_0.filename
            arg_0.source_buffer.filename = arg_1.get_filename()
            if not arg_0.save():
                arg_0.filename = arg_3
        arg_1.destroy()
        return arg_2


def Func(arg_0, arg_1, arg_2):
        ''' Called when a slider is adjusted. '''
        # set the appropriate bot var
        if arg_2.type is NUMBER:
            arg_0.bot._namespace[arg_2.name] = arg_1.get_value()
            arg_0.bot._vars[arg_2.name].value = arg_1.get_value()  ## Not sure if this is how to do this - stu
            publish_event(VARIABLE_UPDATED_EVENT, arg_2)  # pretty dumb for now
        elif arg_2.type is BOOLEAN:
            arg_0.bot._namespace[arg_2.name] = arg_1.get_active()
            arg_0.bot._vars[arg_2.name].value = arg_1.get_active()  ## Not sure if this is how to do this - stu
            publish_event(VARIABLE_UPDATED_EVENT, arg_2)  # pretty dumb for now
        elif arg_2.type is TEXT:
            arg_0.bot._namespace[arg_2.name] = arg_1.get_text()
            arg_0.bot._vars[arg_2.name].value = arg_1.get_text()  ## Not sure if this is how to do this - stu
            publish_event(VARIABLE_UPDATED_EVENT, arg_2)


def Func(arg_0, arg_1):
        """
        var was added in the bot while it ran, possibly
        by livecoding

        :param v:
        :return:
        """
        arg_0.add_variable(arg_1)

        arg_0.window.set_size_request(400, 35 * len(arg_0.widgets.keys()))
        arg_0.window.show_all()


def Func(arg_0, arg_1):
        """
        var was added in the bot

        :param v:
        :return:
        """
        arg_2 = arg_0.widgets[arg_1.name]

        # widgets are all in a single container ..
        arg_3 = arg_2.get_parent()
        arg_0.container.remove(arg_3)
        del arg_0.widgets[arg_1.name]

        arg_0.window.set_size_request(400, 35 * len(arg_0.widgets.keys()))
        arg_0.window.show_all()


def Func(arg_0, arg_1=False, arg_2=True):

    """ Returns cached copies unless otherwise specified.
    """

    if not arg_1:
        arg_3 = Funcr.FuncString(arg_0)
        arg_4 = Func_node(arg_3, [])
    else:
        arg_5 = _cache.id(arg_0)
        if not _cache.has_key(arg_5):
            arg_3 = Funcr.FuncString(arg_0)
            _cache.save(arg_5, Func_node(arg_3, []))
        arg_4 = _cache.load(arg_5, arg_2)

    return arg_4


def Func(arg_0, arg_1):

    """ Expand the path with color information.

    Attempts to extract fill and stroke colors
    from the element and adds it to path attributes.

    """

    _ctx.colormode(RGB, 1.0)

    def _color(arg_2, arg_3=1.0):
        if arg_2 == "none": return None
        arg_4 = int(arg_2[1:],16)
        arg_5 = (arg_4>>16)&0xff
        arg_6 = (arg_4>>8)&0xff
        arg_7 = arg_4&0xff
        return _ctx.color(arg_5/255.0, arg_6/255.0, arg_7/255.0, arg_3)

    arg_1.fill = (0,0,0,0)
    arg_1.stroke = (0,0,0,0)
    arg_1.strokewidth = 0

    # See if we can find an opacity attribute,
    # which is the color's alpha.
    arg_3 = get_attribute(arg_0, "opacity", default="")
    if arg_3 == "":
        arg_3 = 1.0
    else:
        arg_3 = float(arg_3)

    # Colors stored as fill="" or stroke="" attributes.
    try: arg_1.fill = _color(get_attribute(arg_0, "fill", default="#00000"), arg_3)
    except:
        pass
    try: arg_1.stroke = _color(get_attribute(arg_0, "stroke", default="none"), arg_3)
    except:
        pass
    try: arg_1.strokewidth = float(get_attribute(arg_0, "stroke-width", default="1"))
    except:
        pass

    # Colors stored as a CSS style attribute, for example:
    # style="fill:#ff6600;stroke:#ffe600;stroke-width:0.06742057"
    arg_11 = get_attribute(arg_0, "style", default="").split(";")
    for arg_12 in arg_11:
        try:
            if arg_12.startswith("fill:"):
                arg_1.fill = _color(arg_12.replace("fill:", ""))
            elif arg_12.startswith("stroke:"):
                arg_1.stroke = _color(arg_12.replace("stroke:", ""))
            elif arg_12.startswith("stroke-width:"):
                arg_1.strokewidth = float(arg_12.replace("stroke-width:", ""))
        except:
            pass

    # A path with beginning and ending coordinate
    # at the same location is considered closed.
    # Unless it contains a MOVETO somewhere in the middle.
    arg_1.closed = False
    if arg_1[0].x == arg_1[len(arg_1)-1].x and \
       arg_1[0].y == arg_1[len(arg_1)-1].y:
        arg_1.closed = True
    for arg_14 in range(1,-1):
        if arg_1[arg_14].cmd == MOVETO:
            arg_1.closed = False

    return arg_1


def Func(arg_0, arg_1):

        """ Returns a Func of the event handler, remembering the last node clicked.
        """

        arg_2 = events(arg_1, arg_0._ctx)
        arg_2.clicked = arg_0.clicked
        return arg_2


def Func(arg_0, arg_1):

        """ Drags given node to mouse location.
        """

        arg_2 = arg_0.mouse.x - arg_0.graph.x
        arg_3 = arg_0.mouse.y - arg_0.graph.y

        # A dashed line indicates the Func vector.
        arg_4 = arg_0.graph.styles.default
        arg_0._ctx.nofill()
        arg_0._ctx.nostroke()
        if arg_4.stroke:
            arg_0._ctx.strokewidth(arg_4.strokewidth)
            arg_0._ctx.stroke(
                arg_4.stroke.r,
                arg_4.stroke.g,
                arg_4.stroke.g,
                0.75
            )
        arg_5 = arg_0._ctx.line(arg_1.x, arg_1.y, arg_2, arg_3, draw=False)
        try: arg_5._nsBezierPath.setLineDash_count_phase_([2,4], 2, 50)
        except:
            pass
        arg_0._ctx.drawpath(arg_5)
        arg_6 = arg_1.__class__(None).r * 0.75
        arg_0._ctx.oval(arg_2-arg_6/2, arg_3-arg_6/2, arg_6, arg_6)

        arg_1.vx = arg_2 / arg_0.graph.d
        arg_1.vy = arg_3 / arg_0.graph.d


def Func(arg_0, arg_1):

        """ Displays a popup when Funcing over a node.
        """

        if arg_0.popup == False: return
        if arg_0.popup == True or arg_0.popup.node != arg_1:
            if arg_0.popup_text.has_key(arg_1.id):
                arg_2 = arg_0.popup_text[arg_1.id]
            else:
                arg_2 = None
            arg_0.popup = arg_3(arg_0._ctx, arg_1, arg_2)
        arg_0.popup.draw()


def Func(arg_0, arg_1):

        """ Returns a cached Func of the given text in queue.
        """

        if len(arg_0._Funcs) == arg_1:
            arg_0._ctx.font(arg_0.font, arg_0.fontsize)
            arg_2 = arg_0.q[arg_1]
            if len(arg_0.q) > 1:
                # Indicate current text (e.g. 5/13).
                arg_2 += " ("+str(arg_1+1)+"/" + str(len(arg_0.q))+")"
            arg_3 = arg_0._ctx.Func(arg_2, 0, 0, width=arg_0._w)
            arg_4 = arg_0._ctx.textheight(arg_2, width=arg_0._w)
            arg_0._Funcs.append((arg_3, arg_4))

        return arg_0._Funcs[arg_1]


def Func(arg_0):

        """ Draws a popup rectangle with a rotating text queue.
        """

        if len(arg_0.q) > 0:
            arg_0.update()

            if arg_0.delay == 0:

                # Rounded rectangle in the given background color.
                arg_1, arg_2 = arg_0.textpath(arg_0.i)
                arg_3 = arg_0.fontsize
                arg_0._ctx.fill(arg_0.background)
                arg_0._ctx.rect(
                    arg_0.node.x + arg_3*1.0,
                    arg_0.node.y + arg_3*0.5,
                    arg_0._w + arg_3,
                    arg_2 + arg_3*1.5,
                    roundness=0.2
                )

                # Fade in/out the current text.
                arg_4 = 1.0
                if arg_0.fi < 5:
                    arg_4 = 0.2 * arg_0.fi
                if arg_0.fn-arg_0.fi < 5:
                    arg_4 = 0.2 * (arg_0.fn-arg_0.fi)
                arg_0._ctx.fill(
                    arg_0.text.r,
                    arg_0.text.g,
                    arg_0.text.b,
                    arg_0.text.a * arg_4
                )

                arg_0._ctx.translate(arg_0.node.x + arg_3*2.0, arg_0.node.y + arg_3*2.5)
                arg_0._ctx.Funcpath(arg_1)


def Func(arg_0):
    """
    write FILENAME
        Write a local copy of FILENAME using FILENAME_tweaks for local tweaks.
    """
    if len(arg_0) != 1:
        print("Please provide the name of a file to write.")
        return 1

    arg_1 = arg_0[0]
    arg_2 = "files/" + arg_1
    arg_3 = amend_filename(arg_1, "_tweaks")

    if not pkg_resources.resource_exists("edx_lint", arg_2):
        print(u"Don't have file %r to write." % arg_1)
        return 2

    if os.path.exists(arg_1):
        print(u"Checking existing copy of %s" % arg_1)
        arg_4 = TamperEvidentFile(arg_1)
        if not arg_4.validate():
            arg_5 = amend_filename(arg_1, "_backup")
            print(u"Your copy of %s seems to have been edited, renaming it to %s" % (arg_1, arg_5))
            if os.path.exists(arg_5):
                print(u"A previous %s exists, deleting it" % arg_5)
                os.remove(arg_5)
            os.rename(arg_1, arg_5)

    print(u"Reading edx_lint/files/%s" % arg_1)
    arg_6 = configparser.RawConfigParser()
    arg_7 = pkg_resources.resource_string("edx_lint", arg_2).decode("utf8")

    # pkg_resources always reads binary data (in both python2 and python3).
    # ConfigParser.read_string only exists in python3, so we have to wrap the string
    # from pkg_resources in a cStringIO so that we can pass it into ConfigParser.readfp.
    if six.PY2:
        arg_6.readfp(cStringIO(arg_7), arg_2)
    else:
        arg_6.read_string(arg_7, arg_2)     # pylint: disable=no-member

    if os.path.exists(arg_3):
        print(u"Applying local tweaks from %s" % arg_3)
        arg_8 = configparser.RawConfigParser()
        arg_8.read([arg_3])

        merge_configs(arg_6, arg_8)

    print(u"Writing %s" % arg_1)
    arg_9 = cStringIO()
    arg_9.write(WARNING_HEADER.format(arg_1=arg_1, arg_3=arg_3))
    arg_6.write(arg_9)

    arg_10 = TamperEvidentFile(arg_1)
    if six.PY2:
        arg_11 = arg_9.getvalue()
    else:
        arg_11 = arg_9.getvalue().encode("utf8")
    arg_10.write(arg_11)

    return 0


def Func(arg_0, arg_1):
    """Amend a filename with a suffix.

    Func("foo.txt", "_tweak") --> "foo_tweak.txt"

    """
    arg_2, arg_3 = os.path.splitext(arg_0)
    arg_4 = arg_2 + arg_1 + arg_3
    return arg_4


def Func(arg_0):
    """
    check FILENAME
        Check that FILENAME has not been edited since writing.
    """
    if len(arg_0) != 1:
        print("Please provide the name of a file to check.")
        return 1

    arg_1 = arg_0[0]

    if os.path.exists(arg_1):
        print(u"Checking existing copy of %s" % arg_1)
        arg_2 = TamperEvidentFile(arg_1)
        if arg_2.validate():
            print(u"Your copy of %s is good" % arg_1)
        else:
            print(u"Your copy of %s seems to have been edited" % arg_1)
    else:
        print(u"You don't have a copy of %s" % arg_1)

    return 0


def Func(arg_0):
    """Check that a checker's visitors are correctly named.

    A checker has methods named visit_NODETYPE, but it's easy to mis-name
    a visit method, and it will never be called.  This decorator checks
    the class to see that all of its visitors are named after an existing
    node class.
    """
    for arg_1 in dir(arg_0):
        if arg_1.startswith("visit_"):
            if arg_1[6:] not in CLASS_NAMES:
                raise Exception(u"Method {} doesn't correspond to a node class".format(arg_1))
    return arg_0


def Func(arg_0):
    """
    Parse the pylint output-format=parseable lines into PylintError tuples.
    """
    for arg_1 in arg_0:
        if not arg_1.strip():
            continue

        if arg_1[0:5] in ("-"*5, "*"*5):
            continue

        arg_2 = PYLINT_PARSEABLE_REGEX.search(arg_1)
        if arg_2 is None:
            LOG.warning(
                u"Unable to parse %r. If this is a lint failure, please re-run pylint with the "
                u"--output-format=parseable option, otherwise, you can ignore this message.",
                arg_1
            )
            continue

        arg_3 = arg_2.groupdict()
        arg_3['linenum'] = int(arg_3['linenum'])
        yield PylintError(**arg_3)


def Func(arg_0=None):
    """The edx_lint command entry point."""
    if arg_0 is None:
        arg_0 = sys.argv[1:]

    if not arg_0 or arg_0[0] == "help":
        show_help()
        return 0
    elif arg_0[0] == "check":
        return check_Func(arg_0[1:])
    elif arg_0[0] == "list":
        return list_Func(arg_0[1:])
    elif arg_0[0] == "write":
        return write_Func(arg_0[1:])
    else:
        print(u"Don't understand {!r}".format(" ".join(arg_0)))
        show_help()
        return 1


def Func():
    """Print the help string for the edx_lint command."""
    print("""\
Manage local config files from masters in edx_lint.

Commands:
""")
    for arg_0 in [write_main, check_main, list_main]:
        print(arg_0.__doc__.lstrip("\n"))


def Func():
    """
    Parse the description in the README file

    CommandLine:
        python -c "import setup; print(setup.Func())"
    """
    from os.path import dirname, join, exists
    arg_0 = join(dirname(__file__), 'README.md')
    # print('readme_fpath = %r' % (readme_fpath,))
    # This breaks on pip install, so check that it exists.
    if exists(arg_0):
        # try:
        #     # convert markdown to rst for pypi
        #     import pypandoc
        #     return pypandoc.convert(readme_fpath, 'rst')
        # except Exception as ex:
            # strip out markdown to make a clean readme for pypi
            arg_1 = []
            with open(arg_0, 'r') as f:
                arg_2 = False
                for arg_3 in f.readlines():
                    if '# Purpose' in arg_3:
                        arg_2 = True
                    elif arg_3.startswith('##'):
                        break
                    elif arg_2:
                        arg_1 += [arg_3]
            arg_4 = ''.join(arg_1).strip()
            arg_4 = arg_4.replace('\n\n', '_NLHACK_')
            arg_4 = arg_4.replace('\n', ' ')
            arg_4 = arg_4.replace('_NLHACK_', '\n\n')
            return arg_4
    return ''


def Func(arg_0, arg_1, arg_2, arg_3=None,
              arg_4=None, arg_5=None,
              arg_6=(-arg_7.inf, arg_7.inf), arg_9='', **arg_10):
    """
    Create a transformation class object

    Parameters
    ----------
    name : str
        Name of the transformation
    transform : callable ``f(x)``
        A function (preferably a `ufunc`) that computes
        the transformation.
    inverse : callable ``f(x)``
        A function (preferably a `ufunc`) that computes
        the inverse of the transformation.
    breaks : callable ``f(limits)``
        Function to compute the breaks for this transform.
        If None, then a default good enough for a linear
        domain is used.
    minor_breaks : callable ``f(major, limits)``
        Function to compute the minor breaks for this
        transform. If None, then a default good enough for
        a linear domain is used.
    _format : callable ``f(breaks)``
        Function to format the generated breaks.
    domain : array_like
        Domain over which the transformation is valid.
        It should be of length 2.
    doc : str
        Docstring for the class.
    **kwargs : dict
        Attributes of the transform, e.g if base is passed
        in kwargs, then `t.base` would be a valied attribute.

    Returns
    -------
    out : trans
        Transform class
    """
    def _get(arg_11):
        if isinstance(arg_11, (classmethod, staticmethod, MethodType)):
            return arg_11
        else:
            return staticmethod(arg_11)

    arg_12 = '{}_trans'.format(arg_0)

    arg_13 = {'transform': _get(arg_1),
         'inverse': _get(arg_2),
         'domain': arg_6,
         '__doc__': arg_9,
         **arg_10}

    if arg_3:
        arg_13['breaks_'] = _get(arg_3)

    if arg_4:
        arg_13['minor_breaks'] = _get(arg_4)

    if arg_5:
        arg_13['format'] = _get(arg_5)

    return type(arg_12, (trans,), arg_13)


def Func(arg_0):
    """
    Return a trans object

    Parameters
    ----------
    t : str | callable | type | trans
        name of transformation function

    Returns
    -------
    out : trans
    """
    arg_1 = arg_0
    # Make sure trans object is instantiated
    if isinstance(arg_1, str):
        arg_2 = '{}_trans'.format(arg_1)
        arg_1 = globals()[arg_2]()
    if callable(arg_1):
        arg_1 = arg_1()
    if isinstance(arg_1, type):
        arg_1 = arg_1()

    if not isinstance(arg_1, trans):
        raise ValueError("Could not get transform object.")

    return arg_1


def Func(arg_0, arg_1):
        """
        Calculate breaks in data space and return them
        in transformed space.

        Expects limits to be in *transform space*, this
        is the same space as that where the domain is
        specified.

        This method wraps around :meth:`breaks_` to ensure
        that the calculated breaks are within the domain
        the transform. This is helpful in cases where an
        aesthetic requests breaks with limits expanded for
        some padding, yet the expansion goes beyond the
        domain of the transform. e.g for a probability
        transform the breaks will be in the domain
        ``[0, 1]`` despite any outward limits.

        Parameters
        ----------
        limits : tuple
            The scale limits. Size 2.

        Returns
        -------
        out : array_like
            Major breaks
        """
        # clip the breaks to the domain,
        # e.g. probabilities will be in [0, 1] domain
        arg_2 = np.max([arg_0.domain[0], arg_1[0]])
        arg_3 = np.min([arg_0.domain[1], arg_1[1]])
        Func = np.asarray(arg_0.breaks_([arg_2, arg_3]))

        # Some methods(mpl_breaks, extended_breaks) that
        # calculate breaks take the limits as guide posts and
        # not hard limits.
        Func = Func.compress((Func >= arg_0.domain[0]) &
                                 (Func <= arg_0.domain[1]))
        return Func


def Func(arg_0):
        """
        Transform from date to a numerical format
        """
        try:
            arg_0 = date2num(arg_0)
        except AttributeError:
            # numpy datetime64
            # This is not ideal because the operations do not
            # preserve the np.datetime64 type. May be need
            # a datetime64_trans
            arg_0 = [pd.Timestamp(item) for item in arg_0]
            arg_0 = date2num(arg_0)
        return arg_0


def Func(arg_0, arg_1=(0, 1), arg_2=None):
    """
    Rescale numeric vector to have specified minimum and maximum.

    Parameters
    ----------
    x : array_like | numeric
        1D vector of values to manipulate.
    to : tuple
        output range (numeric vector of length two)
    _from : tuple
        input range (numeric vector of length two).
        If not given, is calculated from the range of x

    Returns
    -------
    out : array_like
        Rescaled values

    Examples
    --------
    >>> x = [0, 2, 4, 6, 8, 10]
    >>> Func(x)
    array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])
    >>> Func(x, to=(0, 2))
    array([0. , 0.4, 0.8, 1.2, 1.6, 2. ])
    >>> Func(x, to=(0, 2), _from=(0, 20))
    array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])
    """
    if arg_2 is None:
        arg_2 = np.min(arg_0), np.max(arg_0)
    return np.interp(arg_0, arg_2, arg_1)


def Func(arg_0, arg_1=(0, 1), arg_2=None):
    """
    Rescale numeric vector to have specified maximum.

    Parameters
    ----------
    x : array_like | numeric
        1D vector of values to manipulate.
    to : tuple
        output range (numeric vector of length two)
    _from : tuple
        input range (numeric vector of length two).
        If not given, is calculated from the range of x.
        Only the 2nd (max) element is essential to the
        output.

    Returns
    -------
    out : array_like
        Rescaled values

    Examples
    --------
    >>> x = [0, 2, 4, 6, 8, 10]
    >>> Func(x, (0, 3))
    array([0. , 0.6, 1.2, 1.8, 2.4, 3. ])

    Only the 2nd (max) element of the parameters ``to``
    and ``_from`` are essential to the output.

    >>> Func(x, (1, 3))
    array([0. , 0.6, 1.2, 1.8, 2.4, 3. ])
    >>> Func(x, (0, 20))
    array([ 0.,  4.,  8., 12., 16., 20.])

    If :python:`max(x) < _from[1]` then values will be
    scaled beyond the requested (:python:`to[1]`) maximum.

    >>> Func(x, to=(1, 3), _from=(-1, 6))
    array([0., 1., 2., 3., 4., 5.])

    """
    arg_3 = True

    try:
        len(arg_0)
    except TypeError:
        arg_3 = False
        arg_0 = [arg_0]

    if not hasattr(arg_0, 'dtype'):
        arg_0 = np.asarray(arg_0)

    if arg_2 is None:
        arg_2 = np.array([np.min(arg_0), np.max(arg_0)])

    arg_4 = arg_0/arg_2[1] * arg_1[1]

    if not arg_3:
        arg_4 = arg_4[0]
    return arg_4


def Func(arg_0, arg_1=(0, 1)):
    """
    Truncate infinite values to a range.

    Parameters
    ----------
    x : array_like
        Values that should have infinities squished.
    range : tuple
        The range onto which to squish the infinites.
        Must be of size 2.

    Returns
    -------
    out : array_like
        Values with infinites squished.

    Examples
    --------
    >>> Func([0, .5, .25, np.inf, .44])
    [0.0, 0.5, 0.25, 1.0, 0.44]
    >>> Func([0, -np.inf, .5, .25, np.inf], (-10, 9))
    [0.0, -10.0, 0.5, 0.25, 9.0]
    """
    arg_2 = type(arg_0)

    if not hasattr(arg_0, 'dtype'):
        arg_0 = arg_3.asarray(arg_0)

    arg_0[arg_0 == -arg_3.inf] = arg_1[0]
    arg_0[arg_0 == arg_3.inf] = arg_1[1]

    if not isinstance(arg_0, arg_2):
        arg_0 = arg_2(arg_0)
    return arg_0


def Func(arg_0, arg_1=(0, 1), arg_2=True):
    """
    Squish values into range.

    Parameters
    ----------
    x : array_like
        Values that should have out of range values Funced.
    range : tuple
        The range onto which to Func the values.
    only_finite: boolean
        When true, only Funces finite values.

    Returns
    -------
    out : array_like
        Values with out of range values Funced.

    Examples
    --------
    >>> Func([-1.5, 0.2, 0.5, 0.8, 1.0, 1.2])
    [0.0, 0.2, 0.5, 0.8, 1.0, 1.0]

    >>> Func([-np.inf, -1.5, 0.2, 0.5, 0.8, 1.0, np.inf], only_finite=False)
    [0.0, 0.0, 0.2, 0.5, 0.8, 1.0, 1.0]
    """
    arg_3 = type(arg_0)

    if not hasattr(arg_0, 'dtype'):
        arg_0 = arg_5.asarray(arg_0)

    arg_4 = arg_5.isfinite(arg_0) if arg_2 else True

    arg_0[arg_5.logical_and(arg_0 < arg_1[0], arg_4)] = arg_1[0]
    arg_0[arg_5.logical_and(arg_0 > arg_1[1], arg_4)] = arg_1[1]

    if not isinstance(arg_0, arg_3):
        arg_0 = arg_3(arg_0)
    return arg_0


def Func(arg_0, arg_1=arg_2.finfo(arg_4).eps * 100):
    """
    Determine if range of vector is close to zero.

    Parameters
    ----------
    x : array_like | numeric
        Value(s) to check. If it is an array_like, it
        should be of length 2.
    tol : float
        Tolerance. Default tolerance is the `machine epsilon`_
        times :math:`10^2`.

    Returns
    -------
    out : bool
        Whether ``x`` has zero range.

    Examples
    --------
    >>> Func([1, 1])
    True
    >>> Func([1, 2])
    False
    >>> Func([1, 2], tol=2)
    True

    .. _machine epsilon: https://en.wikipedia.org/wiki/Machine_epsilon
    """
    try:
        if len(arg_0) == 1:
            return True
    except TypeError:
        return True

    if len(arg_0) != 2:
        raise ValueError('x must be length 1 or 2')

    # Deals with array_likes that have non-standard indices
    arg_0 = tuple(arg_0)

    # datetime - pandas, cpython
    if isinstance(arg_0[0], (pd.Timestamp, datetime.datetime)):
        # date2num include timezone info, .toordinal() does not
        arg_0 = date2num(arg_0)
    # datetime - numpy
    elif isinstance(arg_0[0], arg_2.datetime64):
        return arg_0[0] == arg_0[1]
    # timedelta - pandas, cpython
    elif isinstance(arg_0[0], (pd.Timedelta, datetime.timedelta)):
        arg_0 = arg_0[0].total_seconds(), arg_0[1].total_seconds()
    # timedelta - numpy
    elif isinstance(arg_0[0], arg_2.timedelta64):
        return arg_0[0] == arg_0[1]
    elif not isinstance(arg_0[0], (arg_4, int, arg_2.number)):
        raise TypeError(
            "Func objects cannot work with objects "
            "of type '{}'".format(type(arg_0[0])))

    if any(arg_2.isnan(arg_0)):
        return arg_2.nan

    if arg_0[0] == arg_0[1]:
        return True

    if all(arg_2.isinf(arg_0)):
        return False

    arg_6 = arg_2.abs(arg_0).min()
    if arg_6 == 0:
        return False

    return arg_2.abs((arg_0[0] - arg_0[1]) / arg_6) < arg_1


def Func(arg_0, arg_1=(0, 0, 0, 0), arg_2=1):
    """
    Expand a range with a multiplicative or additive constants

    Similar to :func:`expand_range` but both sides of the range
    expanded using different constants

    Parameters
    ----------
    range : tuple
        Range of data. Size 2
    expand : tuple
        Length 2 or 4. If length is 2, then the same constants
        are used for both sides. If length is 4 then the first
        two are are the Multiplicative (*mul*) and Additive (*add*)
        constants for the lower limit, and the second two are
        the constants for the upper limit.
    zero_width : int | float | timedelta
        Distance to use if range has zero width

    Returns
    -------
    out : tuple
        Expanded range

    Examples
    --------
    >>> Func((3, 8))
    (3, 8)
    >>> Func((0, 10), (0.1, 0))
    (-1.0, 11.0)
    >>> Func((0, 10), (0.1, 0, 0.1, 0))
    (-1.0, 11.0)
    >>> Func((0, 10), (0.1, 0, 0, 0))
    (-1.0, 10)
    >>> Func((0, 10), (0, 2))
    (-2, 12)
    >>> Func((0, 10), (0, 2, 0, 2))
    (-2, 12)
    >>> Func((0, 10), (0, 0, 0, 2))
    (0, 12)
    >>> Func((0, 10), (.1, 2))
    (-3.0, 13.0)
    >>> Func((0, 10), (.1, 2, .1, 2))
    (-3.0, 13.0)
    >>> Func((0, 10), (0, 0, .1, 2))
    (0, 13.0)
    """

    if len(arg_1) == 2:
        arg_1 = tuple(arg_1) * 2

    arg_3 = expand_range(arg_0, arg_1[0], arg_1[1], arg_2)[0]
    arg_4 = expand_range(arg_0, arg_1[2], arg_1[3], arg_2)[1]
    return (arg_3, arg_4)


def Func(arg_0, arg_1):
        """
        Append 2 extra breaks at either end of major

        If breaks of transform space are non-equidistant,
        :func:`minor_breaks` add minor breaks beyond the first
        and last major breaks. The solutions is to extend those
        breaks (in transformed space) before the minor break call
        is made. How the breaks depends on the type of transform.
        """
        arg_2 = arg_0.trans
        arg_2 = arg_2 if isinstance(arg_2, type) else arg_2.__class__
        # so far we are only certain about this extending stuff
        # making sense for log transform
        arg_3 = arg_2.__name__.startswith('log')
        arg_4 = np.diff(arg_1)
        arg_5 = arg_4[0]
        if arg_3 and all(arg_4 == arg_5):
            arg_1 = np.hstack([arg_1[0]-arg_5, arg_1, arg_1[-1]+arg_5])
        return arg_1


def Func(arg_0, arg_1):
        """
        Determine good units for representing a sequence of timedeltas
        """
        # Read
        #   [(0.9, 's'),
        #    (9, 'm)]
        # as, break ranges between 0.9 seconds (inclusive)
        # and 9 minutes are represented in seconds. And so on.
        arg_2 = arg_0.value(max(arg_1)) - arg_0.value(min(arg_1))
        arg_3 = arg_0.determine_package(arg_1[0])
        if arg_3 == 'pandas':
            arg_4 = [
                (0.9, 'us'),
                (0.9, 'ms'),
                (0.9, 's'),
                (9, 'm'),
                (6, 'h'),
                (4, 'd'),
                (4, 'w'),
                (4, 'M'),
                (3, 'y')]
            arg_5 = NANOSECONDS
            arg_6 = 'ns'
        else:
            arg_4 = [
                (0.9, 's'),
                (9, 'm'),
                (6, 'h'),
                (4, 'd'),
                (4, 'w'),
                (4, 'M'),
                (3, 'y')]
            arg_5 = SECONDS
            arg_6 = 'ms'

        for arg_7, arg_8 in reversed(arg_4):
            if arg_2 >= arg_7*arg_5[arg_8]:
                return arg_8

        return arg_6


def Func(arg_0, arg_1):
        """
        Convert sequence of numerics to timedelta
        """
        if arg_0.package == 'pandas':
            return [arg_0.type(int(arg_2*arg_0.factor), units='ns')
                    for arg_2 in arg_1]
        else:
            return [arg_0.type(seconds=arg_2*arg_0.factor)
                    for arg_2 in arg_1]


def Func(arg_0, arg_1):
        """
        Convert timedelta to a number corresponding to the
        appropriate units. The appropriate units are those
        determined with the object is initialised.
        """
        if arg_0.package == 'pandas':
            return arg_1.value/NANOSECONDS[arg_0.units]
        else:
            return arg_1.total_seconds()/SECONDS[arg_0.units]


def Func(arg_0, arg_1, arg_2=arg_3.round):
    """
    Round to multiple of any number.
    """
    if not hasattr(arg_0, 'dtype'):
        arg_0 = arg_3.asarray(arg_0)

    return arg_2(arg_0 / arg_1) * arg_1


def Func(arg_0, arg_1=False, arg_2=True):
    """
    Return the minimum and maximum of x

    Parameters
    ----------
    x : array_like
        Sequence
    na_rm : bool
        Whether to remove ``nan`` values.
    finite : bool
        Whether to consider only finite values.

    Returns
    -------
    out : tuple
        (minimum, maximum) of x
    """
    if not hasattr(arg_0, 'dtype'):
        arg_0 = np.asarray(arg_0)

    if arg_1 and arg_2:
        arg_0 = arg_0[np.isfinite(arg_0)]
    elif not arg_1 and np.any(np.isnan(arg_0)):
        return np.nan, np.nan
    elif arg_1:
        arg_0 = arg_0[~np.isnan(arg_0)]
    elif arg_2:
        arg_0 = arg_0[~np.isinf(arg_0)]

    if (len(arg_0)):
        return np.min(arg_0), np.max(arg_0)
    else:
        return float('-inf'), float('inf')


def Func(arg_0):
    """
    Return nearest long integer to x
    """
    if arg_0 == 0:
        return np.int64(0)
    elif arg_0 > 0:
        return np.int64(arg_0 + 0.5)
    else:
        return np.int64(arg_0 - 0.5)


def Func(arg_0):
    """
    Check if value is close to an integer

    Parameters
    ----------
    x : float
        Numeric value to check

    Returns
    -------
    out : bool
    """
    if not np.isfinite(arg_0):
        return False
    return abs(arg_0 - nearest_int(arg_0)) < 1e-10


def Func(arg_0, arg_1):
    """
    Helper to format and tidy up
    """
    # For MPL to play nice
    arg_0.create_dummy_axis()
    # For sensible decimal places
    arg_0.set_locs([arg_2 for arg_2 in arg_1 if ~np.isnan(arg_2)])
    try:
        arg_3 = int(arg_0.orderOfMagnitude)
    except AttributeError:
        arg_3 = 0
    arg_4 = [arg_0(tick) for tick in arg_1]

    # Remove unnecessary decimals
    arg_5 = re.compile(r'\.0+$')
    for arg_6, arg_7 in enumerate(arg_4):
        arg_8 = arg_5.search(arg_7)
        if arg_8:
            arg_4[arg_6] = arg_5.sub('', arg_7)

    # MPL does not add the exponential component
    if arg_3:
        arg_4 = ['{}e{}'.format(s, arg_3) if s != '0' else s
                  for s in arg_4]
    return arg_4


def Func(arg_0=6, arg_1=.01, arg_2=.6, arg_3=.65):
    """
    Get a set of evenly spaced colors in HLS hue space.

    h, l, and s should be between 0 and 1

    Parameters
    ----------

    n_colors : int
        number of colors in the palette
    h : float
        first hue
    l : float
        lightness
    s : float
        saturation

    Returns
    -------
    palette : list
        List of colors as RGB hex strings.

    See Also
    --------
    husl_palette : Make a palette using evenly spaced circular
        hues in the HUSL system.

    Examples
    --------
    >>> len(Func(2))
    2
    >>> len(Func(9))
    9
    """
    arg_4 = np.linspace(0, 1, arg_0 + 1)[:-1]
    arg_4 += arg_1
    arg_4 %= 1
    arg_4 -= arg_4.astype(int)
    arg_5 = [colorsys.hls_to_rgb(h_i, arg_2, arg_3) for h_i in arg_4]
    return arg_5


def Func(arg_0=.01, arg_1=.6, arg_2=.65, arg_3='hls'):
    """
    Utility for making hue palettes for color schemes.

    Parameters
    ----------
    h : float
        first hue. In the [0, 1] range
    l : float
        lightness. In the [0, 1] range
    s : float
        saturation. In the [0, 1] range
    color_space : 'hls' | 'husl'
        Color space to use for the palette

    Returns
    -------
    out : function
        A discrete color palette that takes a single
        :class:`int` parameter ``n`` and returns ``n``
        equally spaced colors. Though the palette
        is continuous, since it is varies the hue it
        is good for categorical data. However if ``n``
        is large enough the colors show continuity.

    Examples
    --------
    >>> Func()(5)
    ['#db5f57', '#b9db57', '#57db94', '#5784db', '#c957db']
    >>> Func(color_space='husl')(5)
    ['#e0697e', '#9b9054', '#569d79', '#5b98ab', '#b675d7']
    """
    if not all([0 <= arg_4 <= 1 for arg_4 in (arg_0, arg_1, arg_2)]):
        arg_5 = ("Func expects values to be between 0 and 1. "
               " I got h={}, l={}, s={}".format(arg_0, arg_1, arg_2))
        raise ValueError(arg_5)

    if arg_3 not in ('hls', 'husl'):
        arg_5 = "color_space should be one of ['hls', 'husl']"
        raise ValueError(arg_5)

    arg_6 = '{}_palette'.format(arg_3)
    arg_7 = globals()[arg_6]

    def _Func(arg_8):
        arg_9 = arg_7(arg_8, arg_0=arg_0, arg_1=arg_1, arg_2=arg_2)
        return [mcolors.rgb2hex(arg_10) for arg_10 in arg_9]

    return _Func