Instruction:
Implement a Python 3 function for
getting the access key of given object and return it in string format.

Response:
def getaccesskey(self, window_name, object_name):
        """
        Get access key of given object

        @param window_name: Window name to look for, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to look for, either full name,
        LDTP's name convention, or a Unix glob. Or menu heirarchy
        @type object_name: string

        @return: access key in string format on success, else LdtpExecutionError on failure.
        @rtype: string
        """
        # Used http://www.danrodney.com/mac/ as reference for
        # mapping keys with specific control
        # In Mac noticed (in accessibility inspector) only menu had access keys
        # so, get the menu_handle of given object and
        # return the access key
        menu_handle = self._get_menu_handle(window_name, object_name)
        key = menu_handle.AXMenuItemCmdChar
        modifiers = menu_handle.AXMenuItemCmdModifiers
        glpyh = menu_handle.AXMenuItemCmdGlyph
        virtual_key = menu_handle.AXMenuItemCmdVirtualKey
        modifiers_type = ""
        if modifiers == 0:
            modifiers_type = "<command>"
        elif modifiers == 1:
            modifiers_type = "<shift><command>"
        elif modifiers == 2:
            modifiers_type = "<option><command>"
        elif modifiers == 3:
            modifiers_type = "<option><shift><command>"
        elif modifiers == 4:
            modifiers_type = "<ctrl><command>"
        elif modifiers == 6:
            modifiers_type = "<ctrl><option><command>"
        # Scroll up
        if virtual_key == 115 and glpyh == 102:
            modifiers = "<option>"
            key = "<cursor_left>"
        # Scroll down
        elif virtual_key == 119 and glpyh == 105:
            modifiers = "<option>"
            key = "<right>"
        # Page up
        elif virtual_key == 116 and glpyh == 98:
            modifiers = "<option>"
            key = "<up>"
        # Page down
        elif virtual_key == 121 and glpyh == 107:
            modifiers = "<option>"
            key = "<down>"
        # Line up
        elif virtual_key == 126 and glpyh == 104:
            key = "<up>"
        # Line down
        elif virtual_key == 125 and glpyh == 106:
            key = "<down>"
        # Noticed in  Google Chrome navigating next tab
        elif virtual_key == 124 and glpyh == 101:
            key = "<right>"
        # Noticed in  Google Chrome navigating previous tab
        elif virtual_key == 123 and glpyh == 100:
            key = "<left>"
        # List application in a window to Force Quit
        elif virtual_key == 53 and glpyh == 27:
            key = "<escape>"
        # FIXME:
        # * Instruments Menu View->Run Browser
        # modifiers==12 virtual_key==48 glpyh==2
        # * Terminal Menu Edit->Start Dictation
        # fn fn - glpyh==148 modifiers==24
        # * Menu Chrome->Clear Browsing Data in Google Chrome
        # virtual_key==51 glpyh==23 [Delete Left (like Backspace on a PC)]
        if not key:
            raise LdtpServerException("No access key associated")
        return modifiers_type + key


Instruction:
Can you generate a brief explanation for the following Python 3 code
def paste(cls):
        pb = AppKit.NSPasteboard.generalPasteboard()

        # If we allow for multiple data types (e.g. a list of data types)
        # we will have to add a condition to check just the first in the
        # list of datatypes)
        data = pb.stringForType_(cls.STRING)
        return data

Response: Get the clipboard data ('Paste').


Instruction:
Write a Python 3 script for
copying the clipboard data to the clipboard.

Response:
def copy(cls, data):
        """Set the clipboard data ('Copy').

        Parameters: data to set (string)
        Optional: datatype if it's not a string
        Returns: True / False on successful copy, Any exception raised (like
                 passes the NSPasteboardCommunicationError) should be caught
                 by the caller.
        """
        pp = pprint.PrettyPrinter()

        copy_data = 'Data to copy (put in pasteboard): %s'
        logging.debug(copy_data % pp.pformat(data))

        # Clear the pasteboard first:
        cleared = cls.clearAll()
        if not cleared:
            logging.warning('Clipboard could not clear properly')
            return False

        # Prepare to write the data
        # If we just use writeObjects the sequence to write to the clipboard is
        # a) Call clearContents()
        # b) Call writeObjects() with a list of objects to write to the
        #    clipboard
        if not isinstance(data, types.ListType):
            data = [data]

        pb = AppKit.NSPasteboard.generalPasteboard()
        pb_set_ok = pb.writeObjects_(data)

        return bool(pb_set_ok)


Instruction:
Write a Python 3 function that can
clear contents of general pasteboard.

Response:
def clearContents(cls):
        """Clear contents of general pasteboard.

        Future enhancement can include specifying which clipboard to clear
        Returns: True on success; caller should expect to catch exceptions,
                 probably from AppKit (ValueError)
        """
        log_msg = 'Request to clear contents of pasteboard: general'
        logging.debug(log_msg)
        pb = AppKit.NSPasteboard.generalPasteboard()
        pb.clearContents()
        return True


Instruction:
Can you tell what is the following Python 3 function doing
def _ldtpize_accessible(self, acc):
        actual_role = self._get_role(acc)
        label = self._get_title(acc)
        if re.match("AXWindow", actual_role, re.M | re.U | re.L):
            # Strip space and new line from window title
            strip = r"( |\n)"
        else:
            # Strip space, colon, dot, underscore and new line from
            # all other object types
            strip = r"( |:|\.|_|\n)"
        if label:
            # Return the role type (if, not in the know list of roles,
            # return ukn - unknown), strip the above characters from name
            # also return labely_by string
            label = re.sub(strip, u"", label)
        role = abbreviated_roles.get(actual_role, "ukn")
        if self._ldtp_debug and role == "ukn":
            print(actual_role, acc)
        return role, label

Response: Return object type stripped object name associated with an object.


Instruction:
How would you implement a function in Python 3 that
returns True if pattern matches given string.

Response:
def _glob_match(self, pattern, string):
        """
        Match given string, by escaping regex characters
        """
        # regex flags Multi-line, Unicode, Locale
        return bool(re.match(fnmatch.translate(pattern), string,
                             re.M | re.U | re.L))


Instruction:
Write a Python 3 function that can
select a menu item.

Response:
def selectmenuitem(self, window_name, object_name):
        """
        Select (click) a menu item.

        @param window_name: Window name to look for, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to look for, either full name,
        LDTP's name convention, or a Unix glob. Or menu heirarchy
        @type object_name: string

        @return: 1 on success.
        @rtype: integer
        """
        menu_handle = self._get_menu_handle(window_name, object_name)
        if not menu_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        menu_handle.Press()
        return 1


Instruction:
Explain what the following Python 3 code does
def doesmenuitemexist(self, window_name, object_name):
        try:
            menu_handle = self._get_menu_handle(window_name, object_name,
                                                False)
            return 1
        except LdtpServerException:
            return 0

Response: Check a menu item exist.


Instruction:
Here you have a function in Python 3, explain what it does
def menuitemenabled(self, window_name, object_name):
        try:
            menu_handle = self._get_menu_handle(window_name, object_name,
                                                False)
            if menu_handle.AXEnabled:
                return 1
        except LdtpServerException:
            pass
        return 0

Response: Verify a menu item is enabled by checking if a menu item is enabled by the object name.


Instruction:
How would you implement a function in Python 3 that
lists all children of a menu item under a given object name.

Response:
def listsubmenus(self, window_name, object_name):
        """
        List children of menu item

        @param window_name: Window name to look for, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to look for, either full name,
        LDTP's name convention, or a Unix glob. Or menu heirarchy
        @type object_name: string

        @return: menu item in list on success.
        @rtype: list
        """
        menu_handle = self._get_menu_handle(window_name, object_name)
        role, label = self._ldtpize_accessible(menu_handle)
        menu_clicked = False
        try:
            if not menu_handle.AXChildren:
                menu_clicked = True
                try:
                    menu_handle.Press()
                    self.wait(1)
                except atomac._a11y.ErrorCannotComplete:
                    pass
                if not menu_handle.AXChildren:
                    raise LdtpServerException(u"Unable to find children under menu %s" % \
                                              label)
            children = menu_handle.AXChildren[0]
            sub_menus = []
            for current_menu in children.AXChildren:
                role, label = self._ldtpize_accessible(current_menu)
                if not label:
                    # All splitters have empty label
                    continue
                sub_menus.append(u"%s%s" % (role, label))
        finally:
            if menu_clicked:
                menu_handle.Cancel()
        return sub_menus


Instruction:
Can you tell what is the following Python 3 function doing
def menucheck(self, window_name, object_name):
        menu_handle = self._get_menu_handle(window_name, object_name)
        if not menu_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        try:
            if menu_handle.AXMenuItemMarkChar:
                # Already checked
                return 1
        except atomac._a11y.Error:
            pass
        menu_handle.Press()
        return 1

Response: Check a menu item.


Instruction:
Can you write a function in Python 3 where it
gets a list of the running applications.

Response:
def _getRunningApps(cls):
        """Get a list of the running applications."""

        def runLoopAndExit():
            AppHelper.stopEventLoop()

        AppHelper.callLater(1, runLoopAndExit)
        AppHelper.runConsoleEventLoop()
        # Get a list of running applications
        ws = AppKit.NSWorkspace.sharedWorkspace()
        apps = ws.runningApplications()
        return apps


Instruction:
Implement a Python 3 function for
getting the current frontmost application. Raise a ValueError exception if no frontmost application is found.

Response:
def getFrontmostApp(cls):
        """Get the current frontmost application.

        Raise a ValueError exception if no GUI applications are found.
        """
        # Refresh the runningApplications list
        apps = cls._getRunningApps()
        for app in apps:
            pid = app.processIdentifier()
            ref = cls.getAppRefByPid(pid)
            try:
                if ref.AXFrontmost:
                    return ref
            except (_a11y.ErrorUnsupported,
                    _a11y.ErrorCannotComplete,
                    _a11y.ErrorAPIDisabled,
                    _a11y.ErrorNotImplemented):
                # Some applications do not have an explicit GUI
                # and so will not have an AXFrontmost attribute
                # Trying to read attributes from Google Chrome Helper returns
                # ErrorAPIDisabled for some reason - opened radar bug 12837995
                pass
        raise ValueError('No GUI application found.')


Instruction:
Can you generate the documentation for the following Python 3 function
def getAnyAppWithWindow(cls):
        # Refresh the runningApplications list
        apps = cls._getRunningApps()
        for app in apps:
            pid = app.processIdentifier()
            ref = cls.getAppRefByPid(pid)
            if hasattr(ref, 'windows') and len(ref.windows()) > 0:
                return ref
        raise ValueError('No GUI application found.')

Response: Get a random app that has windows. Raise a ValueError exception if no GUI applications are found.


Instruction:
Write a Python 3 function for
launching the application with the specified bundle ID.

Response:
def launchAppByBundleId(bundleID):
        """Launch the application with the specified bundle ID"""
        # NSWorkspaceLaunchAllowingClassicStartup does nothing on any
        # modern system that doesn't have the classic environment installed.
        # Encountered a bug when passing 0 for no options on 10.6 PyObjC.
        ws = AppKit.NSWorkspace.sharedWorkspace()
        # Sorry about the length of the following line
        r = ws.launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_(
            bundleID,
            AppKit.NSWorkspaceLaunchAllowingClassicStartup,
            AppKit.NSAppleEventDescriptor.nullDescriptor(),
            None)
        # On 10.6, this returns a tuple - first element bool result, second is
        # a number. Let's use the bool result.
        if not r[0]:
            raise RuntimeError('Error launching specified application.')


Instruction:
How would you code a function in Python 3 to
launch app with a given bundle path.

Response:
def launchAppByBundlePath(bundlePath, arguments=None):
        """Launch app with a given bundle path.

        Return True if succeed.
        """
        if arguments is None:
            arguments = []

        bundleUrl = NSURL.fileURLWithPath_(bundlePath)
        workspace = AppKit.NSWorkspace.sharedWorkspace()
        arguments_strings = list(map(lambda a: NSString.stringWithString_(str(a)),
                                arguments))
        arguments = NSDictionary.dictionaryWithDictionary_({
            AppKit.NSWorkspaceLaunchConfigurationArguments: NSArray.arrayWithArray_(
                arguments_strings)
        })

        return workspace.launchApplicationAtURL_options_configuration_error_(
            bundleUrl,
            AppKit.NSWorkspaceLaunchAllowingClassicStartup,
            arguments,
            None)


Instruction:
Create a Python 3 function to
terminate an application with a given bundle ID. Requires 10. 6.

Response:
def terminateAppByBundleId(bundleID):
        """Terminate app with a given bundle ID.
        Requires 10.6.

        Return True if succeed.
        """
        ra = AppKit.NSRunningApplication
        if getattr(ra, "runningApplicationsWithBundleIdentifier_"):
            appList = ra.runningApplicationsWithBundleIdentifier_(bundleID)
            if appList and len(appList) > 0:
                app = appList[0]
                return app and app.terminate() and True or False
        return False


Instruction:
Can you tell what is the following Python 3 function doing
def _postQueuedEvents(self, interval=0.01):
        while len(self.eventList) > 0:
            (nextEvent, args) = self.eventList.popleft()
            nextEvent(*args)
            time.sleep(interval)

Response: Private method to post queued events to the local cache.


Instruction:
Create a Python 3 function for
adding a keypress to the queue.

Response:
def _addKeyToQueue(self, keychr, modFlags=0, globally=False):
        """Add keypress to queue.

        Parameters: key character or constant referring to a non-alpha-numeric
                    key (e.g. RETURN or TAB)
                    modifiers
                    global or app specific
        Returns: None or raise ValueError exception.
        """
        # Awkward, but makes modifier-key-only combinations possible
        # (since sendKeyWithModifiers() calls this)
        if not keychr:
            return

        if not hasattr(self, 'keyboard'):
            self.keyboard = AXKeyboard.loadKeyboard()

        if keychr in self.keyboard['upperSymbols'] and not modFlags:
            self._sendKeyWithModifiers(keychr,
                                       [AXKeyCodeConstants.SHIFT],
                                       globally)
            return

        if keychr.isupper() and not modFlags:
            self._sendKeyWithModifiers(
                keychr.lower(),
                [AXKeyCodeConstants.SHIFT],
                globally
            )
            return

        if keychr not in self.keyboard:
            self._clearEventQueue()
            raise ValueError('Key %s not found in keyboard layout' % keychr)

        # Press the key
        keyDown = Quartz.CGEventCreateKeyboardEvent(None,
                                                    self.keyboard[keychr],
                                                    True)
        # Release the key
        keyUp = Quartz.CGEventCreateKeyboardEvent(None,
                                                  self.keyboard[keychr],
                                                  False)
        # Set modflags on keyDown (default None):
        Quartz.CGEventSetFlags(keyDown, modFlags)
        # Set modflags on keyUp:
        Quartz.CGEventSetFlags(keyUp, modFlags)

        # Post the event to the given app
        if not globally:
            # To direct output to the correct application need the PSN (macOS <=10.10) or PID(macOS > 10.10):
            macVer, _, _ = platform.mac_ver()
            macVer = int(macVer.split('.')[1])
            if macVer > 10:
                appPid = self._getPid()
                self._queueEvent(Quartz.CGEventPostToPid, (appPid, keyDown))
                self._queueEvent(Quartz.CGEventPostToPid, (appPid, keyUp))
            else:
                appPsn = self._getPsnForPid(self._getPid())
                self._queueEvent(Quartz.CGEventPostToPSN, (appPsn, keyDown))
                self._queueEvent(Quartz.CGEventPostToPSN, (appPsn, keyUp))
        else:
            self._queueEvent(Quartz.CGEventPost, (0, keyDown))
            self._queueEvent(Quartz.CGEventPost, (0, keyUp))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _sendKey(self, keychr, modFlags=0, globally=False):
        escapedChrs = {
            '\n': AXKeyCodeConstants.RETURN,
            '\r': AXKeyCodeConstants.RETURN,
            '\t': AXKeyCodeConstants.TAB,
        }
        if keychr in escapedChrs:
            keychr = escapedChrs[keychr]

        self._addKeyToQueue(keychr, modFlags, globally=globally)
        self._postQueuedEvents()

Response: Send one character with no modifiers.


Instruction:
Implement a function in Python 3 to
press given modifiers (provided in list form). Parameters: modifiers list, global or app specific Optional: keypressed state (default is True (down)) Returns: Unsigned int representing flags to set

Response:
def _pressModifiers(self, modifiers, pressed=True, globally=False):
        """Press given modifiers (provided in list form).

        Parameters: modifiers list, global or app specific
        Optional: keypressed state (default is True (down))
        Returns: Unsigned int representing flags to set
        """
        if not isinstance(modifiers, list):
            raise TypeError('Please provide modifiers in list form')

        if not hasattr(self, 'keyboard'):
            self.keyboard = AXKeyboard.loadKeyboard()

        modFlags = 0

        # Press given modifiers
        for nextMod in modifiers:
            if nextMod not in self.keyboard:
                errStr = 'Key %s not found in keyboard layout'
                self._clearEventQueue()
                raise ValueError(errStr % self.keyboard[nextMod])
            modEvent = Quartz.CGEventCreateKeyboardEvent(
                Quartz.CGEventSourceCreate(0),
                self.keyboard[nextMod],
                pressed
            )
            if not pressed:
                # Clear the modflags:
                Quartz.CGEventSetFlags(modEvent, 0)
            if globally:
                self._queueEvent(Quartz.CGEventPost, (0, modEvent))
            else:
                # To direct output to the correct application need the PSN (macOS <=10.10) or PID(macOS > 10.10):
                macVer, _, _ = platform.mac_ver()
                macVer = int(macVer.split('.')[1])
                if macVer > 10:
                    appPid = self._getPid()
                    self._queueEvent(Quartz.CGEventPostToPid, (appPid, modEvent))
                else:
                    appPsn = self._getPsnForPid(self._getPid())
                    self._queueEvent(Quartz.CGEventPostToPSN, (appPsn, modEvent))
            # Add the modifier flags
            modFlags += AXKeyboard.modKeyFlagConstants[nextMod]

        return modFlags


Instruction:
Here you have a function in Python 3, explain what it does
def _holdModifierKeys(self, modifiers):
        modFlags = self._pressModifiers(modifiers)
        # Post the queued keypresses:
        self._postQueuedEvents()
        return modFlags

Response: Hold given modifier keys.


Instruction:
Write a Python 3 function that can
release given modifiers (provided in list form). Parameters: modifiers list Returns: None

Response:
def _releaseModifiers(self, modifiers, globally=False):
        """Release given modifiers (provided in list form).

        Parameters: modifiers list
        Returns: None
        """
        # Release them in reverse order from pressing them:
        modifiers.reverse()
        modFlags = self._pressModifiers(modifiers, pressed=False,
                                        globally=globally)
        return modFlags


Instruction:
Here you have a function in Python 3, explain what it does
def _releaseModifierKeys(self, modifiers):
        modFlags = self._releaseModifiers(modifiers)
        # Post the queued keypresses:
        self._postQueuedEvents()
        return modFlags

Response: Release given modifier keys.


Instruction:
Implement a function in Python 3 to
check whether given key character is a single character.

Response:
def _isSingleCharacter(keychr):
        """Check whether given keyboard character is a single character.

        Parameters: key character which will be checked.
        Returns: True when given key character is a single character.
        """
        if not keychr:
            return False
        # Regular character case.
        if len(keychr) == 1:
            return True
        # Tagged character case.
        return keychr.count('<') == 1 and keychr.count('>') == 1 and \
               keychr[0] == '<' and keychr[-1] == '>'


Instruction:
Explain what the following Python 3 code does
def _sendKeyWithModifiers(self, keychr, modifiers, globally=False):
        if not self._isSingleCharacter(keychr):
            raise ValueError('Please provide only one character to send')

        if not hasattr(self, 'keyboard'):
            self.keyboard = AXKeyboard.loadKeyboard()

        modFlags = self._pressModifiers(modifiers, globally=globally)

        # Press the non-modifier key
        self._sendKey(keychr, modFlags, globally=globally)

        # Release the modifiers
        self._releaseModifiers(modifiers, globally=globally)

        # Post the queued keypresses:
        self._postQueuedEvents()

Response: Send one character with the given modifiers pressed.


Instruction:
Explain what the following Python 3 code does
def _queueMouseButton(self, coord, mouseButton, modFlags, clickCount=1,
                          dest_coord=None):
        """Private method to handle generic mouse button clicking.

        Parameters: coord (x, y) to click, mouseButton (e.g.,
                    kCGMouseButtonLeft), modFlags set (int)
        Optional: clickCount (default 1; set to 2 for double-click; 3 for
                  triple-click on host)
        Returns: None
        """
        # For now allow only left and right mouse buttons:
        mouseButtons = {
            Quartz.kCGMouseButtonLeft: 'LeftMouse',
            Quartz.kCGMouseButtonRight: 'RightMouse',
        }
        if mouseButton not in mouseButtons:
            raise ValueError('Mouse button given not recognized')

        eventButtonDown = getattr(Quartz,
                                  'kCGEvent%sDown' % mouseButtons[mouseButton])
        eventButtonUp = getattr(Quartz,
                                'kCGEvent%sUp' % mouseButtons[mouseButton])
        eventButtonDragged = getattr(Quartz,
                                     'kCGEvent%sDragged' % mouseButtons[
                                         mouseButton])

        # Press the button
        buttonDown = Quartz.CGEventCreateMouseEvent(None,
                                                    eventButtonDown,
                                                    coord,
                                                    mouseButton)
        # Set modflags (default None) on button down:
        Quartz.CGEventSetFlags(buttonDown, modFlags)

        # Set the click count on button down:
        Quartz.CGEventSetIntegerValueField(buttonDown,
                                           Quartz.kCGMouseEventClickState,
                                           int(clickCount))

        if dest_coord:
            # Drag and release the button
            buttonDragged = Quartz.CGEventCreateMouseEvent(None,
                                                           eventButtonDragged,
                                                           dest_coord,
                                                           mouseButton)
            # Set modflags on the button dragged:
            Quartz.CGEventSetFlags(buttonDragged, modFlags)

            buttonUp = Quartz.CGEventCreateMouseEvent(None,
                                                      eventButtonUp,
                                                      dest_coord,
                                                      mouseButton)
        else:
            # Release the button
            buttonUp = Quartz.CGEventCreateMouseEvent(None,
                                                      eventButtonUp,
                                                      coord,
                                                      mouseButton)
        # Set modflags on the button up:
        Quartz.CGEventSetFlags(buttonUp, modFlags)

        # Set the click count on button up:
        Quartz.CGEventSetIntegerValueField(buttonUp,
                                           Quartz.kCGMouseEventClickState,
                                           int(clickCount))
        # Queue the events
        self._queueEvent(Quartz.CGEventPost,
                         (Quartz.kCGSessionEventTap, buttonDown))
        if dest_coord:
            self._queueEvent(Quartz.CGEventPost,
                             (Quartz.kCGHIDEventTap, buttonDragged))
        self._queueEvent(Quartz.CGEventPost,
                         (Quartz.kCGSessionEventTap, buttonUp))

Response: Private method to handle generic mouse button clicking.


Instruction:
Make a summary of the following Python 3 code
def _leftMouseDragged(self, stopCoord, strCoord, speed):
        # To direct output to the correct application need the PSN:
        appPid = self._getPid()
        # Get current position as start point if strCoord not given
        if strCoord == (0, 0):
            loc = AppKit.NSEvent.mouseLocation()
            strCoord = (loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y)

        # To direct output to the correct application need the PSN:
        appPid = self._getPid()

        # Press left button down
        pressLeftButton = Quartz.CGEventCreateMouseEvent(
            None,
            Quartz.kCGEventLeftMouseDown,
            strCoord,
            Quartz.kCGMouseButtonLeft
        )
        # Queue the events
        Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap, pressLeftButton)
        # Wait for reponse of system, a fuzzy icon appears
        time.sleep(5)
        # Simulate mouse moving speed, k is slope
        speed = round(1 / float(speed), 2)
        xmoved = stopCoord[0] - strCoord[0]
        ymoved = stopCoord[1] - strCoord[1]
        if ymoved == 0:
            raise ValueError('Not support horizontal moving')
        else:
            k = abs(ymoved / xmoved)

        if xmoved != 0:
            for xpos in range(int(abs(xmoved))):
                if xmoved > 0 and ymoved > 0:
                    currcoord = (strCoord[0] + xpos, strCoord[1] + xpos * k)
                elif xmoved > 0 and ymoved < 0:
                    currcoord = (strCoord[0] + xpos, strCoord[1] - xpos * k)
                elif xmoved < 0 and ymoved < 0:
                    currcoord = (strCoord[0] - xpos, strCoord[1] - xpos * k)
                elif xmoved < 0 and ymoved > 0:
                    currcoord = (strCoord[0] - xpos, strCoord[1] + xpos * k)
                # Drag with left button
                dragLeftButton = Quartz.CGEventCreateMouseEvent(
                    None,
                    Quartz.kCGEventLeftMouseDragged,
                    currcoord,
                    Quartz.kCGMouseButtonLeft
                )
                Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap,
                                   dragLeftButton)
                # Wait for reponse of system
                time.sleep(speed)
        else:
            raise ValueError('Not support vertical moving')
        upLeftButton = Quartz.CGEventCreateMouseEvent(
            None,
            Quartz.kCGEventLeftMouseUp,
            stopCoord,
            Quartz.kCGMouseButtonLeft
        )
        # Wait for reponse of system, a plus icon appears
        time.sleep(5)
        # Up left button up
        Quartz.CGEventPost(Quartz.CoreGraphics.kCGHIDEventTap, upLeftButton)

Response: Private method to handle generic mouse left button dragging and dropping and dropping.


Instruction:
Implement a Python 3 function for
waiting for a particular UI event to occur ; this can be built upon in NativeUIElement for specific convenience methods.

Response:
def _waitFor(self, timeout, notification, **kwargs):
        """Wait for a particular UI event to occur; this can be built
        upon in NativeUIElement for specific convenience methods.
        """
        callback = self._matchOther
        retelem = None
        callbackArgs = None
        callbackKwargs = None

        # Allow customization of the callback, though by default use the basic
        # _match() method
        if 'callback' in kwargs:
            callback = kwargs['callback']
            del kwargs['callback']

            # Deal with these only if callback is provided:
            if 'args' in kwargs:
                if not isinstance(kwargs['args'], tuple):
                    errStr = 'Notification callback args not given as a tuple'
                    raise TypeError(errStr)

                # If args are given, notification will pass back the returned
                # element in the first positional arg
                callbackArgs = kwargs['args']
                del kwargs['args']

            if 'kwargs' in kwargs:
                if not isinstance(kwargs['kwargs'], dict):
                    errStr = 'Notification callback kwargs not given as a dict'
                    raise TypeError(errStr)

                callbackKwargs = kwargs['kwargs']
                del kwargs['kwargs']
            # If kwargs are not given as a dictionary but individually listed
            # need to update the callbackKwargs dict with the remaining items in
            # kwargs
            if kwargs:
                if callbackKwargs:
                    callbackKwargs.update(kwargs)
                else:
                    callbackKwargs = kwargs
        else:
            callbackArgs = (retelem,)
            # Pass the kwargs to the default callback
            callbackKwargs = kwargs

        return self._setNotification(timeout, notification, callback,
                                     callbackArgs,
                                     callbackKwargs)


Instruction:
Here you have a function in Python 3, explain what it does
def waitForFocusToMatchCriteria(self, timeout=10, **kwargs):

        def _matchFocused(retelem, **kwargs):
            return retelem if retelem._match(**kwargs) else None

        retelem = None
        return self._waitFor(timeout, 'AXFocusedUIElementChanged',
                             callback=_matchFocused,
                             args=(retelem,),
                             **kwargs)

Response: Convenience method to wait for focused element to change the specified kwargs criteria.


Instruction:
How would you implement a function in Python 3 that
retrieves a list of actions supported by the object.

Response:
def _getActions(self):
        """Retrieve a list of actions supported by the object."""
        actions = _a11y.AXUIElement._getActions(self)
        # strip leading AX from actions - help distinguish them from attributes
        return [action[2:] for action in actions]


Instruction:
Can you generate the documentation for the following Python 3 function
def _performAction(self, action):
        try:
            _a11y.AXUIElement._performAction(self, 'AX%s' % action)
        except _a11y.ErrorUnsupported as e:
            sierra_ver = '10.12'
            if mac_ver()[0] < sierra_ver:
                raise e
            else:
                pass

Response: Perform the specified action.


Instruction:
Can you tell what is the following Python 3 function doing
def _generateChildren(self):
        try:
            children = self.AXChildren
        except _a11y.Error:
            return
        if children:
            for child in children:
                yield child

Response: Generator which yields all AXChildren of the object.


Instruction:
Given the following Python 3 function, write the documentation
def _matchOther(self, obj, **kwargs):
        if obj is not None:
            # Need to check that the returned UI element wasn't destroyed first:
            if self._findFirstR(**kwargs):
                return obj._match(**kwargs)
        return False

Response: Perform _match but on another object not self.


Instruction:
Can you tell what is the following Python 3 function doing
def _generateFind(self, **kwargs):
        for needle in self._generateChildren():
            if needle._match(**kwargs):
                yield needle

Response: Generator which yields matches on AXChildren.


Instruction:
Write a Python 3 function that can
return a list of all children that match the specified criteria.

Response:
def _findAll(self, **kwargs):
        """Return a list of all children that match the specified criteria."""
        result = []
        for item in self._generateFind(**kwargs):
            result.append(item)
        return result


Instruction:
Can you implement a function in Python 3 that
returns a list of all children that match the specified criteria.

Response:
def _findAllR(self, **kwargs):
        """Return a list of all children (recursively) that match the specified
        criteria.
        """
        result = []
        for item in self._generateFindR(**kwargs):
            result.append(item)
        return result


Instruction:
How would you explain what the following Python 3 function does
def _getApplication(self):
        app = self
        while True:
            try:
                app = app.AXParent
            except _a11y.ErrorUnsupported:
                break
        return app

Response: Get the base application UIElement.


Instruction:
Make a summary of the following Python 3 code
def _menuItem(self, menuitem, *args):
        self._activate()
        for item in args:
            # If the item has an AXMenu as a child, navigate into it.
            # This seems like a silly abstraction added by apple's a11y api.
            if menuitem.AXChildren[0].AXRole == 'AXMenu':
                menuitem = menuitem.AXChildren[0]
            # Find AXMenuBarItems and AXMenuItems using a handy wildcard
            role = 'AXMenu*Item'
            try:
                menuitem = menuitem.AXChildren[int(item)]
            except ValueError:
                menuitem = menuitem.findFirst(AXRole='AXMenu*Item',
                                              AXTitle=item)
        return menuitem

Response: Return the specified menu item.


Instruction:
Can you generate the documentation for the following Python 3 function
def _activate(self):
        ra = AppKit.NSRunningApplication
        app = ra.runningApplicationWithProcessIdentifier_(
            self._getPid())
        # NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps
        # == 3 - PyObjC in 10.6 does not expose these constants though so I have
        # to use the int instead of the symbolic names
        app.activateWithOptions_(3)

Response: Activate the application ( bringing menus and windows forward.


Instruction:
Make a summary of the following Python 3 code
def _getBundleId(self):
        ra = AppKit.NSRunningApplication
        app = ra.runningApplicationWithProcessIdentifier_(
            self._getPid())
        return app.bundleIdentifier()

Response: Return the bundle ID of the application.


Instruction:
Make a summary of the following Python 3 code
def menuItem(self, *args):
        menuitem = self._getApplication().AXMenuBar
        return self._menuItem(menuitem, *args)

Response: Return the specified menu item.


Instruction:
Implement a function in Python 3 to
return the specified item in a pop up menu.

Response:
def popUpItem(self, *args):
        """Return the specified item in a pop up menu."""
        self.Press()
        time.sleep(.5)
        return self._menuItem(self, *args)


Instruction:
Write a Python 3 script for
dragging the left mouse button without modifiers pressed. Parameters: coordinates to click on screen (tuple (x, y)) dest coordinates to drag to (tuple (x, y)) interval to send event of btn down, drag and up Returns: None

Response:
def dragMouseButtonLeft(self, coord, dest_coord, interval=0.5):
        """Drag the left mouse button without modifiers pressed.

        Parameters: coordinates to click on screen (tuple (x, y))
                    dest coordinates to drag to (tuple (x, y))
                    interval to send event of btn down, drag and up
        Returns: None
        """

        modFlags = 0
        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,
                               dest_coord=dest_coord)
        self._postQueuedEvents(interval=interval)


Instruction:
Can you tell what is the following Python 3 function doing
def doubleClickDragMouseButtonLeft(self, coord, dest_coord, interval=0.5):
        modFlags = 0
        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,
                               dest_coord=dest_coord)
        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,
                               dest_coord=dest_coord,
                               clickCount=2)
        self._postQueuedEvents(interval=interval)

Response: Double - click and drag the left mouse button without modifiers.


Instruction:
Explain what the following Python 3 code does
def clickMouseButtonLeft(self, coord, interval=None):

        modFlags = 0
        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)
        if interval:
            self._postQueuedEvents(interval=interval)
        else:
            self._postQueuedEvents()

Response: Click the left mouse button without modifiers pressed.


Instruction:
Given the following Python 3 function, write the documentation
def clickMouseButtonRight(self, coord):
        modFlags = 0
        self._queueMouseButton(coord, Quartz.kCGMouseButtonRight, modFlags)
        self._postQueuedEvents()

Response: Click the right mouse button without modifiers pressed.


Instruction:
Make a summary of the following Python 3 code
def clickMouseButtonLeftWithMods(self, coord, modifiers, interval=None):
        modFlags = self._pressModifiers(modifiers)
        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)
        self._releaseModifiers(modifiers)
        if interval:
            self._postQueuedEvents(interval=interval)
        else:
            self._postQueuedEvents()

Response: Click the left mouse button with modifiers pressed.


Instruction:
Create a Python 3 function to
click the right mouse button with modifiers pressed.

Response:
def clickMouseButtonRightWithMods(self, coord, modifiers):
        """Click the right mouse button with modifiers pressed.

        Parameters: coordinates to click; modifiers (list)
        Returns: None
        """
        modFlags = self._pressModifiers(modifiers)
        self._queueMouseButton(coord, Quartz.kCGMouseButtonRight, modFlags)
        self._releaseModifiers(modifiers)
        self._postQueuedEvents()


Instruction:
How would you explain what the following Python 3 function does
def leftMouseDragged(self, stopCoord, strCoord=(0, 0), speed=1):
        self._leftMouseDragged(stopCoord, strCoord, speed)

Response: Click the left mouse button and drag object.


Instruction:
Can you tell what is the following Python 3 function doing
def doubleClickMouse(self, coord):
        modFlags = 0
        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)
        # This is a kludge:
        # If directed towards a Fusion VM the clickCount gets ignored and this
        # will be seen as a single click, so in sequence this will be a double-
        # click
        # Otherwise to a host app only this second one will count as a double-
        # click
        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,
                               clickCount=2)
        self._postQueuedEvents()

Response: Double - click primary mouse button.


Instruction:
Can you tell what is the following Python 3 function doing
def doubleMouseButtonLeftWithMods(self, coord, modifiers):
        modFlags = self._pressModifiers(modifiers)
        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)
        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,
                               clickCount=2)
        self._releaseModifiers(modifiers)
        self._postQueuedEvents()

Response: Double mouse button left with modifiers pressed.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def tripleClickMouse(self, coord):
        # Note above re: double-clicks applies to triple-clicks
        modFlags = 0
        for i in range(2):
            self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags)
        self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags,
                               clickCount=3)
        self._postQueuedEvents()

Response: Triple - click primary mouse button.


Instruction:
Can you generate the documentation for the following Python 3 function
def waitForValueToChange(self, timeout=10):
        # Want to identify that the element whose value changes matches this
        # object's.  Unique identifiers considered include role and position
        # This seems to work best if you set the notification at the application
        # level
        callback = AXCallbacks.returnElemCallback
        retelem = None
        return self.waitFor(timeout, 'AXValueChanged', callback=callback,
                            args=(retelem,))

Response:
Convenience method to wait for value attribute of given element to
        change.


Instruction:
Here you have a function in Python 3, explain what it does
def waitForFocusToChange(self, newFocusedElem, timeout=10):
        return self.waitFor(timeout, 'AXFocusedUIElementChanged',
                            AXRole=newFocusedElem.AXRole,
                            AXPosition=newFocusedElem.AXPosition)

Response: Convenience method to wait for the focused element to change.


Instruction:
Can you generate the documentation for the following Python 3 function
def _convenienceMatch(self, role, attr, match):
        kwargs = {}
        # If the user supplied some text to search for,
        # supply that in the kwargs
        if match:
            kwargs[attr] = match
        return self.findAll(AXRole=role, **kwargs)

Response: Method used by role based convenience functions to find a match


Instruction:
How would you explain what the following Python 3 function does
def _convenienceMatchR(self, role, attr, match):
        kwargs = {}
        # If the user supplied some text to search for,
        # supply that in the kwargs
        if match:
            kwargs[attr] = match
        return self.findAllR(AXRole=role, **kwargs)

Response: Method used by role based convenience functions to find a match


Instruction:
Can you generate the documentation for the following Python 3 function
def imagecapture(self, window_name=None, x=0, y=0,
                     width=None, height=None):
        """
        Captures screenshot of the whole desktop or given window

        @param window_name: Window name to look for, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param x: x co-ordinate value
        @type x: int
        @param y: y co-ordinate value
        @type y: int
        @param width: width co-ordinate value
        @type width: int
        @param height: height co-ordinate value
        @type height: int

        @return: screenshot with base64 encoded for the client
        @rtype: string
        """
        if x or y or (width and width != -1) or (height and height != -1):
            raise LdtpServerException("Not implemented")
        if window_name:
            handle, name, app = self._get_window_handle(window_name)
            try:
                self._grabfocus(handle)
            except:
                pass
            rect = self._getobjectsize(handle)
            screenshot = CGWindowListCreateImage(NSMakeRect(rect[0],
                                                            rect[1], rect[2], rect[3]), 1, 0, 0)
        else:
            screenshot = CGWindowListCreateImage(CGRectInfinite, 1, 0, 0)
        image = CIImage.imageWithCGImage_(screenshot)
        bitmapRep = NSBitmapImageRep.alloc().initWithCIImage_(image)
        blob = bitmapRep.representationUsingType_properties_(NSPNGFileType, None)
        tmpFile = tempfile.mktemp('.png', 'ldtpd_')
        blob.writeToFile_atomically_(tmpFile, False)
        rv = b64encode(open(tmpFile).read())
        os.remove(tmpFile)
        return rv

Response:
Takes a screenshot of the whole desktop or given window
ecords x y width height and returns the base64 encoded image for the client.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def startlog(filename, overwrite=True):

    if not filename:
        return 0

    if overwrite:
        # Create new file, by overwriting existing file
        _mode = 'w'
    else:
        # Append existing file
        _mode = 'a'
    global _file_logger
    # Create logging file handler
    _file_logger = logging.FileHandler(os.path.expanduser(filename), _mode)
    # Log 'Levelname: Messages', eg: 'ERROR: Logged message'
    _formatter = logging.Formatter('%(levelname)-8s: %(message)s')
    _file_logger.setFormatter(_formatter)
    logger.addHandler(_file_logger)
    if _ldtp_debug:
        # On debug, change the default log level to DEBUG
        _file_logger.setLevel(logging.DEBUG)
    else:
        # else log in case of ERROR level and above
        _file_logger.setLevel(logging.ERROR)

    return 1

Response: Start logging on the specified file.


Instruction:
Write a Python 3 script to
remove registered callback on window create

Response:
def removecallback(window_name):
    """
    Remove registered callback on window create

    @param window_name: Window name to look for, either full name,
    LDTP's name convention, or a Unix glob.
    @type window_name: string

    @return: 1 if registration was successful, 0 if not.
    @rtype: integer
    """

    if window_name in _pollEvents._callback:
        del _pollEvents._callback[window_name]
    return _remote_removecallback(window_name)


Instruction:
How would you explain what the following Python 3 function does
def callAfter(func, *args, **kwargs):
    pool = NSAutoreleasePool.alloc().init()
    obj = PyObjCAppHelperCaller_wrap.alloc().initWithArgs_((func, args, kwargs))
    obj.callAfter_(None)
    del obj
    del pool

Response: call a function on the main thread


Instruction:
Can you implement a function in Python 3 that
calls a function on the main thread after a delay

Response:
def callLater(delay, func, *args, **kwargs):
    """call a function on the main thread after a delay (async)"""
    pool = NSAutoreleasePool.alloc().init()
    obj = PyObjCAppHelperCaller_wrap.alloc().initWithArgs_((func, args, kwargs))
    obj.callLater_(delay)
    del obj
    del pool


Instruction:
Can you create a Python 3 function that
stops the current event loop if possible.

Response:
def stopEventLoop():
    """
    Stop the current event loop if possible
    returns True if it expects that it was successful, False otherwise
    """
    stopper = PyObjCAppHelperRunLoopStopper_wrap.currentRunLoopStopper()
    if stopper is None:
        if NSApp() is not None:
            NSApp().terminate_(None)
            return True
        return False
    NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
        0.0,
        stopper,
        'performStop:',
        None,
        False)
    return True


Instruction:
How would you code a function in Python 3 to
run the event loop.

Response:
def runEventLoop(argv=None, unexpectedErrorAlert=None, installInterrupt=None, pdb=None, main=NSApplicationMain):
    """Run the event loop, ask the user if we should continue if an
    exception is caught. Use this function instead of NSApplicationMain().
    """
    if argv is None:
        argv = sys.argv

    if pdb is None:
        pdb = 'USE_PDB' in os.environ

    if pdb:
        from PyObjCTools import Debugging
        Debugging.installVerboseExceptionHandler()
        # bring it to the front, starting from terminal
        # often won't
        activator = PyObjCAppHelperApplicationActivator_wrap.alloc().init()
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            activator,
            'activateNow:',
            NSApplicationDidFinishLaunchingNotification,
            None,
        )
    else:
        Debugging = None

    if installInterrupt is None and pdb:
        installInterrupt = True

    if unexpectedErrorAlert is None:
        unexpectedErrorAlert = unexpectedErrorAlertPdb

    runLoop = NSRunLoop.currentRunLoop()
    stopper = PyObjCAppHelperRunLoopStopper_wrap.alloc().init()
    PyObjCAppHelperRunLoopStopper_wrap.addRunLoopStopper_toRunLoop_(stopper, runLoop)

    firstRun = NSApp() is None
    try:

        while stopper.shouldRun():
            try:
                if firstRun:
                    firstRun = False
                    if installInterrupt:
                        installMachInterrupt()
                    main(argv)
                else:
                    NSApp().run()
            except RAISETHESE:
                traceback.print_exc()
                break
            except:
                exctype, e, tb = sys.exc_info()
                objc_exception = False
                if isinstance(e, objc.error):
                    NSLog("%@", str(e))
                elif not unexpectedErrorAlert():
                    NSLog("%@", "An exception has occured:")
                    traceback.print_exc()
                    sys.exit(0)
                else:
                    NSLog("%@", "An exception has occured:")
                    traceback.print_exc()
            else:
                break

    finally:
        if Debugging is not None:
            Debugging.removeExceptionHandler()
        PyObjCAppHelperRunLoopStopper_wrap.removeRunLoopStopperFromRunLoop_(runLoop)


Instruction:
Here you have a function in Python 3, explain what it does
def keypress(self, data):
        try:
            window = self._get_front_most_window()
        except (IndexError,):
            window = self._get_any_window()
        key_press_action = KeyPressAction(window, data)
        return 1

Response: Keypress key. NOTE : keyrelease should be called


Instruction:
Can you implement a function in Python 3 that
releases key. NOTE: keypress should be called before this @param data: data to type. @type data: string @return: 1 on success. @rtype: integer

Response:
def keyrelease(self, data):
        """
        Release key. NOTE: keypress should be called before this

        @param data: data to type.
        @type data: string

        @return: 1 on success.
        @rtype: integer
        """
        try:
            window = self._get_front_most_window()
        except (IndexError,):
            window = self._get_any_window()
        key_release_action = KeyReleaseAction(window, data)
        return 1


Instruction:
Here you have a function in Python 3, explain what it does
def enterstring(self, window_name, object_name='', data=''):
        if not object_name and not data:
            return self.generatekeyevent(window_name)
        else:
            object_handle = self._get_object_handle(window_name, object_name)
            if not object_handle.AXEnabled:
                raise LdtpServerException(u"Object %s state disabled" % object_name)
            self._grabfocus(object_handle)
            object_handle.sendKeys(data)
            return 1

Response:
Type string sequence.

        @param window_name: Window name to focus on, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to focus on, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string
        @param data: data to type.
        @type data: string

        @return: 1 on success.
        @rtype: integer


Instruction:
Can you generate the documentation for the following Python 3 function
def gettextvalue(self, window_name, object_name, startPosition=0, endPosition=0):
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        return object_handle.AXValue

Response: Get the text value of a specific object in a given window.


Instruction:
Here you have a function in Python 3, explain what it does
def inserttext(self, window_name, object_name, position, data):
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        existing_data = object_handle.AXValue
        size = len(existing_data)
        if position < 0:
            position = 0
        if position > size:
            position = size
        object_handle.AXValue = existing_data[:position] + data + \
                                existing_data[position:]
        return 1

Response: Insert string sequence in given position.


Instruction:
Can you create a Python 3 function that
verifies partial text for a given object name and window name.

Response:
def verifypartialmatch(self, window_name, object_name, partial_text):
        """
        Verify partial text

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string
        @param partial_text: Partial text to match
        @type object_name: string

        @return: 1 on success.
        @rtype: integer
        """
        try:
            if re.search(fnmatch.translate(partial_text),
                         self.gettextvalue(window_name,
                                           object_name)):
                return 1
        except:
            pass
        return 0


Instruction:
Given the following Python 3 function, write the documentation
def verifysettext(self, window_name, object_name, text):
        try:
            return int(re.match(fnmatch.translate(text),
                                self.gettextvalue(window_name,
                                                  object_name)))
        except:
            return 0

Response: Verify that the text is set correctly with the object name.


Instruction:
Can you implement a function in Python 3 that
verifies if text state of an object is enabled or not.

Response:
def istextstateenabled(self, window_name, object_name):
        """
        Verifies text state enabled or not

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string

        @return: 1 on success 0 on failure.
        @rtype: integer
        """
        try:
            object_handle = self._get_object_handle(window_name, object_name)
            if object_handle.AXEnabled:
                return 1
        except LdtpServerException:
            pass
        return 0


Instruction:
Can you generate a brief explanation for the following Python 3 code
def getcharcount(self, window_name, object_name):
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        return object_handle.AXNumberOfCharacters

Response: Get the number of characters in an object.


Instruction:
Given the following Python 3 function, write the documentation
def appendtext(self, window_name, object_name, data):
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        object_handle.AXValue += data
        return 1

Response:
Append string sequence.

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string
        @param data: data to type.
        @type data: string

        @return: 1 on success.
        @rtype: integer


Instruction:
Implement a function in Python 3 to
get cursor position of the object in the specified window.

Response:
def getcursorposition(self, window_name, object_name):
        """
        Get cursor position

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string

        @return: Cursor position on success.
        @rtype: integer
        """
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        return object_handle.AXSelectedTextRange.loc


Instruction:
Write a Python 3 function that can
set the cursor position of the object in the specified window.

Response:
def setcursorposition(self, window_name, object_name, cursor_position):
        """
        Set cursor position

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string
        @param cursor_position: Cursor position to be set
        @type object_name: string

        @return: 1 on success.
        @rtype: integer
        """
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        object_handle.AXSelectedTextRange.loc = cursor_position
        return 1


Instruction:
How would you explain what the following Python 3 function does
def cuttext(self, window_name, object_name, start_position, end_position=-1):
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        size = object_handle.AXNumberOfCharacters
        if end_position == -1 or end_position > size:
            end_position = size
        if start_position < 0:
            start_position = 0
        data = object_handle.AXValue
        Clipboard.copy(data[start_position:end_position])
        object_handle.AXValue = data[:start_position] + data[end_position:]
        return 1

Response:
Cut text from start position to end position
 Arcs.


Instruction:
How would you explain what the following Python 3 function does
def deletetext(self, window_name, object_name, start_position, end_position=-1):
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        size = object_handle.AXNumberOfCharacters
        if end_position == -1 or end_position > size:
            end_position = size
        if start_position < 0:
            start_position = 0
        data = object_handle.AXValue
        object_handle.AXValue = data[:start_position] + data[end_position:]
        return 1

Response: Delete all the text from start_position to end_position.


Instruction:
Implement a Python 3 function for
pasting text from start position to end position @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param position: Position to paste the text, default 0 @type object_name: integer @return: 1 on success. @rtype: integer

Response:
def pastetext(self, window_name, object_name, position=0):
        """
        paste text from start position to end position

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string
        @param position: Position to paste the text, default 0
        @type object_name: integer

        @return: 1 on success.
        @rtype: integer
        """
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        size = object_handle.AXNumberOfCharacters
        if position > size:
            position = size
        if position < 0:
            position = 0
        clipboard = Clipboard.paste()
        data = object_handle.AXValue
        object_handle.AXValue = data[:position] + clipboard + data[position:]
        return 1


Instruction:
How would you explain what the following Python 3 function does
def main(port=4118, parentpid=None):
    if "LDTP_DEBUG" in os.environ:
        _ldtp_debug = True
    else:
        _ldtp_debug = False
    _ldtp_debug_file = os.environ.get('LDTP_DEBUG_FILE', None)
    if _ldtp_debug:
        print("Parent PID: {}".format(int(parentpid)))
    if _ldtp_debug_file:
        with open(unicode(_ldtp_debug_file), "a") as fp:
            fp.write("Parent PID: {}".format(int(parentpid)))
    server = LDTPServer(('', port), allow_none=True, logRequests=_ldtp_debug,
                        requestHandler=RequestHandler)
    server.register_introspection_functions()
    server.register_multicall_functions()
    ldtp_inst = core.Core()
    server.register_instance(ldtp_inst)
    if parentpid:
        thread.start_new_thread(notifyclient, (parentpid,))
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass
    except:
        if _ldtp_debug:
            print(traceback.format_exc())
        if _ldtp_debug_file:
            with open(_ldtp_debug_file, "a") as fp:
                fp.write(traceback.format_exc())

Response: Entry point. Parse command line options and start up a server.


Instruction:
Create a Python 3 function to
log the message in the root logger with the log level level.

Response:
def log(self, message, level=logging.DEBUG):
        """
        Logs the message in the root logger with the log level
        @param message: Message to be logged
        @type message: string
        @param level: Log level, defaul DEBUG
        @type level: integer

        @return: 1 on success and 0 on error
        @rtype: integer
        """
        if _ldtp_debug:
            print(message)
        self.logger.log(level, str(message))
        return 1


Instruction:
Write a Python 3 script to
stop logging. @return: 1 on success and 0 on error @rtype: integer

Response:
def stoplog(self):
        """ Stop logging.

        @return: 1 on success and 0 on error
        @rtype: integer
        """
        if self._file_logger:
            self.logger.removeHandler(_file_logger)
            self._file_logger = None
        return 1


Instruction:
Write a Python 3 function for
capturing the entire desktop or given window.

Response:
def imagecapture(self, window_name=None, out_file=None, x=0, y=0,
                     width=None, height=None):
        """
        Captures screenshot of the whole desktop or given window

        @param window_name: Window name to look for, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param x: x co-ordinate value
        @type x: integer
        @param y: y co-ordinate value
        @type y: integer
        @param width: width co-ordinate value
        @type width: integer
        @param height: height co-ordinate value
        @type height: integer

        @return: screenshot filename
        @rtype: string
        """
        if not out_file:
            out_file = tempfile.mktemp('.png', 'ldtp_')
        else:
            out_file = os.path.expanduser(out_file)

        ### Windows compatibility
        if _ldtp_windows_env:
            if width == None:
                width = -1
            if height == None:
                height = -1
            if window_name == None:
                window_name = ''
        ### Windows compatibility - End
        data = self._remote_imagecapture(window_name, x, y, width, height)
        f = open(out_file, 'wb')
        f.write(b64decode(data))
        f.close()
        return out_file


Instruction:
Write a Python 3 script to
call by the LDTP when a new window is created.

Response:
def onwindowcreate(self, window_name, fn_name, *args):
        """
        On window create, call the function with given arguments

        @param window_name: Window name to look for, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param fn_name: Callback function
        @type fn_name: function
        @param *args: arguments to be passed to the callback function
        @type *args: var args

        @return: 1 if registration was successful, 0 if not.
        @rtype: integer
        """
        self._pollEvents._callback[window_name] = ["onwindowcreate", fn_name, args]
        return self._remote_onwindowcreate(window_name)


Instruction:
Given the following Python 3 function, write the documentation
def registerevent(self, event_name, fn_name, *args):
        if not isinstance(event_name, str):
            raise ValueError("event_name should be string")
        self._pollEvents._callback[event_name] = [event_name, fn_name, args]
        return self._remote_registerevent(event_name)

Response: Register a new event in the poll events list.


Instruction:
Explain what the following Python 3 code does
def deregisterevent(self, event_name):

        if event_name in self._pollEvents._callback:
            del self._pollEvents._callback[event_name]
        return self._remote_deregisterevent(event_name)

Response: Removes callback of registered event with given event name.


Instruction:
Write a Python 3 function for
registering a keystroke event in the poll events list.

Response:
def registerkbevent(self, keys, modifiers, fn_name, *args):
        """
        Register keystroke events

        @param keys: key to listen
        @type keys: string
        @param modifiers: control / alt combination using gtk MODIFIERS
        @type modifiers: int
        @param fn_name: Callback function
        @type fn_name: function
        @param *args: arguments to be passed to the callback function
        @type *args: var args

        @return: 1 if registration was successful, 0 if not.
        @rtype: integer
        """
        event_name = "kbevent%s%s" % (keys, modifiers)
        self._pollEvents._callback[event_name] = [event_name, fn_name, args]
        return self._remote_registerkbevent(keys, modifiers)


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

        event_name = "kbevent%s%s" % (keys, modifiers)
        if event_name in _pollEvents._callback:
            del _pollEvents._callback[event_name]
        return self._remote_deregisterkbevent(keys, modifiers)

Response: Removes a callback from the event loop that was registered with the given keys and modifiers.


Instruction:
How would you explain what the following Python 3 function does
def windowuptime(self, window_name):
        tmp_time = self._remote_windowuptime(window_name)
        if tmp_time:
            tmp_time = tmp_time.split('-')
            start_time = tmp_time[0].split(' ')
            end_time = tmp_time[1].split(' ')
            _start_time = datetime.datetime(int(start_time[0]), int(start_time[1]),
                                            int(start_time[2]), int(start_time[3]),
                                            int(start_time[4]), int(start_time[5]))
            _end_time = datetime.datetime(int(end_time[0]), int(end_time[1]),
                                          int(end_time[2]), int(end_time[3]),
                                          int(end_time[4]), int(end_time[5]))
            return _start_time, _end_time
        return None

Response: Get the uptime of a given window.


Instruction:
Explain what the following Python 3 code does
def verifyscrollbarvertical(self, window_name, object_name):
        try:
            object_handle = self._get_object_handle(window_name, object_name)
            if object_handle.AXOrientation == "AXVerticalOrientation":
                return 1
        except:
            pass
        return 0

Response: Verify scrollbar is vertical


Instruction:
Write a Python 3 script to
verify scrollbar is horizontal.

Response:
def verifyscrollbarhorizontal(self, window_name, object_name):
        """
        Verify scrollbar is horizontal

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string

        @return: 1 on success.
        @rtype: integer
        """
        try:
            object_handle = self._get_object_handle(window_name, object_name)
            if object_handle.AXOrientation == "AXHorizontalOrientation":
                return 1
        except:
            pass
        return 0


Instruction:
Can you generate a brief explanation for the following Python 3 code
def setmax(self, window_name, object_name):
        object_handle = self._get_object_handle(window_name, object_name)
        object_handle.AXValue = 1
        return 1

Response: Set the max value of the object name in the specified window.


Instruction:
Create a Python 3 function to
set the minimum value of the object name in the specified window.

Response:
def setmin(self, window_name, object_name):
        """
        Set min value

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string

        @return: 1 on success.
        @rtype: integer
        """
        object_handle = self._get_object_handle(window_name, object_name)
        object_handle.AXValue = 0
        return 1


Instruction:
Here you have a function in Python 3, explain what it does
def scrollup(self, window_name, object_name):
        if not self.verifyscrollbarvertical(window_name, object_name):
            raise LdtpServerException('Object not vertical scrollbar')
        return self.setmin(window_name, object_name)

Response: Scroll up the object in the specified window.


Instruction:
Implement a function in Python 3 to
scroll down the object in the specified window.

Response:
def scrolldown(self, window_name, object_name):
        """
        Scroll down

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string

        @return: 1 on success.
        @rtype: integer
        """
        if not self.verifyscrollbarvertical(window_name, object_name):
            raise LdtpServerException('Object not vertical scrollbar')
        return self.setmax(window_name, object_name)


Instruction:
How would you explain what the following Python 3 function does
def scrollleft(self, window_name, object_name):
        if not self.verifyscrollbarhorizontal(window_name, object_name):
            raise LdtpServerException('Object not horizontal scrollbar')
        return self.setmin(window_name, object_name)

Response: Scroll left operation for the given object in the specified window.


Instruction:
Make a summary of the following Python 3 code
def scrollright(self, window_name, object_name):
        if not self.verifyscrollbarhorizontal(window_name, object_name):
            raise LdtpServerException('Object not horizontal scrollbar')
        return self.setmax(window_name, object_name)

Response: Scrolls the right of an object in the specified window.


Instruction:
How would you code a function in Python 3 to
press scrollbar up with number of iterations to perform on slider increase

Response:
def oneup(self, window_name, object_name, iterations):
        """
        Press scrollbar up with number of iterations

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string
        @param interations: iterations to perform on slider increase
        @type iterations: integer

        @return: 1 on success.
        @rtype: integer
        """
        if not self.verifyscrollbarvertical(window_name, object_name):
            raise LdtpServerException('Object not vertical scrollbar')
        object_handle = self._get_object_handle(window_name, object_name)
        i = 0
        minValue = 1.0 / 8
        flag = False
        while i < iterations:
            if object_handle.AXValue <= 0:
                raise LdtpServerException('Minimum limit reached')
            object_handle.AXValue -= minValue
            time.sleep(1.0 / 100)
            flag = True
            i += 1
        if flag:
            return 1
        else:
            raise LdtpServerException('Unable to decrease scrollbar')


Instruction:
Can you create a Python 3 function that
presses scrollbar right with number of iterations

Response:
def oneright(self, window_name, object_name, iterations):
        """
        Press scrollbar right with number of iterations

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string
        @param interations: iterations to perform on slider increase
        @type iterations: integer

        @return: 1 on success.
        @rtype: integer
        """
        if not self.verifyscrollbarhorizontal(window_name, object_name):
            raise LdtpServerException('Object not horizontal scrollbar')
        object_handle = self._get_object_handle(window_name, object_name)
        i = 0
        maxValue = 1.0 / 8
        flag = False
        while i < iterations:
            if object_handle.AXValue >= 1:
                raise LdtpServerException('Maximum limit reached')
            object_handle.AXValue += maxValue
            time.sleep(1.0 / 100)
            flag = True
            i += 1
        if flag:
            return 1
        else:
            raise LdtpServerException('Unable to increase scrollbar')


Instruction:
Write a Python 3 function for
pressing scrollbar left with number of iterations @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. @type object_name: string @param interations: iterations to perform on slider increase @type iterations: integer @return: 1 on success. @rtype: integer

Response:
def oneleft(self, window_name, object_name, iterations):
        """
        Press scrollbar left with number of iterations

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string
        @param interations: iterations to perform on slider increase
        @type iterations: integer

        @return: 1 on success.
        @rtype: integer
        """
        if not self.verifyscrollbarhorizontal(window_name, object_name):
            raise LdtpServerException('Object not horizontal scrollbar')
        object_handle = self._get_object_handle(window_name, object_name)
        i = 0
        minValue = 1.0 / 8
        flag = False
        while i < iterations:
            if object_handle.AXValue <= 0:
                raise LdtpServerException('Minimum limit reached')
            object_handle.AXValue -= minValue
            time.sleep(1.0 / 100)
            flag = True
            i += 1
        if flag:
            return 1
        else:
            raise LdtpServerException('Unable to decrease scrollbar')


Instruction:
Make a summary of the following Python 3 code
def selecttabindex(self, window_name, object_name, tab_index):
        children = self._get_tab_children(window_name, object_name)
        length = len(children)
        if tab_index < 0 or tab_index > length:
            raise LdtpServerException(u"Invalid tab index %s" % tab_index)
        tab_handle = children[tab_index]
        if not tab_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        tab_handle.Press()
        return 1

Response: Select tab based on index.


Instruction:
Make a summary of the following Python 3 code
def verifytabname(self, window_name, object_name, tab_name):
        try:
            tab_handle = self._get_tab_handle(window_name, object_name, tab_name)
            if tab_handle.AXValue:
                return 1
        except LdtpServerException:
            pass
        return 0

Response: Verify the object name of a specific object in a given window.


Instruction:
Write a Python 3 script for
getting the number of children of a given object in a given window.

Response:
def gettabcount(self, window_name, object_name):
        """
        Get tab count.

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string

        @return: tab count on success.
        @rtype: integer
        """
        children = self._get_tab_children(window_name, object_name)
        return len(children)


Instruction:
Write a Python 3 function that can
get the tab name of a given object.

Response:
def gettabname(self, window_name, object_name, tab_index):
        """
        Get tab name

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string
        @param tab_index: Index of tab (zero based index)
        @type object_name: int

        @return: text on success.
        @rtype: string
        """
        children = self._get_tab_children(window_name, object_name)
        length = len(children)
        if tab_index < 0 or tab_index > length:
            raise LdtpServerException(u"Invalid tab index %s" % tab_index)
        tab_handle = children[tab_index]
        if not tab_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        return tab_handle.AXTitle


Instruction:
Given the following Python 3 function, write the documentation
def generatemouseevent(self, x, y, eventType="b1c",
                           drag_button_override='drag_default_button'):
        """
        Generate mouse event on x, y co-ordinates.

        @param x: X co-ordinate
        @type x: int
        @param y: Y co-ordinate
        @type y: int
        @param eventType: Mouse click type
        @type eventType: str
        @param drag_button_override: Any drag_xxx value
                Only relevant for movements, i.e. |type| = "abs" or "rel"
                Quartz is not fully compatible with windows, so for drags
                the drag button must be explicitly defined. generatemouseevent
                will remember the last button pressed by default, and drag
                that button, use this argument to override that.
        @type drag_button_override: str

        @return: 1 on success.
        @rtype: integer
        """
        if drag_button_override not in mouse_click_override:
            raise ValueError('Unsupported drag_button_override type: %s' % \
                             drag_button_override)
        global drag_button_remembered
        point = (x, y)
        button = centre  # Only matters for "other" buttons
        click_type = None
        if eventType == "abs" or eventType == "rel":
            if drag_button_override is not 'drag_default_button':
                events = [mouse_click_override[drag_button_override]]
            elif drag_button_remembered:
                events = [drag_button_remembered]
            else:
                events = [move]
            if eventType == "rel":
                point = CGEventGetLocation(CGEventCreate(None))
                point.x += x
                point.y += y
        elif eventType == "b1p":
            events = [press_left]
            drag_button_remembered = drag_left
        elif eventType == "b1r":
            events = [release_left]
            drag_button_remembered = None
        elif eventType == "b1c":
            events = [press_left, release_left]
        elif eventType == "b1d":
            events = [press_left, release_left]
            click_type = double_click
        elif eventType == "b2p":
            events = [press_other]
            drag_button_remembered = drag_other
        elif eventType == "b2r":
            events = [release_other]
            drag_button_remembered = None
        elif eventType == "b2c":
            events = [press_other, release_other]
        elif eventType == "b2d":
            events = [press_other, release_other]
            click_type = double_click
        elif eventType == "b3p":
            events = [press_right]
            drag_button_remembered = drag_right
        elif eventType == "b3r":
            events = [release_right]
            drag_button_remembered = None
        elif eventType == "b3c":
            events = [press_right, release_right]
        elif eventType == "b3d":
            events = [press_right, release_right]
            click_type = double_click
        else:
            raise LdtpServerException(u"Mouse event '%s' not implemented" % eventType)

        for event in events:
            CG_event = CGEventCreateMouseEvent(None, event, point, button)
            if click_type:
                CGEventSetIntegerValueField(
                    CG_event, kCGMouseEventClickState, click_type)
            CGEventPost(kCGHIDEventTap, CG_event)
            # Give the event time to happen
            time.sleep(0.01)
        return 1

Response: Generate mouse event on x y.


Instruction:
Given the following Python 3 function, write the documentation
def doubleclick(self, window_name, object_name):
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        self._grabfocus(object_handle)
        x, y, width, height = self._getobjectsize(object_handle)
        window = self._get_front_most_window()
        # Mouse double click on the object
        # object_handle.doubleClick()
        window.doubleClickMouse((x + width / 2, y + height / 2))
        return 1

Response: Double click on the object with the given name.


Instruction:
How would you explain what the following Python 3 function does
def selectitem(self, window_name, object_name, item_name):
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        self._grabfocus(object_handle.AXWindow)
        try:
            object_handle.Press()
        except AttributeError:
            # AXPress doesn't work with Instruments
            # So did the following work around
            x, y, width, height = self._getobjectsize(object_handle)
            # Mouse left click on the object
            # Note: x + width/2, y + height / 2 doesn't work
            self.generatemouseevent(x + 5, y + 5, "b1c")
            self.wait(5)
            handle = self._get_sub_menu_handle(object_handle, item_name)
            x, y, width, height = self._getobjectsize(handle)
            # on OSX 10.7 default "b1c" doesn't work
            # so using "b1d", verified with Fusion test, this works
            self.generatemouseevent(x + 5, y + 5, "b1d")
            return 1
        # Required for menuitem to appear in accessibility list
        self.wait(1)
        menu_list = re.split(";", item_name)
        try:
            menu_handle = self._internal_menu_handler(object_handle, menu_list,
                                                      True)
            # Required for menuitem to appear in accessibility list
            self.wait(1)
            if not menu_handle.AXEnabled:
                raise LdtpServerException(u"Object %s state disabled" % \
                                          menu_list[-1])
            menu_handle.Press()
        except LdtpServerException:
            object_handle.activate()
            object_handle.sendKey(AXKeyCodeConstants.ESCAPE)
            raise
        return 1

Response: Select a specific item in a combo box or layered pane.


Instruction:
Write a Python 3 script for
selecting combo box item based on index.

Response:
def selectindex(self, window_name, object_name, item_index):
        """
        Select combo box item / layered pane based on index

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string
        @param item_index: Item index to select
        @type object_name: integer

        @return: 1 on success.
        @rtype: integer
        """
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        self._grabfocus(object_handle.AXWindow)
        try:
            object_handle.Press()
        except AttributeError:
            # AXPress doesn't work with Instruments
            # So did the following work around
            x, y, width, height = self._getobjectsize(object_handle)
            # Mouse left click on the object
            # Note: x + width/2, y + height / 2 doesn't work
            self.generatemouseevent(x + 5, y + 5, "b1c")
        # Required for menuitem to appear in accessibility list
        self.wait(2)
        if not object_handle.AXChildren:
            raise LdtpServerException(u"Unable to find menu")
        # Get AXMenu
        children = object_handle.AXChildren[0]
        if not children:
            raise LdtpServerException(u"Unable to find menu")
        children = children.AXChildren
        tmp_children = []
        for child in children:
            role, label = self._ldtpize_accessible(child)
            # Don't add empty label
            # Menu separator have empty label's
            if label:
                tmp_children.append(child)
        children = tmp_children
        length = len(children)
        try:
            if item_index < 0 or item_index > length:
                raise LdtpServerException(u"Invalid item index %d" % item_index)
            menu_handle = children[item_index]
            if not menu_handle.AXEnabled:
                raise LdtpServerException(u"Object %s state disabled" % menu_list[-1])
            self._grabfocus(menu_handle)
            x, y, width, height = self._getobjectsize(menu_handle)
            # on OSX 10.7 default "b1c" doesn't work
            # so using "b1d", verified with Fusion test, this works
            window = object_handle.AXWindow
            # For some reason,
            # self.generatemouseevent(x + 5, y + 5, "b1d")
            # doesn't work with Fusion settings
            # Advanced window, so work around with this
            # ldtp.selectindex('*Advanced', 'Automatic', 1)
            """
            Traceback (most recent call last):
               File "build/bdist.macosx-10.8-intel/egg/atomac/ldtpd/utils.py", line 178, in _dispatch
                  return getattr(self, method)(*args)
               File "build/bdist.macosx-10.8-intel/egg/atomac/ldtpd/combo_box.py", line 146, in selectindex
                  self.generatemouseevent(x + 5, y + 5, "b1d")
               File "build/bdist.macosx-10.8-intel/egg/atomac/ldtpd/mouse.py", line 97, in generatemouseevent
                  window=self._get_front_most_window()
               File "build/bdist.macosx-10.8-intel/egg/atomac/ldtpd/utils.py", line 185, in _get_front_most_window
                  front_app=atomac.NativeUIElement.getFrontmostApp()
               File "build/bdist.macosx-10.8-intel/egg/atomac/AXClasses.py", line 114, in getFrontmostApp
                  raise ValueError('No GUI application found.')
            ValueError: No GUI application found.
            """
            window.doubleClickMouse((x + 5, y + 5))
            # If menuitem already pressed, set child to None
            # So, it doesn't click back in combobox in finally block
            child = None
        finally:
            if child:
                child.Cancel()
        return 1


Instruction:
How would you code a function in Python 3 to
get all menu items from a specific object.

Response:
def getallitem(self, window_name, object_name):
        """
        Get all combo box item

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string

        @return: list of string on success.
        @rtype: list
        """
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        object_handle.Press()
        # Required for menuitem to appear in accessibility list
        self.wait(1)
        child = None
        try:
            if not object_handle.AXChildren:
                raise LdtpServerException(u"Unable to find menu")
            # Get AXMenu
            children = object_handle.AXChildren[0]
            if not children:
                raise LdtpServerException(u"Unable to find menu")
            children = children.AXChildren
            items = []
            for child in children:
                label = self._get_title(child)
                # Don't add empty label
                # Menu separator have empty label's
                if label:
                    items.append(label)
        finally:
            if child:
                # Set it back, by clicking combo box
                child.Cancel()
        return items


Instruction:
Write a Python 3 script for
showing combo box list or menu entry for a given object.

Response:
def showlist(self, window_name, object_name):
        """
        Show combo box list / menu

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string

        @return: 1 on success.
        @rtype: integer
        """
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        object_handle.Press()
        return 1


Instruction:
Can you generate the documentation for the following Python 3 function
def hidelist(self, window_name, object_name):
        object_handle = self._get_object_handle(window_name, object_name)
        object_handle.activate()
        object_handle.sendKey(AXKeyCodeConstants.ESCAPE)
        return 1

Response: Hide combo box list / menu


Instruction:
Write a Python 3 script for
verifying drop down list / menu poped up by object name.

Response:
def verifydropdown(self, window_name, object_name):
        """
        Verify drop down list / menu poped up

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string

        @return: 1 on success 0 on failure.
        @rtype: integer
        """
        try:
            object_handle = self._get_object_handle(window_name, object_name)
            if not object_handle.AXEnabled or not object_handle.AXChildren:
                return 0
            # Get AXMenu
            children = object_handle.AXChildren[0]
            if children:
                return 1
        except LdtpServerException:
            pass
        return 0


Instruction:
Can you generate the documentation for the following Python 3 function
def verifyselect(self, window_name, object_name, item_name):
        try:
            object_handle = self._get_object_handle(window_name, object_name)
            if not object_handle.AXEnabled:
                return 0
            role, label = self._ldtpize_accessible(object_handle)
            title = self._get_title(object_handle)
            if re.match(item_name, title, re.M | re.U | re.L) or \
                    re.match(item_name, label, re.M | re.U | re.L) or \
                    re.match(item_name, u"%u%u" % (role, label),
                             re.M | re.U | re.L):
                return 1
        except LdtpServerException:
            pass
        return 0

Response: Verify the selected item in combo box.


Instruction:
Can you implement a function in Python 3 that
gets current selected combobox value.

Response:
def getcombovalue(self, window_name, object_name):
        """
        Get current selected combobox value

        @param window_name: Window name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type window_name: string
        @param object_name: Object name to type in, either full name,
        LDTP's name convention, or a Unix glob.
        @type object_name: string

        @return: selected item on success, else LdtpExecutionError on failure.
        @rtype: string
        """
        object_handle = self._get_object_handle(window_name, object_name)
        if not object_handle.AXEnabled:
            raise LdtpServerException(u"Object %s state disabled" % object_name)
        return self._get_title(object_handle)